mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
feat(studio): book themes with palette, font pairing and motif set
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import { BOOK_COLOR_TOKENS, bookThemeColor, type BookColorToken, type BookTheme } from '@trek/shared';
|
||||
import { Unlink } from 'lucide-react';
|
||||
import '../../../styles/studio-theme.css';
|
||||
|
||||
/**
|
||||
* The book's theme colours under a colour's own swatches in the inspector.
|
||||
* Picking one sets the colour and links it, so the element follows the next
|
||||
* theme the book takes; the chain button unlinks it and keeps the colour. A
|
||||
* book without a theme shows nothing here.
|
||||
*/
|
||||
export function StudioThemeLink({
|
||||
theme,
|
||||
token,
|
||||
onLink,
|
||||
onUnlink,
|
||||
t,
|
||||
}: {
|
||||
theme: BookTheme | undefined;
|
||||
/** The token the colour follows now, if any. */
|
||||
token: BookColorToken | undefined;
|
||||
onLink: (token: BookColorToken, hex: string) => void;
|
||||
onUnlink: () => void;
|
||||
t: (k: string) => string;
|
||||
}) {
|
||||
if (!theme) return null;
|
||||
return (
|
||||
<div className="st-theme-link">
|
||||
<span className="st-theme-link-label">{t('studio.theme.linked')}</span>
|
||||
<div className="st-swatches">
|
||||
{BOOK_COLOR_TOKENS.map((key) => {
|
||||
const hex = bookThemeColor(theme, key);
|
||||
const name = t(`studio.theme.token.${key}`);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={key}
|
||||
className={`st-swatch ${token === key ? 'is-linked' : ''}`}
|
||||
style={{ background: hex }}
|
||||
title={name}
|
||||
aria-label={name}
|
||||
aria-pressed={token === key}
|
||||
onClick={() => onLink(key, hex)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{token && (
|
||||
<button
|
||||
type="button"
|
||||
className="st-theme-unlink"
|
||||
onClick={onUnlink}
|
||||
title={t('studio.theme.unlink')}
|
||||
aria-label={t('studio.theme.unlink')}
|
||||
>
|
||||
<Unlink size={13} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import {
|
||||
BOOK_FONT_SLOTS,
|
||||
BOOK_PALETTE_KEYS,
|
||||
BOOK_THEME_DECORATIONS,
|
||||
BOOK_THEME_MOTIFS,
|
||||
BOOK_THEME_PRESETS,
|
||||
bookThemeOf,
|
||||
type BookFontSlot,
|
||||
type BookPaletteKey,
|
||||
type BookThemeFont,
|
||||
type BookThemePreset,
|
||||
} from '@trek/shared';
|
||||
import { Check, ImageIcon, RotateCcw } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import '../../../styles/studio-theme.css';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import { fontStack } from '../bookFonts';
|
||||
import { Choice, Line, Picks, Section, Switch } from '../StudioControls';
|
||||
import { StudioFontPicker } from '../StudioFontPicker';
|
||||
import { PanelHead } from '../StudioPanelHead';
|
||||
import type { StudioT } from '../StudioSidebar';
|
||||
import { useStudioTheme } from './useStudioTheme';
|
||||
|
||||
/**
|
||||
* The Theme section of the rail: twelve built-in looks, the palette, the
|
||||
* typefaces and the motifs of the one being put together, and applying it to
|
||||
* the book or to the page that is open.
|
||||
*
|
||||
* Nothing changes on the page until it is applied: picking a theme and
|
||||
* trying colours is a draft, so the panel can be played with freely, and an
|
||||
* apply is one undo step however many pages it recoloured.
|
||||
*/
|
||||
|
||||
/** One built-in theme as a card: its paper, its display face in its ink, its three accents. */
|
||||
function ThemeCard({
|
||||
preset,
|
||||
on,
|
||||
inUse,
|
||||
onPick,
|
||||
t,
|
||||
}: {
|
||||
preset: BookThemePreset;
|
||||
on: boolean;
|
||||
inUse: boolean;
|
||||
onPick: () => void;
|
||||
t: StudioT;
|
||||
}) {
|
||||
const display = useMemo(() => bookThemeOf(preset.id).fonts.display, [preset.id]);
|
||||
const { palette } = preset;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`st-theme-card ${on ? 'is-on' : ''}`}
|
||||
aria-pressed={on}
|
||||
onClick={onPick}
|
||||
title={t(preset.descrKey)}
|
||||
>
|
||||
<span className="st-theme-sheet" style={{ background: palette.paper }}>
|
||||
<span
|
||||
className="st-theme-word"
|
||||
style={{
|
||||
fontFamily: fontStack(display.font),
|
||||
color: palette.ink,
|
||||
fontStyle: display.italic ? 'italic' : undefined,
|
||||
}}
|
||||
>
|
||||
Aa
|
||||
</span>
|
||||
<span className="st-theme-dots" aria-hidden>
|
||||
{[palette.accent, palette.accent2, palette.accent3].map((c, i) => (
|
||||
<span key={i} style={{ background: c }} />
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
<span className="st-theme-name">
|
||||
<span>{t(preset.labelKey)}</span>
|
||||
{inUse && (
|
||||
<span className="st-theme-inuse" title={t('studio.theme.inUse')} aria-label={t('studio.theme.inUse')}>
|
||||
<Check size={12} strokeWidth={2.6} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** One palette entry: its colour, which is the picker, and its name. */
|
||||
function PaletteEntry({
|
||||
name,
|
||||
hex,
|
||||
onPick,
|
||||
t,
|
||||
}: {
|
||||
name: BookPaletteKey;
|
||||
hex: string;
|
||||
onPick: (hex: string) => void;
|
||||
t: StudioT;
|
||||
}) {
|
||||
const label = t(`studio.theme.token.${name}`);
|
||||
return (
|
||||
<label className="st-theme-colour">
|
||||
<span className="st-theme-chip" style={{ background: hex }}>
|
||||
<input type="color" value={hex} aria-label={label} onChange={(e) => onPick(e.target.value)} />
|
||||
</span>
|
||||
<span className="st-theme-colour-name">{label}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
/** The script a theme falls back to when one is switched on: the handwriting most themes pair with. */
|
||||
const DEFAULT_SCRIPT = 'caveat';
|
||||
|
||||
/**
|
||||
* One typeface slot, in the Studio's own font picker. The script can be
|
||||
* switched off, since a calm theme sets no handwriting at all.
|
||||
*/
|
||||
function FontSlot({
|
||||
slot,
|
||||
face,
|
||||
onPick,
|
||||
t,
|
||||
}: {
|
||||
slot: BookFontSlot;
|
||||
face: BookThemeFont | null;
|
||||
onPick: (font: string | null, weight?: number) => void;
|
||||
t: StudioT;
|
||||
}) {
|
||||
const label = t(`studio.theme.slot.${slot}`);
|
||||
const picker = face && (
|
||||
<StudioFontPicker font={face.font} weight={face.weight ?? 400} onPick={(p) => onPick(p.font, p.weight)} t={t} />
|
||||
);
|
||||
if (slot !== 'script')
|
||||
return (
|
||||
<Line label={label} wide>
|
||||
{picker}
|
||||
</Line>
|
||||
);
|
||||
return (
|
||||
<div className="st-theme-script">
|
||||
<Switch label={label} on={!!face} onToggle={() => onPick(face ? null : DEFAULT_SCRIPT)} />
|
||||
{picker ?? <p className="st-hint">{t('studio.theme.noScript')}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StudioThemePanel({ t }: { t: StudioT }) {
|
||||
const theme = useStudioTheme();
|
||||
const toast = useToast();
|
||||
const { draft } = theme;
|
||||
|
||||
const apply = (scope: 'book' | 'page') => {
|
||||
const done = theme.apply(scope);
|
||||
if (!done) return;
|
||||
if (done.pages > 0) toast.success(t('studio.theme.applied'));
|
||||
else toast.info(t('studio.theme.nothing'));
|
||||
};
|
||||
|
||||
const fromPhotos = async () => {
|
||||
if (!(await theme.fromPhotos())) toast.info(t('studio.theme.noPhotoColours'));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PanelHead label={t('studio.theme.panel')} />
|
||||
<div className="st-panel-scroll st-theme">
|
||||
<p className="st-hint">{t('studio.theme.intro')}</p>
|
||||
|
||||
<div className="st-section-label">{t('studio.theme.themes')}</div>
|
||||
<div className="st-theme-grid">
|
||||
{BOOK_THEME_PRESETS.map((preset) => (
|
||||
<ThemeCard
|
||||
key={preset.id}
|
||||
preset={preset}
|
||||
on={draft.id === preset.id}
|
||||
inUse={theme.current?.id === preset.id}
|
||||
onPick={() => theme.pick(preset.id)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{theme.edited && (
|
||||
<button type="button" className="st-theme-reset" onClick={theme.reset}>
|
||||
<RotateCcw size={13} />
|
||||
{t('studio.theme.reset')}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<Section label={t('studio.theme.palette')}>
|
||||
<div className="st-theme-palette">
|
||||
{BOOK_PALETTE_KEYS.map((key) => (
|
||||
<PaletteEntry
|
||||
key={key}
|
||||
name={key}
|
||||
hex={draft.palette[key]}
|
||||
onPick={(hex) => theme.setColour(key, hex)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="st-theme-photos"
|
||||
onClick={() => void fromPhotos()}
|
||||
disabled={!theme.hasPhotos || theme.reading}
|
||||
>
|
||||
<ImageIcon size={14} />
|
||||
{t('studio.theme.fromPhotos')}
|
||||
</button>
|
||||
</Section>
|
||||
|
||||
<Section label={t('studio.theme.fonts')}>
|
||||
{BOOK_FONT_SLOTS.map((slot) => (
|
||||
<FontSlot
|
||||
key={slot}
|
||||
slot={slot}
|
||||
face={draft.fonts[slot]}
|
||||
onPick={(font, weight) => theme.setFont(slot, font, weight)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section label={t('studio.theme.motifs')} hint={t('studio.theme.motifsHint')} defaultOpen={false}>
|
||||
<Picks
|
||||
value={draft.motifs}
|
||||
options={BOOK_THEME_MOTIFS.map((m) => ({ value: m, label: t(`studio.theme.motif.${m}`) }))}
|
||||
onToggle={theme.toggleMotif}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
<Section label={t('studio.theme.decoration')} defaultOpen={false}>
|
||||
<Choice
|
||||
value={draft.decoration}
|
||||
options={BOOK_THEME_DECORATIONS.map((d) => ({ value: d, label: t(`studio.theme.decoration.${d}`) }))}
|
||||
onPick={theme.setDecoration}
|
||||
ariaLabel={t('studio.theme.decoration')}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
<div className="st-theme-apply">
|
||||
<Switch label={t('studio.theme.adopt')} on={theme.adopt} onToggle={() => theme.setAdopt(!theme.adopt)} />
|
||||
<p className="st-hint">{t('studio.theme.adoptHint')}</p>
|
||||
<button
|
||||
type="button"
|
||||
className="st-theme-btn is-primary"
|
||||
onClick={() => apply('book')}
|
||||
disabled={!theme.canApply}
|
||||
>
|
||||
{t('studio.theme.applyBook')}
|
||||
</button>
|
||||
<button type="button" className="st-theme-btn" onClick={() => apply('page')} disabled={!theme.canApply}>
|
||||
{t('studio.theme.applyPage')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { BookDocument, PaletteSwatch } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The colours of the book's photographs, for "palette from photos".
|
||||
*
|
||||
* Read in the browser from the thumbnails the Studio already shows: each one
|
||||
* is drawn 24 pixels across onto a canvas that never reaches the page, its
|
||||
* pixels are put into coarse buckets, and the fullest buckets are the photo's
|
||||
* swatches. The shared engine clusters them across photos and picks the
|
||||
* accents (bookPaletteFromPhotos), so the choice itself is the same one the
|
||||
* assistant's design makes from a photo palette.
|
||||
*/
|
||||
|
||||
/** The side of the sample drawn from each photo. */
|
||||
const SAMPLE = 24;
|
||||
/** How many photos are read at most: enough for a book's character, few enough to be instant. */
|
||||
const MAX_THEME_PHOTOS = 12;
|
||||
/** How many swatches one photo gives. */
|
||||
const PER_PHOTO = 6;
|
||||
|
||||
const toHex = (r: number, g: number, b: number) =>
|
||||
`#${[r, g, b]
|
||||
.map((v) =>
|
||||
Math.max(0, Math.min(255, Math.round(v)))
|
||||
.toString(16)
|
||||
.padStart(2, '0')
|
||||
)
|
||||
.join('')}`;
|
||||
|
||||
/**
|
||||
* The swatches of an RGBA buffer: the pixels grouped by their top four bits a
|
||||
* channel, each group's mean colour and its share of the opaque pixels.
|
||||
*/
|
||||
export function swatchesFromPixels(data: ArrayLike<number>): PaletteSwatch[] {
|
||||
const buckets = new Map<number, { r: number; g: number; b: number; n: number }>();
|
||||
let total = 0;
|
||||
for (let i = 0; i + 3 < data.length; i += 4) {
|
||||
if ((data[i + 3] ?? 0) < 128) continue;
|
||||
const r = data[i] ?? 0;
|
||||
const g = data[i + 1] ?? 0;
|
||||
const b = data[i + 2] ?? 0;
|
||||
const key = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4);
|
||||
const bucket = buckets.get(key) ?? { r: 0, g: 0, b: 0, n: 0 };
|
||||
bucket.r += r;
|
||||
bucket.g += g;
|
||||
bucket.b += b;
|
||||
bucket.n += 1;
|
||||
buckets.set(key, bucket);
|
||||
total += 1;
|
||||
}
|
||||
if (!total) return [];
|
||||
return [...buckets.values()]
|
||||
.sort((a, b) => b.n - a.n)
|
||||
.slice(0, PER_PHOTO)
|
||||
.map((c) => ({ hex: toHex(c.r / c.n, c.g / c.n, c.b / c.n), share: c.n / total }));
|
||||
}
|
||||
|
||||
/** The photo ids a book shows, placed first, each once, at most MAX_THEME_PHOTOS. */
|
||||
export function bookPhotoIds(doc: BookDocument | null): number[] {
|
||||
const ids = (doc?.spreads ?? []).flatMap((s) =>
|
||||
s.elements.flatMap((e) => (e.kind === 'photo' && e.photoId != null ? [e.photoId] : []))
|
||||
);
|
||||
return [...new Set(ids)].slice(0, MAX_THEME_PHOTOS);
|
||||
}
|
||||
|
||||
/** One photo's swatches, or none when it cannot be read (gone, refused, still loading when aborted). */
|
||||
export async function readPhotoSwatches(src: string, signal?: AbortSignal): Promise<PaletteSwatch[]> {
|
||||
try {
|
||||
const img = new Image();
|
||||
img.decoding = 'async';
|
||||
img.src = src;
|
||||
await img.decode();
|
||||
if (signal?.aborted) return [];
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = SAMPLE;
|
||||
canvas.height = SAMPLE;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) return [];
|
||||
ctx.drawImage(img, 0, 0, SAMPLE, SAMPLE);
|
||||
return swatchesFromPixels(ctx.getImageData(0, 0, SAMPLE, SAMPLE).data);
|
||||
} catch {
|
||||
// A photo that will not load or will not be read gives no colours; the others still do.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import {
|
||||
BOOK_THEME_IDS,
|
||||
bookPaletteFromPhotos,
|
||||
bookThemeOf,
|
||||
setBookTheme,
|
||||
type BookFontSlot,
|
||||
type BookPaletteKey,
|
||||
type BookTheme,
|
||||
type BookThemeDecoration,
|
||||
type BookThemeId,
|
||||
type BookThemeMotif,
|
||||
type SetBookThemeRequest,
|
||||
} from '@trek/shared';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useStudioStore } from '../../../store/studioStore';
|
||||
import { photoSrc } from '../bookRender';
|
||||
import { bookPhotoIds, readPhotoSwatches } from './themePhotoColours';
|
||||
|
||||
/**
|
||||
* The Theme panel's state: the theme being put together (a draft, so trying
|
||||
* colours costs nothing until it is applied), and applying it through the
|
||||
* same `setBookTheme` the assistant's `set_book_theme` runs, so the panel and
|
||||
* the assistant cannot recolour a book two different ways.
|
||||
*/
|
||||
|
||||
/** What an apply did: how many pages changed, or null when the book refused it (read-only, no book). */
|
||||
type ThemeApplyResult = { pages: number } | null;
|
||||
|
||||
/** The theme a book without one starts the panel on: the first of the list. */
|
||||
const firstTheme = (): BookTheme => bookThemeOf(BOOK_THEME_IDS[0]);
|
||||
|
||||
/** The draft as `set_book_theme` takes it: the whole of it, so the result is exactly what the panel shows. */
|
||||
export function themeRequest(draft: BookTheme, spreadIds: string[] | undefined, adopt: boolean): SetBookThemeRequest {
|
||||
return {
|
||||
...(draft.id ? { theme: draft.id } : {}),
|
||||
palette: { ...draft.palette },
|
||||
fonts: { ...draft.fonts },
|
||||
motifs: [...draft.motifs],
|
||||
decoration: draft.decoration,
|
||||
...(spreadIds ? { spreadIds } : {}),
|
||||
adopt,
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a draft differs from the built-in theme it is named after. */
|
||||
export function isEdited(draft: BookTheme): boolean {
|
||||
if (!draft.id) return false;
|
||||
return JSON.stringify(draft) !== JSON.stringify(bookThemeOf(draft.id));
|
||||
}
|
||||
|
||||
export function useStudioTheme() {
|
||||
const doc = useStudioStore((s) => s.doc);
|
||||
const active = useStudioStore((s) => s.activeSpread);
|
||||
const readOnly = useStudioStore((s) => s.readOnly);
|
||||
const commit = useStudioStore((s) => s.commit);
|
||||
const current = doc?.theme;
|
||||
|
||||
const [draft, setDraft] = useState<BookTheme>(() => current ?? firstTheme());
|
||||
const [adopt, setAdopt] = useState(true);
|
||||
const [reading, setReading] = useState(false);
|
||||
|
||||
// The book's theme changed under the panel (applied, undone, another editor): the draft follows it,
|
||||
// set while rendering rather than in an effect, so the panel never paints the old draft first.
|
||||
const [seen, setSeen] = useState(current);
|
||||
if (seen !== current) {
|
||||
setSeen(current);
|
||||
if (current) setDraft(current);
|
||||
}
|
||||
|
||||
const pick = useCallback((id: BookThemeId) => setDraft(bookThemeOf(id)), []);
|
||||
const setColour = useCallback(
|
||||
(key: BookPaletteKey, hex: string) => setDraft((d) => ({ ...d, palette: { ...d.palette, [key]: hex } })),
|
||||
[]
|
||||
);
|
||||
const setFont = useCallback(
|
||||
(slot: BookFontSlot, font: string | null, weight?: number) =>
|
||||
setDraft((d) => {
|
||||
if (font === null) return slot === 'script' ? { ...d, fonts: { ...d.fonts, script: null } } : d;
|
||||
// A family picked by hand is set upright, at the weight the picker snapped to that family.
|
||||
return { ...d, fonts: { ...d.fonts, [slot]: weight === undefined ? { font } : { font, weight } } };
|
||||
}),
|
||||
[]
|
||||
);
|
||||
const toggleMotif = useCallback(
|
||||
(motif: BookThemeMotif) =>
|
||||
setDraft((d) => ({
|
||||
...d,
|
||||
motifs: d.motifs.includes(motif) ? d.motifs.filter((m) => m !== motif) : [...d.motifs, motif],
|
||||
})),
|
||||
[]
|
||||
);
|
||||
const setDecoration = useCallback((decoration: BookThemeDecoration) => setDraft((d) => ({ ...d, decoration })), []);
|
||||
const reset = useCallback(() => setDraft((d) => (d.id ? bookThemeOf(d.id) : d)), []);
|
||||
|
||||
const photoIds = useMemo(() => bookPhotoIds(doc), [doc]);
|
||||
|
||||
/** Accents from the book's photos. Resolves false when the photos give no colour to take. */
|
||||
const fromPhotos = useCallback(async (): Promise<boolean> => {
|
||||
setReading(true);
|
||||
try {
|
||||
const swatches = await Promise.all(photoIds.map((id) => readPhotoSwatches(photoSrc(id, false))));
|
||||
const palette = bookPaletteFromPhotos(draft.palette, swatches);
|
||||
if (palette) setDraft((d) => ({ ...d, palette }));
|
||||
return palette !== null;
|
||||
} finally {
|
||||
setReading(false);
|
||||
}
|
||||
}, [photoIds, draft.palette]);
|
||||
|
||||
const apply = useCallback(
|
||||
(scope: 'book' | 'page'): ThemeApplyResult => {
|
||||
const spread = doc?.spreads[active];
|
||||
if (!doc || readOnly || (scope === 'page' && !spread)) return null;
|
||||
let result: ThemeApplyResult = null;
|
||||
commit((d) => {
|
||||
const made = setBookTheme(d, themeRequest(draft, scope === 'page' && spread ? [spread.id] : undefined, adopt));
|
||||
if (!made.ok) return d;
|
||||
result = { pages: made.spreadIds.length };
|
||||
return made.doc;
|
||||
});
|
||||
return result;
|
||||
},
|
||||
[doc, active, readOnly, commit, draft, adopt]
|
||||
);
|
||||
|
||||
return {
|
||||
draft,
|
||||
current,
|
||||
edited: isEdited(draft),
|
||||
adopt,
|
||||
setAdopt,
|
||||
reading,
|
||||
hasPhotos: photoIds.length > 0,
|
||||
canApply: !!doc && !readOnly,
|
||||
pick,
|
||||
setColour,
|
||||
setFont,
|
||||
toggleMotif,
|
||||
setDecoration,
|
||||
reset,
|
||||
fromPhotos,
|
||||
apply,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user