feat(studio): the Templates panel offers the decorated templates with a style filter

The Templates section of the rail now opens on the decorated templates of
the page's kind, covers two to a row and spreads at full width, each card
the page renderer drawing the page the click will lay: this page's photos
and words in it, in the book theme, a cover in the journey's title and
subtitle as the assistant's layout sets it. A row of style chips narrows
the set to one archetype. A click is one undo step on the page as it is
then, refused for the other kind of page, and opens the photos when frames
are left empty. The book's own layouts and the built-in wireframes follow
below, and the help guide and the wiki describe the panel as it now is.

The panel moved out of StudioSidebar into its own file; the sidebar keeps the
rail, and its two physical sides went with the code, so the rtl baseline
entry goes too. The Travel panel and a template's map build the journey
they draw with one helper.
This commit is contained in:
Maurice
2026-10-23 23:00:24 +00:00
parent 49f7a447d3
commit ff749611c6
38 changed files with 729 additions and 151 deletions
+14 -107
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import {
Camera, ChevronDown, ImagePlus, ChevronUp, Compass, Copy, FileDown, Files, ImageIcon, Layers, LayoutTemplate,
Palette, Plus, Search, Shapes, Sticker, Trash2, Upload, X,
@@ -11,10 +11,7 @@ import { useToast } from '../shared/Toast'
import { SpreadThumb } from './SpreadThumb'
import { folioLabel, foliosOf } from './bookSheets'
import { photoSrc } from './bookRender'
import {
BOOK_COVER_TEMPLATES as COVER_TEMPLATES, BOOK_TEMPLATES as TEMPLATES, applyBookTemplate as applyTemplate,
bookElementId as uid,
} from '@trek/shared'
import { bookElementId as uid } from '@trek/shared'
import {
bookCoordValue as coordValue, formatBookCoords, formatBookDate, type BookCoordFormat as CoordFormat,
} from '@trek/shared'
@@ -25,7 +22,7 @@ import { StudioStickersPanel } from './StudioStickersPanel'
import { StudioLayersPanel } from './StudioLayersPanel'
import { StudioTravelPanel } from './StudioTravelPanel'
import { StudioThemePanel } from './theme/StudioThemePanel'
import { StudioSavedLayouts } from './StudioSavedLayouts'
import { StudioTemplatesPanel } from './templates/StudioTemplatesPanel'
import { MAX_SPREAD_FILE_BYTES, importSpread } from './spreadFile'
import { StudioContentFilter } from './StudioContentFilter'
import { emptyKeyFor, matchingEntries, matchingPhotos, photosFor, type PhotoFilter } from './photoFilter'
@@ -45,6 +42,13 @@ import type { StudioUploader } from './studioUpload'
type Section = 'pages' | 'content' | 'elements' | 'stickers' | 'travel' | 'templates' | 'layers' | 'theme'
export interface JourneySource {
/**
* The journey's title and subtitle, which a cover is set in when the book has
* no title of its own. The Studio always gives them; a source built only for
* the content browser may leave them out.
*/
title?: string
subtitle?: string | null
entries: {
id: number
title: string | null
@@ -166,7 +170,10 @@ export function StudioSidebar({
)}
{section === 'layers' && <StudioLayersPanel t={t} />}
{section === 'theme' && <StudioThemePanel t={t} />}
{section === 'templates' && <TemplatesPanel page={page} pxPerMm={pxPerMm} t={t} onOpenContent={() => setSection('content')} />}
{section === 'templates' && (
<StudioTemplatesPanel page={page} pxPerMm={pxPerMm} t={t} locale={locale} source={source} stats={stats}
path={path} onOpenContent={() => setSection('content')} />
)}
</aside>
</>
)
@@ -776,103 +783,3 @@ function ContentPanel({
</>
)
}
/**
* Layouts for the current spread.
*
* Each card draws the arrangement itself rather than naming it — "hero + story"
* means nothing until you have seen it, and a diagram is faster to read than a
* label anyway.
*/
function TemplatesPanel({
page, pxPerMm, t, onOpenContent,
}: { page: BookPageSetup; pxPerMm: number; t: (k: string) => string; onOpenContent: () => void }) {
const doc = useStudioStore(s => s.doc)
const active = useStudioStore(s => s.activeSpread)
const commit = useStudioStore(s => s.commit)
const spread = doc?.spreads[active]
const list = useElementSize<HTMLDivElement>()
const CARD_W = Math.max(MIN_PREVIEW_W, list.width - THUMB_CHROME)
const doc2 = doc
const cardIsSingle = (doc2?.spreads[active]?.role ?? 'inner') !== 'inner'
// A cover card is one page wide, not two — scaling it as a spread would draw
// the layout at half size in the left half of the card.
const scale = useMemo(
() => CARD_W / (page.pageWidth * (cardIsSingle ? 1 : 2) * pxPerMm),
[CARD_W, page.pageWidth, pxPerMm, cardIsSingle],
)
if (!spread) return null
const single = spread.role !== 'inner'
/*
* The cover has its own set. It used to have none — the panel said covers
* are designed by hand, which was true and unhelpful: the cover is the page
* people care most about and the one they had no starting point for.
*/
const templates = single ? COVER_TEMPLATES : TEMPLATES
return (
<>
<Head label={t('journey.studio.templates')} count={templates.length} />
<div className="st-panel-scroll">
<StudioSavedLayouts page={page} width={CARD_W} pxPerMm={pxPerMm} t={t} />
{(
<div className="st-thumbs" ref={list.ref}>
{templates.map(tpl => {
const slots = tpl.build(page)
return (
<button
type="button"
key={tpl.id}
className="st-thumb"
onClick={() => {
let empties = 0
commit(d => ({
...d,
spreads: d.spreads.map((sp, i) => {
if (i !== active) return sp
const next = applyTemplate(sp, tpl, page)
empties = next.elements.filter(e => e.kind === 'photo' && e.photoId == null).length
return next
}),
}))
// The layout left frames waiting for a picture — so put the
// pictures within reach instead of making the user go and
// find the panel that holds them.
if (empties > 0) onOpenContent()
}}
>
<div
className="st-thumb-sheet"
style={{ width: CARD_W, height: page.pageHeight * pxPerMm * scale }}
>
{slots.map((slot, i) => (
<span
key={i}
className={`st-tpl-slot is-${slot.kind}`}
style={{
left: slot.frame.x * pxPerMm * scale,
top: slot.frame.y * pxPerMm * scale,
width: slot.frame.w * pxPerMm * scale,
height: Math.max(2, slot.frame.h * pxPerMm * scale),
}}
/>
))}
{!single && (
<span
className="st-tpl-fold"
style={{ left: page.pageWidth * pxPerMm * scale }}
/>
)}
</div>
<span className="st-thumb-label">{t(tpl.labelKey)}</span>
</button>
)
})}
</div>
)}
</div>
</>
)
}
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { Check, RouteOff } from 'lucide-react'
import type {
BookBadgeVariant, BookElement, BookMapScope, BookMetric, BookPageSetup, BookTravelContext, JourneyStats,
BookBadgeVariant, BookElement, BookMapScope, BookMetric, BookPageSetup, JourneyStats,
} from '@trek/shared'
import {
BOOK_METRICS, bookBadgeValue, bookCountryMark, bookCountryName, bookElementId as uid, bookTravelBadge,
@@ -9,6 +9,7 @@ import {
} from '@trek/shared'
import { useStudioStore } from '../../store/studioStore'
import { PanelHead } from './StudioPanelHead'
import { studioTravelContext } from './studioTravelContext'
import { Section } from './StudioControls'
import { TravelPreview } from './TravelPreview'
import { fetchRoads } from './roadRoute'
@@ -167,21 +168,11 @@ export function StudioTravelPanel({
}
/*
* What the book engine's factories read: the journey, its recorded way and
* the words in the reader's language. Every tile below is built by the
* factory the engine's `add` calls. Where it lands is the panel's own:
* centred across the spread, where `add` takes the right page. The day word
* is the engine's too, handed over as its template: `t` leaves the `{day}`
* in it untouched, and `bookDayText` puts the number there.
* What the book engine's factories read (studioTravelContext.ts). Every tile
* below is built by the factory the engine's `add` calls. Where it lands is
* the panel's own: centred across the spread, where `add` takes the right page.
*/
const travel: BookTravelContext = {
locale, stats, path, entries: [],
labels: {
day: t('journey.studio.day'), stations: t('journey.studio.stations'), summary: t('journey.studio.summary'),
countries: t('journey.studio.countries'), distance: t('journey.studio.metric.distance'),
pros: t('journey.editor.pros'), cons: t('journey.editor.cons'),
},
}
const travel = studioTravelContext(stats, path, locale, t)
const at = (size: { w: number; h: number }) => centre(size.w, size.h)
/**
@@ -0,0 +1,33 @@
import type { BookTravelContext, JourneyStats } from '@trek/shared';
/**
* What the book engine's travel factories read, as the Studio knows it: the
* journey's figures, its recorded way and the words in the reader's
* language. The Travel panel builds its tiles with it, and the Templates
* panel lays a template's map with it, so both draw the same journey.
*
* The day word is the engine's template: `t` leaves the `{day}` in it
* untouched, and `bookDayText` puts the number there.
*/
export function studioTravelContext(
stats: JourneyStats,
path: [number, number][][],
locale: string,
t: (k: string) => string
): BookTravelContext {
return {
locale,
stats,
path,
entries: [],
labels: {
day: t('journey.studio.day'),
stations: t('journey.studio.stations'),
summary: t('journey.studio.summary'),
countries: t('journey.studio.countries'),
distance: t('journey.studio.metric.distance'),
pros: t('journey.editor.pros'),
cons: t('journey.editor.cons'),
},
};
}
@@ -0,0 +1,148 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BookDocument } from '@trek/shared';
import { bookPageSetupSchema, decoratedTemplatesFor, normalizeBookDocument } from '@trek/shared';
import { act, fireEvent, render, screen } from '../../../../tests/helpers/render';
import { useStudioStore } from '../../../store/studioStore';
import { StudioTemplatesPanel } from './StudioTemplatesPanel';
/**
* The Templates panel: the decorated templates of the open page's kind, each
* a button named after its template and drawn as the page it lays, a style
* filter, and a click that lays the page out in one undo step.
*/
const t = (k: string) => k;
const page = bookPageSetupSchema.parse({});
const source = {
title: 'Azores',
subtitle: 'Nine islands in the Atlantic',
entries: [{ id: 4, title: 'Sintra', story: 'Up through the fog.', location: 'Serra de Sintra', date: '2026-05-14' }],
};
const book = (title = 'Portugal'): BookDocument =>
normalizeBookDocument({
version: 1,
title,
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 },
spreads: [
{
id: 'sp-cover',
role: 'cover',
background: null,
entryId: null,
parked: [],
elements: [{ id: 'ph', kind: 'photo', frame: { x: 0, y: 0, w: 50, h: 50 }, photoId: 7 }],
},
{ id: 'sp-in', role: 'inner', background: null, entryId: 4, parked: [], elements: [] },
],
});
/* jsdom lays nothing out; the cards measure their row to scale the page drawing into it. */
const size = Object.getOwnPropertyDescriptors(HTMLElement.prototype);
beforeAll(() => {
Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { configurable: true, get: () => 220 });
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, get: () => 600 });
});
afterAll(() => {
for (const key of ['offsetWidth', 'offsetHeight'] as const) {
const was = size[key];
if (was) Object.defineProperty(HTMLElement.prototype, key, was);
}
});
beforeEach(() => {
useStudioStore.getState().load(book());
useStudioStore.setState({ readOnly: false });
});
const panel = (onOpenContent = vi.fn()) =>
render(
<StudioTemplatesPanel
page={page}
pxPerMm={96 / 25.4}
t={t}
locale="en"
source={source}
stats={null}
path={[]}
onOpenContent={onOpenContent}
/>
);
const spreadOf = (i: number) => useStudioStore.getState().doc?.spreads[i];
describe('the Templates panel', () => {
it('offers the cover templates on the cover, each a named button drawn with the page photo and the book title', () => {
panel();
for (const tpl of decoratedTemplatesFor('single')) {
expect(screen.getByRole('button', { name: tpl.labelKey })).toBeTruthy();
}
expect(screen.queryByRole('button', { name: 'studio.templates.name.polaroidStack' })).toBeNull();
const card = screen.getByRole('button', { name: 'studio.templates.name.minimalSerifClassic' });
expect(card.textContent).toContain('Portugal');
expect(card.querySelector('img')?.getAttribute('src')).toContain('/api/photos/7/');
expect(screen.getByText('studio.templates.decorated')).toBeTruthy();
expect(screen.getByText('journey.studio.builtInLayouts')).toBeTruthy();
});
it('narrows the set to one archetype from the style chips', () => {
panel();
const chips = screen.getByRole('radiogroup', { name: 'studio.templates.style' });
expect(chips.querySelectorAll('[role="radio"]')).toHaveLength(8);
fireEvent.click(screen.getByRole('radio', { name: 'studio.templates.archetype.postcard' }));
expect(
screen.getByRole('radio', { name: 'studio.templates.archetype.postcard' }).getAttribute('aria-checked')
).toBe('true');
const names = decoratedTemplatesFor('single', 'postcard').map((tpl) => tpl.labelKey);
for (const name of names) expect(screen.getByRole('button', { name })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'studio.templates.name.gridBadgeCircle' })).toBeNull();
});
it('lays the page out on a click, as one undo step, keeping its photo', () => {
panel();
fireEvent.click(screen.getByRole('button', { name: 'studio.templates.name.postcardHouses' }));
const cover = spreadOf(0);
expect(cover?.elements.some((e) => e.kind === 'sticker' && e.stickerId === 'rowHouses')).toBe(true);
expect(cover?.elements.find((e) => e.kind === 'photo')).toMatchObject({ photoId: 7 });
expect(cover?.elements.some((e) => e.kind === 'text' && e.text === 'Portugal')).toBe(true);
expect(useStudioStore.getState().past).toHaveLength(1);
useStudioStore.getState().undo();
expect(spreadOf(0)?.elements.map((e) => e.id)).toEqual(['ph']);
});
it("sets a cover in the journey's subtitle, bound to it, and in the journey's title when the book has none", () => {
panel();
fireEvent.click(screen.getByRole('button', { name: 'studio.templates.name.minimalSerifClassic' }));
const texts = (spreadOf(0)?.elements ?? []).flatMap((e) => (e.kind === 'text' ? [e] : []));
expect(texts.map((e) => e.text)).toEqual(['Portugal', 'Nine islands in the Atlantic', '2026']);
expect(texts[1]?.binding).toEqual({ source: 'journey.subtitle' });
act(() => useStudioStore.getState().load(book('')));
fireEvent.click(screen.getByRole('button', { name: 'studio.templates.name.minimalSerifClassic' }));
const untitled = (spreadOf(0)?.elements ?? []).flatMap((e) => (e.kind === 'text' ? [e.text] : []));
expect(untitled[0]).toBe('Azores');
});
it('offers the spread templates on a double page, sets it in its entry and opens the photos for empty frames', () => {
useStudioStore.getState().setActiveSpread(1);
const onOpenContent = vi.fn();
panel(onOpenContent);
for (const tpl of decoratedTemplatesFor('inner')) {
expect(screen.getByRole('button', { name: tpl.labelKey })).toBeTruthy();
}
fireEvent.click(screen.getByRole('button', { name: 'studio.templates.name.storyQuote' }));
const inner = spreadOf(1);
const title = inner?.elements.find((e) => e.kind === 'text' && e.text === 'Sintra');
expect(title?.kind === 'text' && title.binding).toEqual({ source: 'entry.title', entryId: 4 });
expect(onOpenContent).toHaveBeenCalledTimes(1);
});
it('lays a built-in layout out from the same panel', () => {
useStudioStore.getState().setActiveSpread(1);
panel();
fireEvent.click(screen.getByText('journey.studio.tpl.grid4'));
expect(spreadOf(1)?.elements.filter((e) => e.kind === 'photo')).toHaveLength(4);
});
});
@@ -0,0 +1,251 @@
import type { BookDecoratedTemplate, BookPageSetup, BookSpread, BookTemplate, JourneyStats } from '@trek/shared';
import {
applyBookTemplate as applyTemplate,
BOOK_COVER_TEMPLATES as COVER_TEMPLATES,
BOOK_TEMPLATES as TEMPLATES,
} from '@trek/shared';
import { memo, useDeferredValue, useMemo, useState } from 'react';
import { useElementSize } from '../../../hooks/useElementSize';
import { useStudioStore } from '../../../store/studioStore';
import '../../../styles/studio-templates.css';
import { SpreadThumb } from '../SpreadThumb';
import { Choice } from '../StudioControls';
import { PanelHead } from '../StudioPanelHead';
import { StudioSavedLayouts } from '../StudioSavedLayouts';
import {
ARCHETYPE_FILTERS,
emptyFrames,
layTemplate,
pageKind,
previewIds,
studioTemplateWords,
templatesForSpread,
templateTravel,
type ArchetypeFilter,
type TemplateContext,
type TemplateSource,
} from './templatesModel';
/**
* The Templates section of the rail: the decorated templates first, then the
* book's own layouts and the built-in wireframes.
*
* A decorated template is a whole designed page, and its card is that page as
* the click will lay it: this page's photos and words poured into it, in the
* book's theme, drawn by the page renderer at a small scale. Covers are drawn
* two to a row so the set can be compared at a glance; a double spread takes
* the full width. A row of style chips narrows the set to one archetype.
*/
/** The smallest a preview is drawn, and the button's border and padding the row's width still includes. */
const MIN_PREVIEW_W = 96;
const THUMB_CHROME = (2 + 3) * 2;
/** The gap between two cover cards in a row, as studio-templates.css sets it. */
const PAIR_GAP = 8;
type Translate = (k: string, params?: Record<string, string | number>) => string;
/** How wide a card draws its page, from the measured row: the full row, or half of it for a cover. */
function previewWidths(row: number, single: boolean): { full: number; card: number } {
const full = Math.max(MIN_PREVIEW_W, row - THUMB_CHROME);
return { full, card: single ? Math.max(MIN_PREVIEW_W / 2, (row - PAIR_GAP) / 2 - THUMB_CHROME) : full };
}
interface DecoratedCardProps {
tpl: BookDecoratedTemplate;
spread: BookSpread;
page: BookPageSetup;
ctx: TemplateContext;
width: number;
pxPerMm: number;
label: string;
onPick: (tpl: BookDecoratedTemplate) => void;
}
/** One decorated template, drawn as the page it makes of the page that is open. */
const DecoratedCard = memo(function DecoratedCard({
tpl,
spread,
page,
ctx,
width,
pxPerMm,
label,
onPick,
}: DecoratedCardProps) {
const preview = useMemo(
() => layTemplate(spread, tpl, page, ctx, previewIds(`tpl-${tpl.id}`)),
[spread, tpl, page, ctx]
);
return (
<button type="button" className="st-thumb st-tpl-card" title={label} aria-label={label} onClick={() => onPick(tpl)}>
<span aria-hidden className="st-tpl-art">
<SpreadThumb
spread={preview}
page={page}
width={width}
pxPerMm={pxPerMm}
fold={tpl.kind === 'inner'}
className="st-thumb-sheet"
/>
</span>
<span className="st-thumb-label st-tpl-label">{label}</span>
</button>
);
});
/** The built-in layouts, drawn as the frames they lay out: the wireframes Studio has always had. */
function BuiltInLayouts({
spread,
page,
pxPerMm,
width,
t,
onPick,
}: {
spread: BookSpread;
page: BookPageSetup;
pxPerMm: number;
width: number;
t: Translate;
onPick: (tpl: BookTemplate) => void;
}) {
const single = spread.role !== 'inner';
// A cover card is one page wide, not two: scaled as a spread it would draw at half size.
const scale = width / (page.pageWidth * (single ? 1 : 2) * pxPerMm);
const templates = single ? COVER_TEMPLATES : TEMPLATES;
return (
<div className="st-thumbs">
{templates.map((tpl) => (
<button type="button" key={tpl.id} className="st-thumb" onClick={() => onPick(tpl)}>
{/* A page is laid out from its top left in either reading direction. */}
<div dir="ltr" className="st-thumb-sheet" style={{ width, height: page.pageHeight * pxPerMm * scale }}>
{tpl.build(page).map((slot, i) => (
<span
key={i}
className={`st-tpl-slot is-${slot.kind}`}
style={{
insetInlineStart: slot.frame.x * pxPerMm * scale,
top: slot.frame.y * pxPerMm * scale,
width: slot.frame.w * pxPerMm * scale,
height: Math.max(2, slot.frame.h * pxPerMm * scale),
}}
/>
))}
{!single && <span className="st-tpl-fold" style={{ insetInlineStart: page.pageWidth * pxPerMm * scale }} />}
</div>
<span className="st-thumb-label">{t(tpl.labelKey)}</span>
</button>
))}
</div>
);
}
export function StudioTemplatesPanel({
page,
pxPerMm,
t,
locale,
source,
stats,
path,
onOpenContent,
}: {
page: BookPageSetup;
pxPerMm: number;
t: Translate;
locale: string;
source: TemplateSource;
stats: JourneyStats | null;
path: [number, number][][];
/** Opens the panel of the journey's photos, for frames a layout left empty. */
onOpenContent: () => void;
}) {
const doc = useStudioStore((s) => s.doc);
const active = useStudioStore((s) => s.activeSpread);
const commit = useStudioStore((s) => s.commit);
const select = useStudioStore((s) => s.select);
const [filter, setFilter] = useState<ArchetypeFilter>('all');
const list = useElementSize<HTMLDivElement>();
// The cards redraw from the page as it is; deferred, so typing on the page never waits on them.
const spread = useDeferredValue(doc?.spreads[active]);
const theme = doc?.theme;
const title = doc?.title ?? '';
const ctx = useMemo<TemplateContext | null>(() => {
if (!spread) return null;
const words = studioTemplateWords(title, spread, source, locale);
return { theme, words, travel: templateTravel(stats, path, locale, t), locale };
}, [spread, theme, title, source, stats, path, locale, t]);
if (!doc || !spread || !ctx) return null;
const single = spread.role !== 'inner';
const templates = templatesForSpread(spread, filter);
const { full, card: cardWidth } = previewWidths(list.width, single);
/**
* One undo step: the page laid out, nothing selected, and the photos at hand
* when frames are left empty. It works on the page as it is now, not as the
* deferred cards last drew it: a click right after moving to another page
* lays nothing when the layout is for the other kind of page.
*/
const lay = (make: (sp: BookSpread) => BookSpread | null) => {
const done: { page: BookSpread | null } = { page: null };
commit((d) => {
const now = d.spreads[active];
const next = now ? make(now) : null;
done.page = next;
return next ? { ...d, spreads: d.spreads.map((sp, i) => (i === active ? next : sp)) } : d;
});
if (!done.page) return;
select([]);
if (emptyFrames(done.page) > 0) onOpenContent();
};
const pickDecorated = (tpl: BookDecoratedTemplate) =>
lay((sp) =>
pageKind(sp) === tpl.kind
? layTemplate(sp, tpl, page, { ...ctx, words: studioTemplateWords(title, sp, source, locale) })
: null
);
const pickBuiltIn = (tpl: BookTemplate) =>
lay((sp) => (pageKind(sp) === (tpl.role ?? 'inner') ? applyTemplate(sp, tpl, page) : null));
return (
<>
<PanelHead label={t('journey.studio.templates')} count={templates.length} />
<div className="st-panel-scroll">
<div className="st-section st-tpl-section">
<div className="st-section-label">{t('studio.templates.decorated')}</div>
<Choice<ArchetypeFilter>
value={filter}
ariaLabel={t('studio.templates.style')}
onPick={setFilter}
options={ARCHETYPE_FILTERS.map((a) => ({
value: a,
label: a === 'all' ? t('studio.templates.all') : t(`studio.templates.archetype.${a}`),
}))}
/>
<div className={`st-tpl-grid ${single ? 'is-pages' : 'is-spreads'}`} ref={list.ref}>
{templates.map((tpl) => (
<DecoratedCard
key={tpl.id}
tpl={tpl}
spread={spread}
page={page}
ctx={ctx}
width={cardWidth}
pxPerMm={pxPerMm}
label={t(tpl.labelKey)}
onPick={pickDecorated}
/>
))}
</div>
<p className="st-hint">{t('studio.templates.hint')}</p>
</div>
<StudioSavedLayouts page={page} width={full} pxPerMm={pxPerMm} t={t} />
<BuiltInLayouts spread={spread} page={page} pxPerMm={pxPerMm} width={full} t={t} onPick={pickBuiltIn} />
</div>
</>
);
}
@@ -0,0 +1,83 @@
import { describe, expect, it } from 'vitest';
import type { BookSpread } from '@trek/shared';
import { bookSpreadSchema, journeyStatsSchema } from '@trek/shared';
import { pageKind, studioTemplateWords, templateTravel, templatesForSpread } from './templatesModel';
/**
* What the Templates panel lays a page out with: which templates a page
* takes, the words their empty roles take (the same the assistant's layout
* gives), and the journey's figures for a template's map.
*/
const t = (k: string) => `[${k}]`;
const spread = (role: BookSpread['role'], entryId: number | null = null) =>
bookSpreadSchema.parse({ id: `sp-${role}`, role, entryId, elements: [] });
const source = {
title: 'Azores',
subtitle: 'Nine islands in the Atlantic',
entries: [{ id: 4, title: 'Sintra', story: 'Up through the fog.', location: 'Serra de Sintra', date: '2026-05-14' }],
};
describe('the templates a page takes', () => {
it('takes the covers on every single page and the spreads on a double one', () => {
for (const role of ['cover', 'first', 'last', 'back'] as const) expect(pageKind(spread(role))).toBe('single');
expect(pageKind(spread('inner'))).toBe('inner');
expect(templatesForSpread(spread('back'), 'all').every((tpl) => tpl.kind === 'single')).toBe(true);
expect(templatesForSpread(spread('inner'), 'postcard').every((tpl) => tpl.archetype === 'postcard')).toBe(true);
});
});
describe('the words of a template', () => {
it("sets a cover in the book's title, the journey's when the book has none, and the journey's subtitle bound to it", () => {
const own = studioTemplateWords(' Portugal ', spread('cover'), source, 'en');
expect(own.title).toEqual({ text: 'Portugal' });
expect(own.subtitle).toEqual({ text: 'Nine islands in the Atlantic', binding: { source: 'journey.subtitle' } });
expect(own.date).toEqual({ text: '2026' });
expect(studioTemplateWords('', spread('cover'), source, 'en').title).toEqual({ text: 'Azores' });
});
it('leaves a cover without a title when neither the book nor the journey has one, rather than a sample word', () => {
const words = studioTemplateWords('', spread('cover'), { ...source, title: '', subtitle: null }, 'en');
expect(words.title).toBeUndefined();
expect(words.subtitle).toBeUndefined();
});
it('sets a page made from an entry in that entry, bound to it', () => {
const words = studioTemplateWords('Portugal', spread('inner', 4), source, 'en');
expect(words.title).toEqual({ text: 'Sintra', binding: { source: 'entry.title', entryId: 4 } });
expect(words.date?.binding).toEqual({ source: 'entry.date', entryId: 4, value: '2026-05-14' });
expect(studioTemplateWords('Portugal', spread('inner'), source, 'en')).toEqual({});
});
});
describe('the journey of a template map', () => {
it('has none while the figures load, and the travel words of the reader once they are in', () => {
expect(templateTravel(null, [], 'en', t)).toBeNull();
const stats = journeyStatsSchema.parse({
journeyId: 1,
distance: 1200,
days: 3,
steps: 2,
photos: 0,
places: 0,
furthest: 900,
countries: [],
points: [],
start: '2026-05-12',
end: '2026-05-14',
});
const travel = templateTravel(stats, [[[38.7, -9.1]]], 'de', t);
expect(travel).toMatchObject({ locale: 'de', stats, path: [[[38.7, -9.1]]], entries: [] });
expect(travel?.labels).toEqual({
day: '[journey.studio.day]',
stations: '[journey.studio.stations]',
summary: '[journey.studio.summary]',
countries: '[journey.studio.countries]',
distance: '[journey.studio.metric.distance]',
pros: '[journey.editor.pros]',
cons: '[journey.editor.cons]',
});
});
});
@@ -0,0 +1,116 @@
import type {
BookCoverArchetype,
BookDecoratedTemplate,
BookDocument,
BookPageSetup,
BookSpread,
BookTemplateKind,
BookTemplateWords,
BookTravelContext,
JourneyStats,
} from '@trek/shared';
import { BOOK_COVER_ARCHETYPES, applyDecoratedTemplate, bookTemplateWords, decoratedTemplatesFor } from '@trek/shared';
import { studioTravelContext } from '../studioTravelContext';
/**
* What the Templates panel lays out and draws: the decorated templates a page
* can take, the words and the figures they are filled with, and the page one
* template makes. The card and the click run the same function, so a card
* shows the page the click gives, with this page's own photos and words in it.
*/
export type ArchetypeFilter = BookCoverArchetype | 'all';
/** The panel's style filter: every template, or those of one archetype. */
export const ARCHETYPE_FILTERS: readonly ArchetypeFilter[] = ['all', ...BOOK_COVER_ARCHETYPES];
/** Which templates a page takes: a single page (the cover, the first, the last, the back) or a double spread. */
export function pageKind(spread: BookSpread): BookTemplateKind {
return spread.role === 'inner' ? 'inner' : 'single';
}
/** The decorated templates for a page: covers for a single page, spreads for a double one. */
export function templatesForSpread(spread: BookSpread, filter: ArchetypeFilter): BookDecoratedTemplate[] {
return decoratedTemplatesFor(pageKind(spread), filter === 'all' ? null : filter);
}
/** What the Studio knows of the journey that a template takes words and a map from. */
export interface TemplateSource {
/** The journey's title, for a cover of a book without its own, and its subtitle. */
title?: string;
subtitle?: string | null;
entries: readonly {
id: number;
title: string | null;
story: string | null;
location: string | null;
date: string | null;
}[];
}
/** Everything a page is laid out on a template with. */
export interface TemplateContext {
theme: BookDocument['theme'];
words: BookTemplateWords;
travel: BookTravelContext | null;
locale: string;
}
/**
* The words a template's empty roles take, as the assistant's layout gives
* them (template-op.ts in shared): on a single page the book's title, or the
* journey's when the book has none, the journey's subtitle and the year; on
* a page made from a journal entry that entry's title, place, date and story.
*/
export function studioTemplateWords(
bookTitle: string,
spread: BookSpread,
source: TemplateSource,
locale: string
): BookTemplateWords {
return bookTemplateWords(spread, {
bookTitle: bookTitle.trim() || (source.title ?? ''),
subtitle: source.subtitle ?? null,
locale,
entries: source.entries,
});
}
/** The journey's figures and way, for a template's map; null while they are loading or failed. */
export function templateTravel(
stats: JourneyStats | null,
path: [number, number][][],
locale: string,
t: (k: string) => string
): BookTravelContext | null {
return stats ? studioTravelContext(stats, path, locale, t) : null;
}
/** A page laid out on a template: what a card draws and what a click commits. */
export function layTemplate(
spread: BookSpread,
tpl: BookDecoratedTemplate,
page: BookPageSetup,
ctx: TemplateContext,
newId?: (prefix: string) => string
): BookSpread {
return applyDecoratedTemplate(spread, tpl, page, {
theme: ctx.theme ?? null,
words: ctx.words,
travel: ctx.travel,
locale: ctx.locale,
...(newId ? { newId } : {}),
});
}
/** Ids for a card's drawing that stay the same from one render to the next, so its keys do too. */
export function previewIds(prefix: string): (kind: string) => string {
let n = 0;
return (kind) => `${prefix}-${kind}${(n += 1)}`;
}
/** How many frames a laid page is left waiting for a picture in. */
export function emptyFrames(spread: BookSpread): number {
return spread.elements.filter((e) => e.kind === 'photo' && e.photoId == null).length;
}