The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
feat(journey): the shared book engine lays out, edits and designs whole books
Maurice4570ace78c54
diff --git a/client/src/components/Studio/StudioInspector.tsx b/client/src/components/Studio/StudioInspector.tsxindex 7d27d96ad..570ba7b24 100644--- a/client/src/components/Studio/StudioInspector.tsx+++ b/client/src/components/Studio/StudioInspector.tsx@@ -10,7 +10,7 @@ import { FRAME_SHAPES, SHAPE_GROUPS } from './shapes'import { ShapeGlyph } from './StudioElementsPanel'import { TravelInspector } from './StudioTravelInspector'import { Swatches } from './StudioSwatches'-import { formatBookCoords } from './entryText'+import { formatBookCoords } from '@trek/shared'import { iconComponent, iconLabel, searchIcons } from './iconLibrary'import { Choice, Line, NumField, Section, Switch } from './StudioControls'import { FontButtons, WeightLine } from './StudioTypeControls'diff --git a/client/src/components/Studio/StudioTravelInspector.tsx b/client/src/components/Studio/StudioTravelInspector.tsxindex 50908e230..453e897a9 100644--- a/client/src/components/Studio/StudioTravelInspector.tsx+++ b/client/src/components/Studio/StudioTravelInspector.tsx@@ -3,14 +3,12 @@ import type {BookBadgeElement, BookCountriesElement, BookElement, BookListElement, BookMapElement,BookMetric, BookStatsElement, JourneyStats,} from '@trek/shared'-import { BOOK_METRICS } from '@trek/shared'-import { isStale, refreshPatch } from './travelRefresh'+import { BOOK_METRICS, isStale, refreshPatch, routeFor } from '@trek/shared'import { Swatches } from './StudioSwatches'import { FontButtons, WeightLine } from './StudioTypeControls'import { sourceIdOf, useMapSources } from './mapSources'import { printDpi, tileView } from './mapTiles'import { useCartoApiKey } from '../../hooks/useTileUrl'-import { routeFor } from './travelRefresh'import { Choice, Line, Picks, Section, Switch } from './StudioControls'import { fetchRoads } from './roadRoute'diff --git a/client/src/components/Studio/StudioTravelPanel.tsx b/client/src/components/Studio/StudioTravelPanel.tsxindex f9c7ac240..449b6549d 100644--- a/client/src/components/Studio/StudioTravelPanel.tsx+++ b/client/src/components/Studio/StudioTravelPanel.tsx@@ -6,8 +6,7 @@ import { useStudioStore } from '../../store/studioStore'import { PanelHead } from './StudioPanelHead'import { Section } from './StudioControls'import { TravelPreview } from './TravelPreview'-import { formatBookCoords } from './entryText'-import { routeFor } from './travelRefresh'+import { formatBookCoords, routeFor } from '@trek/shared'import { useMapSources } from './mapSources'import { fetchRoads } from './roadRoute'diff --git a/client/src/components/Studio/applyTemplate.ts b/client/src/components/Studio/applyTemplate.tsdeleted file mode 100644index efb1e4f1c..000000000--- a/client/src/components/Studio/applyTemplate.ts+++ /dev/null@@ -1,240 +0,0 @@-import type { BookElement, BookPageSetup, BookSpread, JourneyStats } from '@trek/shared'-import { MAX_TEXT_LENGTH } from '@trek/shared'-import type { SpreadTemplate } from './bookTemplates.data'-import { formatBookCoords, formatBookDate } from './entryText'-import { coordValue } from './resolveBindings'--/**- * Laying an entry out on a template somebody drew.- *- * ── Why this exists ──────────────────────────────────────────────────────- *- * The layouts written as code in autoLayout.ts are what a function can reason- * its way to: a picture here, words there, margins that add up. What they are- * not is *designed* — a panel bled off one edge, a shape running off the- * corner, a strip of pictures at two sizes with the coordinates set under them.- * Those decisions come from looking at a page, and the editor is where looking- * at a page happens.- *- * So the templates are drawn in Studio and read back out (see- * bookTemplates.data.ts). This is the other half: taking one of those spreads- * and putting an entry into it.- *- * ── What it fills, and what it leaves alone ──────────────────────────────- *- * Only what the entry can answer for:- *- * - text carrying a `binding` — the title, the story, a caption- * - empty photo frames, taking the entry's photographs in order- * - the day, coordinate, date and country marks- * - the stats and countries elements, from the journey's figures- *- * Everything else is the design and is copied as drawn. A panel stays where it- * was put; a decorative shape keeps its colour. That division is the whole- * contract between the person who draws a template and the code that uses it.- *- * ── Sizes ────────────────────────────────────────────────────────────────- *- * The template's numbers are fractions of the page it was drawn on, so they are- * multiplied back up here. A template built on a 210mm square lays out on an A4- * landscape book without being redrawn.- */--export interface TemplateEntry {- id: number- title: string | null- story: string | null- location: string | null- date: string | null- photos: { photoId: number; width: number | null; height: number | null; caption?: string | null }[]- lat?: number | null- lng?: number | null- country?: string | null- dayNumber?: number | null- dayCount?: number | null-}--export interface TemplateContext {- page: BookPageSetup- locale: string- stats: JourneyStats | null- /** Already translated, because this module has no translation context. */- dayLabel: string-}--let seq = 0-const uid = (p: string) => `${p}-${(seq++).toString(36)}-${Math.floor(Math.random() * 1e6).toString(36)}`--/** How well a template suits an entry: more is better, -1 means unusable. */-export function templateFit(template: SpreadTemplate, entry: TemplateEntry): number {- const frames = template.elements.filter(e => e.kind === 'photo').length- const photos = entry.photos.length- const wantsStory = template.elements.some(e => e.kind === 'text' && e.binding?.source === 'entry.story')- const hasStory = !!(entry.story || '').trim()-- /*- * A template is a template *for an entry* when it uses one.- *- * The distinction has to come out of the drawing rather than from a label- * somebody remembers to set: a summary spread is all figures and country- * outlines and reads perfectly well on its own, and dropping a day's- * photographs into it would be nonsense. Bindings are how a page says it- * expects an entry.- */- const usesEntry = template.elements.some(- e => ('binding' in e && e.binding) || (e.kind === 'photo' && e.photoId == null),- )- if (!usesEntry) return -1-- /*- * A template with three frames and an entry with one picture leaves two- * placeholders on a finished page, which is worse than a simpler layout.- * More pictures than frames is fine — the extra ones are parked.- */- if (frames > photos + 1) return -1- if (wantsStory && !hasStory) return -1-- // Closest match wins: a two-frame template for two pictures beats a one-frame- // one, and both beat a template that would leave a hole.- return 100 - Math.abs(frames - photos) * 10 - (wantsStory === hasStory ? 0 : 5)-}--/** Fill a template with an entry, and hand back the spread it makes. */-export function applyTemplate(- template: SpreadTemplate,- entry: TemplateEntry,- ctx: TemplateContext,-): BookSpread {- const { page } = ctx- const PW = page.pageWidth- const PH = page.pageHeight-- let nextPhoto = 0- // A journal entry has no length limit and a text element does — see the note- // in the contract. Poured in whole, one long day is a book that will not save.- const story = (entry.story || '').trim().slice(0, MAX_TEXT_LENGTH)- const heading = (entry.title || entry.location || '').slice(0, MAX_TEXT_LENGTH)-- const elements = template.elements.map(el => {- const out = {- ...el,- id: uid(el.kind[0]),- frame: {- x: round2(el.frame.x * PW),- y: round2(el.frame.y * PH),- w: round2(el.frame.w * PW),- h: round2(el.frame.h * PH),- },- } as BookElement-- // Sizes came out as fractions of the page height, so they go back up.- if ('size' in out && typeof out.size === 'number') out.size = round2(out.size * PH)- if ('radius' in out && typeof out.radius === 'number') out.radius = round2(out.radius * PW)- if ('strokeWidth' in out && typeof out.strokeWidth === 'number') {- out.strokeWidth = round2(out.strokeWidth * PW)- }-- if (out.kind === 'text' && out.binding) {- const source = out.binding.source- const format = out.binding.format- // What the words were made from, where they were made rather than copied.- let value: string | undefined- if (source === 'entry.title') out.text = heading- else if (source === 'entry.story') out.text = story- else if (source === 'entry.date') {- out.text = formatBookDate(entry.date, ctx.locale)- value = entry.date ?? undefined- }- // The place, as its name or as its point — see the `format` note in the- // contract. A stop the entry cannot answer keeps the words the template- // was drawn with, the same bargain fillBadge makes below.- else if (source === 'entry.location') {- if (format && entry.lat != null && entry.lng != null) {- out.text = formatBookCoords(entry.lat, entry.lng, format)- value = coordValue(entry.lat, entry.lng)- } else if (!format && entry.location) {- out.text = entry.location- }- }- out.binding = { ...out.binding, entryId: entry.id, ...(value ? { value } : {}) }- }-- if (out.kind === 'photo' && out.photoId == null) {- const photo = entry.photos[nextPhoto++]- if (photo) out.photoId = photo.photoId- }-- if (out.kind === 'badge') fillBadge(out, entry, ctx)-- if (out.kind === 'countries' && ctx.stats) {- out.codes = ctx.stats.countries.map(c => c.code)- out.names = ctx.stats.countries.map(c => c.name)- }-- // The figures live in one map on the element, keyed by metric — the same- // shape the panels write when a stats element is placed by hand.- if (out.kind === 'stats' && ctx.stats) {- out.values = {- distance: ctx.stats.distance,- days: ctx.stats.days,- steps: ctx.stats.steps,- photos: ctx.stats.photos,- places: ctx.stats.places,- countries: ctx.stats.countries.length,- furthest: ctx.stats.furthest,- }- }-- return out- })-- return {- id: uid('sp'),- role: 'inner',- background: template.background,- elements,- parked: [],- entryId: entry.id,- }-}--/**- * The small marks, filled from the stop.- *- * A badge whose value the entry cannot answer keeps the one it was drawn with:- * a template showing "DAY 1" on an entry with no date is a template that reads- * as a placeholder, which is exactly what it is until a date exists.- */-function fillBadge(el: BookElement & { kind: 'badge' }, entry: TemplateEntry, ctx: TemplateContext) {- if (el.variant === 'day' && entry.dayNumber) {- el.text = `${ctx.dayLabel} ${entry.dayNumber}`- }- if (el.variant === 'coords' && entry.lat != null && entry.lng != null) {- el.text = formatBookCoords(entry.lat, entry.lng)- }- if ((el.variant === 'flag' || el.variant === 'country') && entry.country) {- el.code = entry.country- el.text = countryName(entry.country, ctx).toUpperCase()- }- if (el.variant === 'date' && entry.date) {- const d = new Date(`${entry.date}T00:00:00`)- if (!Number.isNaN(d.getTime())) {- el.text = String(d.getDate())- el.sub = d.toLocaleDateString(ctx.locale, { month: 'long' }).toUpperCase()- }- }- if (el.variant === 'distance' && ctx.stats?.distance) {- el.text = `${Math.round(ctx.stats.distance / 1000).toLocaleString(ctx.locale)} km`- }-}--function countryName(code: string, ctx: TemplateContext): string {- const known = ctx.stats?.countries.find(c => c.code === code)- try {- return new Intl.DisplayNames([ctx.locale], { type: 'region' }).of(code) ?? known?.name ?? code- } catch {- return known?.name ?? code- }-}--const round2 = (n: number) => Math.round(n * 100) / 100diff --git a/client/src/components/Studio/autoLayout.ts b/client/src/components/Studio/autoLayout.tsdeleted file mode 100644index 2e85c369f..000000000--- a/client/src/components/Studio/autoLayout.ts+++ /dev/null@@ -1,1661 +0,0 @@-import type {- BookDocument, BookElement, BookMetric, BookPageSetup, BookSpread, JourneyStats,-} from '@trek/shared'-import {- MAX_BOOK_COUNTRIES, MAX_BOOK_TITLE, MAX_COUNTRY_NAME, MAX_MAP_POINTS,- MAX_MAP_POINT_LABEL, MAX_PATH_POINTS, MAX_PATH_SEGMENTS, MAX_SPREADS,- MAX_SPREAD_ELEMENTS, MAX_TEXT_LENGTH, blankBook, blankSpread,-} from '@trek/shared'-import { SPREAD_TEMPLATES } from './bookTemplates.data'-import { applyTemplate, templateFit } from './applyTemplate'-import { formatBookCoords, formatBookDate } from './entryText'--/**- * The auto mode: turn a journey into a book.- *- * The one rule that shapes everything else is that this produces an **ordinary- * document**. There is no "auto layout" state that locks, no template engine- * that re-runs behind the user's back — it lays the pages out once, and from- * that moment every element is as editable as one dragged in by hand. That is- * what makes an auto mode feel generous rather than restrictive.- *- * The colours in here are print ink, not app chrome, and deliberately do not- * follow the user's theme: a book is printed once and read on paper, where an- * accent colour chosen for a dark UI means nothing — and the renderer has no- * theme to ask. Hence the theme-lint exemptions below.- *- * Templates are chosen by what the material actually is: how many photos the- * entry has, whether they are portrait or landscape, how much story there is to- * set. A page of three landscape photos wants a different grid than a page of- * one portrait, and picking by shape is the difference between a book that looks- * arranged and one that looks poured in.- */--export interface AutoPhoto {- photoId: number- width: number | null- height: number | null- caption?: string | null-}--export interface AutoEntry {- id: number- title: string | null- story: string | null- location: string | null- date: string | null- photos: AutoPhoto[]- /**- * Where this stop is, when the journey's figures know.- *- * Filled from the stats points rather than carried on the entry: the entry- * knows a place name, the stats know what that place resolved to. A page can- * then print the flag, the country outline and the coordinates — which is- * most of what makes a printed travel page look like one.- */- lat?: number | null- lng?: number | null- country?: string | null- /** Which day of the journey this is, 1-based. Null when the dates do not say. */- dayNumber?: number | null- /** How many days the journey runs, for the progress rule along the foot. */- dayCount?: number | null-}--export interface AutoInput {- /**- * The app's language, not the browser's. A book whose captions are dated in- * the reader's OS locale while the rest of it is written in the app's is a- * mismatch nobody asked for.- */- locale: string- title: string- subtitle: string | null- coverPhotoId: number | null- entries: AutoEntry[]- page: BookPageSetup- /**- * What the journey adds up to. Null when the figures could not be fetched —- * the book then simply has no summary pages rather than pages with nothing- * on them.- */- stats: JourneyStats | null- /**- * The heading over a list of bare stops, already translated.- *- * Passed in rather than looked up: this module builds a document and has no- * business reaching for a translation context — the same reason it takes the- * locale instead of reading it.- */- stationsLabel: string- /** The word before a day number on a chip — "DAY 5". Already translated. */- dayLabel: string- /**- * The real geometry of the route, when the journey has any.- *- * GPX and KML imports are the only thing in TREK that stores an actual path- * — every other route is a straight line between stops. The editor already- * fetches it for the Travel panel; an auto-laid-out book used to hard-code an- * empty array here and throw it away, which is why the one journey with a- * recorded track still printed a map drawn with a ruler.- */- path?: [number, number][][]- /** "TRIP SUMMARY" over the figures. */- summaryLabel: string- /** "COUNTRIES" over the outlines. */- countriesLabel: string-}--let seq = 0-const uid = (p: string) => `${p}-${(seq++).toString(36)}-${Math.floor(Math.random() * 1e6).toString(36)}`--const isPortrait = (p: AutoPhoto) => (p.width && p.height ? p.height > p.width * 1.08 : false)-const isPano = (p: AutoPhoto) => (p.width && p.height ? p.width > p.height * 2 : false)--function text(- frame: { x: number; y: number; w: number; h: number },- value: string,- opts: Partial<Extract<BookElement, { kind: 'text' }>> = {},-): BookElement {- return {- id: uid('t'),- kind: 'text',- frame,- rotation: 0,- opacity: 1,- locked: false,- text: value.slice(0, MAX_TEXT_LENGTH),- font: 'sans',- size: 11,- weight: 400,- italic: false,- align: 'left',- leading: 1.45,- tracking: 0,- color: '#1a1a1a', // theme-lint-disable — book ink, not app chrome- binding: null,- overridden: false,- ...opts,- } as BookElement-}--/**- * A picture, or the place one goes.- *- * `photoId` may be null: that is an empty frame, which the renderer draws as an- * outline saying a photograph belongs here and which takes one by drag. A page- * laid out with frames is a page somebody can finish; the same page with the- * pictures simply left out is a page they have to design.- */-function photo(- frame: { x: number; y: number; w: number; h: number },- photoId: number | null,- opts: Partial<Extract<BookElement, { kind: 'photo' }>> = {},-): BookElement {- return {- id: uid('p'),- kind: 'photo',- frame,- rotation: 0,- opacity: 1,- locked: false,- photoId,- fit: 'cover',- focalX: 0.5,- focalY: 0.5,- radius: 0,- filter: 'none',- mask: null,- frameStyle: 'none',- ...opts,- } as BookElement-}--function shape(- frame: { x: number; y: number; w: number; h: number },- fill: string | null,- opts: Partial<Extract<BookElement, { kind: 'shape' }>> = {},-): BookElement {- return {- id: uid('s'),- kind: 'shape',- frame,- rotation: 0,- opacity: 1,- locked: false,- shape: 'rect',- fill,- gradient: 'none',- stroke: null,- strokeWidth: 0,- radius: 0,- ...opts,- } as BookElement-}--/**- * Ink for the travel elements.- *- * A single warm accent against near-black, chosen once here so the summary- * spread, the country page and the marks on the entries read as one book rather- * than as three features that happen to share a document.- */-const INK = '#1a1a1a' // theme-lint-disable — book ink, not app chrome-const ACCENT = '#c2410c' // theme-lint-disable — book ink, not app chrome--const travelBase = {- rotation: 0,- opacity: 1,- locked: false,- font: 'sans' as const,- color: INK,- // Ink, not the app's orange — see the note on `accent` in the contract.- accent: INK,- textScale: 1,- stale: false,-}--function statsEl(- frame: { x: number; y: number; w: number; h: number },- stats: JourneyStats,- metrics: BookMetric[],- layout: 'grid' | 'row' | 'column' = 'grid',- opts: Partial<Extract<BookElement, { kind: 'stats' }>> = {},-): BookElement {- return {- ...travelBase,- id: uid('st'),- kind: 'stats',- frame,- metrics,- layout,- showIcons: true,- units: 'metric',- values: {- distance: stats.distance,- days: stats.days,- steps: stats.steps,- photos: stats.photos,- countries: stats.countries.length,- places: stats.places,- furthest: stats.furthest,- },- ...opts,- } as BookElement-}--function mapEl(- frame: { x: number; y: number; w: number; h: number },- stats: JourneyStats,- opts: Partial<Extract<BookElement, { kind: 'map' }>> = {},-): BookElement {- return {- ...travelBase,- id: uid('mp'),- kind: 'map',- frame,- style: 'minimal',- showLand: true,- showRoute: true,- showPins: true,- showLabels: false,- // The drawn line, for the same reason the panel places one: the contract- // stays plain so old books do not change, and new books look like a book.- routeStyle: 'drawn',- routeArc: 'bow',- routeDash: 'arcs',- pinStyle: 'photo',- countries: stats.countries.slice(0, MAX_BOOK_COUNTRIES).map(c => c.code),- points: stats.points.slice(0, MAX_MAP_POINTS).map(pt => ({- lat: pt.lat,- lng: pt.lng,- label: pt.label.slice(0, MAX_MAP_POINT_LABEL),- photoId: pt.photoId ?? null,- })),- /*- * The fields the contract would default for a parsed element, spelled out- * because this one is cast. `path` in particular is read as an array while- * the map draws, so leaving it out is not a cosmetic difference.- */- path: [],- roads: [],- fitPadding: 0.5,- fitToCountries: true,- clip: 'rect',- ...opts,- } as BookElement-}--function countriesEl(- frame: { x: number; y: number; w: number; h: number },- stats: JourneyStats,- names: string[],- opts: Partial<Extract<BookElement, { kind: 'countries' }>> = {},-): BookElement {- return {- ...travelBase,- id: uid('co'),- kind: 'countries',- frame,- codes: stats.countries.slice(0, MAX_BOOK_COUNTRIES).map(c => c.code),- names: names.slice(0, MAX_BOOK_COUNTRIES).map(n => n.slice(0, MAX_COUNTRY_NAME)),- layout: 'list',- showOutline: true,- showFlag: false,- showName: true,- align: 'center',- ...opts,- } as BookElement-}--function badgeEl(- frame: { x: number; y: number; w: number; h: number },- variant: 'flag' | 'date' | 'day' | 'coords' | 'country' | 'distance',- value: { text?: string; sub?: string; code?: string | null },- opts: Partial<Extract<BookElement, { kind: 'badge' }>> = {},-): BookElement {- return {- ...travelBase,- id: uid('bd'),- kind: 'badge',- frame,- variant,- text: value.text ?? '',- sub: value.sub ?? '',- code: value.code ?? null,- style: 'plain',- // Built by hand rather than parsed, so the contract's defaults do not- // apply: left out, a mark reads as having been given a colour, and a chip- // draws its words in ink on an ink-coloured capsule.- autoColor: true,- showIcon: true,- showLabel: true,- autoIconColor: true,- iconColor: INK,- ...opts,- } as BookElement-}--/**- * ── The marks a printed travel page is made of ──────────────────────────- *- * Individually trivial: a flag beside a country's name, a line of coordinates- * under a place, a chip saying which day this is, a rule along the foot with a- * dot on it. Collectively they are the difference between a page that was- * designed and a page that was filled in — which is the whole of what these- * books look like, and none of it is expensive.- */--/** A country's flag with its name beside it, the way a page opens. */-function flagRow(- frame: { x: number; y: number; w: number; h: number },- code: string | null,- name: string,-): BookElement | null {- if (!code && !name) return null- // A badge centres what is in it, so the frame is cut to the words rather than- // given the column: a flag floating in the middle of a text page reads as a- // mistake, and there is no alignment on the badge contract to say otherwise.- frame = { ...frame, w: Math.min(frame.w, 14 + name.length * 1.7) }- return badgeEl(frame, 'flag', { text: name.toUpperCase(), code }, {- style: 'plain',- textScale: 0.85,- })-}--/** Where on earth this is, set small under the name. */-function coordsMark(- frame: { x: number; y: number; w: number; h: number },- lat: number | null | undefined,- lng: number | null | undefined,-): BookElement | null {- if (lat == null || lng == null) return null- return badgeEl(frame, 'coords', {- text: formatBookCoords(lat, lng),- }, { style: 'plain', textScale: 0.7 })-}--/** The "DAY 5" chip. Small, solid, and the only filled shape on most pages. */-function dayChip(- frame: { x: number; y: number; w: number; h: number },- day: number | null | undefined,- label: string,-): BookElement | null {- if (!day) return null- return badgeEl(frame, 'day', { text: `${label} ${day}` }, { style: 'chip', textScale: 0.75 })-}--/**- * A rule along the foot with a dot showing how far into the journey this is.- *- * Two elements and a division, and it turns a page from one of many into the- * ninth of fourteen. Drawn rather than an element type of its own: it is a line- * and a dot, and a new element kind for that would be a schema entry nobody- * would ever set by hand.- */-function progressRule(- x: number,- y: number,- w: number,- day: number | null | undefined,- total: number | null | undefined,-): BookElement[] {- if (!day || !total || total < 2) return []- const t = Math.min(1, Math.max(0, (day - 1) / (total - 1)))- const dot = 2.2- return [- shape({ x, y, w, h: 0.3 }, '#cfc9bd'), // theme-lint-disable — book ink, not app chrome- shape({ x: x + w * t - dot / 2, y: y - dot / 2 + 0.15, w: dot, h: dot }, ACCENT, { shape: 'ellipse' }),- ]-}--/**- * The country's outline, printed pale behind everything else.- *- * Polarsteps puts it on every place page and it is why those pages read as- * belonging to somewhere. Opacity rather than a lighter colour, so it sits- * under the type on any paper colour.- */-function countryWatermark(- frame: { x: number; y: number; w: number; h: number },- code: string | null | undefined,-): BookElement | null {- if (!code) return null- return {- ...travelBase,- id: uid('wm'),- kind: 'countries',- frame,- codes: [code],- names: [''],- layout: 'column',- showOutline: true,- showFlag: false,- showName: false,- align: 'center',- opacity: 0.1,- } as BookElement-}--/** The stop on a small map of its own, the way an entry page opens. */-function placeMap(- frame: { x: number; y: number; w: number; h: number },- entry: AutoEntry,- stats: JourneyStats | null,-): BookElement | null {- if (entry.lat == null || entry.lng == null) return null- return {- ...travelBase,- id: uid('mp'),- kind: 'map',- frame,- points: [{ lat: entry.lat, lng: entry.lng, label: entry.location ?? '', photoId: null }],- countries: entry.country ? [entry.country] : (stats?.countries.map(c => c.code) ?? []),- style: 'minimal',- source: 'vector',- tileUrl: '',- attribution: '',- zoom: 5,- // Deliberately the plain treatment: this is one dot on a country outline,- // and a bowed casing around a single stop would be decoration.- routeStyle: 'plain',- routeArc: 'straight',- routeDash: 'solid',- pinStyle: 'dot',- path: [],- roads: [],- fitPadding: 0.5,- /*- * This one is the "where in the world was this" mark beside an entry, so it- * wants the country whole with a dot in it — the opposite of the route map,- * which wants the trip.- */- fitToCountries: true,- clip: 'rect',- showLand: true,- showRoute: false,- showPins: true,- showLabels: false,- } as BookElement-}--/**- * The day of the month, set as a numeral with its month beneath.- *- * A date line reading "12 June 2026" is information; the same date as a figure- * is a mark on the page. Travel books have set dates this way for as long as- * they have existed, and it is the cheapest thing in this file that makes a- * spread look composed.- */-function dateMark(iso: string | null, locale: string, frame: { x: number; y: number; w: number; h: number }): BookElement | null {- if (!iso) return null- const d = new Date(`${iso}T00:00:00`)- if (Number.isNaN(d.getTime())) return null- return badgeEl(frame, 'date', {- text: String(d.getDate()),- sub: d.toLocaleDateString(locale, { month: 'long' }).toUpperCase(),- }, { style: 'stacked' })-}--/** A full-bleed frame: out past the trim on every side the page is cut on. */-function bleedFrame(page: BookPageSetup, spread: boolean) {- const w = spread ? page.pageWidth * 2 : page.pageWidth- return { x: -page.bleed, y: -page.bleed, w: w + page.bleed * 2, h: page.pageHeight + page.bleed * 2 }-}--function coverSpread(input: AutoInput): BookSpread {- const { page } = input- const m = 18- const els: BookElement[] = []-- if (input.coverPhotoId != null) {- els.push(photo(bleedFrame(page, false), input.coverPhotoId, { focalY: 0.42 }))- // A scrim so the title survives whatever the photo does underneath it —- // faded, not a flat panel, or it would cut the picture in half.- els.push(shape(- { x: -page.bleed, y: page.pageHeight * 0.38, w: page.pageWidth + page.bleed * 2, h: page.pageHeight * 0.62 + page.bleed },- '#000000', // theme-lint-disable — book ink, not app chrome- { opacity: 0.72, gradient: 'down' },- ))- }-- const light = input.coverPhotoId != null- els.push(text(- { x: m, y: page.pageHeight - m - 46, w: page.pageWidth - m * 2, h: 30 },- input.title,- {- size: 34, weight: 700, leading: 1.05, tracking: -0.02,- color: light ? '#ffffff' : '#111111', // theme-lint-disable — book ink, not app chrome- binding: { source: 'journey.title' },- },- ))- if (input.subtitle) {- els.push(text(- { x: m, y: page.pageHeight - m - 12, w: page.pageWidth - m * 2, h: 8 },- input.subtitle,- { size: 12, weight: 400, color: light ? '#ffffff' : '#444444', opacity: light ? 0.85 : 1, binding: { source: 'journey.subtitle' } }, // theme-lint-disable — book ink, not app chrome- ))- }-- return { id: uid('sp'), role: 'cover', background: input.coverPhotoId != null ? null : '#f4f2ee', elements: els, parked: [], entryId: null } // theme-lint-disable — book ink, not app chrome-}--/**- * One entry, one spread. Which template depends on the material:- * a panorama gets the width it needs, a portrait gets a tall column beside the- * story, several photos get a grid, and no photos at all get a quiet text page- * rather than an empty frame.- */-/**- * Whether an entry has anything to fill a spread with.- *- * A journey built from a trip starts out as one skeleton entry per stop:- * a date, a place name, and nothing else. Each of those used to get a spread- * of its own — a numeral on the left, a heading on the right and two-thirds of- * a metre of empty paper. Ten stops made ten of them.- */-function hasSubstance(entry: AutoEntry): boolean {- return entry.photos.length > 0 || !!(entry.story || '').trim()-}--/** What one station row costs: its date, its name, and the rule under it. */-const STATION_ELEMENTS = 3-/** And what the heading above the list costs: an accent rule and a word. */-const STATIONS_HEADING = 2--/**- * How many stations one page holds.- *- * Thirteen is where the type gets too tight — but the contract caps a spread at- * MAX_SPREAD_ELEMENTS, and a spread is two of these pages, so thirteen rows a- * page is eighty elements and a book the server refuses to store. Whichever- * limit runs out first is the answer.- */-const STATIONS_PER_PAGE = Math.min(- 13,- Math.floor((MAX_SPREAD_ELEMENTS - STATIONS_HEADING) / STATION_ELEMENTS / 2),-)--/**- * The stops that had nothing to say, as a list.- *- * Two columns of date and place, which is what an itinerary looks like in every- * printed travel book ever bound — and which turns ten near-empty spreads into- * one page that means something. Consecutive ones only, so the book stays in- * the order it happened.- */-function stationsSpread(entries: AutoEntry[], input: AutoInput, label: string): BookSpread {- const { page } = input- const W = page.pageWidth- const H = page.pageHeight- const m = 18- const els: BookElement[] = []-- els.push(shape({ x: m, y: m + 12, w: 14, h: 0.5 }, ACCENT))- els.push(text({ x: m, y: m + 18, w: W - m * 2, h: 8 }, label.toUpperCase(), {- size: 8, weight: 600, tracking: 0.16, color: '#8a8578', // theme-lint-disable — book ink, not app chrome- }))-- const columns: AutoEntry[][] = [- entries.slice(0, STATIONS_PER_PAGE),- entries.slice(STATIONS_PER_PAGE, STATIONS_PER_PAGE * 2),- ]- const top = m + 34- const step = Math.min(13, (H - top - m) / Math.max(1, STATIONS_PER_PAGE))-- columns.forEach((column, side) => {- const x = side * W + m- const w = W - m * 2- column.forEach((entry, i) => {- const y = top + i * step- const date = formatBookDate(entry.date, input.locale)- if (date) {- // Set in small caps, so the words on the page are not the words in the- // journal — and a bound element has to hold exactly its source or- // opening the book would quietly rewrite it. See resolveBindings.ts.- els.push(text({ x, y, w: w * 0.32, h: 5 }, date.toUpperCase(), {- size: 7, weight: 600, tracking: 0.1, color: '#a09a8e', // theme-lint-disable — book ink, not app chrome- }))- }- const name = entry.title || entry.location || ''- if (name) {- els.push(text({ x: x + w * 0.34, y: y - 1.5, w: w * 0.66, h: 7 }, name, {- size: 11, weight: 600, color: '#141414', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.title', entryId: entry.id },- }))- }- // A hairline under each row, the way a printed itinerary rules its lines.- els.push(shape({ x, y: y + step - 4.5, w, h: 0.15 }, '#ddd8cf')) // theme-lint-disable — book ink, not app chrome- })- })-- return {- id: uid('sp'),- role: 'inner',- background: '#faf8f4', // theme-lint-disable — book ink, not app chrome- elements: els,- parked: [],- entryId: null,- }-}--/**- * ── The entry spreads ────────────────────────────────────────────────────- *- * Five layouts rather than one, chosen by what the entry actually has and- * alternating as the book goes on. A book where every spread is built the same- * way reads as a template even when each page is fine on its own; the variety- * is not decoration, it is what makes the thing look printed.- *- * Each of them is built from the same parts a person would reach for in the- * editor — a flag, a country outline, a small map, a date numeral, a day chip,- * a rule along the foot. That is deliberate: what the auto layout produces has- * to be something you can take apart and rearrange, not a special case the- * panels cannot make.- */--/**- * ── The panels ───────────────────────────────────────────────────────────- *- * The thing the first version of this file was missing.- *- * A printed travel book is not photographs on paper with captions: it is- * built out of *areas* — a page laid solid in ink with pale type on it, a band- * down the outer edge, a picture that overruns the panel it sits against, a- * box ruled around a block of text. Those areas are what carry the design, and- * every one of them is a rectangle with a fill, drawn before the things that- * sit on top of it.- *- * Which is all layering is: the document paints in array order, so a panel- * pushed first is a panel everything else lands on. Nothing here needs a- * feature the editor does not already have — it needed using.- */--/** Near-black with a blue cast, the colour these books lay a page in. */-const PANEL_INK = '#12161d' // theme-lint-disable — book ink, not app chrome--/** Type on a panel, and the paper colour of the quiet pages. */-const PANEL_TYPE = '#f2efe9' // theme-lint-disable — book ink, not app chrome-const CREAM = '#faf8f4' // theme-lint-disable — book ink, not app chrome--/** A whole page laid in colour, bleeding off its three outer edges. */-function pagePanel(page: BookPageSetup, side: 'left' | 'right', fill: string): BookElement {- const b = page.bleed- return shape({- x: side === 'left' ? -b : page.pageWidth,- y: -b,- w: page.pageWidth + b,- h: page.pageHeight + b * 2,- }, fill)-}--/** A band down the outer edge — the cheapest mark that says "designed". */-function edgeBand(page: BookPageSetup, side: 'left' | 'right', fill: string, width = 8): BookElement {- const b = page.bleed- return shape({- x: side === 'left' ? -b : page.pageWidth * 2 - width,- y: -b,- w: width + b,- h: page.pageHeight + b * 2,- }, fill)-}--/** A box ruled around something, with nothing inside it. */-function ruleBox(- frame: { x: number; y: number; w: number; h: number },- colour: string,- radius = 0,-): BookElement {- return shape(frame, null, { stroke: colour, strokeWidth: 0.3, radius })-}--/**- * Which page the picture is on. Alternating keeps the book moving.- *- * Named for the picture rather than the words because that is the half a reader- * sees first, and because naming it the other way makes every call site below- * read backwards.- */-type Hand = 'left' | 'right'--interface EntryContext {- entry: AutoEntry- input: AutoInput- /** Position in the book, for alternating the layouts. */- index: number- hand: Hand-}--/** The heading block: rule, date line, title. Returns where it ended. */-function headingBlock(- els: BookElement[],- entry: AutoEntry,- input: AutoInput,- x: number,- y: number,- w: number,- opts: { size?: number; ink?: string; muted?: string } = {},-): number {- const size = opts.size ?? 22- const ink = opts.ink ?? '#141414' // theme-lint-disable — book ink, not app chrome- const muted = opts.muted ?? '#8a8578' // theme-lint-disable — book ink, not app chrome- const heading = entry.title || entry.location || ''- const meta = [formatBookDate(entry.date, input.locale), entry.location].filter(Boolean).join(' · ')- let cy = y-- if (meta || heading) {- els.push(shape({ x, y: cy - 6, w: Math.min(14, w * 0.18), h: 0.5 }, ACCENT))- }- if (meta) {- // Two facts run together and upper-cased: neither the date nor the place as- // the journal holds them, so this line is not bound to either.- els.push(text({ x, y: cy, w, h: 5 }, meta.toUpperCase(), {- size: 7.5, weight: 600, tracking: 0.14, color: muted,- }))- cy += 8- }- if (heading) {- els.push(text({ x, y: cy, w, h: size * 0.6 }, heading, {- size, weight: 700, leading: 1.1, tracking: -0.02, color: ink,- binding: { source: 'entry.title', entryId: entry.id },- }))- cy += size * 0.75- }- return cy-}--/** The foot: the day chip and the rule that says how far in this is. */-function footMarks(els: BookElement[], ctx: EntryContext, x: number, w: number, y: number) {- const { entry, input } = ctx- els.push(...progressRule(x, y, w, entry.dayNumber, entry.dayCount))-- // Above the dot, not above the middle: the chip and the rule are one mark- // saying how far in this page is, and a chip parked at the centre of a line- // whose dot is elsewhere says nothing at all.- const day = entry.dayNumber- const total = entry.dayCount- if (!day) return- const t = total && total > 1 ? Math.min(1, Math.max(0, (day - 1) / (total - 1))) : 0- const cw = 24- const cx = Math.min(x + w - cw, Math.max(x, x + w * t - cw / 2))- const chip = dayChip({ x: cx, y: y - 11, w: cw, h: 7 }, day, input.dayLabel)- if (chip) els.push(chip)-}--/**- * A stop, with nothing written about it yet.- *- * The country pale behind, the name large, the coordinates beneath it, and the- * picture page waiting as a frame. This is Polarsteps' place page, and it is- * the answer to what a page should look like when the only thing known about a- * day is where it was.- */-function placeSpread(ctx: EntryContext): BookSpread {- const { entry, input, hand } = ctx- const { page } = input- const H = page.pageHeight- const m = 18- const els: BookElement[] = []-- const photoPage = hand === 'left' ? 0 : page.pageWidth- const textPage = hand === 'left' ? page.pageWidth : 0- const tx = textPage + m- const colW = page.pageWidth - m * 2-- const wm = countryWatermark({ x: tx, y: H * 0.22, w: colW, h: H * 0.4 }, entry.country)- if (wm) els.push(wm)-- const flag = flagRow({ x: tx, y: m + 4, w: colW * 0.7, h: 7 }, entry.country ?? null, countryOf(entry, input))- if (flag) els.push(flag)-- const name = entry.title || entry.location || ''- if (name) {- els.push(text({ x: tx, y: H * 0.42, w: colW, h: 20 }, name, {- size: 26, weight: 700, tracking: -0.02, color: '#141414', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.title', entryId: entry.id },- }))- }- const coords = coordsMark({ x: tx, y: H * 0.42 + 22, w: colW, h: 6 }, entry.lat, entry.lng)- if (coords) els.push(coords)-- footMarks(els, ctx, tx, colW, H - m - 6)-- // The picture page: one frame, edge to edge, waiting.- els.push(photo({ x: photoPage + m, y: m, w: page.pageWidth - m * 2, h: H - m * 2 }, null))-- return sheet(els, entry, '#faf8f4') // theme-lint-disable — book ink, not app chrome-}--/**- * A day that was written about: words on one page, one picture on the other.- *- * The picture runs off three edges and stops dead on the gutter — across the- * fold or up to it, never almost, because an overhang of a few millimetres has- * no reading and disappears into the spine anyway.- */-function storySpread(ctx: EntryContext): BookSpread {- const { entry, input, hand } = ctx- const { page } = input- const H = page.pageHeight- const m = 18- const els: BookElement[] = []- const hero = entry.photos[0]-- const textPage = hand === 'left' ? page.pageWidth : 0- const tx = textPage + m- const colW = page.pageWidth - m * 2- const onLeft = hand === 'left'-- if (hero) {- // Bleeding off the outer edge and the top and bottom, flush to the fold.- els.push(photo(- {- x: onLeft ? -page.bleed : page.pageWidth,- y: -page.bleed,- w: page.pageWidth + page.bleed,- h: H + page.bleed * 2,- },- hero.photoId,- { focalX: isPortrait(hero) ? 0.5 : 0.55 },- ))- if (hero.caption) {- els.push(text({ x: (onLeft ? 0 : page.pageWidth) + m, y: H - m - 6, w: page.pageWidth * 0.6, h: 5 }, hero.caption, {- size: 7.5, weight: 500, color: '#ffffff', opacity: 0.9, // theme-lint-disable — book ink, not app chrome- binding: { source: 'photo.caption', entryId: entry.id, photoId: hero.photoId },- }))- }- } else {- /*- * No photograph yet, but the page it will sit on is already the page. An- * empty frame is what the renderer draws as an outline and what a dragged- * photo fills — so the layout is finished and the picture is the only thing- * missing, rather than the other way round.- */- els.push(photo({- x: (onLeft ? 0 : page.pageWidth) + m,- y: m,- w: page.pageWidth - m * 2,- h: H - m * 2,- }, null))- }-- // A small map of the stop, top of the text page — the mark that says where.- const map = placeMap({ x: tx, y: m, w: 26, h: 20 }, entry, input.stats)- if (map) els.push(map)-- const flag = flagRow({ x: tx + (map ? 32 : 0), y: m + 6, w: colW - (map ? 32 : 0), h: 7 }, entry.country ?? null, countryOf(entry, input))- if (flag) els.push(flag)-- const cy = headingBlock(els, entry, input, tx, m + 34, colW, { size: 20 })- const story = (entry.story || '').trim()- if (story) {- els.push(text({ x: tx, y: cy + 3, w: colW, h: H - cy - m - 34 }, story, {- size: 10, leading: 1.62, color: '#2a2a2a', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.story', entryId: entry.id },- }))- }-- const mark = dateMark(entry.date, input.locale, { x: tx, y: H - m - 30, w: 26, h: 20 })- if (mark) els.push(mark)- footMarks(els, ctx, tx, colW, H - m - 4)-- return sheet(els, entry, '#ffffff') // theme-lint-disable — book ink, not app chrome-}--/**- * A panorama across the fold, with the day underneath it.- *- * The one case where the gutter is an asset rather than something to design- * around: a wide picture wants the whole sheet.- */-function panoSpread(ctx: EntryContext): BookSpread {- const { entry, input } = ctx- const { page } = input- const W = page.pageWidth * 2- const H = page.pageHeight- const m = 18- const gut = 6- const els: BookElement[] = []- const [hero, ...rest] = entry.photos-- els.push(photo({ x: -page.bleed, y: -page.bleed, w: W + page.bleed * 2, h: H * 0.58 + page.bleed }, hero.photoId))-- const cy = headingBlock(els, entry, input, m, H * 0.58 + 16, page.pageWidth - m * 2, { size: 18 })- const story = (entry.story || '').trim()- if (story) {- els.push(text({ x: m, y: cy + 2, w: page.pageWidth - m * 2, h: H - cy - m - 12 }, story, {- size: 10, leading: 1.6, color: '#2a2a2a', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.story', entryId: entry.id },- }))- }-- const strip = rest.slice(0, 3)- if (strip.length) {- const cw = (page.pageWidth - m * 2 - gut * (strip.length - 1)) / strip.length- strip.forEach((p, i) => {- els.push(photo({ x: page.pageWidth + m + i * (cw + gut), y: H * 0.58 + 16, w: cw, h: H * 0.26 }, p.photoId))- })- }-- const flag = flagRow({ x: page.pageWidth + m, y: H - m - 16, w: page.pageWidth - m * 2, h: 7 }, entry.country ?? null, countryOf(entry, input))- if (flag) els.push(flag)- footMarks(els, ctx, page.pageWidth + m, page.pageWidth - m * 2, H - m - 4)-- return sheet(els, entry, '#ffffff') // theme-lint-disable — book ink, not app chrome-}--/**- * Several pictures: one large, the rest ruled beneath it.- *- * The hero takes a page and the others sit in a row under the text, which is- * how a magazine sets a picture story and how these books do too.- */-function gallerySpread(ctx: EntryContext): BookSpread {- const { entry, input, hand } = ctx- const { page } = input- const H = page.pageHeight- const m = 18- const gut = 5- const els: BookElement[] = []- const [hero, ...rest] = entry.photos-- const heroOnLeft = hand === 'left'- const heroX = heroOnLeft ? -page.bleed : page.pageWidth- const textX = (heroOnLeft ? page.pageWidth : 0) + m- const colW = page.pageWidth - m * 2-- els.push(photo(- { x: heroX, y: -page.bleed, w: page.pageWidth + page.bleed, h: H + page.bleed * 2 },- hero.photoId,- { focalX: isPortrait(hero) ? 0.5 : 0.55 },- ))-- const flag = flagRow({ x: textX, y: m + 2, w: colW, h: 7 }, entry.country ?? null, countryOf(entry, input))- const cy = headingBlock(els, entry, input, textX, m + (flag ? 26 : 16), colW, { size: 19 })- if (flag) els.push(flag)-- const strip = rest.slice(0, 3)- const stripH = strip.length ? (strip.length === 1 ? H * 0.28 : H * 0.22) : 0- // The foot carries the rule and the chip, so nothing else may end there.- const footRoom = 22- const story = (entry.story || '').trim()- if (story) {- const h = H - cy - m - (stripH ? stripH + 12 : 0) - footRoom- els.push(text({ x: textX, y: cy + 2, w: colW, h: Math.max(18, h) }, story, {- size: 10, leading: 1.62, color: '#2a2a2a', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.story', entryId: entry.id },- }))- }-- if (strip.length) {- const cw = (colW - gut * (strip.length - 1)) / strip.length- strip.forEach((p, i) => {- els.push(photo({ x: textX + i * (cw + gut), y: H - m - footRoom - stripH, w: cw, h: stripH }, p.photoId))- })- }-- footMarks(els, ctx, textX, colW, H - m - 4)- return sheet(els, entry, '#ffffff') // theme-lint-disable — book ink, not app chrome-}--/**- * One picture over the whole sheet, the words set on top of it.- *- * Used sparingly — every few spreads — because it is the loudest page in the- * book and a book of loud pages has no loud pages.- */-function immersiveSpread(ctx: EntryContext): BookSpread {- const { entry, input } = ctx- const { page } = input- const W = page.pageWidth * 2- const H = page.pageHeight- const m = 20- const els: BookElement[] = []- const hero = entry.photos[0]-- els.push(photo(bleedFrame(page, true), hero ? hero.photoId : null, { focalY: 0.45 }))-- // A panel behind the type: white on an unknown photograph is a coin toss.- els.push(shape({ x: -page.bleed, y: H * 0.56, w: W + page.bleed * 2, h: H * 0.44 + page.bleed }, '#0d0d0f', { // theme-lint-disable — book ink, not app chrome- gradient: 'up', opacity: 0.72,- }))-- const cy = headingBlock(els, entry, input, m, H * 0.68, page.pageWidth - m * 2, {- size: 24,- ink: '#ffffff', // theme-lint-disable — book ink, not app chrome- muted: '#d8d3ca', // theme-lint-disable — book ink, not app chrome- })- const story = (entry.story || '').trim()- if (story) {- els.push(text({ x: page.pageWidth + m, y: H * 0.68, w: page.pageWidth - m * 2, h: H * 0.26 }, story, {- size: 9.5, leading: 1.6, color: '#efece6', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.story', entryId: entry.id },- }))- }- void cy-- const coords = coordsMark({ x: m, y: H - m - 5, w: page.pageWidth - m * 2, h: 5 }, entry.lat, entry.lng)- if (coords) els.push(coords)-- return sheet(els, entry, '#0d0d0f') // theme-lint-disable — book ink, not app chrome-}--/**- * A page laid in ink, the picture overrunning it.- *- * The composition these books use more than any other: one page solid, the- * other a photograph, and something crossing the join so the two halves read- * as one sheet rather than as two pages that happen to be adjacent. Here the- * crossing is a second picture, sitting half on the panel and half off it.- */-function panelSpread(ctx: EntryContext): BookSpread {- const { entry, input, hand } = ctx- const { page } = input- const H = page.pageHeight- const m = 20- const els: BookElement[] = []- const [hero, ...rest] = entry.photos-- const panelSide = hand === 'left' ? 'right' : 'left'- const panelX = panelSide === 'left' ? 0 : page.pageWidth- const tx = panelX + m- const colW = page.pageWidth - m * 2-- // The panel first: everything after it lands on top.- els.push(pagePanel(page, panelSide, PANEL_INK))-- if (hero) {- els.push(photo({- x: panelSide === 'left' ? page.pageWidth : -page.bleed,- y: -page.bleed,- w: page.pageWidth + page.bleed,- h: H + page.bleed * 2,- }, hero.photoId, { focalX: isPortrait(hero) ? 0.5 : 0.55 }))- } else {- els.push(photo({- x: (panelSide === 'left' ? page.pageWidth : 0) + m,- y: m,- w: colW,- h: H - m * 2,- }, null))- }-- const flag = flagRow({ x: tx, y: m, w: colW, h: 7 }, entry.country ?? null, countryOf(entry, input))- if (flag) els.push(flag)-- const cy = headingBlock(els, entry, input, tx, m + 30, colW, {- size: 21, ink: PANEL_TYPE, muted: '#a8a094', // theme-lint-disable — book ink, not app chrome- })- const story = (entry.story || '').trim()- if (story) {- els.push(text({ x: tx, y: cy + 3, w: colW, h: H - cy - m - 46 }, story, {- size: 9.5, leading: 1.66, color: '#d9d4cb', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.story', entryId: entry.id },- }))- }-- /*- * A second picture across the fold, half on the panel.- *- * This is the whole point of the layout: without it the spread is two pages,- * with it the spread is one. Pushed last so it sits over both.- */- const crossing = rest[0]- if (crossing) {- const cw = 62- const ch = 46- els.push(photo({- x: page.pageWidth - cw * 0.55,- y: H - m - ch - 14,- w: cw,- h: ch,- }, crossing.photoId, { radius: 1 }))- }-- footMarks(els, ctx, tx, colW, H - m - 4)- return sheet(els, entry, CREAM)-}--/**- * A band down the edge, a ruled box, and pictures at two sizes.- *- * The quiet counterpart to the panel spread — nothing solid across a whole- * page, but enough drawing that it does not read as a photograph with a- * caption. The box around the text is doing the same job a panel does: it- * makes the words an object on the page rather than something poured onto it.- */-function bandSpread(ctx: EntryContext): BookSpread {- const { entry, input, hand } = ctx- const { page } = input- const H = page.pageHeight- const m = 20- const gut = 5- const els: BookElement[] = []- const photos = entry.photos-- const bandSide = hand === 'left' ? 'left' : 'right'- els.push(edgeBand(page, bandSide, ACCENT, 6))-- // The big picture takes most of one page, off the top and the outer edge.- const heroSide = hand === 'left' ? 'left' : 'right'- const heroX = heroSide === 'left' ? 6 : page.pageWidth- const heroW = page.pageWidth - 6 + (heroSide === 'left' ? 0 : page.bleed)- if (photos[0]) {- els.push(photo({ x: heroX, y: -page.bleed, w: heroW, h: H * 0.62 }, photos[0].photoId))- } else {- els.push(photo({ x: heroX + m, y: m, w: heroW - m * 2, h: H * 0.5 }, null))- }-- const textPage = heroSide === 'left' ? page.pageWidth : 0- const tx = textPage + m- const colW = page.pageWidth - m * 2-- // The words in a ruled box, set in from it on every side.- const boxY = m + 6- const boxH = H * 0.52- els.push(ruleBox({ x: tx, y: boxY, w: colW, h: boxH }, '#d8d2c6', 1.5)) // theme-lint-disable — book ink, not app chrome-- const flag = flagRow({ x: tx + 8, y: boxY + 8, w: colW - 16, h: 6 }, entry.country ?? null, countryOf(entry, input))- if (flag) els.push(flag)-- const cy = headingBlock(els, entry, input, tx + 8, boxY + 30, colW - 16, { size: 18 })- const story = (entry.story || '').trim()- if (story) {- els.push(text({ x: tx + 8, y: cy + 2, w: colW - 16, h: boxY + boxH - cy - 12 }, story, {- size: 9.5, leading: 1.6, color: '#2a2a2a', // theme-lint-disable — book ink, not app chrome- binding: { source: 'entry.story', entryId: entry.id },- }))- }-- // Two smaller pictures under the box, and one that overlaps the hero above.- const rest = photos.slice(1, 3)- if (rest.length) {- const cw = (colW - gut * (rest.length - 1)) / rest.length- rest.forEach((ph, i) => {- els.push(photo({ x: tx + i * (cw + gut), y: boxY + boxH + 10, w: cw, h: H * 0.2 }, ph.photoId, { radius: 1 }))- })- }- const overlap = photos[3]- if (overlap) {- els.push(photo({ x: heroX + 14, y: H * 0.62 - 26, w: 52, h: 40 }, overlap.photoId, { radius: 1 }))- }-- const mark = dateMark(entry.date, input.locale, { x: heroX + 14, y: H - m - 34, w: 26, h: 22 })- if (mark) els.push(mark)- footMarks(els, ctx, tx, colW, H - m - 4)- return sheet(els, entry, '#ffffff') // theme-lint-disable — book ink, not app chrome-}--/** The country a stop is in, named in the book's language. */-function countryOf(entry: AutoEntry, input: AutoInput): string {- if (!entry.country) return ''- const named = input.stats?.countries.find(c => c.code === entry.country)- try {- return new Intl.DisplayNames([input.locale], { type: 'region' }).of(entry.country) ?? named?.name ?? ''- } catch {- return named?.name ?? ''- }-}--function sheet(els: BookElement[], entry: AutoEntry, background: string): BookSpread {- return { id: uid('sp'), role: 'inner', background, elements: els, parked: [], entryId: entry.id }-}--/**- * Pick a layout for an entry.- *- * By what it has first — a panorama wants the fold, a stop with no pictures- * wants the place page — and by where it sits in the book second, so two- * neighbours with the same contents do not come out identical. The hand- * alternates for the same reason: a book whose pictures are all on the left is- * a book you can feel the template through.- */-/**- * A hand-drawn template for this entry, if one of them fits.- *- * Tried before the layouts written below, and that order is the point: a page- * somebody designed beats a page a function reasoned its way to, every time.- * The built-in layouts are what an entry falls back on when no template suits- * it — a book of six pictures has nowhere to go in a template drawn for two.- *- * Rotated by position so a run of similar entries does not come out as a run- * of identical pages, which is the failure the built-ins had before them.- */-function templateSpread(entry: AutoEntry, input: AutoInput, index: number): BookSpread | null {- if (SPREAD_TEMPLATES.length === 0) return null-- const scored = SPREAD_TEMPLATES- .map(t => ({ t, fit: templateFit(t, entry) }))- .filter(x => x.fit >= 0)- .sort((a, b) => b.fit - a.fit)- if (scored.length === 0) return null-- // Everything within a few points of the best is equally suitable, so the- // position picks between them rather than the order they happen to be in.- const best = scored[0].fit- const equals = scored.filter(x => x.fit >= best - 5)- const pick = equals[index % equals.length]-- return applyTemplate(pick.t, entry, {- page: input.page,- locale: input.locale,- stats: input.stats,- dayLabel: input.dayLabel,- })-}--function entrySpread(entry: AutoEntry, input: AutoInput, index = 0): BookSpread {- const hand: Hand = index % 2 === 0 ? 'left' : 'right'- const ctx: EntryContext = { entry, input, index, hand }- const photos = entry.photos.slice(0, 5)- const withPhotos = { ...entry, photos }- const c = { ...ctx, entry: withPhotos }-- const story = (entry.story || '').trim()- // The place page is for a stop nobody wrote about. Words want a page with- // room for them, even when the pictures have not arrived.- const fromTemplate = templateSpread(withPhotos, input, index)- if (fromTemplate) return fromTemplate-- if (photos.length === 0 && !story) return placeSpread(c)- // Guarded: an entry can have words and no pictures at all.- if (photos.length > 0 && isPano(photos[0])) return panoSpread(c)-- /*- * Six layouts on a rotation, so the book does not read as a template.- *- * By contents first — a panorama wants the fold, a stop with nothing said- * about it wants the place page — and then by position, so two neighbours- * with the same contents come out differently. The full-bleed page is kept- * to every sixth and never the first: a book should not open at its own- * volume, and a book of loud pages has no loud page.- */- switch (index % 6) {- case 0: return photos.length > 1 ? gallerySpread(c) : storySpread(c)- case 1: return panelSpread(c)- case 2: return photos.length > 2 ? bandSpread(c) : storySpread(c)- case 3: return photos.length ? immersiveSpread(c) : panelSpread(c)- case 4: return photos.length > 1 ? bandSpread(c) : panelSpread(c)- default: return photos.length > 1 ? gallerySpread(c) : storySpread(c)- }-}--/**- * The back cover.- *- * A book that stops mid-page reads as unfinished, and a printer needs the- * closing single page anyway — the cover sheet is one piece of card with a front- * and a back. Quiet on purpose: the last thing a reader sees should be a full- * stop, not another layout.- */-/**- * The journey at a glance: the route drawn, and what it came to.- *- * This is the spread a travel book opens on and the one a photo album cannot- * have — it is made entirely of facts the trip already carried. The map takes- * the left page because a route is read before it is quantified, and the- * figures sit on the right where the eye lands second.- *- * Omitted rather than left empty when there is nothing to draw: a journey whose- * stops carry no coordinates has no route, and a page holding a blank frame- * over the words "0 KM" is worse than no page.- */-/**- * Country names in the book's language.- *- * The API answers in English because it does not know who will read the book;- * `Intl.DisplayNames` is the same CLDR data Atlas uses for regions, so a German- * book says "Island" from the same two-letter code an English one reads as- * "Iceland".- */-function countryNames(input: AutoInput): string[] {- const codes = input.stats?.countries ?? []- let display: Intl.DisplayNames | null = null- try {- display = new Intl.DisplayNames([input.locale], { type: 'region' })- } catch {- display = null- }- return codes.map(c => display?.of(c.code.toUpperCase()) || c.name || c.code.toUpperCase())-}--function summarySpread(input: AutoInput): BookSpread | null {- const stats = input.stats- if (!stats) return null- // Something has to be worth printing. One stop is a pin, not a journey.- if (stats.points.length < 2 && !stats.distance && !stats.days) return null-- const { page } = input- const W = page.pageWidth- const H = page.pageHeight- const m = 18- const els: BookElement[] = []-- if (stats.points.length >= 2) {- // With the recorded track, when the journey has one: the editor fetches it- // and this was the line that threw it away.- els.push(mapEl({ x: m, y: m, w: W - m * 2, h: H - m * 2 }, stats, {- path: (input.path ?? []).slice(0, MAX_PATH_SEGMENTS).map(seg => seg.slice(0, MAX_PATH_POINTS)),- }))- }-- // Which figures are worth the space: everything the journey actually has.- // A "0 PHOTOS" tile is a hole in a composition, not information.- const metrics: BookMetric[] = ([- ['distance', stats.distance],- ['days', stats.days],- ['steps', stats.steps],- ['photos', stats.photos],- ['countries', stats.countries.length],- ['furthest', stats.furthest],- ] as [BookMetric, number][])- .filter(([, v]) => v > 0)- .map(([k]) => k)- .slice(0, 6)-- const rx = W + m- const colW = W - m * 2-- els.push(shape({ x: rx, y: m + 14, w: colW * 0.16, h: 0.5 }, ACCENT))- els.push(text({ x: rx, y: m + 20, w: colW, h: 7 }, input.summaryLabel.toUpperCase(), {- size: 9, weight: 700, tracking: 0.18, color: '#141414', // theme-lint-disable — book ink, not app chrome- }))-- if (metrics.length) {- els.push(statsEl(- { x: rx, y: m + 36, w: colW, h: H * 0.42 },- stats,- metrics,- 'grid',- ))- }-- /*- * The furthest point, drawn.- *- * Two dots, a line and a distance — the one figure on this page that is about- * a relationship rather than a total, and the one Polarsteps gives its own- * drawing to. It is worth the space for the same reason: "10,382 km" means- * nothing until it is a line between two names.- */- const home = stats.points[0]- const far = furthestPoint(stats)- if (stats.furthest > 0 && home && far && far !== home) {- const y = H - m - 26- const lineW = colW - 16- els.push(shape({ x: rx + 8, y, w: lineW, h: 0.3 }, '#cfc9bd')) // theme-lint-disable — book ink, not app chrome- for (const t of [0, 1]) {- els.push(shape(- { x: rx + 8 + lineW * t - 1.4, y: y - 1.25, w: 2.8, h: 2.8 },- t === 0 ? '#8a8578' : ACCENT, // theme-lint-disable — book ink, not app chrome- { shape: 'ellipse' },- ))- }- els.push(badgeEl(- { x: rx + 8 + lineW * 0.5 - 17, y: y - 11, w: 34, h: 8 },- 'distance',- { text: formatKm(stats.furthest, input.locale) },- { style: 'chip', textScale: 0.7 },- ))- els.push(text({ x: rx + 4, y: y + 4, w: lineW * 0.5, h: 5 }, (home.label || '').toUpperCase(), {- size: 6.5, weight: 600, tracking: 0.1, color: '#8a8578', // theme-lint-disable — book ink, not app chrome- }))- els.push(text({ x: rx + 4 + lineW * 0.5, y: y + 4, w: lineW * 0.5 + 4, h: 5 }, (far.label || '').toUpperCase(), {- size: 6.5, weight: 600, tracking: 0.1, align: 'right', color: '#8a8578', // theme-lint-disable — book ink, not app chrome- }))- }-- return { id: uid('sp'), role: 'inner', background: null, elements: els, parked: [], entryId: null }-}--/** The stop that ended up furthest from the first one. */-function furthestPoint(stats: JourneyStats) {- const home = stats.points[0]- if (!home) return null- let best = home- let bestD = 0- for (const p of stats.points) {- const d = Math.hypot(p.lat - home.lat, (p.lng - home.lng) * Math.cos((home.lat * Math.PI) / 180))- if (d > bestD) { bestD = d; best = p }- }- return best-}--/** Metres as the books print them: "1,189 km", in the book's own language. */-function formatKm(metres: number, locale: string): string {- return `${Math.round(metres / 1000).toLocaleString(locale)} km`-}--function countriesSpread(input: AutoInput, names: string[]): BookSpread | null {- const stats = input.stats- if (!stats || stats.countries.length < 2) return null-- const { page } = input- const W = page.pageWidth- const H = page.pageHeight- const m = 20- const rows = stats.countries.length- // Tall enough to breathe, but never taller than the page it sits on.- const height = Math.min(H - m * 2 - 24, Math.max(H * 0.4, rows * 26))-- /*- * Dark, because the printed one is.- *- * It is the single most recognisable page in these books: pale outlines on- * near-black, names above them, nothing else on the sheet. On white it is a- * list with pictures; on black it is the page people photograph.- */- const ink = '#f2efe9' // theme-lint-disable — book ink, not app chrome-- return {- id: uid('sp'),- role: 'inner',- background: '#12161d', // theme-lint-disable — book ink, not app chrome- elements: [- text({ x: W + m, y: m + 16, w: W - m * 2, h: 8 }, input.countriesLabel.toUpperCase(), {- size: 9, weight: 700, tracking: 0.2, align: 'center', color: ink,- }),- countriesEl(- { x: W + m, y: (H - height) / 2 + 10, w: W - m * 2, h: height },- stats,- names,- { color: ink, accent: ink },- ),- ],- parked: [],- entryId: null,- }-}--function backSpread(input: AutoInput): BookSpread {- const { page } = input- const m = 18- const els: BookElement[] = []-- const dates = input.entries- .map(e => e.date)- .filter((d): d is string => !!d)- .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))- const span = dates.length- ? [formatBookDate(dates[0], input.locale), formatBookDate(dates[dates.length - 1], input.locale)].filter(Boolean).join(' — ')- : ''-- els.push(shape({ x: -page.bleed, y: -page.bleed, w: page.pageWidth + page.bleed * 2, h: page.pageHeight + page.bleed * 2 }, '#141414')) // theme-lint-disable — book ink, not app chrome-- els.push(text({ x: m, y: page.pageHeight * 0.5 - 16, w: page.pageWidth - m * 2, h: 12 }, input.title, {- size: 15, weight: 600, align: 'center', color: '#ffffff', tracking: -0.01, // theme-lint-disable — book ink, not app chrome- binding: { source: 'journey.title' },- }))- if (span) {- els.push(text({ x: m, y: page.pageHeight * 0.5, w: page.pageWidth - m * 2, h: 6 }, span, {- size: 8.5, align: 'center', color: '#ffffff', opacity: 0.55, // theme-lint-disable — book ink, not app chrome- }))- }- /*- * The closing tally, as a figures element rather than a built string.- *- * It used to be `${places} Orte` — German, hardcoded, in a book that follows- * the app's language everywhere else. The element takes its labels from the- * same translations as the rest of Studio, so the last page of a French book- * is finally in French.- */- if (input.stats) {- const closing: BookMetric[] = ([- ['days', input.stats.days],- ['places', input.stats.places],- ['photos', input.stats.photos],- ] as [BookMetric, number][])- .filter(([, v]) => v > 0)- .map(([k]) => k)-- if (closing.length) {- els.push(statsEl(- { x: m, y: page.pageHeight * 0.5 + 6, w: page.pageWidth - m * 2, h: 22 },- input.stats,- closing,- 'row',- {- showIcons: false,- // Set against the dark card, and quiet: this is a full stop, not a- // second summary page.- color: '#ffffff', // theme-lint-disable — book ink, not app chrome- accent: '#ffffff', // theme-lint-disable — book ink, not app chrome- opacity: 0.55,- textScale: 0.8,- },- ))- }- }-- return { id: uid('sp'), role: 'back', background: '#141414', elements: els, parked: [], entryId: null } // theme-lint-disable — book ink, not app chrome-}--export function buildBook(input: AutoInput): BookDocument {- const spreads: BookSpread[] = [coverSpread(input), blankSpread('first')]-- /*- * The summary and the countries open the book, before the entries.- *- * They are the answer to "where did you go", and a reader who has that- * answer reads the entries as places on a route rather than as a sequence of- * unrelated days. Both return null when the journey has nothing to say with- * them, so a book is never padded with an empty page.- */- const summary = summarySpread(input)- if (summary) spreads.push(summary)-- const countries = countriesSpread(input, countryNames(input))- if (countries) spreads.push(countries)-- /*- * Entries with something on them get a spread each; runs of bare ones share- * a list. Consecutive runs only — a book of a journey is in the order it- * happened, and gathering every bare entry at the end would break that.- */- let laid = 0- let run: AutoEntry[] = []- const flushRun = () => {- if (run.length === 0) return- // One bare entry between two real ones is not a list, it is a line. It gets- // the same page as its neighbours would rather than a page of its own.- for (let i = 0; i < run.length; i += STATIONS_PER_PAGE * 2) {- spreads.push(stationsSpread(run.slice(i, i + STATIONS_PER_PAGE * 2), input, input.stationsLabel))- }- run = []- }- for (const entry of input.entries) {- if (hasSubstance(entry)) {- flushRun()- spreads.push(entrySpread(entry, input, laid++))- } else {- run.push(entry)- }- }- flushRun()- spreads.push(blankSpread('last'), backSpread(input))- return {- version: 1,- title: input.title.slice(0, MAX_BOOK_TITLE),- page: withFirstPage(input.page),- spreads: spreads.slice(0, MAX_SPREADS),- }-}--/**- * The page setup for a book that opens on a single page.- *- * `startAt` numbers the first page inside the covers. A book from before the- * single first page existed opened straight onto a spread and started at 2,- * so that its left-hand page read as the second page of the object. With a- * first page in front of that spread the first page is page 1 — so a book laid- * out with one starts there, whatever the setup it inherited said (#2317).- * Nothing else of the setup is touched: the format and the folio styling are- * the person's, only the count moved with the page that moved.- */-function withFirstPage(page: BookPageSetup): BookPageSetup {- return { ...page, pageNumbers: { ...page.pageNumbers, startAt: 1 } }-}--/**- * A book nobody has laid out yet.- *- * What a journey with no book now opens on. It used to open on the auto layout,- * which was generous and wrong: it decided what the book was before its author- * had said anything, and everything after that was undoing rather than making.- * The layout is still one click away, on the Auto layout menu, and it reads- * very differently when it is offered than when it has already happened.- *- * The covers are here rather than left out because a book has them and there is- * no other way to add one: the pages rail only inserts inner spreads, between- * the two. The single first and last pages likewise (#2317). Empty, though, in- * the same way the spread between them is. The same blank book the assistant's- * `create_book` writes (shared/src/book/book-pages.ts).- */-export function emptyBook(input: AutoInput): BookDocument {- return blankBook({ title: input.title, page: input.page })-}--/**- * Lay one spread out again, from the entry it came from.- *- * The whole-book version throws away everything; this is for the far more- * common "this page came out wrong" — it rebuilds the spread its entry would- * produce and leaves every other page alone.- *- * Returns null for a spread that has no entry behind it: the cover, the back- * cover, the summary, the country page and anything added by hand. Those were- * not generated from an entry, so there is nothing to regenerate them from, and- * silently replacing them with a blank page would be worse than refusing.- */-export function relayoutSpread(spread: BookSpread, input: AutoInput): BookSpread | null {- if (spread.role !== 'inner' || spread.entryId == null) return null- const entry = input.entries.find(e => e.id === spread.entryId)- if (!entry) return null- // Its own id is kept, so the pages rail does not scroll and the selection- // does not jump — from the outside it is the same page, rearranged.- const index = input.entries.indexOf(entry)- return { ...entrySpread(entry, input, index < 0 ? 0 : index), id: spread.id }-}--/**- * Hand the journey's loose gallery photos to the entries.- *- * Photos that already sit on an entry stay there. The rest are shared out in- * order, so a book built from a journey whose pictures all live in the gallery- * still gets pictures on its pages instead of a run of empty text spreads.- */-export function distributeGallery(entries: AutoEntry[], gallery: AutoPhoto[]): AutoEntry[] {- const taken = new Set(entries.flatMap(e => e.photos.map(p => p.photoId)))- const loose = gallery.filter(p => !taken.has(p.photoId))- if (!loose.length || !entries.length) return entries-- const per = Math.max(1, Math.floor(loose.length / entries.length))- let i = 0- return entries.map((e, idx) => {- if (e.photos.length >= 4) return e- const want = Math.min(4 - e.photos.length, idx === entries.length - 1 ? loose.length - i : per)- const slice = loose.slice(i, i + Math.max(0, want))- i += slice.length- return { ...e, photos: [...e.photos, ...slice] }- })-}diff --git a/client/src/components/Studio/bookTemplates.data.ts b/client/src/components/Studio/bookTemplates.data.tsdeleted file mode 100644index fa8bc6bac..000000000--- a/client/src/components/Studio/bookTemplates.data.ts+++ /dev/null@@ -1,1279 +0,0 @@-import type { BookElement } from '@trek/shared'--/**- * The spread templates, as data.- *- * ── Where these come from ────────────────────────────────────────────────- *- * Not from this file's author. They were built by hand in Studio and read back- * out of the document — which is the point: what a page should look like is a- * matter of taste, and taste is not something a layout function arrives at by- * reasoning. The editor is the design tool, and this is its output.- *- * To add one: build the spread in Studio, then run- *- * node scripts/extract-templates.cjs <journeyId>- *- * from server/ and commit what it writes here.- *- * ── Why the numbers are fractions ────────────────────────────────────────- *- * Every frame is divided by the page it was drawn on — x and w by one page's- * width, y and h by its height — and type sizes by the page height. A template- * built on a 210mm square therefore lays out on an A4 landscape book without- * being redrawn, which it would otherwise have to be for every trim size the- * picker offers.- *- * ── What gets filled in ──────────────────────────────────────────────────- *- * Elements carrying a `binding` take their text from the entry; empty photo- * frames take its photographs in order; the day, coordinate and country marks- * take what the entry knows about its stop. Everything else — the panels, the- * rules, the shapes that run off the page — is the design, and is kept as it- * was drawn.- */--export interface SpreadTemplate {- id: string- background: string | null- /** Frames and sizes are fractions — see the note above. */- elements: BookElement[]-}--export const SPREAD_TEMPLATES: SpreadTemplate[] = [- {- id: 'ref-1',- background: null,- elements: [- {- "id": "p-iy13loy",- "frame": {- "x": 0.0238,- "y": 0.0238,- "w": 0.9524,- "h": 0.9524- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.572289143475242,- "focalY": 0.5726791042512355,- "radius": 0.0238,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "s-kafy6t4",- "frame": {- "x": 1.5898,- "y": 0.0238,- "w": 0.3864,- "h": 0.9524- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "shape",- "shape": "rect",- "fill": "#111111",- "gradient": "none",- "stroke": null,- "strokeWidth": 0,- "strokeStyle": "solid",- "radius": 0- },- {- "id": "t-v4jhfu6",- "frame": {- "x": 1.5898,- "y": 0.0563,- "w": 0.3864,- "h": 0.0613- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "COUNTRIES",- "font": "sans",- "size": 0.1429,- "weight": 700,- "italic": false,- "align": "center",- "leading": 1.1,- "tracking": -0.02,- "color": "#ffffff",- "binding": null,- "overridden": true- },- {- "id": "t-nh804rp",- "frame": {- "x": 1.1136,- "y": 0.0563,- "w": 0.3864,- "h": 0.0613- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "SUMMARY",- "font": "sans",- "size": 0.1429,- "weight": 700,- "italic": false,- "align": "center",- "leading": 1.1,- "tracking": -0.02,- "color": "#111111",- "binding": null,- "overridden": true- },- {- "id": "s-8c3kwzk",- "frame": {- "x": 1.0812,- "y": 0.1757,- "w": 0.4511,- "h": 0.5743- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#111111",- "textScale": 1.5,- "weight": 700,- "stale": false,- "kind": "stats",- "metrics": [- "distance",- "days",- "steps",- "photos",- "countries",- "places"- ],- "layout": "grid",- "showIcons": true,- "units": "metric",- "values": {- "distance": 352677,- "days": 1,- "steps": 2,- "photos": 3,- "countries": 2,- "places": 0,- "furthest": 352677- }- },- {- "id": "b-15vswaz",- "frame": {- "x": 1.1768,- "y": 0.7685,- "w": 0.2587,- "h": 0.066- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#111111",- "textScale": 1,- "weight": 700,- "stale": false,- "kind": "badge",- "variant": "distance",- "text": "0 km",- "sub": "Distance",- "code": null,- "style": "chip",- "autoColor": true,- "showIcon": true,- "showLabel": true,- "autoIconColor": true,- "iconColor": "#111111"- },- {- "id": "c-jdsxmvn",- "frame": {- "x": 1.628,- "y": 0.2315,- "w": 0.31,- "h": 0.537- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#ffffff",- "accent": "#ffffff",- "textScale": 0.7,- "weight": 700,- "stale": false,- "kind": "countries",- "codes": [- "DE",- "NL"- ],- "names": [- "Germany",- "Netherlands"- ],- "layout": "list",- "showOutline": true,- "showFlag": false,- "showName": true,- "align": "center"- }- ],- },- {- id: 'ref-2',- background: null,- elements: [- {- "id": "s-f7yltlr",- "frame": {- "x": -0.1264,- "y": 0.6775,- "w": 0.5595,- "h": 0.5973- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "shape",- "shape": "flower-5",- "fill": "#111111",- "gradient": "none",- "stroke": null,- "strokeWidth": 0,- "strokeStyle": "solid",- "radius": 0- },- {- "id": "s-0fpxqfa",- "frame": {- "x": 1.0762,- "y": 0.6437,- "w": 0.8635,- "h": 0.2829- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "shape",- "shape": "rect",- "fill": "#111111",- "gradient": "none",- "stroke": "#11224f",- "strokeWidth": 0.0024,- "strokeStyle": "solid",- "radius": 0- },- {- "id": "p-b5dnke1",- "frame": {- "x": 0.0238,- "y": 0.0238,- "w": 1.9524,- "h": 0.3062- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": 69,- "fit": "cover",- "focalX": 0.42168673729754674,- "focalY": 0.23833399057977409,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "t-kvtn36a",- "frame": {- "x": 0.0762,- "y": 0.3843,- "w": 0.8476,- "h": 0.0479- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet",- "font": "sans",- "size": 0.1048,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.title",- "entryId": 62- },- "overridden": false- },- {- "id": "t-cnhlrmk",- "frame": {- "x": 0.0762,- "y": 0.452,- "w": 0.8476,- "h": 0.1917- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",- "font": "sans",- "size": 0.0476,- "weight": 400,- "italic": false,- "align": "left",- "leading": 1.55,- "tracking": 0,- "color": "#1a1a1a",- "binding": {- "source": "entry.story",- "entryId": 62- },- "overridden": false- },- {- "id": "li-w82p1lh",- "frame": {- "x": 1.1161,- "y": 0.6769,- "w": 0.7837,- "h": 0.0731- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#ffffff",- "accent": "#ffffff",- "textScale": 1,- "weight": 700,- "stale": false,- "kind": "list",- "items": [- {- "text": "TEST1",- "tone": "pro"- },- {- "text": "TEST1",- "tone": "con"- }- ],- "layout": "columns",- "showMarks": true,- "proLabel": "PROS",- "conLabel": "Cons"- },- {- "id": "t-gabkf9x",- "frame": {- "x": 1.0762,- "y": 0.3843,- "w": 0.8476,- "h": 0.1917- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",- "font": "sans",- "size": 0.0476,- "weight": 400,- "italic": false,- "align": "left",- "leading": 1.55,- "tracking": 0,- "color": "#1a1a1a",- "binding": {- "source": "entry.story",- "entryId": 62- },- "overridden": false- },- {- "id": "s-vkl7noe",- "frame": {- "x": 1.0762,- "y": 0.6034,- "w": 0.5,- "h": 0.0024- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "shape",- "shape": "rect",- "fill": "#141414",- "gradient": "none",- "stroke": null,- "strokeWidth": 0,- "strokeStyle": "solid",- "radius": 0- },- {- "id": "p-s3anbzj",- "frame": {- "x": 0.1836,- "y": 0.7134,- "w": 0.2,- "h": 0.2171- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": 68,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "polaroid"- },- {- "id": "p-874qk6j",- "frame": {- "x": 0.5893,- "y": 0.7134,- "w": 0.2,- "h": 0.2171- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": 69,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": "heart",- "frameStyle": "polaroid"- },- {- "id": "b-gmtenyt",- "frame": {- "x": 0.5993,- "y": 0.8893,- "w": 0.18,- "h": 0.05- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#111111",- "textScale": 1.2,- "weight": 700,- "stale": false,- "kind": "badge",- "variant": "coords",- "text": "51°10'N 10°27'E",- "sub": "",- "code": null,- "style": "plain",- "autoColor": true,- "showIcon": true,- "showLabel": true,- "autoIconColor": true,- "iconColor": "#111111"- },- {- "id": "b-4rd95kg",- "frame": {- "x": 0.1936,- "y": 0.8893,- "w": 0.18,- "h": 0.05- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#111111",- "textScale": 1.2,- "weight": 700,- "stale": false,- "kind": "badge",- "variant": "coords",- "text": "51°10'N 10°27'E",- "sub": "",- "code": null,- "style": "plain",- "autoColor": true,- "showIcon": true,- "showLabel": true,- "autoIconColor": true,- "iconColor": "#111111"- }- ],- },- {- id: 'ref-3',- background: null,- elements: [- {- "id": "p-sa5cabi",- "frame": {- "x": 0.025,- "y": 0.025,- "w": 1.9512,- "h": 0.5919- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "t-kws7inb",- "frame": {- "x": 0.054,- "y": 0.688,- "w": 0.8919,- "h": 0.2294- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet",- "font": "sans",- "size": 0.2381,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.title",- "entryId": 62- },- "overridden": false- },- {- "id": "t-1zzydde",- "frame": {- "x": 1.0808,- "y": 0.6542,- "w": 0.8385,- "h": 0.1917- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",- "font": "sans",- "size": 0.0476,- "weight": 400,- "italic": false,- "align": "left",- "leading": 1.55,- "tracking": 0,- "color": "#1a1a1a",- "binding": {- "source": "entry.story",- "entryId": 62- },- "overridden": false- },- {- "id": "t-kht4sfu",- "frame": {- "x": 0.054,- "y": 0.6542,- "w": 0.36,- "h": 0.0314- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "August 19, 2026",- "font": "sans",- "size": 0.0762,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.date",- "entryId": 62,- "value": "2026-08-19"- },- "overridden": false- }- ],- },- {- id: 'ref-4',- background: null,- elements: [- {- "id": "s-19c5q0x",- "frame": {- "x": -0.1119,- "y": 0.4164,- "w": 0.7143,- "h": 0.7143- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "shape",- "shape": "ellipse",- "fill": "#141414",- "gradient": "none",- "stroke": null,- "strokeWidth": 0,- "strokeStyle": "solid",- "radius": 0- },- {- "id": "p-e8ee9j8",- "frame": {- "x": 0.0816,- "y": 0.0763,- "w": 0.3367,- "h": 0.3827- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "polaroid"- },- {- "id": "p-fimcc5x",- "frame": {- "x": 0.5662,- "y": 0.202,- "w": 0.3367,- "h": 0.3827- },- "rotation": -10.1,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "polaroid"- },- {- "id": "p-nva57q1",- "frame": {- "x": 0.1739,- "y": 0.5,- "w": 0.3367,- "h": 0.3827- },- "rotation": 5.1,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": "seal",- "frameStyle": "polaroid"- },- {- "id": "t-7zfrwms",- "frame": {- "x": 1.0762,- "y": 0.1605,- "w": 0.8476,- "h": 0.0895- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet",- "font": "sans",- "size": 0.1429,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.title",- "entryId": 63- },- "overridden": false- },- {- "id": "t-culm58m",- "frame": {- "x": 1.0762,- "y": 0.2676,- "w": 0.8476,- "h": 0.2073- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",- "font": "sans",- "size": 0.0476,- "weight": 400,- "italic": false,- "align": "left",- "leading": 1.55,- "tracking": 0,- "color": "#1a1a1a",- "binding": {- "source": "entry.story",- "entryId": 62- },- "overridden": false- },- {- "id": "li-dukbgme",- "frame": {- "x": 1.0762,- "y": 0.5116,- "w": 0.72,- "h": 0.0731- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#c2410c",- "textScale": 1,- "weight": 700,- "stale": false,- "kind": "list",- "items": [- {- "text": "TEST1",- "tone": "pro"- },- {- "text": "TEST1",- "tone": "con"- }- ],- "layout": "columns",- "showMarks": true,- "proLabel": "Pros",- "conLabel": "Cons"- },- {- "id": "t-x3ysuxa",- "frame": {- "x": 1.0762,- "y": 0.116,- "w": 0.36,- "h": 0.0314- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "August 19, 2026",- "font": "sans",- "size": 0.069,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.date",- "entryId": 62,- "value": "2026-08-19"- },- "overridden": false- }- ],- },- {- id: 'ref-5',- background: null,- elements: [- {- "id": "p-adrg53f",- "frame": {- "x": 0.025,- "y": 0.025,- "w": 0.475,- "h": 0.9512- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "t-crm4sem",- "frame": {- "x": 0.5297,- "y": 0.119,- "w": 0.4258,- "h": 0.8012- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet",- "font": "sans",- "size": 0.2381,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.title",- "entryId": 62- },- "overridden": false- },- {- "id": "s-3dhohc7",- "frame": {- "x": 1.0762,- "y": 0.3541,- "w": 0.5,- "h": 0.0024- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "shape",- "shape": "rect",- "fill": "#f2f2f2",- "gradient": "none",- "stroke": "#141414",- "strokeWidth": 0.0005,- "strokeStyle": "solid",- "radius": 0- },- {- "id": "t-0l6zeg7",- "frame": {- "x": 1.0762,- "y": 0.119,- "w": 0.8346,- "h": 0.2047- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",- "font": "sans",- "size": 0.0476,- "weight": 400,- "italic": false,- "align": "left",- "leading": 1.55,- "tracking": 0,- "color": "#1a1a1a",- "binding": {- "source": "entry.story",- "entryId": 62- },- "overridden": false- },- {- "id": "p-igt1irs",- "frame": {- "x": 1.0762,- "y": 0.4469,- "w": 0.368,- "h": 0.2495- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "shadow"- },- {- "id": "p-2akhm3w",- "frame": {- "x": 1.5105,- "y": 0.4469,- "w": 0.368,- "h": 0.2495- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "shadow"- },- {- "id": "bd-g6o9fvm",- "frame": {- "x": 0.53,- "y": 0.4577,- "w": 0.2604,- "h": 0.062- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#111111",- "textScale": 1,- "weight": 700,- "stale": false,- "kind": "badge",- "variant": "weather",- "text": "Partly cloudy",- "sub": "",- "code": "partly",- "style": "chip",- "autoColor": true,- "showIcon": true,- "showLabel": true,- "autoIconColor": false,- "iconColor": "#ffffff"- },- {- "id": "bd-ewxvw6v",- "frame": {- "x": 0.53,- "y": 0.5406,- "w": 0.2607,- "h": 0.062- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#111111",- "textScale": 1,- "weight": 700,- "stale": false,- "kind": "badge",- "variant": "mood",- "text": "Amazing",- "sub": "",- "code": "amazing",- "style": "chip",- "autoColor": true,- "showIcon": true,- "showLabel": true,- "autoIconColor": false,- "iconColor": "#ffffff"- },- {- "id": "t-az8f0nc",- "frame": {- "x": 0.5297,- "y": 0.0858,- "w": 0.36,- "h": 0.0347- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "August 19, 2026",- "font": "sans",- "size": 0.0714,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.date",- "entryId": 62,- "value": "2026-08-19"- },- "overridden": false- }- ],- },- {- id: 'ref-6',- background: null,- elements: [- {- "id": "s-7go39mg",- "frame": {- "x": 0.0238,- "y": 0.309,- "w": 0.9524,- "h": 0.666- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "shape",- "shape": "triangle",- "fill": "#141414",- "gradient": "none",- "stroke": null,- "strokeWidth": 0,- "strokeStyle": "solid",- "radius": 0- },- {- "id": "p-a9065nh",- "frame": {- "x": 0.0238,- "y": 0.0238,- "w": 0.2745,- "h": 0.9512- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "p-fvcm5kq",- "frame": {- "x": 0.3628,- "y": 0.0914,- "w": 0.2745,- "h": 0.8848- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "p-aski19e",- "frame": {- "x": 0.7017,- "y": 0.0238,- "w": 0.2745,- "h": 0.9512- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "p-tfs5cdi",- "frame": {- "x": 1.0238,- "y": 0.0238,- "w": 0.9524,- "h": 0.45- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "photo",- "photoId": null,- "fit": "cover",- "focalX": 0.5,- "focalY": 0.5,- "radius": 0,- "filter": "none",- "mask": null,- "frameStyle": "none"- },- {- "id": "t-9zjrvsn",- "frame": {- "x": 1.0592,- "y": 0.5,- "w": 0.8476,- "h": 0.0518- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet",- "font": "sans",- "size": 0.1048,- "weight": 700,- "italic": false,- "align": "left",- "leading": 1.1,- "tracking": -0.02,- "color": "#1a1a1a",- "binding": {- "source": "entry.title",- "entryId": 62- },- "overridden": false- },- {- "id": "t-4lgyrab",- "frame": {- "x": 1.0592,- "y": 0.5682,- "w": 0.8476,- "h": 0.1995- },- "rotation": 0,- "opacity": 1,- "locked": false,- "kind": "text",- "text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",- "font": "sans",- "size": 0.0476,- "weight": 400,- "italic": false,- "align": "left",- "leading": 1.55,- "tracking": 0,- "color": "#1a1a1a",- "binding": {- "source": "entry.story",- "entryId": 62- },- "overridden": false- },- {- "id": "li-93gcznw",- "frame": {- "x": 1.0592,- "y": 0.7876,- "w": 0.72,- "h": 0.0731- },- "rotation": 0,- "opacity": 1,- "locked": false,- "font": "sans",- "color": "#1a1a1a",- "accent": "#c2410c",- "textScale": 1,- "weight": 700,- "stale": false,- "kind": "list",- "items": [- {- "text": "TEST1",- "tone": "pro"- },- {- "text": "TEST1",- "tone": "con"- }- ],- "layout": "columns",- "showMarks": true,- "proLabel": "Pros",- "conLabel": "Cons"- }- ],- },-]diff --git a/client/src/components/Studio/entryText.ts b/client/src/components/Studio/entryText.tsdeleted file mode 100644index 7b9459be0..000000000--- a/client/src/components/Studio/entryText.ts+++ /dev/null@@ -1,63 +0,0 @@-/**- * The words a journal entry lends to a page.- *- * Three things print an entry's date or its point: the chips in the Entries- * tab, the template filler, and the auto layout. They used to do it with five- * private helpers between them — two long-date formatters that were copies of- * each other, and three coordinate formatters, one of which printed degrees and- * minutes where the other two printed seconds. A journey-wide mark and an entry- * mark on the same spread read as a bug when they disagree by a notation.- *- * There is a second, harder reason for one implementation. A bound element is- * re-read when the book is opened (see resolveBindings.ts), and re-reading is- * only invisible while the resolver produces exactly the string the chip- * produced. One character of drift and every open rewrites the element, which- * the autosave then writes back — a book that saves itself every time someone- * looks at it. Sharing the function is what holds that invariant.- */--export type CoordFormat = 'dms' | 'decimal'--/** One axis, as degrees, minutes and seconds. */-function dms(v: number, pos: string, neg: string): string {- const hemisphere = v >= 0 ? pos : neg- const abs = Math.abs(v)- const deg = Math.floor(abs)- const min = Math.floor((abs - deg) * 60)- const sec = Math.round((((abs - deg) * 60) - min) * 60)- return `${deg}° ${min}' ${sec}" ${hemisphere}`-}--/**- * A point, set for print.- *- * Neither form carries a minus sign: a printed page says 33° 51' S, not- * -33.8688, and the hemisphere letter is both shorter and unambiguous. Decimal- * keeps four places — about eleven metres, which is the width of the building- * you were standing next to and finer than a book needs.- */-export function formatBookCoords(lat: number, lng: number, format: CoordFormat = 'dms'): string {- if (format === 'decimal') {- const dec = (v: number, pos: string, neg: string) =>- `${Math.abs(v).toFixed(4)}° ${v >= 0 ? pos : neg}`- return `${dec(lat, 'N', 'S')} ${dec(lng, 'E', 'W')}`- }- return `${dms(lat, 'N', 'S')} ${dms(lng, 'E', 'W')}`-}--/**- * The entry's day, spelled out.- *- * Parsed at local midnight rather than as UTC, because the date on a journal- * entry is the day the writer had, not an instant — reading it as UTC moves it- * a day backwards for anyone west of Greenwich. Note this is deliberately not- * `utils/formatters.ts:formatDate`, which is the short weekday form the sidebar- * badges use and hides the year inside the current one; a page in a book that- * outlives the year has to say which year it was.- */-export function formatBookDate(iso: string | null, locale: string): string {- if (!iso) return ''- const d = new Date(`${iso}T00:00:00`)- if (Number.isNaN(d.getTime())) return ''- return d.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric' })-}diff --git a/client/src/components/Studio/iconLibrary.ts b/client/src/components/Studio/iconLibrary.tsindex a015263a6..a0997a880 100644--- a/client/src/components/Studio/iconLibrary.ts+++ b/client/src/components/Studio/iconLibrary.ts@@ -1,6 +1,7 @@import * as LucideIcons from 'lucide-react'import { resolvePluginIcon } from '../shared/PluginIcon'import type { LucideIcon } from 'lucide-react'+import { BOOK_DESIGN_ICONS } from '@trek/shared'/*** Every drawing in lucide, as a list a picker can show.@@ -58,19 +59,12 @@ export const ICON_NAMES: string[] = buildNames()* Filtered against the real export list, so a lucide version that renames one* of them quietly drops it instead of drawing a fallback in the shelf.*/-const FEATURED = [- 'Plane', 'Train', 'TrainFront', 'Car', 'Bus', 'Ship', 'Bike', 'Footprints', 'Sailboat',- 'MapPin', 'Map', 'Compass', 'Navigation', 'Route', 'Globe', 'Milestone', 'Signpost',- 'Mountain', 'MountainSnow', 'Waves', 'TreePine', 'Palmtree', 'Flower2', 'Leaf', 'Bird', 'Fish',- 'Sun', 'Sunrise', 'Sunset', 'Moon', 'Cloud', 'CloudRain', 'CloudLightning', 'Snowflake',- 'Umbrella', 'Thermometer', 'Wind',- 'Tent', 'Backpack', 'Luggage', 'BedDouble', 'Hotel', 'Key', 'Anchor',- 'Coffee', 'UtensilsCrossed', 'Wine', 'Beer', 'IceCream', 'Croissant',- 'Camera', 'Image', 'Film', 'Music', 'BookOpen', 'PenLine', 'Quote', 'Sticker',- 'Heart', 'Star', 'Sparkles', 'Flag', 'Ticket', 'Gift', 'PartyPopper',- 'Clock', 'CalendarDays', 'CreditCard', 'Wallet', 'ShoppingBag',- 'Landmark', 'Church', 'Castle', 'Building2', 'Home', 'Binoculars', 'Telescope',-]+/*+ * The shelf itself lives in @trek/shared (book-icons.ts), because the book+ * engine places icons from the same list: the assistant may only name a+ * drawing a person could pick here.+ */+const FEATURED: readonly string[] = BOOK_DESIGN_ICONS/** The starter shelf, minus anything this version of lucide does not have. */export const FEATURED_ICONS: string[] = FEATURED.filter(name => ICON_NAMES.includes(name))diff --git a/client/src/components/Studio/mapSources.ts b/client/src/components/Studio/mapSources.tsindex fbf89f4e6..e127c363b 100644--- a/client/src/components/Studio/mapSources.ts+++ b/client/src/components/Studio/mapSources.ts@@ -1,4 +1,5 @@import type { BookFrame } from '@trek/shared'+import { BOOK_RELIEF_TILES, BOOK_SATELLITE_TILES } from '@trek/shared'import { attributionFor } from './mapTiles'/**@@ -72,9 +73,7 @@ export function sourceIdOf(el: { source: string; tileUrl: string }, options: Map* reverse of the slippy convention. The substitution is by name, so the order* in the template is all that matters.*/-const RELIEF_TILES = 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best'- + '/BlueMarble_ShadedRelief_Bathymetry/default/GoogleMapsCompatible_Level8'- + '/{z}/{y}/{x}.jpeg'+const RELIEF_TILES = BOOK_RELIEF_TILES/*** Real satellite imagery, and the answer to what relief cannot do.@@ -97,8 +96,7 @@ const RELIEF_TILES = 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best'* Attribution is not optional under that licence, which is why it travels into* the document with the source.*/-const SATELLITE_TILES = 'https://tiles.maps.eox.at/wmts/1.0.0'- + '/s2cloudless_3857/default/g/{z}/{y}/{x}.jpg'+const SATELLITE_TILES = BOOK_SATELLITE_TILES/*** What a book may be made of.diff --git a/client/src/components/Studio/resolveBindings.ts b/client/src/components/Studio/resolveBindings.tsindex 2a39f58da..d62a84478 100644--- a/client/src/components/Studio/resolveBindings.ts+++ b/client/src/components/Studio/resolveBindings.ts@@ -1,6 +1,5 @@import type { BookDocument } from '@trek/shared'-import { MAX_TEXT_LENGTH } from '@trek/shared'-import { formatBookCoords, formatBookDate } from './entryText'+import { MAX_TEXT_LENGTH, bookCoordValue, formatBookCoords, formatBookDate } from '@trek/shared'/*** Reading a book's bound text back out of the journey.@@ -137,7 +136,7 @@ function resolveOne(binding: Binding, src: BindingSource, locale: string): Resol// the field is genuinely absent rather than defaulted.if (!binding.format) return { text: entry.location ?? '' }if (entry.lat == null || entry.lng == null) return null- const value = coordValue(entry.lat, entry.lng)+ const value = bookCoordValue(entry.lat, entry.lng)if (!binding.value || binding.value === value) return nullreturn { text: formatBookCoords(entry.lat, entry.lng, binding.format), value }}@@ -145,8 +144,3 @@ function resolveOne(binding: Binding, src: BindingSource, locale: string): Resoldefault: return null}}--/** What a point is, as one string, for the comparison above. */-export function coordValue(lat: number, lng: number): string {- return `${lat},${lng}`-}diff --git a/client/src/components/Studio/travelRefresh.ts b/client/src/components/Studio/travelRefresh.tsdeleted file mode 100644index 7a2f1a31c..000000000--- a/client/src/components/Studio/travelRefresh.ts+++ /dev/null@@ -1,142 +0,0 @@-import type { BookElement, JourneyStats } from '@trek/shared'--/**- * Keeping a travel element in step with the journey it came from.- *- * A travel element carries its own values — see the note in `book.schema.ts` —- * which is what lets the print renderer work without a network. The cost is- * that a journey edited afterwards leaves the page holding yesterday's numbers,- * and these two functions are how the editor offers to fix that without ever- * doing it behind the user's back.- *- * Pure, and separate from the inspector that calls them, so the rules can be- * tested against literal objects rather than through a rendered panel.- */--/** The metrics a stats element can show, resolved from live figures. */-export function liveMetrics(stats: JourneyStats): Record<string, number> {- return {- distance: stats.distance,- days: stats.days,- steps: stats.steps,- photos: stats.photos,- countries: stats.countries.length,- places: stats.places,- furthest: stats.furthest,- }-}--/**- * Whether an element's stored values still match the journey.- *- * Compared, not tracked with a timestamp. A timestamp would say "the journey- * was edited", which is true every time anyone fixes a typo in a caption, and- * would mark a summary page stale over a change that did not move a single- * number on it.- *- * Only the figures the element actually shows are compared, for the same- * reason: a page showing distance and days does not go stale because a- * photograph was added.- */-export function isStale(el: BookElement, stats: JourneyStats | null): boolean {- if (!stats) return false-- if (el.kind === 'stats') {- const live = liveMetrics(stats)- return el.metrics.some(m => (el.values[m] ?? 0) !== live[m])- }- if (el.kind === 'countries') {- return el.codes.join(',') !== stats.countries.map(c => c.code).join(',')- }- if (el.kind === 'map') {- // Against the route this map is of, which is not always the whole journey.- const live = routeFor(stats, el.tripId)- // The route is compared by shape rather than element-by-element: a- // four-hundred-point deep-equal on every render would cost more than it- // could ever catch, and a changed route almost always changes its length or- // one of its ends.- if (el.points.length !== live.length) return true- if (!el.points.length) return false- const a = el.points[0]- const b = live[0]- const y = el.points[el.points.length - 1]- const z = live[live.length - 1]- if (a.lat !== b.lat || a.lng !== b.lng || y.lat !== z.lat || y.lng !== z.lng) return true-- /*- * And whether the photographs moved.- *- * A marker draws the entry's own first picture, so adding one to an entry- * changes the map without moving a single stop — the shape test above would- * never notice, and the only way to get the picture onto the page was to- * delete the map and place it again.- *- * Compared in full rather than by its ends, unlike the coordinates: a photo- * added to the middle of a journey is the ordinary case, where a stop added- * to the middle is not. It is a few hundred numbers joined into a string,- * which costs nothing next to the render it happens in.- */- const shown = el.points.map(p => p.photoId ?? 0).join(',')- const now = live.map(p => p.photoId ?? 0).join(',')- return shown !== now- }- return false-}--/**- * The stops a map of this scope should draw.- *- * `null` is the journey entire. A trip id narrows it to that trip's own stops,- * which is the difference between a book with one map of everywhere and a book- * with a page per trip — and, on a journey made of two trips, the difference- * between a route and a route with an eight-hundred-kilometre ruler line across- * the middle of it joining two places nobody travelled between.- */-export function routeFor(stats: JourneyStats, tripId: number | null): JourneyStats['points'] {- if (tripId == null) return stats.points- return stats.points.filter(p => p.tripId === tripId)-}--/**- * The patch that takes an element's values from the journey as it stands now.- *- * Returns null for an element that carries no journey figures, so a caller can- * offer refresh for the whole selection and let the ones that have nothing to- * refresh say so.- */-export function refreshPatch(el: BookElement, stats: JourneyStats): Partial<BookElement> | null {- if (el.kind === 'stats') {- return { stale: false, values: liveMetrics(stats) } as Partial<BookElement>- }-- if (el.kind === 'countries') {- const codes = stats.countries.map(c => c.code)- return {- stale: false,- codes,- // A country the element already had keeps the name it was given, which is- // the one in the book's language; a new country falls back to the API's- // English until someone re-places the element.- names: codes.map((code, i) => {- const had = el.codes.indexOf(code)- return had >= 0 ? (el.names[had] ?? code) : (stats.countries[i]?.name ?? code)- }),- } as Partial<BookElement>- }-- if (el.kind === 'map') {- const live = routeFor(stats, el.tripId)- return {- stale: false,- // Only the countries this map's own stops fall in: a map of one trip that- // listed every country in the journey would outline places it does not- // show.- countries: el.tripId == null- ? stats.countries.map(c => c.code)- : [...new Set(live.map(p => p.country).filter((c): c is string => !!c))],- points: live.map(p => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: p.photoId ?? null })),- } as Partial<BookElement>- }-- return null-}diff --git a/client/src/pages/journeyStudio/useJourneyStudio.test.tsx b/client/src/pages/journeyStudio/useJourneyStudio.test.tsxindex ce50cd1cf..a4ae91a96 100644--- a/client/src/pages/journeyStudio/useJourneyStudio.test.tsx+++ b/client/src/pages/journeyStudio/useJourneyStudio.test.tsx@@ -35,12 +35,11 @@ vi.mock('../../api/websocket', async importOriginal => ({sendBookCursor: vi.fn(),}))-const autoLayout = await vi.importActual<typeof import('../../components/Studio/autoLayout')>(- '../../components/Studio/autoLayout',-)-const buildBook = vi.fn(autoLayout.buildBook)-vi.mock('../../components/Studio/autoLayout', async importOriginal => {- const actual = await importOriginal<typeof import('../../components/Studio/autoLayout')>()+// The auto layout lives in @trek/shared now; the hook's call into it is watched through a partial mock.+const shared = await vi.importActual<typeof import('@trek/shared')>('@trek/shared')+const buildBook = vi.fn(shared.buildBook)+vi.mock('@trek/shared', async importOriginal => {+ const actual = await importOriginal<typeof import('@trek/shared')>()return { ...actual, buildBook: (...args: Parameters<typeof actual.buildBook>) => buildBook(...args) }})diff --git a/client/src/pages/journeyStudio/useJourneyStudio.ts b/client/src/pages/journeyStudio/useJourneyStudio.tsindex 3d4929497..b88aca375 100644--- a/client/src/pages/journeyStudio/useJourneyStudio.ts+++ b/client/src/pages/journeyStudio/useJourneyStudio.ts@@ -1,7 +1,10 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'import { useLocation, useNavigate, useParams } from 'react-router'-import type { BookElement, BookPageNumbers, JourneyStats } from '@trek/shared'-import { bookElementId as elementId, bookPageSetupSchema } from '@trek/shared'+import type { AutoEntry, AutoInput, AutoPhoto, BookElement, BookPageNumbers, JourneyStats } from '@trek/shared'+import {+ autoEntriesWithStops, bookElementId as elementId, bookPageSetupSchema, bookPath, buildBook, distributeGallery,+ emptyBook, relayoutSpread,+} from '@trek/shared'import { journeyApi } from '../../api/client'import { useJourneyStore, type GalleryPhoto, type JourneyEntry, type JourneyPhoto } from '../../store/journeyStore'import { useStudioStore } from '../../store/studioStore'@@ -16,10 +19,6 @@ import type { ProviderPhotoGroup } from '../../components/Journey/JourneyDetailPimport { useProviderPhotoAdds } from '../journeyDetail/useProviderPhotoAdds'import { useIsMobile } from '../../hooks/useIsMobile'import { PAGE_PRESETS, clampPageSize, type PagePresetId } from '../../components/Studio/pagePresets'-import {- buildBook, distributeGallery, emptyBook, relayoutSpread,- type AutoEntry, type AutoInput, type AutoPhoto,-} from '../../components/Studio/autoLayout'import { resolveBindings } from '../../components/Studio/resolveBindings'/** CSS defines 1in as 96px and 25.4mm, so this factor is exact, not a guess. */@@ -50,40 +49,6 @@ export const STUDIO_INSET = 16* an editor that reflex would cost you the page you were working on. Only an* Escape with nothing selected leaves.*/-/**- * A journey's tracks, thinned to what a printed line can show.- *- * A three-week drive is hundreds of thousands of GPS fixes. At the size a map- * is printed, a point every fifteen metres and a point every kilometre are the- * same picture, and only one of them fits in a document that has to be saved,- * sent over a websocket and parsed on the other side.- *- * Thinned by taking every nth point rather than by simplifying the geometry:- * Douglas-Peucker would keep the shape better, and it is a hundred lines of- * code to gain something nobody can see at 60mm across. The ends of every- * segment are kept, because a track that stops short of where it ended reads- * as a bug.- */-export function bookPath(tracks: { points: readonly unknown[][] }[]): [number, number][][] {- const SEGMENTS = 40- const PER_SEGMENT = 600- const out: [number, number][][] = []- for (const track of tracks.slice(0, SEGMENTS)) {- // Normalised on the way in: the contract types a pair as a tuple, and Zod- // infers that loosely enough that the pair has to be rebuilt to stay one.- const pts = track.points- .map(p => [Number(p[0]), Number(p[1])] as [number, number])- .filter(p => Number.isFinite(p[0]) && Number.isFinite(p[1]))- if (pts.length < 2) continue- if (pts.length <= PER_SEGMENT) { out.push(pts); continue }- const step = (pts.length - 1) / (PER_SEGMENT - 1)- const thinned: [number, number][] = []- for (let i = 0; i < PER_SEGMENT; i++) thinned.push(pts[Math.round(i * step)])- out.push(thinned)- }- return out-}-/*** The page a Studio with no document yet reports.*@@ -301,36 +266,13 @@ export function useJourneyStudio() {const withPhotos = distributeGallery(entries, gallery)/*- * Give every entry what the journey's figures know about its stop.- *- * The entry carries a place name; the stats carry what that name resolved- * to — coordinates and a country. Matched by date first and by name second,- * because a day usually has one stop and two stops on one day are told- * apart by what they are called.- *- * With these a page can print the flag, the country's outline and the- * coordinates, which is most of what makes a printed travel page look like- * one rather than like a document.+ * Give every entry what the journey's figures know about its stop: the+ * coordinates and country its place resolved to and which day it is, so a+ * page can print the flag, the outline and the coordinates. The matching+ * is shared (autoEntriesWithStops) so the server's design tool reads the+ * same stops.*/- const points = stats?.points ?? []- const dayCount = stats?.days ?? null- const first = stats?.start ? Date.parse(`${stats.start}T00:00:00`) : Number.NaN- const placed = withPhotos.map(entry => {- const point = points.find(p => p.date && entry.date && p.date === entry.date)- ?? points.find(p => p.label && entry.location && p.label === entry.location)- const at = entry.date ? Date.parse(`${entry.date}T00:00:00`) : Number.NaN- const dayNumber = Number.isFinite(at) && Number.isFinite(first)- ? Math.floor((at - first) / 86_400_000) + 1- : null- return {- ...entry,- lat: point?.lat ?? null,- lng: point?.lng ?? null,- country: point?.country ?? null,- dayNumber: dayNumber && dayNumber > 0 ? dayNumber : null,- dayCount,- }- })+ const placed = autoEntriesWithStops(withPhotos, stats)const preset = PAGE_PRESETS['square-210']diff --git a/client/tests/unit/studio/applyTemplate.test.ts b/client/tests/unit/studio/applyTemplate.test.tsindex 3a8b7b28e..824499c22 100644--- a/client/tests/unit/studio/applyTemplate.test.ts+++ b/client/tests/unit/studio/applyTemplate.test.ts@@ -1,8 +1,14 @@import { describe, it, expect } from 'vitest'-import type { BookElement, JourneyStats } from '@trek/shared'-import { bookPageSetupSchema } from '@trek/shared'-import { applyTemplate, templateFit, type TemplateEntry } from '../../../src/components/Studio/applyTemplate'-import type { SpreadTemplate } from '../../../src/components/Studio/bookTemplates.data'+import type { AutoEntry, AutoTemplate, BookElement, JourneyStats } from '@trek/shared'+import { applyAutoTemplate, autoTemplateFit, bookElementId, bookPageSetupSchema } from '@trek/shared'++/** The client names these were written against, now the shared auto layout's. */+type SpreadTemplate = AutoTemplate+type TemplateEntry = AutoEntry+type TemplateContext = Omit<Parameters<typeof applyAutoTemplate>[2], 'newId'>+const templateFit = autoTemplateFit+const applyTemplate = (t: SpreadTemplate, e: TemplateEntry, ctx: TemplateContext) =>+ applyAutoTemplate(t, e, { ...ctx, newId: bookElementId })/*** Laying an entry onto a template somebody drew (#1973).diff --git a/client/tests/unit/studio/autoLayout.contract.test.ts b/client/tests/unit/studio/autoLayout.contract.test.tsindex a9186d564..01d7cd909 100644--- a/client/tests/unit/studio/autoLayout.contract.test.ts+++ b/client/tests/unit/studio/autoLayout.contract.test.ts@@ -1,7 +1,6 @@import { describe, it, expect } from 'vitest'import type { BookPageSetup, JourneyStats } from '@trek/shared'-import { bookDocumentSchema, bookPageSetupSchema } from '@trek/shared'-import { buildBook, emptyBook, type AutoEntry, type AutoInput } from '../../../src/components/Studio/autoLayout'+import { bookDocumentSchema, bookPageSetupSchema, buildBook, emptyBook, type AutoEntry, type AutoInput } from '@trek/shared'/*** The auto layout writes journey data straight into a book document, and thediff --git a/client/tests/unit/studio/autoLayout.stations.test.ts b/client/tests/unit/studio/autoLayout.stations.test.tsindex 3e4aa0826..28b82598d 100644--- a/client/tests/unit/studio/autoLayout.stations.test.ts+++ b/client/tests/unit/studio/autoLayout.stations.test.ts@@ -1,14 +1,13 @@-import { describe, it, expect, vi } from 'vitest'+import { describe, it, expect } from 'vitest'/*- * These cases are about the layouts written in autoLayout.ts, which are what an- * entry falls back on when no hand-drawn template suits it. With the real- * templates in place they would be testing whichever spread somebody last drew- * in Studio — so the set is empty here on purpose.+ * These cases are about the layouts written as code in the shared auto layout+ * (shared/src/book/auto), which are what an entry falls back on when no+ * hand-drawn template suits it. With the real templates in place they would be+ * testing whichever spread somebody last drew in Studio, so the input passes an+ * empty template set on purpose.*/-vi.mock('../../../src/components/Studio/bookTemplates.data', () => ({ SPREAD_TEMPLATES: [] }))-import { bookDocumentSchema, bookPageSetupSchema, type BookSpread } from '@trek/shared'-import { buildBook, type AutoEntry, type AutoInput } from '../../../src/components/Studio/autoLayout'+import { bookDocumentSchema, bookPageSetupSchema, buildBook, type AutoEntry, type AutoInput, type BookSpread } from '@trek/shared'/*** A journey with little in it (#1973).@@ -37,6 +36,7 @@ const rich = (id: number): AutoEntry => ({const document = (entries: AutoEntry[]) => buildBook({locale: 'en', title: 'T', subtitle: null, coverPhotoId: null,entries, page, stats: null, stationsLabel: 'Stations', dayLabel: 'DAY', summaryLabel: 'Trip summary', countriesLabel: 'Countries',+ templates: [],})function build(entries: AutoEntry[]): BookSpread[] {diff --git a/client/tests/unit/studio/autoLayout.travel.test.ts b/client/tests/unit/studio/autoLayout.travel.test.tsindex 6f04af806..c66aa97b8 100644--- a/client/tests/unit/studio/autoLayout.travel.test.ts+++ b/client/tests/unit/studio/autoLayout.travel.test.ts@@ -1,15 +1,14 @@-import { describe, it, expect, vi } from 'vitest'+import { describe, it, expect } from 'vitest'/*- * These cases are about the layouts written in autoLayout.ts, which are what an- * entry falls back on when no hand-drawn template suits it. With the real- * templates in place they would be testing whichever spread somebody last drew- * in Studio — so the set is empty here on purpose.+ * These cases are about the layouts written as code in the shared auto layout+ * (shared/src/book/auto), which are what an entry falls back on when no+ * hand-drawn template suits it. With the real templates in place they would be+ * testing whichever spread somebody last drew in Studio, so the inputs pass an+ * empty template set on purpose.*/-vi.mock('../../../src/components/Studio/bookTemplates.data', () => ({ SPREAD_TEMPLATES: [] }))-import type { BookPageSetup, BookSpread, JourneyStats } from '@trek/shared'-import { buildBook, emptyBook, type AutoEntry, type AutoInput } from '../../../src/components/Studio/autoLayout'-import { bookPageSetupSchema } from '@trek/shared'+import type { AutoEntry, AutoInput, BookPageSetup, BookSpread, JourneyStats } from '@trek/shared'+import { bookPageSetupSchema, buildBook, emptyBook } from '@trek/shared'/*** The auto layout, once it knows what the journey adds up to (#1973).@@ -62,6 +61,7 @@ function build(over: Partial<AutoInput> = {}) {entries: [entry()],page,stats: stats(),+ templates: [],...over,})}@@ -312,6 +312,7 @@ describe('an empty book', () => {entries: [entry()],page,stats: stats(),+ templates: [],}it('has a cover, a first page, a spread, a last page and a back cover, and nothing on any of them', () => {diff --git a/client/tests/unit/studio/entryText.test.ts b/client/tests/unit/studio/entryText.test.tsindex 1ef1d903c..77ff82a82 100644--- a/client/tests/unit/studio/entryText.test.ts+++ b/client/tests/unit/studio/entryText.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { formatBookCoords, formatBookDate } from '../../../src/components/Studio/entryText'+import { formatBookCoords, formatBookDate } from '@trek/shared'/*** The strings a journal entry lends to a page (#1973).diff --git a/client/tests/unit/studio/mapScope.test.ts b/client/tests/unit/studio/mapScope.test.tsindex 153a4ea59..6c5fb5f12 100644--- a/client/tests/unit/studio/mapScope.test.ts+++ b/client/tests/unit/studio/mapScope.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest'import type { BookElement, JourneyStats } from '@trek/shared'-import { isStale, refreshPatch, routeFor } from '../../../src/components/Studio/travelRefresh'+import { isStale, refreshPatch, routeFor } from '@trek/shared'/*** A map of one trip, out of a journey made of several (#1973).diff --git a/client/tests/unit/studio/pageSetup.test.tsx b/client/tests/unit/studio/pageSetup.test.tsxindex 9c8e7c5df..727837af8 100644--- a/client/tests/unit/studio/pageSetup.test.tsx+++ b/client/tests/unit/studio/pageSetup.test.tsx@@ -1,10 +1,9 @@import { describe, it, expect } from 'vitest'import type { BookPageSetup, BookSpread } from '@trek/shared'-import { bookPageSetupSchema, normalizeBookDocument } from '@trek/shared'+import { bookPageSetupSchema, normalizeBookDocument, relayoutSpread, type AutoInput } from '@trek/shared'import { render } from '../../helpers/render'import { SpreadView } from '../../../src/components/Studio/SpreadView'import { PAGE_MAX_MM, PAGE_MIN_MM, PAGE_PRESETS, clampPageSize } from '../../../src/components/Studio/pagePresets'-import { relayoutSpread, type AutoInput } from '../../../src/components/Studio/autoLayout'/*** A free trim size, page numbers, and laying out again (#1973).diff --git a/client/tests/unit/studio/resolveBindings.test.ts b/client/tests/unit/studio/resolveBindings.test.tsindex ecc39f63b..52814045c 100644--- a/client/tests/unit/studio/resolveBindings.test.ts+++ b/client/tests/unit/studio/resolveBindings.test.ts@@ -1,9 +1,7 @@import { describe, it, expect } from 'vitest'import type { BookDocument, BookElement } from '@trek/shared'-import { normalizeBookDocument } from '@trek/shared'-import {- resolveBindings, coordValue, type BindingSource,-} from '../../../src/components/Studio/resolveBindings'+import { bookCoordValue as coordValue, normalizeBookDocument } from '@trek/shared'+import { resolveBindings, type BindingSource } from '../../../src/components/Studio/resolveBindings'/*** A bound element catching up with the journal (#1973).diff --git a/client/tests/unit/studio/travelRefresh.test.ts b/client/tests/unit/studio/travelRefresh.test.tsindex 815c62650..61a9d215e 100644--- a/client/tests/unit/studio/travelRefresh.test.ts+++ b/client/tests/unit/studio/travelRefresh.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest'import type { BookElement, JourneyStats } from '@trek/shared'-import { isStale, liveMetrics, refreshPatch } from '../../../src/components/Studio/travelRefresh'+import { isStale, liveMetrics, refreshPatch } from '@trek/shared'/*** Keeping a travel element in step with its journey (#1973).diff --git a/server/scripts/extract-templates.cjs b/server/scripts/extract-templates.cjsindex f8a2f862e..5d0ff6a86 100644--- a/server/scripts/extract-templates.cjs+++ b/server/scripts/extract-templates.cjs@@ -4,13 +4,14 @@* Reads the book from a journey and writes the spreads out as data: every* measurement divided by the page it was drawn on, so the same template lays* out on an A4 landscape book as it does on the 210mm square it was designed- * for. Run from server/, output goes to the client.+ * for. Run from server/; the output is the shared auto layout's data file+ * (shared/src/book/auto/auto-templates.data.ts). Run Prettier on it before committing.*/const Database = require('better-sqlite3');const fs = require('fs');const JOURNEY = Number(process.argv[2] || 7);-const OUT = process.argv[3] || '../client/src/components/Studio/bookTemplates.data.ts';+const OUT = process.argv[3] || '../shared/src/book/auto/auto-templates.data.ts';const db = new Database('data/travel.db', { readonly: true });const row = db.prepare('SELECT document FROM journey_books WHERE journey_id = ?').get(JOURNEY);@@ -62,7 +63,7 @@ const body = spreads).join('\n');-const file = `import type { BookElement } from '@trek/shared'+const file = `import type { BookElement } from '../book.schema';/*** The spread templates, as data.@@ -97,16 +98,16 @@ const file = `import type { BookElement } from '@trek/shared'* was drawn.*/-export interface SpreadTemplate {- id: string- background: string | null- /** Frames and sizes are fractions — see the note above. */- elements: BookElement[]+export interface AutoTemplate {+ id: string;+ background: string | null;+ /** Frames and sizes are fractions; see the note above. */+ elements: BookElement[];}-export const SPREAD_TEMPLATES: SpreadTemplate[] = [+export const AUTO_TEMPLATES: readonly AutoTemplate[] = [${body}-]+];`;fs.writeFileSync(OUT, file);diff --git a/shared/src/book/auto/auto-book-spreads.ts b/shared/src/book/auto/auto-book-spreads.tsnew file mode 100644index 000000000..94ed336d4--- /dev/null+++ b/shared/src/book/auto/auto-book-spreads.ts@@ -0,0 +1,301 @@+import { formatBookDate } from '../book-text';+import {+ MAX_PATH_POINTS,+ MAX_PATH_SEGMENTS,+ MAX_SPREAD_ELEMENTS,+ type BookElement,+ type BookMetric,+ type BookSpread,+} from '../book.schema';+import type { JourneyStats } from '../journey-stats.schema';+import {+ ACCENT,+ badgeEl,+ bleedFrame,+ countriesEl,+ mapEl,+ photo,+ shape,+ statsEl,+ text,+ type NewId,+} from './auto-elements';+import type { AutoEntry, AutoInput } from './auto-types';++/**+ * The pages of a book that are not one entry's: the cover, the list of bare+ * stops, the journey at a glance, the countries and the back cover.+ */++/** What one station row costs (its date, its name and the rule under it), and the heading above the list. */+const STATION_ELEMENTS = 3;+const STATIONS_HEADING = 2;++/**+ * How many stations one page holds: thirteen is where the type gets too+ * tight, and a spread is two of these pages under `MAX_SPREAD_ELEMENTS`.+ */+const ROWS_THE_CAP_ALLOWS = Math.floor((MAX_SPREAD_ELEMENTS - STATIONS_HEADING) / STATION_ELEMENTS / 2);+export const STATIONS_PER_PAGE = Math.min(13, ROWS_THE_CAP_ALLOWS);++/** The span line's printed separator (an em dash), kept as the Studio has always set it. */+const SPAN_JOIN = ' \u2014 ';++export function coverSpread(input: AutoInput, newId: NewId): BookSpread {+ const { page } = input;+ const m = 18;+ const els: BookElement[] = [];+ const light = input.coverPhotoId != null;++ if (input.coverPhotoId != null) {+ els.push(photo(newId, bleedFrame(page, false), input.coverPhotoId, { focalY: 0.42 }));+ // A scrim so the title survives whatever the photo does underneath it, faded rather than a flat panel.+ const scrim = {+ x: -page.bleed,+ y: page.pageHeight * 0.38,+ w: page.pageWidth + page.bleed * 2,+ h: page.pageHeight * 0.62 + page.bleed,+ };+ els.push(shape(newId, scrim, '#000000', { opacity: 0.72, gradient: 'down' }));+ }++ const titleStyle = {+ size: 34,+ weight: 700 as const,+ leading: 1.05,+ tracking: -0.02,+ color: light ? '#ffffff' : '#111111',+ binding: { source: 'journey.title' as const },+ };+ const titleFrame = { x: m, y: page.pageHeight - m - 46, w: page.pageWidth - m * 2, h: 30 };+ els.push(text(newId, titleFrame, input.title, titleStyle));+ if (input.subtitle) {+ const subStyle = {+ size: 12,+ weight: 400 as const,+ color: light ? '#ffffff' : '#444444',+ opacity: light ? 0.85 : 1,+ binding: { source: 'journey.subtitle' as const },+ };+ const subFrame = { x: m, y: page.pageHeight - m - 12, w: page.pageWidth - m * 2, h: 8 };+ els.push(text(newId, subFrame, input.subtitle, subStyle));+ }+ const background = input.coverPhotoId != null ? null : '#f4f2ee';+ return { id: newId('sp'), role: 'cover', background, elements: els, parked: [], entryId: null };+}++/**+ * The stops that had nothing to say, as a list: two columns of date and+ * place, which is what an itinerary looks like in every printed travel book.+ * Consecutive ones only, so the book stays in the order it happened.+ */+export function stationsSpread(entries: AutoEntry[], input: AutoInput, newId: NewId): BookSpread {+ const { page } = input;+ const W = page.pageWidth;+ const H = page.pageHeight;+ const m = 18;+ const els: BookElement[] = [];++ els.push(shape(newId, { x: m, y: m + 12, w: 14, h: 0.5 }, ACCENT));+ const headStyle = { size: 8, weight: 600 as const, tracking: 0.16, color: '#8a8578' };+ els.push(text(newId, { x: m, y: m + 18, w: W - m * 2, h: 8 }, input.stationsLabel.toUpperCase(), headStyle));++ const columns = [entries.slice(0, STATIONS_PER_PAGE), entries.slice(STATIONS_PER_PAGE, STATIONS_PER_PAGE * 2)];+ const top = m + 34;+ const step = Math.min(13, (H - top - m) / Math.max(1, STATIONS_PER_PAGE));+ columns.forEach((column, side) => {+ const x = side * W + m;+ const w = W - m * 2;+ column.forEach((entry, i) => {+ const y = top + i * step;+ const date = formatBookDate(entry.date, input.locale);+ if (date) {+ // Set in small caps, so not the journal's words: a bound element has to hold exactly its source.+ const dateStyle = { size: 7, weight: 600 as const, tracking: 0.1, color: '#a09a8e' };+ els.push(text(newId, { x, y, w: w * 0.32, h: 5 }, date.toUpperCase(), dateStyle));+ }+ const name = entry.title || entry.location || '';+ if (name) {+ const nameStyle = {+ size: 11,+ weight: 600 as const,+ color: '#141414',+ binding: { source: 'entry.title' as const, entryId: entry.id },+ };+ els.push(text(newId, { x: x + w * 0.34, y: y - 1.5, w: w * 0.66, h: 7 }, name, nameStyle));+ }+ // A hairline under each row, the way a printed itinerary rules its lines.+ els.push(shape(newId, { x, y: y + step - 4.5, w, h: 0.15 }, '#ddd8cf'));+ });+ });+ return { id: newId('sp'), role: 'inner', background: '#faf8f4', elements: els, parked: [], entryId: null };+}++/** The stop that ended up furthest from the first one. */+function furthestPoint(stats: JourneyStats) {+ const home = stats.points[0];+ if (!home) return null;+ let best = home;+ let bestD = 0;+ for (const p of stats.points) {+ const d = Math.hypot(p.lat - home.lat, (p.lng - home.lng) * Math.cos((home.lat * Math.PI) / 180));+ if (d > bestD) {+ bestD = d;+ best = p;+ }+ }+ return best;+}++/** Metres as the books print them, "1,189 km", in the book's own language. */+function formatKm(metres: number, locale: string): string {+ return `${Math.round(metres / 1000).toLocaleString(locale)} km`;+}++/** Which figures are worth the space: everything the journey actually has, at most six. */+function summaryMetrics(stats: JourneyStats): BookMetric[] {+ const all: [BookMetric, number][] = [+ ['distance', stats.distance],+ ['days', stats.days],+ ['steps', stats.steps],+ ['photos', stats.photos],+ ['countries', stats.countries.length],+ ['furthest', stats.furthest],+ ];+ return all+ .filter(([, v]) => v > 0)+ .map(([k]) => k)+ .slice(0, 6);+}++/** The furthest point, drawn: two dots, a line and a distance. */+function furthestMarks(+ input: AutoInput,+ stats: JourneyStats,+ newId: NewId,+ at: { x: number; w: number },+): BookElement[] {+ const home = stats.points[0];+ const far = furthestPoint(stats);+ if (!(stats.furthest > 0 && home && far && far !== home)) return [];+ const H = input.page.pageHeight;+ const y = H - 18 - 26;+ const lineW = at.w - 16;+ const rx = at.x;+ const els: BookElement[] = [shape(newId, { x: rx + 8, y, w: lineW, h: 0.3 }, '#cfc9bd')];+ for (const t of [0, 1]) {+ const dot = { x: rx + 8 + lineW * t - 1.4, y: y - 1.25, w: 2.8, h: 2.8 };+ els.push(shape(newId, dot, t === 0 ? '#8a8578' : ACCENT, { shape: 'ellipse' }));+ }+ const chip = { x: rx + 8 + lineW * 0.5 - 17, y: y - 11, w: 34, h: 8 };+ const km = { text: formatKm(stats.furthest, input.locale) };+ els.push(badgeEl(newId, chip, 'distance', km, { style: 'chip', textScale: 0.7 }));+ const label = { size: 6.5, weight: 600 as const, tracking: 0.1, color: '#8a8578' };+ els.push(text(newId, { x: rx + 4, y: y + 4, w: lineW * 0.5, h: 5 }, (home.label || '').toUpperCase(), label));+ const farFrame = { x: rx + 4 + lineW * 0.5, y: y + 4, w: lineW * 0.5 + 4, h: 5 };+ els.push(text(newId, farFrame, (far.label || '').toUpperCase(), { ...label, align: 'right' }));+ return els;+}++/**+ * The journey at a glance: the route drawn on the left, what it came to on the+ * right. Omitted rather than left empty when there is nothing to draw.+ */+export function summarySpread(input: AutoInput, newId: NewId): BookSpread | null {+ const stats = input.stats;+ if (!stats) return null;+ // Something has to be worth printing. One stop is a pin, not a journey.+ if (stats.points.length < 2 && !stats.distance && !stats.days) return null;+ const { page } = input;+ const W = page.pageWidth;+ const H = page.pageHeight;+ const m = 18;+ const els: BookElement[] = [];++ if (stats.points.length >= 2) {+ const path = (input.path ?? []).slice(0, MAX_PATH_SEGMENTS).map((seg) => seg.slice(0, MAX_PATH_POINTS));+ els.push(mapEl(newId, { x: m, y: m, w: W - m * 2, h: H - m * 2 }, stats, { path }));+ }+ const metrics = summaryMetrics(stats);+ const rx = W + m;+ const colW = W - m * 2;+ els.push(shape(newId, { x: rx, y: m + 14, w: colW * 0.16, h: 0.5 }, ACCENT));+ const headStyle = { size: 9, weight: 700 as const, tracking: 0.18, color: '#141414' };+ els.push(text(newId, { x: rx, y: m + 20, w: colW, h: 7 }, input.summaryLabel.toUpperCase(), headStyle));+ if (metrics.length) els.push(statsEl(newId, { x: rx, y: m + 36, w: colW, h: H * 0.42 }, stats, metrics, 'grid'));+ els.push(...furthestMarks(input, stats, newId, { x: rx, w: colW }));+ return { id: newId('sp'), role: 'inner', background: null, elements: els, parked: [], entryId: null };+}++/** Pale outlines on near-black, names above them: the page people photograph. Two countries or more. */+export function countriesSpread(input: AutoInput, names: string[], newId: NewId): BookSpread | null {+ const stats = input.stats;+ if (!stats || stats.countries.length < 2) return null;+ const { page } = input;+ const W = page.pageWidth;+ const H = page.pageHeight;+ const m = 20;+ const rows = stats.countries.length;+ // Tall enough to breathe, but never taller than the page it sits on.+ const height = Math.min(H - m * 2 - 24, Math.max(H * 0.4, rows * 26));+ const ink = '#f2efe9';+ const headStyle = { size: 9, weight: 700 as const, tracking: 0.2, align: 'center' as const, color: ink };+ const headFrame = { x: W + m, y: m + 16, w: W - m * 2, h: 8 };+ const head = text(newId, headFrame, input.countriesLabel.toUpperCase(), headStyle);+ const frame = { x: W + m, y: (H - height) / 2 + 10, w: W - m * 2, h: height };+ const outlines = countriesEl(newId, frame, stats, names, { color: ink, accent: ink });+ return {+ id: newId('sp'),+ role: 'inner',+ background: '#12161d',+ elements: [head, outlines],+ parked: [],+ entryId: null,+ };+}++/** The back cover: quiet on purpose, the last thing a reader sees should be a full stop. */+export function backSpread(input: AutoInput, newId: NewId): BookSpread {+ const { page } = input;+ const m = 18;+ const els: BookElement[] = [];+ const dates = input.entries+ .map((e) => e.date)+ .filter((d): d is string => !!d)+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));+ const first = dates[0];+ const last = dates[dates.length - 1];+ const ends = first && last ? [formatBookDate(first, input.locale), formatBookDate(last, input.locale)] : [];+ const span = ends.filter(Boolean).join(SPAN_JOIN);++ els.push(shape(newId, bleedFrame(page, false), '#141414'));+ const titleStyle = {+ size: 15,+ weight: 600 as const,+ align: 'center' as const,+ color: '#ffffff',+ tracking: -0.01,+ binding: { source: 'journey.title' as const },+ };+ const titleFrame = { x: m, y: page.pageHeight * 0.5 - 16, w: page.pageWidth - m * 2, h: 12 };+ els.push(text(newId, titleFrame, input.title, titleStyle));+ if (span) {+ const spanStyle = { size: 8.5, align: 'center' as const, color: '#ffffff', opacity: 0.55 };+ els.push(text(newId, { x: m, y: page.pageHeight * 0.5, w: page.pageWidth - m * 2, h: 6 }, span, spanStyle));+ }+ // The closing tally, as a figures element: it takes its labels from the Studio's translations.+ if (input.stats) {+ const tally: [BookMetric, number][] = [+ ['days', input.stats.days],+ ['places', input.stats.places],+ ['photos', input.stats.photos],+ ];+ const closing = tally.filter(([, v]) => v > 0).map(([k]) => k);+ if (closing.length) {+ const quiet = { showIcons: false, color: '#ffffff', accent: '#ffffff', opacity: 0.55, textScale: 0.8 };+ const frame = { x: m, y: page.pageHeight * 0.5 + 6, w: page.pageWidth - m * 2, h: 22 };+ els.push(statsEl(newId, frame, input.stats, closing, 'row', quiet));+ }+ }+ return { id: newId('sp'), role: 'back', background: '#141414', elements: els, parked: [], entryId: null };+}diff --git a/shared/src/book/auto/auto-book.ts b/shared/src/book/auto/auto-book.tsnew file mode 100644index 000000000..2c0fdc7a3--- /dev/null+++ b/shared/src/book/auto/auto-book.ts@@ -0,0 +1,231 @@+import { bookElementId } from '../book-ids';+import { blankBook, blankSpread } from '../book-pages';+import { MAX_BOOK_TITLE, MAX_SPREADS, type BookDocument, type BookPageSetup, type BookSpread } from '../book.schema';+import type { JourneyStats } from '../journey-stats.schema';+import {+ STATIONS_PER_PAGE,+ backSpread,+ countriesSpread,+ coverSpread,+ stationsSpread,+ summarySpread,+} from './auto-book-spreads';+import { countryNames, isPano, type NewId } from './auto-elements';+import {+ bandSpread,+ gallerySpread,+ immersiveSpread,+ panelSpread,+ panoSpread,+ placeSpread,+ storySpread,+ type EntryContext,+} from './auto-spreads';+import { applyAutoTemplate, autoTemplateFit } from './auto-template-apply';+import { AUTO_TEMPLATES } from './auto-templates.data';+import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';++/**+ * The auto mode: turn a journey into a book.+ *+ * The one rule that shapes everything else is that this produces an ordinary+ * document. There is no "auto layout" state that locks, no template engine+ * that re-runs behind the user's back: it lays the pages out once, and from+ * that moment every element is as editable as one dragged in by hand.+ *+ * Templates are chosen by what the material actually is: how many photos the+ * entry has, whether they are portrait or landscape, how much story there is+ * to set. Moved here from the Studio (client/src/components/Studio/autoLayout.ts)+ * so the Studio and the server's design tool lay a book out the same way;+ * `auto-layout.parity.spec.ts` holds the move to the old code's output.+ */++const idsOf = (input: AutoInput): NewId => input.newId ?? bookElementId;++/**+ * Whether an entry has anything to fill a spread with. A journey built from a+ * trip starts as one skeleton entry per stop: a date, a place name, nothing+ * else. Those share a list rather than taking a spread each.+ */+export function autoEntryHasSubstance(entry: AutoEntry): boolean {+ return entry.photos.length > 0 || !!(entry.story || '').trim();+}++/**+ * A hand-drawn template for this entry, if one of them fits. Tried before the+ * layouts written as code: a page somebody designed beats a page a function+ * reasoned its way to. Rotated by position so a run of similar entries does+ * not come out as a run of identical pages.+ */+function templateSpread(entry: AutoEntry, input: AutoInput, index: number, newId: NewId): BookSpread | null {+ const templates = input.templates ?? AUTO_TEMPLATES;+ const scored = templates+ .map((t) => ({ t, fit: autoTemplateFit(t, entry) }))+ .filter((x) => x.fit >= 0)+ .sort((a, b) => b.fit - a.fit);+ const best = scored[0];+ if (!best) return null;+ // Everything within a few points of the best is equally suitable, so the position picks between them.+ const equals = scored.filter((x) => x.fit >= best.fit - 5);+ const pick = equals[index % equals.length] ?? best;+ const ctx = { page: input.page, locale: input.locale, stats: input.stats, dayLabel: input.dayLabel, newId };+ return applyAutoTemplate(pick.t, entry, ctx);+}++/**+ * One entry, one spread: a drawn template when one fits, else one of the+ * layouts written as code, by contents first (a panorama wants the fold, a+ * stop with nothing said about it wants the place page) and then by position.+ * The full-bleed page is kept to every sixth and never the first.+ */+function entrySpread(entry: AutoEntry, input: AutoInput, index: number, newId: NewId): BookSpread {+ const hand = index % 2 === 0 ? 'left' : 'right';+ const photos = entry.photos.slice(0, 5);+ const withPhotos = { ...entry, photos };+ const c: EntryContext = { entry: withPhotos, input, index, hand, newId };+ const story = (entry.story || '').trim();++ const fromTemplate = templateSpread(withPhotos, input, index, newId);+ if (fromTemplate) return fromTemplate;+ if (photos.length === 0 && !story) return placeSpread(c);+ const first = photos[0];+ if (first && isPano(first)) return panoSpread(c);+ switch (index % 6) {+ case 0:+ return photos.length > 1 ? gallerySpread(c) : storySpread(c);+ case 1:+ return panelSpread(c);+ case 2:+ return photos.length > 2 ? bandSpread(c) : storySpread(c);+ case 3:+ return photos.length ? immersiveSpread(c) : panelSpread(c);+ case 4:+ return photos.length > 1 ? bandSpread(c) : panelSpread(c);+ default:+ return photos.length > 1 ? gallerySpread(c) : storySpread(c);+ }+}++/**+ * The page setup for a book that opens on a single page: the first page+ * inside the covers is page 1 (#2317). Nothing else of the setup is touched.+ */+function withFirstPage(page: BookPageSetup): BookPageSetup {+ return { ...page, pageNumbers: { ...page.pageNumbers, startAt: 1 } };+}++/** The spreads the entries make: one each for entries with substance, a shared list for runs of bare ones. */+function entrySpreads(input: AutoInput, newId: NewId): BookSpread[] {+ const out: BookSpread[] = [];+ let laid = 0;+ let run: AutoEntry[] = [];+ const flushRun = () => {+ for (let i = 0; i < run.length; i += STATIONS_PER_PAGE * 2) {+ out.push(stationsSpread(run.slice(i, i + STATIONS_PER_PAGE * 2), input, newId));+ }+ run = [];+ };+ for (const entry of input.entries) {+ if (autoEntryHasSubstance(entry)) {+ flushRun();+ out.push(entrySpread(entry, input, laid++, newId));+ } else {+ run.push(entry);+ }+ }+ flushRun();+ return out;+}++/**+ * The whole book: the cover, the first page, the journey at a glance and its+ * countries (both left out when the journey has nothing to say with them),+ * the entries in the order they happened, the last page and the back cover.+ */+export function buildBook(input: AutoInput): BookDocument {+ const newId = idsOf(input);+ const spreads: BookSpread[] = [coverSpread(input, newId), blankSpread('first', newId)];+ const summary = summarySpread(input, newId);+ if (summary) spreads.push(summary);+ const countries = countriesSpread(input, countryNames(input), newId);+ if (countries) spreads.push(countries);+ spreads.push(...entrySpreads(input, newId));+ spreads.push(blankSpread('last', newId), backSpread(input, newId));+ return {+ version: 1,+ title: input.title.slice(0, MAX_BOOK_TITLE),+ page: withFirstPage(input.page),+ spreads: spreads.slice(0, MAX_SPREADS),+ };+}++/**+ * A book nobody has laid out yet: what a journey with no book opens on. The+ * layout is offered, not applied; the same blank book `create_book` writes.+ */+export function emptyBook(input: AutoInput): BookDocument {+ return blankBook({ title: input.title, page: input.page, newId: idsOf(input) });+}++/**+ * Lay one spread out again, from the entry it came from, keeping its id so the+ * pages rail does not jump. Null for a spread that has no entry behind it (the+ * covers, the summary, anything added by hand): there is nothing to rebuild it+ * from, and replacing it with a blank page would be worse than refusing.+ */+export function relayoutSpread(spread: BookSpread, input: AutoInput): BookSpread | null {+ if (spread.role !== 'inner' || spread.entryId == null) return null;+ const entry = input.entries.find((e) => e.id === spread.entryId);+ if (!entry) return null;+ const index = input.entries.indexOf(entry);+ return { ...entrySpread(entry, input, index < 0 ? 0 : index, idsOf(input)), id: spread.id };+}++/**+ * Hand the journey's loose gallery photos to the entries. Photos that already+ * sit on an entry stay there; the rest are shared out in order, so a book+ * built from a journey whose pictures all live in the gallery still gets+ * pictures on its pages.+ */+export function distributeGallery(entries: AutoEntry[], gallery: readonly AutoPhoto[]): AutoEntry[] {+ const taken = new Set(entries.flatMap((e) => e.photos.map((p) => p.photoId)));+ const loose = gallery.filter((p) => !taken.has(p.photoId));+ if (!loose.length || !entries.length) return entries;+ const per = Math.max(1, Math.floor(loose.length / entries.length));+ let i = 0;+ return entries.map((e, idx) => {+ if (e.photos.length >= 4) return e;+ const want = Math.min(4 - e.photos.length, idx === entries.length - 1 ? loose.length - i : per);+ const slice = loose.slice(i, i + Math.max(0, want));+ i += slice.length;+ return { ...e, photos: [...e.photos, ...slice] };+ });+}++/**+ * Give every entry what the journey's figures know about its stop: the+ * coordinates and country its place resolved to, and which day of the+ * journey it is. Matched by date first and by name second, because a day+ * usually has one stop and two stops on one day are told apart by name.+ */+export function autoEntriesWithStops(entries: readonly AutoEntry[], stats: JourneyStats | null): AutoEntry[] {+ const points = stats?.points ?? [];+ const dayCount = stats?.days ?? null;+ // Calendar days counted in UTC: a local midnight would lose a day across a change to summer time.+ const first = stats?.start ? Date.parse(`${stats.start}T00:00:00Z`) : Number.NaN;+ return entries.map((entry) => {+ const byDate = points.find((p) => p.date && entry.date && p.date === entry.date);+ const point = byDate ?? points.find((p) => p.label && entry.location && p.label === entry.location);+ const at = entry.date ? Date.parse(`${entry.date}T00:00:00Z`) : Number.NaN;+ const known = Number.isFinite(at) && Number.isFinite(first);+ const dayNumber = known ? Math.floor((at - first) / 86_400_000) + 1 : null;+ return {+ ...entry,+ lat: point?.lat ?? null,+ lng: point?.lng ?? null,+ country: point?.country ?? null,+ dayNumber: dayNumber && dayNumber > 0 ? dayNumber : null,+ dayCount,+ };+ });+}diff --git a/shared/src/book/auto/auto-elements.ts b/shared/src/book/auto/auto-elements.tsnew file mode 100644index 000000000..5cc0fa344--- /dev/null+++ b/shared/src/book/auto/auto-elements.ts@@ -0,0 +1,380 @@+import { formatBookCoords } from '../book-text';+import {+ MAX_BOOK_COUNTRIES,+ MAX_COUNTRY_NAME,+ MAX_MAP_POINTS,+ MAX_MAP_POINT_LABEL,+ MAX_TEXT_LENGTH,+ type BookElement,+ type BookFrame,+ type BookMetric,+ type BookPageSetup,+ type BookSpread,+} from '../book.schema';+import type { JourneyStats } from '../journey-stats.schema';+import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';++/**+ * The parts the auto layout builds its pages from: a text, a picture, a+ * shape, the travel elements and the small marks a printed travel page is+ * made of. The same parts a person reaches for in the Studio, so what the+ * layout produces can be taken apart and rearranged like anything else.+ *+ * The colours are print ink, not app chrome: a book is printed once and read+ * on paper, and the renderer has no theme to ask.+ */++/** Mints an id for an element or a page. */+export type NewId = (prefix: string) => string;++type Of<K extends BookElement['kind']> = Partial<Extract<BookElement, { kind: K }>>;++export const isPortrait = (p: AutoPhoto) => (p.width && p.height ? p.height > p.width * 1.08 : false);+export const isPano = (p: AutoPhoto) => (p.width && p.height ? p.width > p.height * 2 : false);++/** Near-black ink, and the one warm accent the travel marks share. */+const INK = '#1a1a1a';+export const ACCENT = '#c2410c';+/** Near-black with a blue cast, the colour these books lay a page in. */+export const PANEL_INK = '#12161d';+/** Type on a panel, and the paper colour of the quiet pages. */+export const PANEL_TYPE = '#f2efe9';+export const CREAM = '#faf8f4';++export function text(newId: NewId, frame: BookFrame, value: string, opts: Of<'text'> = {}): BookElement {+ return {+ id: newId('t'),+ kind: 'text',+ frame,+ rotation: 0,+ opacity: 1,+ locked: false,+ text: value.slice(0, MAX_TEXT_LENGTH),+ font: 'sans',+ size: 11,+ weight: 400,+ italic: false,+ align: 'left',+ leading: 1.45,+ tracking: 0,+ color: INK,+ binding: null,+ overridden: false,+ ...opts,+ } as BookElement;+}++/**+ * A picture, or the place one goes. `photoId` null is an empty frame, which+ * the renderer draws as an outline and which takes a photo by drag.+ */+export function photo(newId: NewId, frame: BookFrame, photoId: number | null, opts: Of<'photo'> = {}): BookElement {+ return {+ id: newId('p'),+ kind: 'photo',+ frame,+ rotation: 0,+ opacity: 1,+ locked: false,+ photoId,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ ...opts,+ } as BookElement;+}++export function shape(newId: NewId, frame: BookFrame, fill: string | null, opts: Of<'shape'> = {}): BookElement {+ return {+ id: newId('s'),+ kind: 'shape',+ frame,+ rotation: 0,+ opacity: 1,+ locked: false,+ shape: 'rect',+ fill,+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ radius: 0,+ ...opts,+ } as BookElement;+}++/** What every travel element the layout places starts from: ink, not the app's orange. */+const travelBase = {+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans' as const,+ color: INK,+ accent: INK,+ textScale: 1,+ stale: false,+};++/** The figures a stats element carries, keyed by metric. */+export function statsValues(stats: JourneyStats): Record<BookMetric, number> {+ return {+ distance: stats.distance,+ days: stats.days,+ steps: stats.steps,+ photos: stats.photos,+ countries: stats.countries.length,+ places: stats.places,+ furthest: stats.furthest,+ };+}++export function statsEl(+ newId: NewId,+ frame: BookFrame,+ stats: JourneyStats,+ metrics: BookMetric[],+ layout: 'grid' | 'row' | 'column' = 'grid',+ opts: Of<'stats'> = {},+): BookElement {+ return {+ ...travelBase,+ id: newId('st'),+ kind: 'stats',+ frame,+ metrics,+ layout,+ showIcons: true,+ units: 'metric',+ values: statsValues(stats),+ ...opts,+ } as BookElement;+}++export function mapEl(newId: NewId, frame: BookFrame, stats: JourneyStats, opts: Of<'map'> = {}): BookElement {+ const points = stats.points.slice(0, MAX_MAP_POINTS).map((pt) => ({+ lat: pt.lat,+ lng: pt.lng,+ label: pt.label.slice(0, MAX_MAP_POINT_LABEL),+ photoId: pt.photoId ?? null,+ }));+ return {+ ...travelBase,+ id: newId('mp'),+ kind: 'map',+ frame,+ style: 'minimal',+ showLand: true,+ showRoute: true,+ showPins: true,+ showLabels: false,+ // The drawn line: the contract stays plain so old books do not change, and new books look like a book.+ routeStyle: 'drawn',+ routeArc: 'bow',+ routeDash: 'arcs',+ pinStyle: 'photo',+ countries: stats.countries.slice(0, MAX_BOOK_COUNTRIES).map((c) => c.code),+ points,+ path: [],+ roads: [],+ fitPadding: 0.5,+ fitToCountries: true,+ clip: 'rect',+ ...opts,+ } as BookElement;+}++export function countriesEl(+ newId: NewId,+ frame: BookFrame,+ stats: JourneyStats,+ names: string[],+ opts: Of<'countries'> = {},+): BookElement {+ return {+ ...travelBase,+ id: newId('co'),+ kind: 'countries',+ frame,+ codes: stats.countries.slice(0, MAX_BOOK_COUNTRIES).map((c) => c.code),+ names: names.slice(0, MAX_BOOK_COUNTRIES).map((n) => n.slice(0, MAX_COUNTRY_NAME)),+ layout: 'list',+ showOutline: true,+ showFlag: false,+ showName: true,+ align: 'center',+ ...opts,+ } as BookElement;+}++type AutoBadgeVariant = 'flag' | 'date' | 'day' | 'coords' | 'country' | 'distance';++export function badgeEl(+ newId: NewId,+ frame: BookFrame,+ variant: AutoBadgeVariant,+ value: { text?: string; sub?: string; code?: string | null },+ opts: Of<'badge'> = {},+): BookElement {+ return {+ ...travelBase,+ id: newId('bd'),+ kind: 'badge',+ frame,+ variant,+ text: value.text ?? '',+ sub: value.sub ?? '',+ code: value.code ?? null,+ style: 'plain',+ // Built by hand rather than parsed, so the contract's defaults do not apply.+ autoColor: true,+ showIcon: true,+ showLabel: true,+ autoIconColor: true,+ iconColor: INK,+ ...opts,+ } as BookElement;+}++/** A country's flag with its name beside it, the frame cut to the words. */+export function flagRow(newId: NewId, frame: BookFrame, code: string | null, name: string): BookElement | null {+ if (!code && !name) return null;+ const cut = { ...frame, w: Math.min(frame.w, 14 + name.length * 1.7) };+ return badgeEl(newId, cut, 'flag', { text: name.toUpperCase(), code }, { style: 'plain', textScale: 0.85 });+}++/** Where on earth this is, set small under the name. */+export function coordsMark(+ newId: NewId,+ frame: BookFrame,+ lat: number | null | undefined,+ lng: number | null | undefined,+): BookElement | null {+ if (lat == null || lng == null) return null;+ return badgeEl(newId, frame, 'coords', { text: formatBookCoords(lat, lng) }, { style: 'plain', textScale: 0.7 });+}++/** The "DAY 5" chip. Small, solid, and the only filled shape on most pages. */+export function dayChip(newId: NewId, frame: BookFrame, day: number | null | undefined, label: string) {+ if (!day) return null;+ return badgeEl(newId, frame, 'day', { text: `${label} ${day}` }, { style: 'chip', textScale: 0.75 });+}++/** A rule along the foot with a dot showing how far into the journey this is. */+export function progressRule(+ newId: NewId,+ at: { x: number; y: number; w: number },+ day: number | null | undefined,+ total: number | null | undefined,+): BookElement[] {+ if (!day || !total || total < 2) return [];+ const { x, y, w } = at;+ const t = Math.min(1, Math.max(0, (day - 1) / (total - 1)));+ const dot = 2.2;+ const dotFrame = { x: x + w * t - dot / 2, y: y - dot / 2 + 0.15, w: dot, h: dot };+ return [shape(newId, { x, y, w, h: 0.3 }, '#cfc9bd'), shape(newId, dotFrame, ACCENT, { shape: 'ellipse' })];+}++/** The country's outline, printed pale behind everything else. */+export function countryWatermark(newId: NewId, frame: BookFrame, code: string | null | undefined): BookElement | null {+ if (!code) return null;+ return {+ ...travelBase,+ id: newId('wm'),+ kind: 'countries',+ frame,+ codes: [code],+ names: [''],+ layout: 'column',+ showOutline: true,+ showFlag: false,+ showName: false,+ align: 'center',+ opacity: 0.1,+ } as BookElement;+}++/** The stop on a small map of its own, the way an entry page opens: the country whole with a dot in it. */+export function placeMap(+ newId: NewId,+ frame: BookFrame,+ entry: AutoEntry,+ stats: JourneyStats | null,+): BookElement | null {+ if (entry.lat == null || entry.lng == null) return null;+ return {+ ...travelBase,+ id: newId('mp'),+ kind: 'map',+ frame,+ points: [{ lat: entry.lat, lng: entry.lng, label: entry.location ?? '', photoId: null }],+ countries: entry.country ? [entry.country] : (stats?.countries.map((c) => c.code) ?? []),+ style: 'minimal',+ source: 'vector',+ tileUrl: '',+ attribution: '',+ zoom: 5,+ // The plain treatment: one dot on a country outline, a bowed casing would be decoration.+ routeStyle: 'plain',+ routeArc: 'straight',+ routeDash: 'solid',+ pinStyle: 'dot',+ path: [],+ roads: [],+ fitPadding: 0.5,+ fitToCountries: true,+ clip: 'rect',+ showLand: true,+ showRoute: false,+ showPins: true,+ showLabels: false,+ } as BookElement;+}++/** The day of the month as a numeral with its month beneath: a mark rather than a line of information. */+export function dateMark(newId: NewId, iso: string | null, locale: string, frame: BookFrame): BookElement | null {+ if (!iso) return null;+ const d = new Date(`${iso}T00:00:00`);+ if (Number.isNaN(d.getTime())) return null;+ const value = { text: String(d.getDate()), sub: d.toLocaleDateString(locale, { month: 'long' }).toUpperCase() };+ return badgeEl(newId, frame, 'date', value, { style: 'stacked' });+}++/** A full-bleed frame: out past the trim on every side the page is cut on. */+export function bleedFrame(page: BookPageSetup, spread: boolean): BookFrame {+ const w = spread ? page.pageWidth * 2 : page.pageWidth;+ return { x: -page.bleed, y: -page.bleed, w: w + page.bleed * 2, h: page.pageHeight + page.bleed * 2 };+}++/** The country a stop is in, named in the book's language. */+export function countryOf(entry: AutoEntry, input: AutoInput): string {+ if (!entry.country) return '';+ const named = input.stats?.countries.find((c) => c.code === entry.country);+ try {+ return new Intl.DisplayNames([input.locale], { type: 'region' }).of(entry.country) ?? named?.name ?? '';+ } catch {+ return named?.name ?? '';+ }+}++/**+ * Country names in the book's language: the API answers in English, and+ * `Intl.DisplayNames` is the same CLDR data Atlas uses for regions.+ */+export function countryNames(input: AutoInput): string[] {+ const codes = input.stats?.countries ?? [];+ let display: Intl.DisplayNames | null = null;+ try {+ display = new Intl.DisplayNames([input.locale], { type: 'region' });+ } catch {+ display = null;+ }+ return codes.map((c) => display?.of(c.code.toUpperCase()) || c.name || c.code.toUpperCase());+}++/** An inner spread made from one entry. */+export function sheet(newId: NewId, els: BookElement[], entry: AutoEntry, background: string): BookSpread {+ return { id: newId('sp'), role: 'inner', background, elements: els, parked: [], entryId: entry.id };+}diff --git a/shared/src/book/auto/auto-layout.parity-inputs.json b/shared/src/book/auto/auto-layout.parity-inputs.jsonnew file mode 100644index 000000000..01dce466b--- /dev/null+++ b/shared/src/book/auto/auto-layout.parity-inputs.json@@ -0,0 +1,1036 @@+{+ "A": {+ "input": {+ "locale": "en-GB",+ "title": "Atlantic coast",+ "subtitle": "Two weeks north",+ "coverPhotoId": 100,+ "entries": [+ {+ "id": 1,+ "title": "Day 1 in Lisboa",+ "story": null,+ "location": "Lisboa",+ "date": "2026-05-01",+ "photos": [],+ "lat": 38.72,+ "lng": -9.14,+ "country": "PT",+ "dayNumber": 1,+ "dayCount": 14+ },+ {+ "id": 2,+ "title": "Day 2 in Lisboa",+ "story": "Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while r",+ "location": "Lisboa",+ "date": "2026-05-02",+ "photos": [+ {+ "photoId": 100,+ "width": 4000,+ "height": 3000,+ "caption": "Tram 28"+ }+ ],+ "lat": 38.72,+ "lng": -9.14,+ "country": "PT",+ "dayNumber": 2,+ "dayCount": 14+ },+ {+ "id": 3,+ "title": "Day 3 in Porto",+ "story": "Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for the north coast stopped light enough at while. Good look a road along and wherever was to for the north coast stopped. While ran the we the good look a road along and wherever was to for.\n Coast stopped light enough at while ran the we the good look a road along and. Was to for the north coast stopped light. A road along and wherever was to for the. The we the good look a road along and wherever. Light enough at while ran the we the good look a.\n For the north coast stopped light enough at while ran the we. Along and wherever was to for the north coast stopped light enough at. The good look a road along and wherever was to for the north coast. At while ran the we the good look a road along and wherever was to. North coast stopped light enough at while ran the we the good look a road along.\n Wherever was to for the north coast stopped. Look a road along and wherever was to for.",+ "location": "Porto",+ "date": "2026-05-03",+ "photos": [+ {+ "photoId": 101,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 102,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 41.15,+ "lng": -8.61,+ "country": "PT",+ "dayNumber": 3,+ "dayCount": 14+ },+ {+ "id": 4,+ "title": "Day 4 in Porto",+ "story": "A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a r",+ "location": "Porto",+ "date": "2026-05-04",+ "photos": [+ {+ "photoId": 103,+ "width": 6000,+ "height": 2000,+ "caption": "The bridge"+ },+ {+ "photoId": 104,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 41.15,+ "lng": -8.61,+ "country": "PT",+ "dayNumber": 4,+ "dayCount": 14+ },+ {+ "id": 5,+ "title": null,+ "story": null,+ "location": "Santiago",+ "date": "2026-05-05",+ "photos": [+ {+ "photoId": 105,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 106,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 107,+ "width": 3000,+ "height": 4000,+ "caption": null+ }+ ],+ "lat": 42.88,+ "lng": -8.54,+ "country": "ES",+ "dayNumber": 5,+ "dayCount": 14+ },+ {+ "id": 6,+ "title": "Day 6 in Santiago",+ "story": "Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for t",+ "location": "Santiago",+ "date": "2026-05-06",+ "photos": [+ {+ "photoId": 108,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 109,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 110,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 111,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 42.88,+ "lng": -8.54,+ "country": "ES",+ "dayNumber": 6,+ "dayCount": 14+ },+ {+ "id": 7,+ "title": "Day 7 in Oviedo",+ "story": "For the north coast stopped light enough at. Along and where",+ "location": "Oviedo",+ "date": "2026-05-07",+ "photos": [+ {+ "photoId": 112,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 113,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 114,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 115,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 116,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 43.36,+ "lng": -5.85,+ "country": "ES",+ "dayNumber": 7,+ "dayCount": 14+ },+ {+ "id": 8,+ "title": "Day 8 in Oviedo",+ "story": "Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for the north coast stopped light enough at while. Good look a road along and wherever was to for the north coast stopped. While ran the we the good look a road along and wherever was to for.\n Coast stopped light enough at while ran the we the good look a road along and. Was to for the north coast stopped light. A road along and wherever was to for the. The we the good look a road along and wherever. Light enough at while ran the we the good look a.\n For the north coast stopped light enough at while ran the we. Along and wherever was to for the north coast stopped light enough at. The good look a road along and wherever was to for the north coast. At while ran the we the good look a road along and wherever was to. Nort",+ "location": "Oviedo",+ "date": "2026-05-08",+ "photos": [+ {+ "photoId": 117,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 118,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 119,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 120,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 121,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 122,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 123,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 124,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 43.36,+ "lng": -5.85,+ "country": "ES",+ "dayNumber": 8,+ "dayCount": 14+ },+ {+ "id": 9,+ "title": "Day 9 in Bilbao",+ "story": null,+ "location": "Bilbao",+ "date": "2026-05-09",+ "photos": [+ {+ "photoId": 125,+ "width": null,+ "height": null,+ "caption": null+ }+ ],+ "lat": 43.26,+ "lng": -2.93,+ "country": "ES",+ "dayNumber": 9,+ "dayCount": 14+ },+ {+ "id": 10,+ "title": "Day 10 in Bilbao",+ "story": "At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wh",+ "location": "Bilbao",+ "date": "2026-05-10",+ "photos": [+ {+ "photoId": 126,+ "width": 4000,+ "height": 3000,+ "caption": "Dusk"+ }+ ],+ "lat": 43.26,+ "lng": -2.93,+ "country": "ES",+ "dayNumber": 10,+ "dayCount": 14+ },+ {+ "id": 11,+ "title": "Day 11 in Biarritz",+ "story": null,+ "location": "Biarritz",+ "date": "2026-05-11",+ "photos": [+ {+ "photoId": 127,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 128,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 129,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 43.48,+ "lng": -1.56,+ "country": "FR",+ "dayNumber": 11,+ "dayCount": 14+ },+ {+ "id": 12,+ "title": "Day 12 in Biarritz",+ "story": null,+ "location": "Biarritz",+ "date": "2026-05-12",+ "photos": [],+ "lat": 43.48,+ "lng": -1.56,+ "country": "FR",+ "dayNumber": 12,+ "dayCount": 14+ }+ ],+ "page": {+ "preset": "square-210",+ "pageWidth": 210,+ "pageHeight": 210,+ "bleed": 3,+ "safe": 5,+ "pageNumbers": {+ "show": false,+ "startAt": 2,+ "position": "outer",+ "margin": 12,+ "size": 8,+ "autoColor": true,+ "color": "#8a8578",+ "font": "sans"+ }+ },+ "stats": {+ "journeyId": 1,+ "distance": 1420000,+ "days": 14,+ "steps": 12,+ "photos": 41,+ "places": 12,+ "furthest": 980000,+ "countries": [+ {+ "code": "PT",+ "name": "Portugal",+ "places": 4,+ "firstVisit": "2026-05-01"+ },+ {+ "code": "ES",+ "name": "Spain",+ "places": 5,+ "firstVisit": "2026-05-05"+ },+ {+ "code": "FR",+ "name": "France",+ "places": 3,+ "firstVisit": "2026-05-11"+ }+ ],+ "points": [+ {+ "lat": 38.72,+ "lng": -9.14,+ "label": "Lisboa",+ "date": "2026-05-01",+ "country": "PT",+ "tripId": null,+ "photoId": 100,+ "entryId": 1+ },+ {+ "lat": 41.15,+ "lng": -8.61,+ "label": "Porto",+ "date": "2026-05-03",+ "country": "PT",+ "tripId": null,+ "photoId": null,+ "entryId": 2+ },+ {+ "lat": 42.88,+ "lng": -8.54,+ "label": "Santiago",+ "date": "2026-05-05",+ "country": "ES",+ "tripId": null,+ "photoId": 102,+ "entryId": 3+ },+ {+ "lat": 43.36,+ "lng": -5.85,+ "label": "Oviedo",+ "date": "2026-05-07",+ "country": "ES",+ "tripId": null,+ "photoId": null,+ "entryId": 4+ },+ {+ "lat": 43.26,+ "lng": -2.93,+ "label": "Bilbao",+ "date": "2026-05-09",+ "country": "ES",+ "tripId": null,+ "photoId": 104,+ "entryId": 5+ },+ {+ "lat": 43.48,+ "lng": -1.56,+ "label": "Biarritz",+ "date": "2026-05-11",+ "country": "FR",+ "tripId": null,+ "photoId": null,+ "entryId": 6+ },+ {+ "lat": 44.84,+ "lng": -0.58,+ "label": "Bordeaux",+ "date": "2026-05-13",+ "country": "FR",+ "tripId": null,+ "photoId": 106,+ "entryId": 7+ }+ ],+ "trips": [],+ "excluded": [],+ "start": "2026-05-01",+ "end": "2026-05-14"+ },+ "path": [+ [+ [+ 38.72,+ -9.14+ ],+ [+ 39.5,+ -9+ ],+ [+ 41.15,+ -8.61+ ]+ ],+ [+ [+ 42.88,+ -8.54+ ],+ [+ 43.3,+ -6+ ],+ [+ 43.36,+ -5.85+ ],+ [+ 43.26,+ -2.93+ ]+ ]+ ],+ "stationsLabel": "Stations",+ "dayLabel": "DAY",+ "summaryLabel": "Trip summary",+ "countriesLabel": "Countries"+ }+ },+ "B": {+ "input": {+ "locale": "de-DE",+ "title": "Brandenburg",+ "subtitle": null,+ "coverPhotoId": null,+ "entries": [+ {+ "id": 201,+ "title": "Stop 1",+ "story": null,+ "location": "Town 1",+ "date": "2026-08-01",+ "photos": []+ },+ {+ "id": 202,+ "title": "Stop 2",+ "story": null,+ "location": "Town 2",+ "date": "2026-08-02",+ "photos": []+ },+ {+ "id": 203,+ "title": "Stop 3",+ "story": null,+ "location": "Town 3",+ "date": "2026-08-03",+ "photos": []+ },+ {+ "id": 204,+ "title": "Stop 4",+ "story": null,+ "location": "Town 4",+ "date": "2026-08-04",+ "photos": []+ },+ {+ "id": 205,+ "title": "Stop 5",+ "story": null,+ "location": "Town 5",+ "date": "2026-08-05",+ "photos": []+ },+ {+ "id": 206,+ "title": "Stop 6",+ "story": null,+ "location": "Town 6",+ "date": null,+ "photos": []+ },+ {+ "id": 207,+ "title": null,+ "story": null,+ "location": "Town 7",+ "date": "2026-08-07",+ "photos": []+ },+ {+ "id": 208,+ "title": "Stop 8",+ "story": null,+ "location": "Town 8",+ "date": "2026-08-08",+ "photos": []+ },+ {+ "id": 209,+ "title": "Stop 9",+ "story": "Good look a road along and wherever was to for. While ran the we the good look a road along and. Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good.",+ "location": "Town 9",+ "date": "2026-08-09",+ "photos": [+ {+ "photoId": 130,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 131,+ "width": 3000,+ "height": 4000,+ "caption": null+ }+ ]+ },+ {+ "id": 210,+ "title": "Stop 10",+ "story": null,+ "location": "Town 10",+ "date": "2026-08-10",+ "photos": []+ },+ {+ "id": 211,+ "title": "Stop 11",+ "story": null,+ "location": "Town 11",+ "date": "2026-08-11",+ "photos": []+ },+ {+ "id": 212,+ "title": "Stop 12",+ "story": null,+ "location": "Town 12",+ "date": null,+ "photos": []+ },+ {+ "id": 213,+ "title": "Stop 13",+ "story": null,+ "location": "Town 13",+ "date": "2026-08-13",+ "photos": []+ },+ {+ "id": 214,+ "title": null,+ "story": null,+ "location": "Town 14",+ "date": "2026-08-14",+ "photos": []+ },+ {+ "id": 215,+ "title": "Stop 15",+ "story": null,+ "location": "Town 15",+ "date": "2026-08-15",+ "photos": []+ },+ {+ "id": 216,+ "title": "Stop 16",+ "story": null,+ "location": "Town 16",+ "date": "2026-08-16",+ "photos": []+ },+ {+ "id": 217,+ "title": "Stop 17",+ "story": null,+ "location": "Town 17",+ "date": "2026-08-17",+ "photos": []+ },+ {+ "id": 218,+ "title": "Stop 18",+ "story": null,+ "location": "Town 18",+ "date": null,+ "photos": []+ },+ {+ "id": 219,+ "title": "Stop 19",+ "story": null,+ "location": "Town 19",+ "date": "2026-08-19",+ "photos": []+ },+ {+ "id": 220,+ "title": "Stop 20",+ "story": null,+ "location": "Town 20",+ "date": "2026-08-20",+ "photos": []+ },+ {+ "id": 221,+ "title": null,+ "story": null,+ "location": "Town 21",+ "date": "2026-08-21",+ "photos": []+ },+ {+ "id": 222,+ "title": "Stop 22",+ "story": null,+ "location": "Town 22",+ "date": "2026-08-22",+ "photos": []+ },+ {+ "id": 223,+ "title": "Stop 23",+ "story": null,+ "location": "Town 23",+ "date": "2026-08-23",+ "photos": []+ },+ {+ "id": 224,+ "title": "Stop 24",+ "story": null,+ "location": "Town 24",+ "date": null,+ "photos": []+ },+ {+ "id": 225,+ "title": "Stop 25",+ "story": null,+ "location": "Town 25",+ "date": "2026-08-25",+ "photos": []+ },+ {+ "id": 226,+ "title": "Stop 26",+ "story": null,+ "location": "Town 26",+ "date": "2026-08-26",+ "photos": []+ },+ {+ "id": 227,+ "title": "Stop 27",+ "story": null,+ "location": "Town 27",+ "date": "2026-08-27",+ "photos": []+ },+ {+ "id": 228,+ "title": null,+ "story": null,+ "location": "Town 28",+ "date": "2026-08-28",+ "photos": []+ },+ {+ "id": 229,+ "title": "Stop 29",+ "story": null,+ "location": "Town 29",+ "date": "2026-08-29",+ "photos": []+ },+ {+ "id": 230,+ "title": "Stop 30",+ "story": null,+ "location": "Town 30",+ "date": null,+ "photos": []+ }+ ],+ "page": {+ "preset": "square-210",+ "pageWidth": 210,+ "pageHeight": 210,+ "bleed": 3,+ "safe": 5,+ "pageNumbers": {+ "show": false,+ "startAt": 2,+ "position": "outer",+ "margin": 12,+ "size": 8,+ "autoColor": true,+ "color": "#8a8578",+ "font": "sans"+ }+ },+ "stats": {+ "journeyId": 2,+ "distance": 0,+ "days": 0,+ "steps": 0,+ "photos": 2,+ "places": 1,+ "furthest": 0,+ "countries": [+ {+ "code": "DE",+ "name": "Germany",+ "places": 1,+ "firstVisit": null+ }+ ],+ "points": [+ {+ "lat": 52.52,+ "lng": 13.4,+ "label": "Town 1",+ "date": "2026-08-01",+ "country": "DE",+ "tripId": null,+ "photoId": null,+ "entryId": null+ }+ ],+ "trips": [],+ "excluded": [],+ "start": null,+ "end": null+ },+ "stationsLabel": "Stations",+ "dayLabel": "DAY",+ "summaryLabel": "Trip summary",+ "countriesLabel": "Countries"+ }+ },+ "C": {+ "input": {+ "locale": "fr-FR",+ "title": "Carnet",+ "subtitle": "Automne",+ "coverPhotoId": null,+ "entries": [+ {+ "id": 301,+ "title": "Chapter 1",+ "story": "And wherever was to for the north coast stopped. Good look a road along and wherever was to for. While ran the we the good look a road along and. Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light e",+ "location": null,+ "date": "2026-10-01",+ "photos": []+ },+ {+ "id": 302,+ "title": "Chapter 2",+ "story": "Good look a road along and wherever was to for. While ran the we the good look a road along and. Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along a",+ "location": null,+ "date": "2026-10-02",+ "photos": [+ {+ "photoId": 149,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 150,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 151,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 152,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ]+ },+ {+ "id": 303,+ "title": "Chapter 3",+ "story": "While ran the we the good look a road along and. Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and where",+ "location": null,+ "date": "2026-10-03",+ "photos": []+ },+ {+ "id": 304,+ "title": "Chapter 4",+ "story": "Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good",+ "location": null,+ "date": "2026-10-04",+ "photos": []+ },+ {+ "id": 305,+ "title": "Chapter 5",+ "story": "Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for the north coast stopped light enough at while. Good look a road along and wherever was to for the north coast stopped. While ran the we the",+ "location": null,+ "date": "2026-10-05",+ "photos": []+ }+ ],+ "page": {+ "preset": "a4-portrait",+ "pageWidth": 210,+ "pageHeight": 297,+ "bleed": 3,+ "safe": 5,+ "pageNumbers": {+ "show": false,+ "startAt": 2,+ "position": "outer",+ "margin": 12,+ "size": 8,+ "autoColor": true,+ "color": "#8a8578",+ "font": "sans"+ }+ },+ "stats": null,+ "stationsLabel": "Stations",+ "dayLabel": "DAY",+ "summaryLabel": "Trip summary",+ "countriesLabel": "Countries"+ },+ "gallery": [+ {+ "photoId": 132,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 0"+ },+ {+ "photoId": 133,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 134,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 135,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 136,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 4"+ },+ {+ "photoId": 137,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 138,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 139,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 140,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 8"+ },+ {+ "photoId": 141,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 142,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 143,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 144,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 12"+ },+ {+ "photoId": 145,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 146,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 147,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 148,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 16"+ }+ ]+ }+}diff --git a/shared/src/book/auto/auto-layout.parity.json b/shared/src/book/auto/auto-layout.parity.jsonnew file mode 100644index 000000000..420bb8d06--- /dev/null+++ b/shared/src/book/auto/auto-layout.parity.json@@ -0,0 +1,115 @@+{+ "A/stops": "2e748932e79afc89",+ "A/empty": "3919f57127dd39a9",+ "A/full/head": "e030d61f8d2aa9c5",+ "A/full/spread/0": "6036ca6b48d6e248",+ "A/full/spread/1": "bf4b62404c36aa0e",+ "A/full/spread/2": "688f4ce239f0eb65",+ "A/full/spread/3": "3bc5ecd3ad02ad83",+ "A/full/spread/4": "6fdb7d865a3534c5",+ "A/full/spread/5": "79c58347ba49449c",+ "A/full/relayout/5": "f498524e1bd83d73",+ "A/full/spread/6": "92fffefa67d34ef2",+ "A/full/relayout/6": "b0e25102bc3c6386",+ "A/full/spread/7": "97dc9b4c168d097e",+ "A/full/relayout/7": "b0f02d030b894d85",+ "A/full/spread/8": "9713baa4e2b220cb",+ "A/full/relayout/8": "9713baa4e2b220cb",+ "A/full/spread/9": "d9543f86494f2314",+ "A/full/relayout/9": "d9543f86494f2314",+ "A/full/spread/10": "4158ebac72aa2f82",+ "A/full/relayout/10": "4158ebac72aa2f82",+ "A/full/spread/11": "9095fefd6605bd3a",+ "A/full/relayout/11": "9095fefd6605bd3a",+ "A/full/spread/12": "c607b733a886819d",+ "A/full/relayout/12": "c607b733a886819d",+ "A/full/spread/13": "eeb52e441b993de2",+ "A/full/relayout/13": "1a69cae26847c6b3",+ "A/full/spread/14": "25220218e93c4852",+ "A/full/relayout/14": "25220218e93c4852",+ "A/full/spread/15": "d23c193b720e5459",+ "A/full/spread/16": "2458025780d8cbf3",+ "A/full/spread/17": "01c48fbcefa1c067",+ "A/plain/head": "e030d61f8d2aa9c5",+ "A/plain/spread/0": "6036ca6b48d6e248",+ "A/plain/spread/1": "bf4b62404c36aa0e",+ "A/plain/spread/2": "688f4ce239f0eb65",+ "A/plain/spread/3": "3bc5ecd3ad02ad83",+ "A/plain/spread/4": "6fdb7d865a3534c5",+ "A/plain/spread/5": "77241c40787fee23",+ "A/plain/relayout/5": "dea1552bb3b68330",+ "A/plain/spread/6": "71f875eca927c88d",+ "A/plain/relayout/6": "a8ee238a620ce6e6",+ "A/plain/spread/7": "eb8defdfae4221c7",+ "A/plain/relayout/7": "eb8defdfae4221c7",+ "A/plain/spread/8": "34f52cbb4583cf5a",+ "A/plain/relayout/8": "36678c06b8189638",+ "A/plain/spread/9": "18bff409b40a33d1",+ "A/plain/relayout/9": "00d3d7a2c6d38d11",+ "A/plain/spread/10": "7b58974d5d38a5c0",+ "A/plain/relayout/10": "738530d637d0b8b6",+ "A/plain/spread/11": "7a3bf522f37acca3",+ "A/plain/relayout/11": "539de849990c2012",+ "A/plain/spread/12": "746c3194e39f13cb",+ "A/plain/relayout/12": "80100245e192c30d",+ "A/plain/spread/13": "bf5ded4681177685",+ "A/plain/relayout/13": "ae0a4713176adbc9",+ "A/plain/spread/14": "5c92185debe40114",+ "A/plain/relayout/14": "e1d6c0ad1c25caf0",+ "A/plain/spread/15": "d23c193b720e5459",+ "A/plain/spread/16": "2458025780d8cbf3",+ "A/plain/spread/17": "01c48fbcefa1c067",+ "B/stops": "ac515f9a6b3dfd0c",+ "B/empty": "1a5f7b789f489fd2",+ "B/full/head": "d55061263739b77a",+ "B/full/spread/0": "ac843317bb8d097c",+ "B/full/spread/1": "bf4b62404c36aa0e",+ "B/full/spread/2": "1af653e4557c90b9",+ "B/full/spread/3": "f766c7b6a3cad0fa",+ "B/full/relayout/3": "c0f3d2e84826b420",+ "B/full/spread/4": "8563f01a381c3b8b",+ "B/full/spread/5": "2458025780d8cbf3",+ "B/full/spread/6": "345c342e7364131e",+ "B/plain/head": "d55061263739b77a",+ "B/plain/spread/0": "ac843317bb8d097c",+ "B/plain/spread/1": "bf4b62404c36aa0e",+ "B/plain/spread/2": "1af653e4557c90b9",+ "B/plain/spread/3": "7f57a8719bee79ca",+ "B/plain/relayout/3": "08b7ac0438ad42e6",+ "B/plain/spread/4": "8563f01a381c3b8b",+ "B/plain/spread/5": "2458025780d8cbf3",+ "B/plain/spread/6": "345c342e7364131e",+ "C/stops": "9b6e31f71aa4ba65",+ "C/distribute": "acc3f467a2ffd1e8",+ "C/empty": "0f842f6edbdcbf6e",+ "C/full/head": "0ffba0f701b7ccaa",+ "C/full/spread/0": "ee87e9e195e1edde",+ "C/full/spread/1": "bf4b62404c36aa0e",+ "C/full/spread/2": "973ed5d0aacb1063",+ "C/full/relayout/2": "973ed5d0aacb1063",+ "C/full/spread/3": "8eb39a4e9d726f5e",+ "C/full/relayout/3": "8eb39a4e9d726f5e",+ "C/full/spread/4": "5a037193ef347c07",+ "C/full/relayout/4": "5a037193ef347c07",+ "C/full/spread/5": "71c9f776ce8ffc87",+ "C/full/relayout/5": "71c9f776ce8ffc87",+ "C/full/spread/6": "0debcd2babd7ee6b",+ "C/full/relayout/6": "0debcd2babd7ee6b",+ "C/full/spread/7": "2458025780d8cbf3",+ "C/full/spread/8": "13fbd1cbc3c4ab3a",+ "C/plain/head": "0ffba0f701b7ccaa",+ "C/plain/spread/0": "ee87e9e195e1edde",+ "C/plain/spread/1": "bf4b62404c36aa0e",+ "C/plain/spread/2": "c02ef3d3190977de",+ "C/plain/relayout/2": "c02ef3d3190977de",+ "C/plain/spread/3": "43f652c83b8e9a6e",+ "C/plain/relayout/3": "43f652c83b8e9a6e",+ "C/plain/spread/4": "51e4f11ba222dc88",+ "C/plain/relayout/4": "51e4f11ba222dc88",+ "C/plain/spread/5": "5d6770cfbb726b8e",+ "C/plain/relayout/5": "5d6770cfbb726b8e",+ "C/plain/spread/6": "a1562a8d610bee5f",+ "C/plain/relayout/6": "a1562a8d610bee5f",+ "C/plain/spread/7": "2458025780d8cbf3",+ "C/plain/spread/8": "13fbd1cbc3c4ab3a"+}diff --git a/shared/src/book/auto/auto-layout.parity.spec.ts b/shared/src/book/auto/auto-layout.parity.spec.tsnew file mode 100644index 000000000..a7a7674d6--- /dev/null+++ b/shared/src/book/auto/auto-layout.parity.spec.ts@@ -0,0 +1,156 @@+import { designBook } from '../design/design-book';+import type { JourneyStats } from '../journey-stats.schema';+import { autoEntriesWithStops, buildBook, distributeGallery, emptyBook, relayoutSpread } from './auto-book';+import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';++import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';++/**+ * The auto layout moved here from the Studio still lays a journey out exactly+ * as the Studio's own copy did.+ *+ * `auto-layout.parity.json` holds a digest of every result the old client+ * functions gave on the three journeys in `auto-layout.parity-inputs.json`:+ * every spread of `buildBook` with the drawn templates and with none, every+ * entry spread laid out again, the empty book, the gallery shared out, and the+ * stops matched to the entries. Taken from the client code before it was+ * deleted. Ids the call mints are random and read as `#new`. A deliberate+ * change to a layout changes its digests: say so in the change and write the+ * new ones.+ */++interface Fixture {+ input: AutoInput;+ gallery?: AutoPhoto[];+}++const here = (file: string) => fileURLToPath(new URL(file, import.meta.url));+const fixtures = JSON.parse(readFileSync(here('./auto-layout.parity-inputs.json'), 'utf8')) as Record<string, Fixture>;+const expected = JSON.parse(readFileSync(here('./auto-layout.parity.json'), 'utf8')) as Record<string, string>;++function canonical(value: unknown): string {+ const walk = (v: unknown, key?: string): unknown => {+ if (Array.isArray(v)) return v.map((x) => walk(x));+ if (v && typeof v === 'object') {+ const o = v as Record<string, unknown>;+ return Object.fromEntries(+ Object.keys(o)+ .sort()+ .map((k) => [k, walk(o[k], k)]),+ );+ }+ if (key === 'id' && typeof v === 'string') return '#new';+ return v;+ };+ return JSON.stringify(walk(value));+}++const digest = (v: unknown) => createHash('sha256').update(canonical(v)).digest('hex').slice(0, 16);++/** An entry as the journey has it, before the stops are matched to it. */+const bare = (e: AutoEntry): AutoEntry => ({+ id: e.id,+ title: e.title,+ story: e.story,+ location: e.location,+ date: e.date,+ photos: e.photos,+});++function cases(): Map<string, string> {+ const out = new Map<string, string>();+ for (const [name, fx] of Object.entries(fixtures)) {+ const put = (key: string, v: unknown) => out.set(`${name}/${key}`, digest(v));+ put('stops', autoEntriesWithStops(fx.input.entries.map(bare), fx.input.stats));+ const entries = fx.gallery ? distributeGallery(fx.input.entries, fx.gallery) : fx.input.entries;+ if (fx.gallery) put('distribute', entries);+ const input = { ...fx.input, entries };+ put('empty', emptyBook(input));+ const layouts = (tag: string, templates: AutoInput['templates']) => {+ const run = { ...input, templates };+ const doc = buildBook(run);+ put(`${tag}/head`, { version: doc.version, title: doc.title, page: doc.page, count: doc.spreads.length });+ doc.spreads.forEach((s, i) => {+ put(`${tag}/spread/${i}`, s);+ const again = relayoutSpread(s, run);+ if (again) put(`${tag}/relayout/${i}`, again);+ });+ };+ // With the drawn templates, and with none: the layouts written as code.+ layouts('full', undefined);+ layouts('plain', []);+ }+ return out;+}++describe('the auto layout moved from the Studio', () => {+ const actual = cases();++ it('AUTOPAR-001: covers the same cases the client code was measured on', () => {+ expect([...actual.keys()].sort()).toEqual(Object.keys(expected).sort());+ expect(actual.size).toBeGreaterThan(100);+ });++ it('AUTOPAR-002: lays out every fixture journey exactly as the client code did', () => {+ const differ = [...actual].filter(([key, value]) => expected[key] !== value).map(([key]) => key);+ expect(differ).toEqual([]);+ });++ it('AUTOPAR-003: mints its ids with the function it is given', () => {+ let n = 0;+ const fx = fixtures.A as Fixture;+ const doc = buildBook({ ...fx.input, newId: (p) => `${p}-c${++n}` });+ const ids = doc.spreads.flatMap((s) => [s.id, ...s.elements.map((e) => e.id)]);+ expect(ids.every((id) => /-c\d+$/.test(id))).toBe(true);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('AUTOPAR-004: counts the day of an entry in calendar days, a change to summer time between', () => {+ const stats: JourneyStats = {+ journeyId: 1,+ distance: 0,+ days: 10,+ steps: 1,+ photos: 0,+ places: 1,+ furthest: 0,+ countries: [],+ points: [],+ trips: [],+ excluded: [],+ start: '2026-03-27',+ end: '2026-04-05',+ };+ const entry: AutoEntry = {+ id: 1,+ title: 'Spring',+ story: null,+ location: null,+ date: '2026-03-30',+ photos: [],+ lat: null,+ lng: null,+ country: null,+ dayNumber: null,+ dayCount: null,+ pros: [],+ cons: [],+ };+ expect(autoEntriesWithStops([entry], stats)[0]).toMatchObject({ dayNumber: 4, dayCount: 10 });+ });++ it('AUTOPAR-010: the classic design is the Auto layout, page for page', () => {+ for (const [name, fx] of Object.entries(fixtures)) {+ const input = { ...fx.input, gallery: fx.gallery, candidates: [], photos: [] };+ const result = designBook(null, input, { style: 'classic' });+ const doc = result.doc;+ const head = { version: doc.version, title: doc.title, page: doc.page, count: doc.spreads.length };+ expect(digest(head)).toBe(expected[`${name}/full/head`]);+ doc.spreads.forEach((s, i) => expect(digest(s)).toBe(expected[`${name}/full/spread/${i}`]));+ expect(result.plan.map((r) => r.action).every((a) => a === 'insert')).toBe(true);+ }+ });+});diff --git a/shared/src/book/auto/auto-spreads.ts b/shared/src/book/auto/auto-spreads.tsnew file mode 100644index 000000000..afdad51ac--- /dev/null+++ b/shared/src/book/auto/auto-spreads.ts@@ -0,0 +1,444 @@+import { formatBookDate } from '../book-text';+import type { BookElement, BookSpread } from '../book.schema';+import {+ ACCENT,+ CREAM,+ PANEL_INK,+ PANEL_TYPE,+ bleedFrame,+ coordsMark,+ countryOf,+ countryWatermark,+ dateMark,+ dayChip,+ flagRow,+ isPortrait,+ photo,+ placeMap,+ progressRule,+ shape,+ sheet,+ text,+ type NewId,+} from './auto-elements';+import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';++/**+ * ── The entry spreads ────────────────────────────────────────────────────+ *+ * Seven layouts rather than one, chosen by what the entry actually has and+ * alternating as the book goes on. A book where every spread is built the same+ * way reads as a template even when each page is fine on its own.+ *+ * A printed travel book is built out of areas: a page laid solid in ink with+ * pale type on it, a band down the outer edge, a picture that overruns the+ * panel it sits against, a box ruled around a block of text. The document+ * paints in array order, so a panel pushed first is a panel everything else+ * lands on.+ */++/** Which page the picture is on. Alternating keeps the book moving. */+type Hand = 'left' | 'right';++export interface EntryContext {+ entry: AutoEntry;+ input: AutoInput;+ /** Position in the book, for alternating the layouts. */+ index: number;+ hand: Hand;+ newId: NewId;+}++/** An entry's photos, read where the caller has already made sure there is a first one. */+const withHero = (photos: AutoPhoto[]) => photos as [AutoPhoto, ...AutoPhoto[]];++const storyOf = (entry: AutoEntry) => (entry.story || '').trim();++/** The date and place line's printed separator (a middle dot), kept as the Studio has always set it. */+const META_JOIN = ' \u00b7 ';++/** A whole page laid in colour, bleeding off its three outer edges. */+function pagePanel(ctx: EntryContext, side: Hand, fill: string): BookElement {+ const { page } = ctx.input;+ const b = page.bleed;+ const frame = {+ x: side === 'left' ? -b : page.pageWidth,+ y: -b,+ w: page.pageWidth + b,+ h: page.pageHeight + b * 2,+ };+ return shape(ctx.newId, frame, fill);+}++/** A band down the outer edge: the cheapest mark that says "designed". */+function edgeBand(ctx: EntryContext, side: Hand, fill: string, width: number): BookElement {+ const { page } = ctx.input;+ const b = page.bleed;+ const frame = {+ x: side === 'left' ? -b : page.pageWidth * 2 - width,+ y: -b,+ w: width + b,+ h: page.pageHeight + b * 2,+ };+ return shape(ctx.newId, frame, fill);+}++interface HeadingStyle {+ size?: number;+ ink?: string;+ muted?: string;+}++/** The heading block: rule, date line, title. Returns where it ended. */+function headingBlock(+ ctx: EntryContext,+ els: BookElement[],+ at: { x: number; y: number; w: number },+ opts: HeadingStyle = {},+): number {+ const { entry, input, newId } = ctx;+ const { x, y, w } = at;+ const size = opts.size ?? 22;+ const ink = opts.ink ?? '#141414';+ const muted = opts.muted ?? '#8a8578';+ const heading = entry.title || entry.location || '';+ const meta = [formatBookDate(entry.date, input.locale), entry.location].filter(Boolean).join(META_JOIN);+ let cy = y;++ if (meta || heading) els.push(shape(newId, { x, y: cy - 6, w: Math.min(14, w * 0.18), h: 0.5 }, ACCENT));+ if (meta) {+ // Two facts run together and upper-cased: neither is bound, since the journal holds neither like this.+ const style = { size: 7.5, weight: 600 as const, tracking: 0.14, color: muted };+ els.push(text(newId, { x, y: cy, w, h: 5 }, meta.toUpperCase(), style));+ cy += 8;+ }+ if (heading) {+ const style = {+ size,+ weight: 700 as const,+ leading: 1.1,+ tracking: -0.02,+ color: ink,+ binding: { source: 'entry.title' as const, entryId: entry.id },+ };+ els.push(text(newId, { x, y: cy, w, h: size * 0.6 }, heading, style));+ cy += size * 0.75;+ }+ return cy;+}++/** The foot: the day chip above the dot of the rule that says how far in this is. */+function footMarks(ctx: EntryContext, els: BookElement[], at: { x: number; y: number; w: number }): void {+ const { entry, input, newId } = ctx;+ const { x, y, w } = at;+ els.push(...progressRule(newId, at, entry.dayNumber, entry.dayCount));+ const day = entry.dayNumber;+ const total = entry.dayCount;+ if (!day) return;+ const t = total && total > 1 ? Math.min(1, Math.max(0, (day - 1) / (total - 1))) : 0;+ const cw = 24;+ const cx = Math.min(x + w - cw, Math.max(x, x + w * t - cw / 2));+ const chip = dayChip(newId, { x: cx, y: y - 11, w: cw, h: 7 }, day, input.dayLabel);+ if (chip) els.push(chip);+}++/** The story, bound to the entry, set in a column. */+function storyText(ctx: EntryContext, frame: BookElement['frame'], size: number, leading: number, color: string) {+ const binding = { source: 'entry.story' as const, entryId: ctx.entry.id };+ return text(ctx.newId, frame, storyOf(ctx.entry), { size, leading, color, binding });+}++/** The country's flag and name, where the entry knows its country. */+function flagOf(ctx: EntryContext, frame: BookElement['frame']): BookElement | null {+ return flagRow(ctx.newId, frame, ctx.entry.country ?? null, countryOf(ctx.entry, ctx.input));+}++/**+ * A stop, with nothing written about it yet: the country pale behind, the+ * name large, the coordinates beneath it, and the picture page waiting as a+ * frame.+ */+export function placeSpread(ctx: EntryContext): BookSpread {+ const { entry, input, hand, newId } = ctx;+ const { page } = input;+ const H = page.pageHeight;+ const m = 18;+ const els: BookElement[] = [];+ const photoPage = hand === 'left' ? 0 : page.pageWidth;+ const textPage = hand === 'left' ? page.pageWidth : 0;+ const tx = textPage + m;+ const colW = page.pageWidth - m * 2;++ const wm = countryWatermark(newId, { x: tx, y: H * 0.22, w: colW, h: H * 0.4 }, entry.country);+ if (wm) els.push(wm);+ const flag = flagOf(ctx, { x: tx, y: m + 4, w: colW * 0.7, h: 7 });+ if (flag) els.push(flag);+ const name = entry.title || entry.location || '';+ if (name) {+ const style = {+ size: 26,+ weight: 700 as const,+ tracking: -0.02,+ color: '#141414',+ binding: { source: 'entry.title' as const, entryId: entry.id },+ };+ els.push(text(newId, { x: tx, y: H * 0.42, w: colW, h: 20 }, name, style));+ }+ const coords = coordsMark(newId, { x: tx, y: H * 0.42 + 22, w: colW, h: 6 }, entry.lat, entry.lng);+ if (coords) els.push(coords);+ footMarks(ctx, els, { x: tx, y: H - m - 6, w: colW });+ // The picture page: one frame, edge to edge, waiting.+ els.push(photo(newId, { x: photoPage + m, y: m, w: page.pageWidth - m * 2, h: H - m * 2 }, null));+ return sheet(newId, els, entry, '#faf8f4');+}++/**+ * A day that was written about: words on one page, one picture on the other,+ * running off three edges and stopping dead on the gutter.+ */+export function storySpread(ctx: EntryContext): BookSpread {+ const { entry, input, hand, newId } = ctx;+ const { page } = input;+ const H = page.pageHeight;+ const m = 18;+ const els: BookElement[] = [];+ const hero = entry.photos[0];+ const textPage = hand === 'left' ? page.pageWidth : 0;+ const tx = textPage + m;+ const colW = page.pageWidth - m * 2;+ const onLeft = hand === 'left';++ if (hero) {+ const frame = {+ x: onLeft ? -page.bleed : page.pageWidth,+ y: -page.bleed,+ w: page.pageWidth + page.bleed,+ h: H + page.bleed * 2,+ };+ els.push(photo(newId, frame, hero.photoId, { focalX: isPortrait(hero) ? 0.5 : 0.55 }));+ if (hero.caption) {+ const at = { x: (onLeft ? 0 : page.pageWidth) + m, y: H - m - 6, w: page.pageWidth * 0.6, h: 5 };+ const style = {+ size: 7.5,+ weight: 500 as const,+ color: '#ffffff',+ opacity: 0.9,+ binding: { source: 'photo.caption' as const, entryId: entry.id, photoId: hero.photoId },+ };+ els.push(text(newId, at, hero.caption, style));+ }+ } else {+ // No photograph yet, but the page it will sit on is already the page.+ const frame = { x: (onLeft ? 0 : page.pageWidth) + m, y: m, w: page.pageWidth - m * 2, h: H - m * 2 };+ els.push(photo(newId, frame, null));+ }++ // A small map of the stop, top of the text page: the mark that says where.+ const map = placeMap(newId, { x: tx, y: m, w: 26, h: 20 }, entry, input.stats);+ if (map) els.push(map);+ const flag = flagOf(ctx, { x: tx + (map ? 32 : 0), y: m + 6, w: colW - (map ? 32 : 0), h: 7 });+ if (flag) els.push(flag);++ const cy = headingBlock(ctx, els, { x: tx, y: m + 34, w: colW }, { size: 20 });+ const body = { x: tx, y: cy + 3, w: colW, h: H - cy - m - 34 };+ if (storyOf(entry)) els.push(storyText(ctx, body, 10, 1.62, '#2a2a2a'));+ const mark = dateMark(newId, entry.date, input.locale, { x: tx, y: H - m - 30, w: 26, h: 20 });+ if (mark) els.push(mark);+ footMarks(ctx, els, { x: tx, y: H - m - 4, w: colW });+ return sheet(newId, els, entry, '#ffffff');+}++/** A panorama across the fold, with the day underneath it: the gutter as an asset. */+export function panoSpread(ctx: EntryContext): BookSpread {+ const { entry, input, newId } = ctx;+ const { page } = input;+ const W = page.pageWidth * 2;+ const H = page.pageHeight;+ const m = 18;+ const gut = 6;+ const els: BookElement[] = [];+ const [hero, ...rest] = withHero(entry.photos);++ const band = { x: -page.bleed, y: -page.bleed, w: W + page.bleed * 2, h: H * 0.58 + page.bleed };+ els.push(photo(newId, band, hero.photoId));+ const cy = headingBlock(ctx, els, { x: m, y: H * 0.58 + 16, w: page.pageWidth - m * 2 }, { size: 18 });+ const body = { x: m, y: cy + 2, w: page.pageWidth - m * 2, h: H - cy - m - 12 };+ if (storyOf(entry)) els.push(storyText(ctx, body, 10, 1.6, '#2a2a2a'));+ const strip = rest.slice(0, 3);+ if (strip.length) {+ const cw = (page.pageWidth - m * 2 - gut * (strip.length - 1)) / strip.length;+ strip.forEach((p, i) => {+ const frame = { x: page.pageWidth + m + i * (cw + gut), y: H * 0.58 + 16, w: cw, h: H * 0.26 };+ els.push(photo(newId, frame, p.photoId));+ });+ }+ const flag = flagOf(ctx, { x: page.pageWidth + m, y: H - m - 16, w: page.pageWidth - m * 2, h: 7 });+ if (flag) els.push(flag);+ footMarks(ctx, els, { x: page.pageWidth + m, y: H - m - 4, w: page.pageWidth - m * 2 });+ return sheet(newId, els, entry, '#ffffff');+}++/** Several pictures: one large, the rest ruled beneath the words, the way a magazine sets a picture story. */+export function gallerySpread(ctx: EntryContext): BookSpread {+ const { entry, input, hand, newId } = ctx;+ const { page } = input;+ const H = page.pageHeight;+ const m = 18;+ const gut = 5;+ const els: BookElement[] = [];+ const [hero, ...rest] = withHero(entry.photos);+ const heroOnLeft = hand === 'left';+ const heroX = heroOnLeft ? -page.bleed : page.pageWidth;+ const textX = (heroOnLeft ? page.pageWidth : 0) + m;+ const colW = page.pageWidth - m * 2;++ const heroFrame = { x: heroX, y: -page.bleed, w: page.pageWidth + page.bleed, h: H + page.bleed * 2 };+ els.push(photo(newId, heroFrame, hero.photoId, { focalX: isPortrait(hero) ? 0.5 : 0.55 }));+ const flag = flagOf(ctx, { x: textX, y: m + 2, w: colW, h: 7 });+ const cy = headingBlock(ctx, els, { x: textX, y: m + (flag ? 26 : 16), w: colW }, { size: 19 });+ if (flag) els.push(flag);++ const strip = rest.slice(0, 3);+ const stripH = strip.length ? (strip.length === 1 ? H * 0.28 : H * 0.22) : 0;+ // The foot carries the rule and the chip, so nothing else may end there.+ const footRoom = 22;+ if (storyOf(entry)) {+ const h = H - cy - m - (stripH ? stripH + 12 : 0) - footRoom;+ els.push(storyText(ctx, { x: textX, y: cy + 2, w: colW, h: Math.max(18, h) }, 10, 1.62, '#2a2a2a'));+ }+ if (strip.length) {+ const cw = (colW - gut * (strip.length - 1)) / strip.length;+ strip.forEach((p, i) => {+ const frame = { x: textX + i * (cw + gut), y: H - m - footRoom - stripH, w: cw, h: stripH };+ els.push(photo(newId, frame, p.photoId));+ });+ }+ footMarks(ctx, els, { x: textX, y: H - m - 4, w: colW });+ return sheet(newId, els, entry, '#ffffff');+}++/** One picture over the whole sheet, the words set on top of it: the loudest page, used sparingly. */+export function immersiveSpread(ctx: EntryContext): BookSpread {+ const { entry, input, newId } = ctx;+ const { page } = input;+ const W = page.pageWidth * 2;+ const H = page.pageHeight;+ const m = 20;+ const els: BookElement[] = [];+ const hero = entry.photos[0];++ els.push(photo(newId, bleedFrame(page, true), hero ? hero.photoId : null, { focalY: 0.45 }));+ // A panel behind the type: white on an unknown photograph is a coin toss.+ const scrim = { x: -page.bleed, y: H * 0.56, w: W + page.bleed * 2, h: H * 0.44 + page.bleed };+ els.push(shape(newId, scrim, '#0d0d0f', { gradient: 'up', opacity: 0.72 }));+ const light = { size: 24, ink: '#ffffff', muted: '#d8d3ca' };+ headingBlock(ctx, els, { x: m, y: H * 0.68, w: page.pageWidth - m * 2 }, light);+ const body = { x: page.pageWidth + m, y: H * 0.68, w: page.pageWidth - m * 2, h: H * 0.26 };+ if (storyOf(entry)) els.push(storyText(ctx, body, 9.5, 1.6, '#efece6'));+ const coords = coordsMark(newId, { x: m, y: H - m - 5, w: page.pageWidth - m * 2, h: 5 }, entry.lat, entry.lng);+ if (coords) els.push(coords);+ return sheet(newId, els, entry, '#0d0d0f');+}++/**+ * A page laid in ink, the picture overrunning it: one page solid, the other a+ * photograph, and a second picture crossing the join so the two halves read+ * as one sheet.+ */+export function panelSpread(ctx: EntryContext): BookSpread {+ const { entry, input, hand, newId } = ctx;+ const { page } = input;+ const H = page.pageHeight;+ const m = 20;+ const els: BookElement[] = [];+ const [hero, ...rest] = entry.photos;+ const panelSide: Hand = hand === 'left' ? 'right' : 'left';+ const panelX = panelSide === 'left' ? 0 : page.pageWidth;+ const tx = panelX + m;+ const colW = page.pageWidth - m * 2;++ // The panel first: everything after it lands on top.+ els.push(pagePanel(ctx, panelSide, PANEL_INK));+ if (hero) {+ const frame = {+ x: panelSide === 'left' ? page.pageWidth : -page.bleed,+ y: -page.bleed,+ w: page.pageWidth + page.bleed,+ h: H + page.bleed * 2,+ };+ els.push(photo(newId, frame, hero.photoId, { focalX: isPortrait(hero) ? 0.5 : 0.55 }));+ } else {+ const frame = { x: (panelSide === 'left' ? page.pageWidth : 0) + m, y: m, w: colW, h: H - m * 2 };+ els.push(photo(newId, frame, null));+ }+ const flag = flagOf(ctx, { x: tx, y: m, w: colW, h: 7 });+ if (flag) els.push(flag);+ const onPanel = { size: 21, ink: PANEL_TYPE, muted: '#a8a094' };+ const cy = headingBlock(ctx, els, { x: tx, y: m + 30, w: colW }, onPanel);+ const body = { x: tx, y: cy + 3, w: colW, h: H - cy - m - 46 };+ if (storyOf(entry)) els.push(storyText(ctx, body, 9.5, 1.66, '#d9d4cb'));++ // A second picture across the fold, half on the panel, pushed last so it sits over both.+ const crossing = rest[0];+ if (crossing) {+ const cw = 62;+ const ch = 46;+ const frame = { x: page.pageWidth - cw * 0.55, y: H - m - ch - 14, w: cw, h: ch };+ els.push(photo(newId, frame, crossing.photoId, { radius: 1 }));+ }+ footMarks(ctx, els, { x: tx, y: H - m - 4, w: colW });+ return sheet(newId, els, entry, CREAM);+}++/**+ * A band down the edge, a ruled box, and pictures at two sizes: the quiet+ * counterpart to the panel spread. The box makes the words an object on the+ * page rather than something poured onto it.+ */+export function bandSpread(ctx: EntryContext): BookSpread {+ const { entry, input, hand, newId } = ctx;+ const { page } = input;+ const H = page.pageHeight;+ const m = 20;+ const gut = 5;+ const els: BookElement[] = [];+ const photos = entry.photos;++ els.push(edgeBand(ctx, hand, ACCENT, 6));+ // The big picture takes most of one page, off the top and the outer edge.+ const heroX = hand === 'left' ? 6 : page.pageWidth;+ const heroW = page.pageWidth - 6 + (hand === 'left' ? 0 : page.bleed);+ const first = photos[0];+ if (first) els.push(photo(newId, { x: heroX, y: -page.bleed, w: heroW, h: H * 0.62 }, first.photoId));+ else els.push(photo(newId, { x: heroX + m, y: m, w: heroW - m * 2, h: H * 0.5 }, null));++ const tx = (hand === 'left' ? page.pageWidth : 0) + m;+ const colW = page.pageWidth - m * 2;+ const boxY = m + 6;+ const boxH = H * 0.52;+ // The words in a ruled box, set in from it on every side.+ const box = { x: tx, y: boxY, w: colW, h: boxH };+ els.push(shape(newId, box, null, { stroke: '#d8d2c6', strokeWidth: 0.3, radius: 1.5 }));+ const flag = flagOf(ctx, { x: tx + 8, y: boxY + 8, w: colW - 16, h: 6 });+ if (flag) els.push(flag);+ const cy = headingBlock(ctx, els, { x: tx + 8, y: boxY + 30, w: colW - 16 }, { size: 18 });+ const body = { x: tx + 8, y: cy + 2, w: colW - 16, h: boxY + boxH - cy - 12 };+ if (storyOf(entry)) els.push(storyText(ctx, body, 9.5, 1.6, '#2a2a2a'));++ // Two smaller pictures under the box, and one that overlaps the hero above.+ const rest = photos.slice(1, 3);+ if (rest.length) {+ const cw = (colW - gut * (rest.length - 1)) / rest.length;+ rest.forEach((ph, i) => {+ const frame = { x: tx + i * (cw + gut), y: boxY + boxH + 10, w: cw, h: H * 0.2 };+ els.push(photo(newId, frame, ph.photoId, { radius: 1 }));+ });+ }+ const overlap = photos[3];+ const inset = { x: heroX + 14, y: H * 0.62 - 26, w: 52, h: 40 };+ if (overlap) els.push(photo(newId, inset, overlap.photoId, { radius: 1 }));+ const mark = dateMark(newId, entry.date, input.locale, { x: heroX + 14, y: H - m - 34, w: 26, h: 22 });+ if (mark) els.push(mark);+ footMarks(ctx, els, { x: tx, y: H - m - 4, w: colW });+ return sheet(newId, els, entry, '#ffffff');+}diff --git a/shared/src/book/auto/auto-template-apply.ts b/shared/src/book/auto/auto-template-apply.tsnew file mode 100644index 000000000..ff007008f--- /dev/null+++ b/shared/src/book/auto/auto-template-apply.ts@@ -0,0 +1,173 @@+import { bookCoordValue, formatBookCoords, formatBookDate } from '../book-text';+import {+ MAX_TEXT_LENGTH,+ type BookBadgeElement,+ type BookElement,+ type BookPageSetup,+ type BookSpread,+} from '../book.schema';+import type { JourneyStats } from '../journey-stats.schema';+import { statsValues, type NewId } from './auto-elements';+import type { AutoTemplate } from './auto-templates.data';+import type { AutoEntry } from './auto-types';++/**+ * Laying an entry out on a template somebody drew (`AUTO_TEMPLATES`).+ *+ * Only what the entry can answer for is filled: text carrying a `binding`+ * (the title, the story, a caption), empty photo frames (the entry's photos in+ * order), the day, coordinate, date and country marks, and the stats and+ * countries elements from the journey's figures. Everything else is the design+ * and is copied as drawn. That division is the whole contract between the+ * person who draws a template and the code that uses it.+ *+ * The template's numbers are fractions of the page it was drawn on, so they+ * are multiplied back up here: a template built on a 210mm square lays out on+ * an A4 landscape book without being redrawn. Moved here from the Studio+ * (client/src/components/Studio/applyTemplate.ts) and renamed, since+ * `applyBookTemplate` is the built-in layouts' own function.+ */++export interface AutoTemplateContext {+ page: BookPageSetup;+ locale: string;+ stats: JourneyStats | null;+ /** Already translated, because this module has no translation context. */+ dayLabel: string;+ newId: NewId;+}++const round2 = (n: number) => Math.round(n * 100) / 100;++/** How well a template suits an entry: more is better, -1 means unusable. */+export function autoTemplateFit(template: AutoTemplate, entry: AutoEntry): number {+ const frames = template.elements.filter((e) => e.kind === 'photo').length;+ const photos = entry.photos.length;+ const wantsStory = template.elements.some((e) => e.kind === 'text' && e.binding?.source === 'entry.story');+ const hasStory = !!(entry.story || '').trim();++ // A template is a template for an entry when it uses one: a binding or an empty frame says so.+ const usesEntry = template.elements.some(+ (e) => ('binding' in e && e.binding) || (e.kind === 'photo' && e.photoId == null),+ );+ if (!usesEntry) return -1;++ // Three frames for one picture leaves two placeholders on a finished page; more pictures than frames is fine.+ if (frames > photos + 1) return -1;+ if (wantsStory && !hasStory) return -1;++ return 100 - Math.abs(frames - photos) * 10 - (wantsStory === hasStory ? 0 : 5);+}++/** Fill a template with an entry, and hand back the spread it makes. */+export function applyAutoTemplate(template: AutoTemplate, entry: AutoEntry, ctx: AutoTemplateContext): BookSpread {+ const PW = ctx.page.pageWidth;+ const PH = ctx.page.pageHeight;+ let nextPhoto = 0;+ // A journal entry has no length limit and a text element does.+ const story = (entry.story || '').trim().slice(0, MAX_TEXT_LENGTH);+ const heading = (entry.title || entry.location || '').slice(0, MAX_TEXT_LENGTH);++ const elements = template.elements.map((el) => {+ const frame = {+ x: round2(el.frame.x * PW),+ y: round2(el.frame.y * PH),+ w: round2(el.frame.w * PW),+ h: round2(el.frame.h * PH),+ };+ const out = { ...el, id: ctx.newId(el.kind.charAt(0)), frame } as BookElement;++ // Sizes came out as fractions of the page height, radii and strokes of its width.+ if (out.kind === 'text' && typeof out.size === 'number') out.size = round2(out.size * PH);+ if ((out.kind === 'photo' || out.kind === 'shape') && typeof out.radius === 'number') {+ out.radius = round2(out.radius * PW);+ }+ if (out.kind === 'shape' && typeof out.strokeWidth === 'number') out.strokeWidth = round2(out.strokeWidth * PW);++ if (out.kind === 'text' && out.binding) fillText(out, entry, ctx, { story, heading });+ if (out.kind === 'photo' && out.photoId == null) {+ const picture = entry.photos[nextPhoto++];+ if (picture) out.photoId = picture.photoId;+ }+ if (out.kind === 'badge') fillBadge(out, entry, ctx);+ if (out.kind === 'countries' && ctx.stats) {+ out.codes = ctx.stats.countries.map((c) => c.code);+ out.names = ctx.stats.countries.map((c) => c.name);+ }+ // The figures live in one map on the element, keyed by metric, as the panels write them.+ if (out.kind === 'stats' && ctx.stats) out.values = statsValues(ctx.stats);+ return out;+ });++ return {+ id: ctx.newId('sp'),+ role: 'inner',+ background: template.background,+ elements,+ parked: [],+ entryId: entry.id,+ };+}++type TextEl = Extract<BookElement, { kind: 'text' }>;++/** A bound text, set from the entry; the raw value is kept where the words were made rather than copied. */+function fillText(+ out: TextEl,+ entry: AutoEntry,+ ctx: AutoTemplateContext,+ words: { story: string; heading: string },+): void {+ if (!out.binding) return;+ const { source, format } = out.binding;+ let value: string | undefined;+ if (source === 'entry.title') out.text = words.heading;+ else if (source === 'entry.story') out.text = words.story;+ else if (source === 'entry.date') {+ out.text = formatBookDate(entry.date, ctx.locale);+ value = entry.date ?? undefined;+ } else if (source === 'entry.location') {+ // The place as its name or as its point; a stop the entry cannot answer keeps the drawn words.+ if (format && entry.lat != null && entry.lng != null) {+ out.text = formatBookCoords(entry.lat, entry.lng, format);+ value = bookCoordValue(entry.lat, entry.lng);+ } else if (!format && entry.location) {+ out.text = entry.location;+ }+ }+ out.binding = { ...out.binding, entryId: entry.id, ...(value ? { value } : {}) };+}++/**+ * The small marks, filled from the stop. A badge whose value the entry cannot+ * answer keeps the one it was drawn with.+ */+function fillBadge(el: BookBadgeElement, entry: AutoEntry, ctx: AutoTemplateContext): void {+ if (el.variant === 'day' && entry.dayNumber) el.text = `${ctx.dayLabel} ${entry.dayNumber}`;+ if (el.variant === 'coords' && entry.lat != null && entry.lng != null) {+ el.text = formatBookCoords(entry.lat, entry.lng);+ }+ if ((el.variant === 'flag' || el.variant === 'country') && entry.country) {+ el.code = entry.country;+ el.text = countryName(entry.country, ctx).toUpperCase();+ }+ if (el.variant === 'date' && entry.date) {+ const d = new Date(`${entry.date}T00:00:00`);+ if (!Number.isNaN(d.getTime())) {+ el.text = String(d.getDate());+ el.sub = d.toLocaleDateString(ctx.locale, { month: 'long' }).toUpperCase();+ }+ }+ if (el.variant === 'distance' && ctx.stats?.distance) {+ el.text = `${Math.round(ctx.stats.distance / 1000).toLocaleString(ctx.locale)} km`;+ }+}++function countryName(code: string, ctx: AutoTemplateContext): string {+ const known = ctx.stats?.countries.find((c) => c.code === code);+ try {+ return new Intl.DisplayNames([ctx.locale], { type: 'region' }).of(code) ?? known?.name ?? code;+ } catch {+ return known?.name ?? code;+ }+}diff --git a/shared/src/book/auto/auto-templates.data.ts b/shared/src/book/auto/auto-templates.data.tsnew file mode 100644index 000000000..2b2c8226f--- /dev/null+++ b/shared/src/book/auto/auto-templates.data.ts@@ -0,0 +1,1268 @@+import type { BookElement } from '../book.schema';++/**+ * The spread templates the auto layout tries first, as data.+ *+ * ── Where these come from ────────────────────────────────────────────────+ *+ * Not from this file's author. They were built by hand in Studio and read back+ * out of the document, which is the point: what a page should look like is a+ * matter of taste, and taste is not something a layout function arrives at by+ * reasoning. The editor is the design tool, and this is its output. Moved here+ * from the Studio (client/src/components/Studio/bookTemplates.data.ts) so the+ * server's design tool and the Studio lay a book out with the same set.+ *+ * To add one: build the spread in Studio, then run+ *+ * node scripts/extract-templates.cjs <journeyId>+ *+ * from server/ and commit what it writes here.+ *+ * ── Why the numbers are fractions ────────────────────────────────────────+ *+ * Every frame is divided by the page it was drawn on (x and w by one page's+ * width, y and h by its height) and type sizes by the page height. A template+ * built on a 210mm square therefore lays out on an A4 landscape book without+ * being redrawn. That is also why these are not parsed through the document+ * schema: a size of 0.14 is a fraction here, not a point size.+ *+ * ── What gets filled in ──────────────────────────────────────────────────+ *+ * Elements carrying a `binding` take their text from the entry; empty photo+ * frames take its photographs in order; the day, coordinate and country marks+ * take what the entry knows about its stop. Everything else (the panels, the+ * rules, the shapes that run off the page) is the design, and is kept as it+ * was drawn.+ */++export interface AutoTemplate {+ id: string;+ background: string | null;+ /** Frames and sizes are fractions; see the note above. */+ elements: BookElement[];+}++export const AUTO_TEMPLATES: readonly AutoTemplate[] = [+ {+ id: 'ref-1',+ background: null,+ elements: [+ {+ id: 'p-iy13loy',+ frame: {+ x: 0.0238,+ y: 0.0238,+ w: 0.9524,+ h: 0.9524,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.572289143475242,+ focalY: 0.5726791042512355,+ radius: 0.0238,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 's-kafy6t4',+ frame: {+ x: 1.5898,+ y: 0.0238,+ w: 0.3864,+ h: 0.9524,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'shape',+ shape: 'rect',+ fill: '#111111',+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 0,+ },+ {+ id: 't-v4jhfu6',+ frame: {+ x: 1.5898,+ y: 0.0563,+ w: 0.3864,+ h: 0.0613,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'COUNTRIES',+ font: 'sans',+ size: 0.1429,+ weight: 700,+ italic: false,+ align: 'center',+ leading: 1.1,+ tracking: -0.02,+ color: '#ffffff',+ binding: null,+ overridden: true,+ },+ {+ id: 't-nh804rp',+ frame: {+ x: 1.1136,+ y: 0.0563,+ w: 0.3864,+ h: 0.0613,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'SUMMARY',+ font: 'sans',+ size: 0.1429,+ weight: 700,+ italic: false,+ align: 'center',+ leading: 1.1,+ tracking: -0.02,+ color: '#111111',+ binding: null,+ overridden: true,+ },+ {+ id: 's-8c3kwzk',+ frame: {+ x: 1.0812,+ y: 0.1757,+ w: 0.4511,+ h: 0.5743,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#111111',+ textScale: 1.5,+ weight: 700,+ stale: false,+ kind: 'stats',+ metrics: ['distance', 'days', 'steps', 'photos', 'countries', 'places'],+ layout: 'grid',+ showIcons: true,+ units: 'metric',+ values: {+ distance: 352677,+ days: 1,+ steps: 2,+ photos: 3,+ countries: 2,+ places: 0,+ furthest: 352677,+ },+ },+ {+ id: 'b-15vswaz',+ frame: {+ x: 1.1768,+ y: 0.7685,+ w: 0.2587,+ h: 0.066,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#111111',+ textScale: 1,+ weight: 700,+ stale: false,+ kind: 'badge',+ variant: 'distance',+ text: '0 km',+ sub: 'Distance',+ code: null,+ style: 'chip',+ autoColor: true,+ showIcon: true,+ showLabel: true,+ autoIconColor: true,+ iconColor: '#111111',+ },+ {+ id: 'c-jdsxmvn',+ frame: {+ x: 1.628,+ y: 0.2315,+ w: 0.31,+ h: 0.537,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#ffffff',+ accent: '#ffffff',+ textScale: 0.7,+ weight: 700,+ stale: false,+ kind: 'countries',+ codes: ['DE', 'NL'],+ names: ['Germany', 'Netherlands'],+ layout: 'list',+ showOutline: true,+ showFlag: false,+ showName: true,+ align: 'center',+ },+ ],+ },+ {+ id: 'ref-2',+ background: null,+ elements: [+ {+ id: 's-f7yltlr',+ frame: {+ x: -0.1264,+ y: 0.6775,+ w: 0.5595,+ h: 0.5973,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'shape',+ shape: 'flower-5',+ fill: '#111111',+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 0,+ },+ {+ id: 's-0fpxqfa',+ frame: {+ x: 1.0762,+ y: 0.6437,+ w: 0.8635,+ h: 0.2829,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'shape',+ shape: 'rect',+ fill: '#111111',+ gradient: 'none',+ stroke: '#11224f',+ strokeWidth: 0.0024,+ strokeStyle: 'solid',+ radius: 0,+ },+ {+ id: 'p-b5dnke1',+ frame: {+ x: 0.0238,+ y: 0.0238,+ w: 1.9524,+ h: 0.3062,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: 69,+ fit: 'cover',+ focalX: 0.42168673729754674,+ focalY: 0.23833399057977409,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 't-kvtn36a',+ frame: {+ x: 0.0762,+ y: 0.3843,+ w: 0.8476,+ h: 0.0479,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet',+ font: 'sans',+ size: 0.1048,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.title',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 't-cnhlrmk',+ frame: {+ x: 0.0762,+ y: 0.452,+ w: 0.8476,+ h: 0.1917,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',+ font: 'sans',+ size: 0.0476,+ weight: 400,+ italic: false,+ align: 'left',+ leading: 1.55,+ tracking: 0,+ color: '#1a1a1a',+ binding: {+ source: 'entry.story',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 'li-w82p1lh',+ frame: {+ x: 1.1161,+ y: 0.6769,+ w: 0.7837,+ h: 0.0731,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#ffffff',+ accent: '#ffffff',+ textScale: 1,+ weight: 700,+ stale: false,+ kind: 'list',+ items: [+ {+ text: 'TEST1',+ tone: 'pro',+ },+ {+ text: 'TEST1',+ tone: 'con',+ },+ ],+ layout: 'columns',+ showMarks: true,+ proLabel: 'PROS',+ conLabel: 'Cons',+ },+ {+ id: 't-gabkf9x',+ frame: {+ x: 1.0762,+ y: 0.3843,+ w: 0.8476,+ h: 0.1917,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',+ font: 'sans',+ size: 0.0476,+ weight: 400,+ italic: false,+ align: 'left',+ leading: 1.55,+ tracking: 0,+ color: '#1a1a1a',+ binding: {+ source: 'entry.story',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 's-vkl7noe',+ frame: {+ x: 1.0762,+ y: 0.6034,+ w: 0.5,+ h: 0.0024,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'shape',+ shape: 'rect',+ fill: '#141414',+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 0,+ },+ {+ id: 'p-s3anbzj',+ frame: {+ x: 0.1836,+ y: 0.7134,+ w: 0.2,+ h: 0.2171,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: 68,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'polaroid',+ },+ {+ id: 'p-874qk6j',+ frame: {+ x: 0.5893,+ y: 0.7134,+ w: 0.2,+ h: 0.2171,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: 69,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: 'heart',+ frameStyle: 'polaroid',+ },+ {+ id: 'b-gmtenyt',+ frame: {+ x: 0.5993,+ y: 0.8893,+ w: 0.18,+ h: 0.05,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#111111',+ textScale: 1.2,+ weight: 700,+ stale: false,+ kind: 'badge',+ variant: 'coords',+ text: "51°10'N 10°27'E",+ sub: '',+ code: null,+ style: 'plain',+ autoColor: true,+ showIcon: true,+ showLabel: true,+ autoIconColor: true,+ iconColor: '#111111',+ },+ {+ id: 'b-4rd95kg',+ frame: {+ x: 0.1936,+ y: 0.8893,+ w: 0.18,+ h: 0.05,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#111111',+ textScale: 1.2,+ weight: 700,+ stale: false,+ kind: 'badge',+ variant: 'coords',+ text: "51°10'N 10°27'E",+ sub: '',+ code: null,+ style: 'plain',+ autoColor: true,+ showIcon: true,+ showLabel: true,+ autoIconColor: true,+ iconColor: '#111111',+ },+ ],+ },+ {+ id: 'ref-3',+ background: null,+ elements: [+ {+ id: 'p-sa5cabi',+ frame: {+ x: 0.025,+ y: 0.025,+ w: 1.9512,+ h: 0.5919,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 't-kws7inb',+ frame: {+ x: 0.054,+ y: 0.688,+ w: 0.8919,+ h: 0.2294,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet',+ font: 'sans',+ size: 0.2381,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.title',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 't-1zzydde',+ frame: {+ x: 1.0808,+ y: 0.6542,+ w: 0.8385,+ h: 0.1917,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',+ font: 'sans',+ size: 0.0476,+ weight: 400,+ italic: false,+ align: 'left',+ leading: 1.55,+ tracking: 0,+ color: '#1a1a1a',+ binding: {+ source: 'entry.story',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 't-kht4sfu',+ frame: {+ x: 0.054,+ y: 0.6542,+ w: 0.36,+ h: 0.0314,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'August 19, 2026',+ font: 'sans',+ size: 0.0762,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.date',+ entryId: 62,+ value: '2026-08-19',+ },+ overridden: false,+ },+ ],+ },+ {+ id: 'ref-4',+ background: null,+ elements: [+ {+ id: 's-19c5q0x',+ frame: {+ x: -0.1119,+ y: 0.4164,+ w: 0.7143,+ h: 0.7143,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'shape',+ shape: 'ellipse',+ fill: '#141414',+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 0,+ },+ {+ id: 'p-e8ee9j8',+ frame: {+ x: 0.0816,+ y: 0.0763,+ w: 0.3367,+ h: 0.3827,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'polaroid',+ },+ {+ id: 'p-fimcc5x',+ frame: {+ x: 0.5662,+ y: 0.202,+ w: 0.3367,+ h: 0.3827,+ },+ rotation: -10.1,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'polaroid',+ },+ {+ id: 'p-nva57q1',+ frame: {+ x: 0.1739,+ y: 0.5,+ w: 0.3367,+ h: 0.3827,+ },+ rotation: 5.1,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: 'seal',+ frameStyle: 'polaroid',+ },+ {+ id: 't-7zfrwms',+ frame: {+ x: 1.0762,+ y: 0.1605,+ w: 0.8476,+ h: 0.0895,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet',+ font: 'sans',+ size: 0.1429,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.title',+ entryId: 63,+ },+ overridden: false,+ },+ {+ id: 't-culm58m',+ frame: {+ x: 1.0762,+ y: 0.2676,+ w: 0.8476,+ h: 0.2073,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',+ font: 'sans',+ size: 0.0476,+ weight: 400,+ italic: false,+ align: 'left',+ leading: 1.55,+ tracking: 0,+ color: '#1a1a1a',+ binding: {+ source: 'entry.story',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 'li-dukbgme',+ frame: {+ x: 1.0762,+ y: 0.5116,+ w: 0.72,+ h: 0.0731,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#c2410c',+ textScale: 1,+ weight: 700,+ stale: false,+ kind: 'list',+ items: [+ {+ text: 'TEST1',+ tone: 'pro',+ },+ {+ text: 'TEST1',+ tone: 'con',+ },+ ],+ layout: 'columns',+ showMarks: true,+ proLabel: 'Pros',+ conLabel: 'Cons',+ },+ {+ id: 't-x3ysuxa',+ frame: {+ x: 1.0762,+ y: 0.116,+ w: 0.36,+ h: 0.0314,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'August 19, 2026',+ font: 'sans',+ size: 0.069,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.date',+ entryId: 62,+ value: '2026-08-19',+ },+ overridden: false,+ },+ ],+ },+ {+ id: 'ref-5',+ background: null,+ elements: [+ {+ id: 'p-adrg53f',+ frame: {+ x: 0.025,+ y: 0.025,+ w: 0.475,+ h: 0.9512,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 't-crm4sem',+ frame: {+ x: 0.5297,+ y: 0.119,+ w: 0.4258,+ h: 0.8012,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet',+ font: 'sans',+ size: 0.2381,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.title',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 's-3dhohc7',+ frame: {+ x: 1.0762,+ y: 0.3541,+ w: 0.5,+ h: 0.0024,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'shape',+ shape: 'rect',+ fill: '#f2f2f2',+ gradient: 'none',+ stroke: '#141414',+ strokeWidth: 0.0005,+ strokeStyle: 'solid',+ radius: 0,+ },+ {+ id: 't-0l6zeg7',+ frame: {+ x: 1.0762,+ y: 0.119,+ w: 0.8346,+ h: 0.2047,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',+ font: 'sans',+ size: 0.0476,+ weight: 400,+ italic: false,+ align: 'left',+ leading: 1.55,+ tracking: 0,+ color: '#1a1a1a',+ binding: {+ source: 'entry.story',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 'p-igt1irs',+ frame: {+ x: 1.0762,+ y: 0.4469,+ w: 0.368,+ h: 0.2495,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'shadow',+ },+ {+ id: 'p-2akhm3w',+ frame: {+ x: 1.5105,+ y: 0.4469,+ w: 0.368,+ h: 0.2495,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'shadow',+ },+ {+ id: 'bd-g6o9fvm',+ frame: {+ x: 0.53,+ y: 0.4577,+ w: 0.2604,+ h: 0.062,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#111111',+ textScale: 1,+ weight: 700,+ stale: false,+ kind: 'badge',+ variant: 'weather',+ text: 'Partly cloudy',+ sub: '',+ code: 'partly',+ style: 'chip',+ autoColor: true,+ showIcon: true,+ showLabel: true,+ autoIconColor: false,+ iconColor: '#ffffff',+ },+ {+ id: 'bd-ewxvw6v',+ frame: {+ x: 0.53,+ y: 0.5406,+ w: 0.2607,+ h: 0.062,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#111111',+ textScale: 1,+ weight: 700,+ stale: false,+ kind: 'badge',+ variant: 'mood',+ text: 'Amazing',+ sub: '',+ code: 'amazing',+ style: 'chip',+ autoColor: true,+ showIcon: true,+ showLabel: true,+ autoIconColor: false,+ iconColor: '#ffffff',+ },+ {+ id: 't-az8f0nc',+ frame: {+ x: 0.5297,+ y: 0.0858,+ w: 0.36,+ h: 0.0347,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'August 19, 2026',+ font: 'sans',+ size: 0.0714,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.date',+ entryId: 62,+ value: '2026-08-19',+ },+ overridden: false,+ },+ ],+ },+ {+ id: 'ref-6',+ background: null,+ elements: [+ {+ id: 's-7go39mg',+ frame: {+ x: 0.0238,+ y: 0.309,+ w: 0.9524,+ h: 0.666,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'shape',+ shape: 'triangle',+ fill: '#141414',+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 0,+ },+ {+ id: 'p-a9065nh',+ frame: {+ x: 0.0238,+ y: 0.0238,+ w: 0.2745,+ h: 0.9512,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 'p-fvcm5kq',+ frame: {+ x: 0.3628,+ y: 0.0914,+ w: 0.2745,+ h: 0.8848,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 'p-aski19e',+ frame: {+ x: 0.7017,+ y: 0.0238,+ w: 0.2745,+ h: 0.9512,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 'p-tfs5cdi',+ frame: {+ x: 1.0238,+ y: 0.0238,+ w: 0.9524,+ h: 0.45,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'photo',+ photoId: null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ },+ {+ id: 't-9zjrvsn',+ frame: {+ x: 1.0592,+ y: 0.5,+ w: 0.8476,+ h: 0.0518,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet',+ font: 'sans',+ size: 0.1048,+ weight: 700,+ italic: false,+ align: 'left',+ leading: 1.1,+ tracking: -0.02,+ color: '#1a1a1a',+ binding: {+ source: 'entry.title',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 't-4lgyrab',+ frame: {+ x: 1.0592,+ y: 0.5682,+ w: 0.8476,+ h: 0.1995,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ kind: 'text',+ text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',+ font: 'sans',+ size: 0.0476,+ weight: 400,+ italic: false,+ align: 'left',+ leading: 1.55,+ tracking: 0,+ color: '#1a1a1a',+ binding: {+ source: 'entry.story',+ entryId: 62,+ },+ overridden: false,+ },+ {+ id: 'li-93gcznw',+ frame: {+ x: 1.0592,+ y: 0.7876,+ w: 0.72,+ h: 0.0731,+ },+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans',+ color: '#1a1a1a',+ accent: '#c2410c',+ textScale: 1,+ weight: 700,+ stale: false,+ kind: 'list',+ items: [+ {+ text: 'TEST1',+ tone: 'pro',+ },+ {+ text: 'TEST1',+ tone: 'con',+ },+ ],+ layout: 'columns',+ showMarks: true,+ proLabel: 'Pros',+ conLabel: 'Cons',+ },+ ],+ },+];diff --git a/shared/src/book/auto/auto-types.ts b/shared/src/book/auto/auto-types.tsnew file mode 100644index 000000000..ddf7fbc90--- /dev/null+++ b/shared/src/book/auto/auto-types.ts@@ -0,0 +1,89 @@+import type { BookPageSetup } from '../book.schema';+import type { JourneyStats } from '../journey-stats.schema';+import type { AutoTemplate } from './auto-templates.data';++/**+ * What the auto layout turns into a book: a journey as plain data.+ *+ * Moved here from the Studio (client/src/components/Studio/autoLayout.ts) so+ * the Studio's Auto layout button and the server's design tool lay a book out+ * with one implementation. Labels and the locale come in already chosen: this+ * code builds a document and has no business reaching for a translation table.+ */++export interface AutoPhoto {+ photoId: number;+ width: number | null;+ height: number | null;+ caption?: string | null;+}++export interface AutoEntry {+ id: number;+ title: string | null;+ story: string | null;+ location: string | null;+ date: string | null;+ photos: AutoPhoto[];+ /**+ * Where this stop is, when the journey's figures know.+ *+ * Filled from the stats points rather than carried on the entry: the entry+ * knows a place name, the stats know what that place resolved to. A page can+ * then print the flag, the country outline and the coordinates.+ */+ lat?: number | null;+ lng?: number | null;+ country?: string | null;+ /** Which day of the journey this is, 1-based. Null when the dates do not say. */+ dayNumber?: number | null;+ /** How many days the journey runs, for the progress rule along the foot. */+ dayCount?: number | null;+ /** The journal's mood and weather keys (`amazing`, `partly`), for the marks the book engine places. */+ mood?: string | null;+ weather?: string | null;+ /** The entry's pros and cons, for a list element. */+ pros?: readonly string[];+ cons?: readonly string[];+}++export interface AutoInput {+ /**+ * The app's language, not the browser's. A book whose captions are dated in+ * the reader's OS locale while the rest of it is written in the app's is a+ * mismatch nobody asked for.+ */+ locale: string;+ title: string;+ subtitle: string | null;+ coverPhotoId: number | null;+ entries: AutoEntry[];+ page: BookPageSetup;+ /**+ * What the journey adds up to. Null when the figures could not be fetched:+ * the book then simply has no summary pages rather than pages with nothing+ * on them.+ */+ stats: JourneyStats | null;+ /** The heading over a list of bare stops, already translated. */+ stationsLabel: string;+ /** The word before a day number on a chip ("DAY 5"). Already translated. */+ dayLabel: string;+ /**+ * The real geometry of the route, when the journey has any (GPX and KML+ * imports), already thinned with `bookPath`.+ */+ path?: [number, number][][];+ /** "TRIP SUMMARY" over the figures. */+ summaryLabel: string;+ /** "COUNTRIES" over the outlines. */+ countriesLabel: string;+ /** Mints element and spread ids; the default is `bookElementId`, tests pass a counter. */+ newId?: (prefix: string) => string;+ /**+ * The drawn templates an entry is tried against first. The default is the+ * shipped set (`AUTO_TEMPLATES`); an empty list lays every entry out with the+ * layouts written as code, which is what their tests pin.+ */+ templates?: readonly AutoTemplate[];+}diff --git a/shared/src/book/book-colour.spec.ts b/shared/src/book/book-colour.spec.tsnew file mode 100644index 000000000..77fbafca2--- /dev/null+++ b/shared/src/book/book-colour.spec.ts@@ -0,0 +1,94 @@+import {+ accentFromPalettes,+ clusterPalettes,+ contrastRatio,+ deltaE,+ greyLuminance,+ luminance,+ parseHex,+ readPalette,+ readableInk,+ requiredContrast,+ toHex,+ toHsl,+} from './book-colour';++import { describe, expect, it } from 'vitest';++/** The colour arithmetic the findings and the design engine stand on. */++describe('book colour', () => {+ it('BOOKCLR-001: reads #rrggbb in either case and refuses anything else, and writes it back in lower case', () => {+ expect(parseHex('#FF8000')).toEqual({ r: 255, g: 128, b: 0 });+ expect(parseHex('#ff8000')).toEqual({ r: 255, g: 128, b: 0 });+ expect(parseHex('ff8000')).toBeNull();+ expect(parseHex('#fff')).toBeNull();+ expect(toHex({ r: 255, g: 128, b: 0 })).toBe('#ff8000');+ expect(toHex({ r: 300, g: -5, b: 12.4 })).toBe('#ff000c');+ });++ it('BOOKCLR-002: measures WCAG luminance and contrast at the ends of the scale', () => {+ expect(luminance({ r: 0, g: 0, b: 0 })).toBe(0);+ expect(luminance({ r: 255, g: 255, b: 255 })).toBeCloseTo(1, 5);+ expect(contrastRatio('#000000', '#ffffff')).toBeCloseTo(21, 5);+ expect(contrastRatio('#ffffff', '#000000')).toBeCloseTo(21, 5);+ expect(contrastRatio('#777777', '#777777')).toBeCloseTo(1, 5);+ expect(contrastRatio('nope', '#ffffff')).toBe(1);+ expect(greyLuminance(255)).toBeCloseTo(1, 5);+ });++ it('BOOKCLR-003: asks 4.5:1 of small type and 3:1 from 18 pt', () => {+ expect(requiredContrast(10)).toBe(4.5);+ expect(requiredContrast(18)).toBe(3);+ // The grey the Studio set captions in does not reach 4.5:1 on cream; the near black does.+ expect(contrastRatio('#8a8578', '#faf8f4')).toBeLessThan(4.5);+ expect(contrastRatio('#1a1a1a', '#faf8f4')).toBeGreaterThan(4.5);+ });++ it('BOOKCLR-004: gives hue, saturation and lightness', () => {+ expect(toHsl({ r: 255, g: 0, b: 0 })).toEqual({ h: 0, s: 1, l: 0.5 });+ const blue = toHsl({ r: 0, g: 0, b: 255 });+ expect(blue.h).toBeCloseTo(240, 5);+ expect(toHsl({ r: 128, g: 128, b: 128 }).s).toBe(0);+ });++ it('BOOKCLR-005: puts near colours close and different ones far apart in delta E', () => {+ expect(deltaE('#336699', '#336699')).toBe(0);+ expect(deltaE('#336699', '#35689b')).toBeLessThan(2);+ expect(deltaE('#336699', '#cc3300')).toBeGreaterThan(40);+ expect(deltaE('x', '#cc3300')).toBe(0);+ });++ it('BOOKCLR-006: reads a stored palette, shares and all, and skips what does not parse', () => {+ expect(readPalette(['#AA0000:0.6', '#00aa00', 'bad', '#0000aa:x'])).toEqual([+ { hex: '#aa0000', share: 0.6 },+ { hex: '#00aa00', share: 1 },+ { hex: '#0000aa', share: 1 },+ ]);+ expect(readPalette(null)).toEqual([]);+ });++ it('BOOKCLR-007: clusters near colours across photos, most common first, the same way every time', () => {+ const a = [{ hex: '#c0392b', share: 0.5 }];+ const b = [+ { hex: '#c23b2d', share: 0.4 },+ { hex: '#2c3e50', share: 0.2 },+ ];+ const clusters = clusterPalettes([a, b]);+ expect(clusters).toHaveLength(2);+ expect(clusters[0]?.share).toBeCloseTo(0.9 / 1.1, 5);+ expect(clusterPalettes([b, a])[0]?.share).toBeCloseTo(clusters[0]?.share ?? 0, 5);+ });++ it('BOOKCLR-008: takes an accent that is a colour, not near black or white, and none from grey photos', () => {+ const red = [{ hex: '#c0392b', share: 0.3 }];+ const white = [{ hex: '#fafafa', share: 0.9 }];+ expect(accentFromPalettes([white, red])).toBe('#c0392b');+ expect(accentFromPalettes([[{ hex: '#808080', share: 1 }]])).toBeNull();+ });++ it('BOOKCLR-009: picks the ink that reads on a ground', () => {+ expect(readableInk('#ffffff')).toBe('#1a1a1a');+ expect(readableInk('#111111')).toBe('#ffffff');+ });+});diff --git a/shared/src/book/book-colour.ts b/shared/src/book/book-colour.tsnew file mode 100644index 000000000..a6e564d72--- /dev/null+++ b/shared/src/book/book-colour.ts@@ -0,0 +1,184 @@+/**+ * Colour arithmetic for a printed page: reading `#rrggbb`, the WCAG contrast+ * between two colours, hue, saturation and lightness, the perceived distance+ * between two colours (CIE76 delta E in Lab), and the few colours a set of+ * photographs shares.+ *+ * Pure and small on purpose. The book engine checks every text against what+ * it is set on with these, and the design engine takes a book's accent from+ * its photos with them; neither needs more than this.+ */++export interface Rgb {+ r: number;+ g: number;+ b: number;+}++const HEX = /^#([0-9a-f]{6})$/i;++/** `#rrggbb` as channels 0..255, or null for anything else. */+export function parseHex(hex: string): Rgb | null {+ const m = HEX.exec(hex.trim());+ const digits = m?.[1];+ if (!digits) return null;+ const n = Number.parseInt(digits, 16);+ return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };+}++const byte = (v: number) => Math.max(0, Math.min(255, Math.round(v)));++/** Channels back to `#rrggbb`, lower case. */+export function toHex(c: Rgb): string {+ const n = (byte(c.r) << 16) | (byte(c.g) << 8) | byte(c.b);+ return `#${n.toString(16).padStart(6, '0')}`;+}++const linear = (v: number) => {+ const s = v / 255;+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;+};++/** WCAG relative luminance, 0 (black) to 1 (white). */+export function luminance(c: Rgb): number {+ return 0.2126 * linear(c.r) + 0.7152 * linear(c.g) + 0.0722 * linear(c.b);+}++/** The luminance of a grey of this 0..255 level, for a photo whose mean brightness is all that is known. */+export function greyLuminance(level: number): number {+ return luminance({ r: level, g: level, b: level });+}++/** WCAG contrast ratio between two luminances, 1 to 21. */+export function contrastOfLuminance(a: number, b: number): number {+ const [hi, lo] = a >= b ? [a, b] : [b, a];+ return (hi + 0.05) / (lo + 0.05);+}++/** WCAG contrast ratio between two `#rrggbb` colours; 1 when either does not parse. */+export function contrastRatio(a: string, b: string): number {+ const ca = parseHex(a);+ const cb = parseHex(b);+ if (!ca || !cb) return 1;+ return contrastOfLuminance(luminance(ca), luminance(cb));+}++/** The contrast a text needs: 4.5:1, or 3:1 from 18 pt (large type) up. */+export function requiredContrast(sizePt: number): number {+ return sizePt >= 18 ? 3 : 4.5;+}++export interface Hsl {+ /** Degrees, 0..360. */+ h: number;+ /** 0..1. */+ s: number;+ /** 0..1. */+ l: number;+}++export function toHsl(c: Rgb): Hsl {+ const r = c.r / 255;+ const g = c.g / 255;+ const b = c.b / 255;+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ const d = max - min;+ if (d === 0) return { h: 0, s: 0, l };+ const s = d / (1 - Math.abs(2 * l - 1));+ let h: number;+ if (max === r) h = ((g - b) / d) % 6;+ else if (max === g) h = (b - r) / d + 2;+ else h = (r - g) / d + 4;+ return { h: (h * 60 + 360) % 360, s, l };+}++/** CIE Lab, D65, for the perceived distance between two colours. */+function toLab(c: Rgb): [number, number, number] {+ const r = linear(c.r);+ const g = linear(c.g);+ const b = linear(c.b);+ const x = (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047;+ const y = r * 0.2126 + g * 0.7152 + b * 0.0722;+ const z = (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883;+ const f = (t: number) => (t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116);+ return [116 * f(y) - 16, 500 * (f(x) - f(y)), 200 * (f(y) - f(z))];+}++/** CIE76 delta E between two `#rrggbb` colours: about 2 is just noticeable, 12 plainly another colour. */+export function deltaE(a: string, b: string): number {+ const ca = parseHex(a);+ const cb = parseHex(b);+ if (!ca || !cb) return 0;+ const [l1, a1, b1] = toLab(ca);+ const [l2, a2, b2] = toLab(cb);+ return Math.hypot(l1 - l2, a1 - a2, b1 - b2);+}++/** One colour of a photo's palette and the share of the picture it covers. */+export interface PaletteSwatch {+ hex: string;+ share: number;+}++/**+ * Read a stored palette: `#rrggbb` or `#rrggbb:share` strings, at most five.+ * A missing share counts as an equal part.+ */+export function readPalette(list: readonly string[] | null | undefined): PaletteSwatch[] {+ const out: PaletteSwatch[] = [];+ for (const item of (list ?? []).slice(0, 5)) {+ const [hex = '', share] = item.split(':');+ if (!parseHex(hex)) continue;+ const n = share === undefined ? Number.NaN : Number(share);+ out.push({ hex: hex.toLowerCase(), share: Number.isFinite(n) && n > 0 ? n : 1 });+ }+ return out;+}++/**+ * The colours several palettes share, most common first: swatches within+ * `radius` delta E of a cluster join it (weighted by share), in a fixed order,+ * so the same photos always give the same answer.+ */+export function clusterPalettes(palettes: readonly PaletteSwatch[][], radius = 14): PaletteSwatch[] {+ const clusters: { rgb: Rgb; weight: number }[] = [];+ for (const swatch of palettes.flat()) {+ const rgb = parseHex(swatch.hex);+ if (!rgb) continue;+ const near = clusters.find((c) => deltaE(toHex(c.rgb), swatch.hex) <= radius);+ if (!near) {+ clusters.push({ rgb, weight: swatch.share });+ continue;+ }+ const w = near.weight + swatch.share;+ const mix = (a: number, b: number) => (a * near.weight + b * swatch.share) / w;+ near.rgb = { r: mix(near.rgb.r, rgb.r), g: mix(near.rgb.g, rgb.g), b: mix(near.rgb.b, rgb.b) };+ near.weight = w;+ }+ const total = clusters.reduce((sum, c) => sum + c.weight, 0) || 1;+ return clusters+ .map((c) => ({ hex: toHex(c.rgb), share: c.weight / total }))+ .sort((a, b) => b.share - a.share || a.hex.localeCompare(b.hex));+}++/**+ * The accent a set of photos suggests: the most common shared colour that is+ * a colour at all (saturation over 0.25) and neither near black nor near+ * white (lightness between 0.25 and 0.65). Null when the photos are grey.+ */+export function accentFromPalettes(palettes: readonly PaletteSwatch[][]): string | null {+ for (const swatch of clusterPalettes(palettes)) {+ const rgb = parseHex(swatch.hex);+ if (!rgb) continue;+ const { s, l } = toHsl(rgb);+ if (s > 0.25 && l > 0.25 && l < 0.65) return swatch.hex;+ }+ return null;+}++/** Of two candidate inks, the one that reads better on `ground`. */+export function readableInk(ground: string, dark = '#1a1a1a', light = '#ffffff'): string {+ return contrastRatio(dark, ground) >= contrastRatio(light, ground) ? dark : light;+}diff --git a/shared/src/book/book-doc-ops.spec.ts b/shared/src/book/book-doc-ops.spec.tsnew file mode 100644index 000000000..a6c8b775a--- /dev/null+++ b/shared/src/book/book-doc-ops.spec.ts@@ -0,0 +1,103 @@+import { duplicateBookPage, removeBookLayout, restoreBookLayout, saveBookLayout, setBookSetup } from './book-doc-ops';+import { blankBook } from './book-pages';+import {+ MAX_BOOK_LAYOUTS,+ bookDocumentSchema,+ bookTextElementSchema,+ type BookDocument,+ type BookElement,+ type BookSpread,+} from './book.schema';++import { describe, expect, it } from 'vitest';++/** The operations on a whole book: its setup, a copy of a page, and its own layouts. */++let seq = 0;+const newId = (p: string) => `${p}-d${++seq}`;++const frame = { x: 230, y: 20, w: 100, h: 20 };+const text = (id: string, words: string) =>+ bookTextElementSchema.parse({ id, kind: 'text', frame, text: words }) as BookElement;++function book(): BookDocument {+ const doc = blankBook({ title: 'Iceland', newId: (p) => `${p}-x` });+ const ids = ['sp-cover', 'sp-first', 'sp-in', 'sp-last', 'sp-back'];+ const spreads = doc.spreads.map((s, i) => ({ ...s, id: ids[i] as string }));+ spreads[2] = { ...(spreads[2] as BookSpread), elements: [text('t-1', 'Hello')], entryId: 4 };+ return { ...doc, spreads };+}++function ok<R extends { ok: boolean }>(result: R): Extract<R, { ok: true }> {+ if (!result.ok) throw new Error('refused');+ return result as Extract<R, { ok: true }>;+}++describe('book setup', () => {+ it('BOOKDOC-001: changes the format to a preset size, keeps the elements, and answers the setup it replaced', () => {+ const doc = book();+ const done = ok(setBookSetup(doc, { preset: 'a4-portrait' }));+ expect(done.doc.page).toMatchObject({ preset: 'a4-portrait', pageWidth: 210, pageHeight: 297 });+ expect(done.doc.spreads).toBe(doc.spreads);+ expect(done.previousSetup).toEqual(doc.page);+ expect(bookDocumentSchema.safeParse(done.doc).success).toBe(true);+ });++ it('BOOKDOC-002: a size of its own makes the format custom, a folio colour turns its auto colour off', () => {+ const done = ok(setBookSetup(book(), { pageWidth: 240.004, pageNumbers: { show: true, color: '#112233' } }));+ expect(done.doc.page).toMatchObject({ preset: 'custom', pageWidth: 240 });+ expect(done.doc.page.pageNumbers).toMatchObject({ show: true, color: '#112233', autoColor: false });+ const resized = ok(setBookSetup(book(), { preset: 'a4-portrait', pageHeight: 280 }));+ expect(resized.doc.page).toMatchObject({ preset: 'custom', pageWidth: 210, pageHeight: 280 });+ const same = ok(setBookSetup(book(), { preset: 'a4-portrait', pageWidth: 210 }));+ expect(same.doc.page).toMatchObject({ preset: 'a4-portrait', pageWidth: 210, pageHeight: 297 });+ });++ it('BOOKDOC-003: refuses an empty setup and answers the same book when nothing moves', () => {+ expect(setBookSetup(book(), {})).toMatchObject({ ok: false, error: { code: 'invalid_op' } });+ const doc = book();+ expect(ok(setBookSetup(doc, { bleed: doc.page.bleed })).doc).toBe(doc);+ expect(setBookSetup(doc, { pageWidth: 10 })).toMatchObject({ ok: false, error: { code: 'invalid_op' } });+ });+});++describe('pages and layouts', () => {+ it('BOOKDOC-004: copies an inner page with new ids right after it, and refuses the covers', () => {+ const doc = book();+ const done = ok(duplicateBookPage(doc, { spreadId: 'sp-in' }, { newId }));+ const copy = done.doc.spreads[3] as BookSpread;+ expect(done.doc.spreads).toHaveLength(6);+ expect(copy.id).not.toBe('sp-in');+ expect(copy.entryId).toBe(4);+ expect(copy.elements[0]).toMatchObject({ kind: 'text', text: 'Hello' });+ expect(copy.elements[0]?.id).not.toBe('t-1');+ expect(done.spreadIds).toEqual([copy.id]);+ expect(duplicateBookPage(doc, { spreadId: 'sp-cover' })).toMatchObject({ error: { code: 'protected_spread' } });+ expect(duplicateBookPage(doc, { spreadId: 'sp-nope' })).toMatchObject({ error: { code: 'spread_not_found' } });+ });++ it('BOOKDOC-005: keeps a page as a layout of the book, names it, and stops at the cap', () => {+ const done = ok(saveBookLayout(book(), { spreadId: 'sp-in' }, { newId }));+ const layout = done.doc.layouts?.[0];+ expect(layout).toMatchObject({ name: 'Layout 1', role: 'inner' });+ expect(done.created).toEqual([layout?.id]);+ const named = ok(saveBookLayout(book(), { spreadId: 'sp-in', name: 'Harbour' }));+ expect(named.doc.layouts?.[0]?.name).toBe('Harbour');+ const kept = layout as NonNullable<typeof layout>;+ const full = { ...book(), layouts: Array.from({ length: MAX_BOOK_LAYOUTS }, () => kept) };+ expect(saveBookLayout(full, { spreadId: 'sp-in' })).toMatchObject({ error: { code: 'layouts_full' } });+ });++ it('BOOKDOC-006: takes a layout away, answers it, and puts it back as it was', () => {+ const saved = ok(saveBookLayout(book(), { spreadId: 'sp-in' }, { newId })).doc;+ const layout = saved.layouts?.[0];+ const removed = ok(removeBookLayout(saved, { layoutId: layout?.id }));+ expect(removed.doc.layouts).toEqual([]);+ expect(removed.previousLayout).toEqual(layout);+ const back = ok(restoreBookLayout(removed.doc, removed.previousLayout));+ expect(back.doc.layouts).toEqual([layout]);+ const broken = restoreBookLayout(removed.doc, { ...removed.previousLayout, role: 'sideways' });+ expect(broken).toMatchObject({ ok: false, error: { code: 'invalid_op' } });+ expect(removeBookLayout(saved, { layoutId: 'ly-nope' })).toMatchObject({ error: { code: 'layout_not_found' } });+ });+});diff --git a/shared/src/book/book-doc-ops.ts b/shared/src/book/book-doc-ops.tsnew file mode 100644index 000000000..fd7fe5135--- /dev/null+++ b/shared/src/book/book-doc-ops.ts@@ -0,0 +1,164 @@+import { bookElementId } from './book-ids';+import {+ caught,+ checkedSpread,+ createdIds,+ failOp,+ invalidOp,+ round2,+ type BookEditResult,+ type BookOpError,+ type BookOpsContext,+} from './book-ops-core';+import {+ duplicateBookPageRequestSchema,+ removeBookLayoutRequestSchema,+ saveBookLayoutRequestSchema,+ setBookSetupRequestSchema,+} from './book-ops.schema';+import { BOOK_PAGE_PRESET_SIZES, canEditSpread } from './book-pages';+import { bookLayoutFromSpread, nextBookLayoutName } from './book-saved-layouts';+import {+ MAX_BOOK_LAYOUTS,+ MAX_SPREADS,+ bookLayoutSchema,+ type BookDocument,+ type BookLayout,+ type BookPageSetup,+} from './book.schema';++/**+ * Operations on the book as a whole rather than on a page: its format and+ * page numbers, a copy of a page, and the book's own layouts. Each takes its+ * tool's arguments, parses them again, and answers a result rather than+ * throwing, like the page operations. What a write changed comes back with it+ * (`previousSetup`, `previousLayout`), so the assistant can set it back.+ */++type BookEditDone = Extract<BookEditResult, { ok: true }>;++export type BookDocOpResult =+ (BookEditDone & { previousSetup?: BookPageSetup; previousLayout?: BookLayout }) | { ok: false; error: BookOpError };++const done = (doc: BookDocument, extra: Partial<BookEditDone> = {}): BookEditDone => ({+ ok: true,+ doc,+ spreadIds: [],+ created: [],+ dropped: [],+ ...extra,+});++const refused = (code: BookOpError['code'], message: string): BookDocOpResult => ({+ ok: false,+ error: { code, message, opIndex: null },+});++/**+ * The format and the page numbers. A preset brings its page size unless a+ * size is given, and a size that is not the preset's makes the format custom;+ * elements are not rescaled, as in the Studio. Choosing a folio colour turns+ * its automatic colour off, as the inspector does.+ */+export function setBookSetup(doc: BookDocument, args: unknown): BookDocOpResult {+ const parsed = setBookSetupRequestSchema.safeParse(args);+ if (!parsed.success) return { ok: false, error: invalidOp(parsed.error, null) };+ const a = parsed.data;+ const named = [a.preset, a.pageWidth, a.pageHeight, a.bleed, a.safe, a.pageNumbers].some((v) => v !== undefined);+ if (!named) return refused('invalid_op', 'name at least one field of the setup');+ const before = doc.page;+ const size = a.preset !== undefined && a.preset !== 'custom' ? BOOK_PAGE_PRESET_SIZES[a.preset] : null;+ const numbers = a.pageNumbers ?? {};+ const pickedColour = numbers.color !== undefined && numbers.autoColor === undefined;+ const sized = a.pageWidth !== undefined || a.pageHeight !== undefined;+ const pageWidth = round2(a.pageWidth ?? size?.pageWidth ?? before.pageWidth);+ const pageHeight = round2(a.pageHeight ?? size?.pageHeight ?? before.pageHeight);+ const presetSize = size !== null && pageWidth === size.pageWidth && pageHeight === size.pageHeight;+ const customSize = sized && !presetSize;+ const page: BookPageSetup = {+ ...before,+ preset: customSize ? 'custom' : (a.preset ?? before.preset),+ pageWidth,+ pageHeight,+ bleed: round2(a.bleed ?? before.bleed),+ safe: round2(a.safe ?? before.safe),+ pageNumbers: {+ ...before.pageNumbers,+ ...numbers,+ ...(numbers.margin !== undefined ? { margin: round2(numbers.margin) } : {}),+ ...(pickedColour ? { autoColor: false } : {}),+ },+ };+ // Nothing moved: the very same document back, so a caller can tell nothing changed.+ if (JSON.stringify(page) === JSON.stringify(before)) return { ...done(doc), previousSetup: before };+ return { ...done({ ...doc, page }), previousSetup: before };+}++/** A copy of an inner page with new ids throughout, right after it. The cover, first, last and back refuse. */+export function duplicateBookPage(doc: BookDocument, args: unknown, ctx: BookOpsContext = {}): BookDocOpResult {+ const parsed = duplicateBookPageRequestSchema.safeParse(args);+ if (!parsed.success) return { ok: false, error: invalidOp(parsed.error, null) };+ const newId = ctx.newId ?? bookElementId;+ return caught(() => {+ const index = doc.spreads.findIndex((s) => s.id === parsed.data.spreadId);+ const source = doc.spreads[index];+ if (!source) throw failOp('spread_not_found', `no page ${parsed.data.spreadId}`, null);+ if (!canEditSpread(source)) {+ throw failOp('protected_spread', `${source.id} is the ${source.role} page and cannot be copied`, null);+ }+ if (doc.spreads.length + 1 > MAX_SPREADS) {+ throw failOp('too_many_spreads', `a book holds at most ${MAX_SPREADS} pages`, null);+ }+ const fresh = <E extends { id: string; kind: string }>(e: E): E => ({ ...e, id: newId(e.kind.charAt(0)) });+ const copy = checkedSpread(+ { ...source, id: newId('sp'), elements: source.elements.map(fresh), parked: source.parked.map(fresh) },+ null,+ );+ const spreads = [...doc.spreads.slice(0, index + 1), copy, ...doc.spreads.slice(index + 1)];+ return done({ ...doc, spreads }, { spreadIds: [copy.id], created: createdIds(doc.spreads, spreads) });+ });+}++/** A page's arrangement kept as one of the book's own layouts, named "Layout n" unless a name is given. */+export function saveBookLayout(doc: BookDocument, args: unknown, ctx: BookOpsContext = {}): BookDocOpResult {+ const parsed = saveBookLayoutRequestSchema.safeParse(args);+ if (!parsed.success) return { ok: false, error: invalidOp(parsed.error, null) };+ const newId = ctx.newId ?? bookElementId;+ const spread = doc.spreads.find((s) => s.id === parsed.data.spreadId);+ if (!spread) return refused('spread_not_found', `no page ${parsed.data.spreadId}`);+ const layouts = doc.layouts ?? [];+ if (layouts.length >= MAX_BOOK_LAYOUTS) {+ return refused('layouts_full', `a book keeps at most ${MAX_BOOK_LAYOUTS} layouts; remove one first`);+ }+ const name = parsed.data.name ?? nextBookLayoutName(layouts, 'Layout');+ const layout = { ...bookLayoutFromSpread(spread, doc.page, name), id: newId('ly') };+ return done({ ...doc, layouts: [...layouts, layout] }, { created: [layout.id] });+}++/** One of the book's own layouts taken away; `previousLayout` is what puts it back (`restoreBookLayout`). */+export function removeBookLayout(doc: BookDocument, args: unknown): BookDocOpResult {+ const parsed = removeBookLayoutRequestSchema.safeParse(args);+ if (!parsed.success) return { ok: false, error: invalidOp(parsed.error, null) };+ const layouts = doc.layouts ?? [];+ const layout = layouts.find((l) => l.id === parsed.data.layoutId);+ if (!layout) return refused('layout_not_found', `this book keeps no layout ${parsed.data.layoutId}`);+ const rest = layouts.filter((l) => l.id !== layout.id);+ return { ...done({ ...doc, layouts: rest }), previousLayout: layout };+}++/**+ * A removed layout put back as it was, for the assistant's undo of+ * `remove_book_layout`. The layout comes from a stored undo record, so it is+ * parsed again like every other argument.+ */+export function restoreBookLayout(doc: BookDocument, raw: unknown): BookDocOpResult {+ const parsed = bookLayoutSchema.safeParse(raw);+ if (!parsed.success) return { ok: false, error: invalidOp(parsed.error, null) };+ const layout = parsed.data;+ const layouts = doc.layouts ?? [];+ if (layouts.some((l) => l.id === layout.id)) return done(doc);+ if (layouts.length >= MAX_BOOK_LAYOUTS) {+ return refused('layouts_full', `a book keeps at most ${MAX_BOOK_LAYOUTS} layouts; remove one first`);+ }+ return done({ ...doc, layouts: [...layouts, layout] }, { created: [layout.id] });+}diff --git a/shared/src/book/book-element-ops.schema.ts b/shared/src/book/book-element-ops.schema.tsnew file mode 100644index 000000000..61db44f97--- /dev/null+++ b/shared/src/book/book-element-ops.schema.ts@@ -0,0 +1,309 @@+import { idSchema } from '../common/primitives.schema';+import { BOOK_DESIGN_ICONS } from './book-icons';+import { bookElementIdSchema, bookGridIdSchema, bookSpreadIdSchema } from './book-op-ids';+import {+ BOOK_BADGES,+ BOOK_METRICS,+ BOOK_SHAPES,+ MAX_BOOK_COUNTRIES,+ bookBadgeElementSchema,+ bookCountriesElementSchema,+ bookIconElementSchema,+ bookListElementSchema,+ bookMapElementSchema,+ bookPhotoElementSchema,+ bookShapeElementSchema,+ bookStatsElementSchema,+ bookTextElementSchema,+} from './book.schema';++import { z } from 'zod';++/**+ * The element operations of a book page: create any of the nine kinds, style+ * one, arrange, align, distribute, lock, duplicate, fill, copy from another+ * page, refresh the travel figures, drop in a photo grid. They join the page+ * operations of book-ops.schema.ts, so `edit_book_page` takes them and the one+ * engine (`applyBookOps`) runs them; nothing else implements them.+ *+ * Same rules as the other operations: strict objects, the fields taken from the+ * document's own shapes with their defaults removed (an omitted field leaves+ * the element as it is), every string, array and number bounded.+ */++/** A position in millimetres, inside the bounds the document takes. */+const mmIn = z.number().finite().min(-10000).max(10000);+/** A size the document keeps after rounding to hundredths. */+const sizeIn = z.number().finite().min(0.01).max(10000);+const unit01 = z.number().min(0).max(1);+const ids30 = z.array(bookElementIdSchema).min(1).max(30);++export const bookFrameInSchema = z.strictObject({ x: mmIn, y: mmIn, w: sizeIn, h: sizeIn });++const photo = bookPhotoElementSchema.shape;+const text = bookTextElementSchema.shape;+const shape = bookShapeElementSchema.shape;+const icon = bookIconElementSchema.shape;+const map = bookMapElementSchema.shape;+const stats = bookStatsElementSchema.shape;+const countries = bookCountriesElementSchema.shape;+const badge = bookBadgeElementSchema.shape;+const list = bookListElementSchema.shape;++/** What every kind has: how see-through it is. */+const COMMON = { opacity: unit01.optional() };++/** What the travel kinds share with text: they are typeset. */+const TYPESET = {+ font: map.font.unwrap().optional(),+ color: map.color.unwrap().optional(),+ accent: map.accent.unwrap().optional(),+ textScale: map.textScale.unwrap().optional(),+ weight: map.weight.unwrap().optional(),+};++const PHOTO_PROPS = {+ ...COMMON,+ fit: photo.fit.unwrap().optional(),+ focalX: unit01.optional(),+ focalY: unit01.optional(),+ mask: photo.mask.unwrap().optional(),+ frameStyle: photo.frameStyle.unwrap().optional(),+ filter: photo.filter.unwrap().optional(),+ radius: z.number().finite().min(0).max(500).optional(),+};+const TEXT_PROPS = {+ ...COMMON,+ font: text.font.unwrap().optional(),+ size: text.size.unwrap().optional(),+ weight: text.weight.unwrap().optional(),+ italic: text.italic.unwrap().optional(),+ align: text.align.unwrap().optional(),+ leading: text.leading.unwrap().optional(),+ tracking: text.tracking.unwrap().optional(),+ color: text.color.unwrap().optional(),+};+const SHAPE_PROPS = {+ ...COMMON,+ fill: shape.fill.unwrap().optional(),+ gradient: shape.gradient.unwrap().optional(),+ stroke: shape.stroke.unwrap().optional(),+ strokeWidth: z.number().finite().min(0).max(20).optional(),+ strokeStyle: shape.strokeStyle.unwrap().optional(),+ radius: z.number().finite().min(0).max(500).optional(),+};+const ICON_PROPS = {+ ...COMMON,+ color: icon.color.unwrap().optional(),+ lineWidth: icon.lineWidth.unwrap().optional(),+};+const MAP_PROPS = {+ ...COMMON,+ ...TYPESET,+ style: map.style.unwrap().optional(),+ showLand: map.showLand.unwrap().optional(),+ showRoute: map.showRoute.unwrap().optional(),+ showPins: map.showPins.unwrap().optional(),+ showLabels: map.showLabels.unwrap().optional(),+ routeStyle: map.routeStyle.unwrap().optional(),+ routeArc: map.routeArc.unwrap().optional(),+ routeDash: map.routeDash.unwrap().optional(),+ pinStyle: map.pinStyle.unwrap().optional(),+ clip: map.clip.unwrap().optional(),+ fitPadding: map.fitPadding.unwrap().optional(),+ fitToCountries: map.fitToCountries.unwrap().optional(),+};+const STATS_PROPS = {+ ...COMMON,+ ...TYPESET,+ layout: stats.layout.unwrap().optional(),+ showIcons: stats.showIcons.unwrap().optional(),+ units: stats.units.unwrap().optional(),+};+const COUNTRIES_PROPS = {+ ...COMMON,+ ...TYPESET,+ layout: countries.layout.unwrap().optional(),+ showOutline: countries.showOutline.unwrap().optional(),+ showFlag: countries.showFlag.unwrap().optional(),+ showName: countries.showName.unwrap().optional(),+ align: countries.align.unwrap().optional(),+};+const BADGE_PROPS = {+ ...COMMON,+ ...TYPESET,+ style: badge.style.unwrap().optional(),+ showIcon: badge.showIcon.unwrap().optional(),+ showLabel: badge.showLabel.unwrap().optional(),+ autoColor: badge.autoColor.unwrap().optional(),+ autoIconColor: badge.autoIconColor.unwrap().optional(),+ iconColor: badge.iconColor.unwrap().optional(),+};+const LIST_PROPS = {+ ...COMMON,+ ...TYPESET,+ layout: list.layout.unwrap().optional(),+ showMarks: list.showMarks.unwrap().optional(),+ proLabel: z.string().max(80).optional(),+ conLabel: z.string().max(80).optional(),+};+const metric = z.enum(BOOK_METRICS);+const METRICS = z.array(metric).min(1).max(7);++/**+ * The look of an element, per kind, for `style`. Values the journey owns (a+ * map's stops, a stat's figures, a country's name) are not props: the engine+ * resolves them from the journey, exactly as the Travel panel does.+ */+export const bookElementPropsSchema = z.discriminatedUnion('kind', [+ z.strictObject({ kind: z.literal('photo'), ...PHOTO_PROPS }),+ z.strictObject({ kind: z.literal('text'), ...TEXT_PROPS }),+ z.strictObject({ kind: z.literal('shape'), shape: z.enum(BOOK_SHAPES).optional(), ...SHAPE_PROPS }),+ z.strictObject({ kind: z.literal('icon'), ...ICON_PROPS }),+ z.strictObject({ kind: z.literal('map'), ...MAP_PROPS }),+ z.strictObject({ kind: z.literal('stats'), metrics: METRICS.optional(), ...STATS_PROPS }),+ z.strictObject({ kind: z.literal('countries'), ...COUNTRIES_PROPS }),+ z.strictObject({ kind: z.literal('badge'), ...BADGE_PROPS }),+ z.strictObject({ kind: z.literal('list'), ...LIST_PROPS }),+]);+export type BookElementProps = z.infer<typeof bookElementPropsSchema>;++/** The Studio's text presets: heading, subheading, body, caption and the large quotation mark. */+export const BOOK_TEXT_PRESETS = ['heading', 'subheading', 'body', 'caption', 'quote'] as const;++/**+ * An entry's words need the entry and a photo's caption needs the photo: a+ * binding that names neither reads nothing, and the ids it names are checked+ * against the journey when the engine runs. The `text` op and `add` text share it.+ */+export function bindingNamesItsSource(+ b: { source: string; entryId?: number; photoId?: number } | null | undefined,+): boolean {+ if (!b) return true;+ if (b.source.startsWith('entry.') && b.entryId === undefined) return false;+ return b.source !== 'photo.caption' || b.photoId !== undefined;+}++/** A binding that names its own source: an entry's words carry the entry id, a caption the photo id. */+const bindingIn = text.binding+ .unwrap()+ .unwrap()+ .refine(bindingNamesItsSource, { message: 'an entry binding needs its entryId, a photo binding its photoId' });+const iso2 = z.string().regex(/^[A-Za-z]{2}$/);+const listItem = z.strictObject({ text: z.string().max(400), tone: z.enum(['pro', 'con', 'plain']) });++/**+ * Where a map is of: the whole journey or one trip, the two scopes a stored map+ * can say (its `tripId`). A map of some entries' stops would be stale the moment+ * it was placed and widened to the journey by the first refresh.+ */+const mapScope = z.union([z.literal('journey'), z.strictObject({ tripId: idSchema })]);++/**+ * What to create: the kind, where its content comes from, and its look. A text+ * needs its words or a binding (the engine has no translated sample words); a+ * list needs an entry (its pros and cons) or its lines.+ */+export const bookNewElementSchema = z.discriminatedUnion('kind', [+ z.strictObject({ kind: z.literal('photo'), photoId: idSchema.optional(), ...PHOTO_PROPS }),+ z+ .strictObject({+ kind: z.literal('text'),+ preset: z.enum(BOOK_TEXT_PRESETS).optional(),+ text: z.string().max(2000).optional(),+ binding: bindingIn.optional(),+ ...TEXT_PROPS,+ })+ .refine((v) => v.text !== undefined || v.binding !== undefined, { message: 'give the words or a binding' }),+ z.strictObject({ kind: z.literal('shape'), shape: z.enum(BOOK_SHAPES), ...SHAPE_PROPS }),+ z.strictObject({ kind: z.literal('icon'), name: z.enum(BOOK_DESIGN_ICONS), ...ICON_PROPS }),+ z.strictObject({+ kind: z.literal('map'),+ scope: mapScope,+ source: z.enum(['vector', 'relief', 'satellite']).optional(),+ ...MAP_PROPS,+ }),+ z.strictObject({ kind: z.literal('stats'), metrics: METRICS, ...STATS_PROPS }),+ z.strictObject({+ kind: z.literal('countries'),+ codes: z.array(iso2).max(MAX_BOOK_COUNTRIES).optional(),+ ...COUNTRIES_PROPS,+ }),+ z.strictObject({+ kind: z.literal('badge'),+ variant: z.enum(BOOK_BADGES),+ entryId: idSchema.optional(),+ code: z.string().max(24).optional(),+ text: z.string().max(200).optional(),+ sub: z.string().max(200).optional(),+ ...BADGE_PROPS,+ }),+ z+ .strictObject({+ kind: z.literal('list'),+ entryId: idSchema.optional(),+ items: z.array(listItem).max(60).optional(),+ ...LIST_PROPS,+ })+ .refine((v) => (v.entryId === undefined) !== (v.items === undefined), {+ message: 'give an entryId or the items, not both',+ }),+]);+export type BookNewElement = z.infer<typeof bookNewElementSchema>;++const hasProps = (set: Record<string, unknown>) => Object.keys(set).some((k) => k !== 'kind' && set[k] !== undefined);++/**+ * The new page operations, joined into `bookPageOpSchema` (book-ops.schema.ts+ * spreads them into its union).+ */+export const BOOK_ELEMENT_OP_SCHEMAS = [+ /** Create an element; the frame defaults to the Studio panel's size, centred on the page. */+ z.strictObject({+ op: z.literal('add'),+ element: bookNewElementSchema,+ frame: bookFrameInSchema.optional(),+ rotation: z.number().finite().min(-360).max(360).optional(),+ }),+ /** Restyle an element; `set.kind` must be the element's kind. */+ z+ .strictObject({ op: z.literal('style'), elementId: bookElementIdSchema, set: bookElementPropsSchema })+ .refine((v) => hasProps(v.set), { message: 'name at least one field to set', path: ['set'] }),+ /** Move elements in the paint order, keeping their order among themselves. */+ z.strictObject({+ op: z.literal('arrange'),+ elementIds: ids30,+ to: z.enum(['front', 'forward', 'backward', 'back']),+ }),+ /** Line elements up on an edge or a centre line of the selection, their page, or its safe area. */+ z.strictObject({+ op: z.literal('align'),+ elementIds: ids30,+ edge: z.enum(['left', 'center', 'right', 'top', 'middle', 'bottom']),+ to: z.enum(['selection', 'page', 'safe']).default('selection'),+ }),+ /** Space three or more elements evenly, or by a fixed gap in millimetres. */+ z.strictObject({+ op: z.literal('distribute'),+ elementIds: z.array(bookElementIdSchema).min(3).max(30),+ axis: z.enum(['horizontal', 'vertical']),+ gap: z.number().finite().min(0).max(200).optional(),+ }),+ /** Lock or unlock elements: the one operation a locked element accepts. */+ z.strictObject({ op: z.literal('lock'), elementIds: ids30, locked: z.boolean() }),+ /** Copies with new ids, offset by `dx`/`dy` millimetres (4 each by default), painted on top. */+ z.strictObject({+ op: z.literal('duplicate'),+ elementIds: ids30,+ dx: z.number().finite().min(-500).max(500).optional(),+ dy: z.number().finite().min(-500).max(500).optional(),+ }),+ /** The Studio's fill: a photo to the bleed of its page or the spread, unturned, cover, at the back. */+ z.strictObject({ op: z.literal('fill'), elementId: bookElementIdSchema, scope: z.enum(['page', 'spread']) }),+ /** Copy elements of another page onto this one, with new ids; photos are checked against the gallery. */+ z.strictObject({ op: z.literal('copy_from'), spreadId: bookSpreadIdSchema, elementIds: ids30 }),+ /** Bring travel figures up to date with the journey: the named elements, or every one on the page. */+ z.strictObject({ op: z.literal('refresh_travel'), elementIds: ids30.optional() }),+ /** A photo grid as empty frames in a box, the page's safe area by default. */+ z.strictObject({ op: z.literal('add_grid'), grid: bookGridIdSchema, box: bookFrameInSchema.optional() }),+] as const;diff --git a/shared/src/book/book-element-ops.spec.ts b/shared/src/book/book-element-ops.spec.tsnew file mode 100644index 000000000..6cc8a034c--- /dev/null+++ b/shared/src/book/book-element-ops.spec.ts@@ -0,0 +1,317 @@+import type { AutoEntry } from './auto/auto-types';+import { applyBookOps } from './book-ops';+import type { BookOpsContext } from './book-ops-core';+import type { BookPageOpInput } from './book-ops.schema';+import { blankBook } from './book-pages';+import type { BookTravelContext } from './book-travel';+import {+ bookPhotoElementSchema,+ bookSpreadSchema,+ bookTextElementSchema,+ type BookDocument,+ type BookElement,+ type BookSpread,+} from './book.schema';+import type { JourneyStats } from './journey-stats.schema';++import { describe, expect, it } from 'vitest';++/**+ * The element operations of the book engine: every kind created at the size+ * the Studio's panels give it, restyled, arranged, aligned, distributed,+ * locked, duplicated, filled, copied, refreshed, and the grid and the auto+ * layout, with their refusals. The page is the default square book: 210 mm+ * pages, the fold at 210, 3 mm bleed, 5 mm safe margin.+ */++let seq = 0;+const newId = (p: string) => `${p}-n${++seq}`;++type Frame = { x: number; y: number; w: number; h: number };+type NewElement = Extract<BookPageOpInput, { op: 'add' }>['element'];++const photo = (id: string, photoId: number | null, frame: Frame = { x: 230, y: 20, w: 80, h: 60 }, over = {}) =>+ bookPhotoElementSchema.parse({ id, kind: 'photo', frame, photoId, ...over }) as BookElement;+const text = (id: string, words: string, frame: Frame = { x: 230, y: 120, w: 160, h: 40 }, over = {}) =>+ bookTextElementSchema.parse({ id, kind: 'text', frame, text: words, size: 10, ...over }) as BookElement;++function book(elements: BookElement[], over: Partial<BookSpread> = {}): BookDocument {+ const doc = blankBook({ title: 'Iceland', newId: (p) => `${p}-x` });+ const ids = ['sp-cover', 'sp-first', 'sp-in', 'sp-last', 'sp-back'];+ const spreads = doc.spreads.map((s, i) => ({ ...s, id: ids[i] as string }));+ spreads[2] = { ...(spreads[2] as BookSpread), elements, ...over };+ return { ...doc, spreads };+}++const inner = (doc: BookDocument) => doc.spreads[2] as BookSpread;+const find = (doc: BookDocument, id: string) => inner(doc).elements.find((e) => e.id === id);+const ids = (doc: BookDocument) => inner(doc).elements.map((e) => e.id);++type Point = JourneyStats['points'][number];+const pt = (label: string, lat: number, lng: number, country: string, entryId: number): Point => ({+ lat,+ lng,+ label,+ date: null,+ country,+ tripId: null,+ photoId: entryId === 7 ? 1 : null,+ entryId,+});++const stats: JourneyStats = {+ journeyId: 1,+ distance: 1_189_000,+ days: 14,+ steps: 2,+ photos: 3,+ places: 2,+ furthest: 400_000,+ countries: [+ { code: 'IS', name: 'Iceland', places: 1, firstVisit: '2026-06-02' },+ { code: 'NO', name: 'Norway', places: 1, firstVisit: '2026-06-09' },+ ],+ points: [pt('Reykjavik', 64.14, -21.94, 'IS', 7), pt('Bergen', 60.39, 5.32, 'NO', 8)],+ trips: [],+ excluded: [],+ start: '2026-06-02',+ end: '2026-06-15',+};++const entry: AutoEntry = {+ id: 7,+ title: 'Harbour',+ story: 'A long walk by the water.',+ location: 'Reykjavik',+ date: '2026-06-02',+ photos: [{ photoId: 1, width: 4000, height: 3000 }],+ lat: 64.14,+ lng: -21.94,+ country: 'IS',+ dayNumber: 1,+ dayCount: 14,+ mood: 'amazing',+ pros: ['Light'],+ cons: ['Wind'],+};++const travel: BookTravelContext = {+ locale: 'en',+ stats,+ path: [],+ entries: [entry],+ labels: { day: 'DAY', stations: 'S', summary: 'Sum', countries: 'C', distance: 'D', pros: 'Good', cons: 'Bad' },+};++const gallery = [+ { photoId: 1, caption: 'Harbour', width: 4000, height: 3000 },+ { photoId: 2, caption: null, width: 3000, height: 4000 },+];+const journey = { title: 'Iceland', subtitle: 'June', entries: [entry] };+const ctx: BookOpsContext = { photos: gallery, journey, travel };+const bare: BookOpsContext = { photos: gallery };++const run = (doc: BookDocument, ops: BookPageOpInput[], c: BookOpsContext = ctx) =>+ applyBookOps(doc, { spreadId: 'sp-in', ops }, { newId, ...c });++function ok(result: ReturnType<typeof applyBookOps>): BookDocument {+ if (!result.ok) throw new Error(`refused: ${result.error.code} ${result.error.message}`);+ expect(bookSpreadSchema.safeParse(inner(result.doc)).success).toBe(true);+ return result.doc;+}++const refusal = (result: ReturnType<typeof applyBookOps>) => (result.ok ? null : result.error.code);+const last = (doc: BookDocument) => inner(doc).elements[inner(doc).elements.length - 1] as BookElement;++const addTo = (element: NewElement, c: BookOpsContext) => run(book([]), [{ op: 'add', element }], c);+/** The element one `add` makes on an empty page. */+const added = (element: NewElement, c: BookOpsContext = ctx) => last(ok(addTo(element, c)));+/** The refusal one `add` gets on an empty page. */+const addRefusal = (element: NewElement, c: BookOpsContext = ctx) => refusal(addTo(element, c));++describe('add', () => {+ it('BOOKEL-001: adds a photo frame the size the panel gives it, centred on the right-hand page', () => {+ const page = book([], { parked: [photo('p-park', 2)] });+ const doc = ok(run(page, [{ op: 'add', element: { kind: 'photo', photoId: 2 } }]));+ expect(last(doc)).toMatchObject({ kind: 'photo', photoId: 2 });+ expect(last(doc).frame).toEqual({ x: 267.75, y: 57.75, w: 94.5, h: 94.5 });+ expect(inner(doc).parked).toEqual([]);+ const empty = added({ kind: 'photo', frameStyle: 'polaroid' });+ expect(empty).toMatchObject({ photoId: null, frameStyle: 'polaroid', frame: { w: 94.5, h: 109.62 } });+ expect(addRefusal({ kind: 'photo', photoId: 99 })).toBe('photo_not_in_gallery');+ });++ it('BOOKEL-002: adds a text in a preset, its words given or read from its binding', () => {+ const heading = added({ kind: 'text', preset: 'heading', text: 'Hi' });+ expect(heading).toMatchObject({ size: 30, weight: 700, leading: 1.1, tracking: -0.02, overridden: false });+ const caption = added({ kind: 'text', preset: 'caption', text: 'Note', italic: true });+ expect(caption).toMatchObject({ size: 7.5, weight: 600, tracking: 0.14, color: '#8a8578', italic: true });+ const bound = { source: 'journey.title' as const };+ const title = added({ kind: 'text', binding: bound });+ expect(title).toMatchObject({ text: 'Iceland', binding: bound, overridden: false });+ expect(added({ kind: 'text', binding: bound, text: 'Mine' })).toMatchObject({ text: 'Mine', overridden: true });+ expect(addRefusal({ kind: 'text', binding: { source: 'entry.date', entryId: 7 } })).toBe('text_required');+ expect(addRefusal({ kind: 'text' })).toBe('invalid_op');+ expect(addRefusal({ kind: 'text', binding: { source: 'entry.story' }, text: 'x' })).toBe('invalid_op');+ expect(addRefusal({ kind: 'text', binding: { source: 'photo.caption' }, text: 'x' })).toBe('invalid_op');+ });++ it('BOOKEL-003: adds a rule as a hairline, a banner wide, and an icon from the shelf only', () => {+ expect(added({ kind: 'shape', shape: 'line' })).toMatchObject({ shape: 'rect', frame: { w: 105, h: 0.5 } });+ const banner = added({ kind: 'shape', shape: 'banner-ribbon', fill: null });+ expect(banner).toMatchObject({ fill: null, frame: { w: 107.1, h: 34.65 } });+ const icon = added({ kind: 'icon', name: 'Compass', color: '#c2410c' });+ expect(icon).toMatchObject({ name: 'Compass', color: '#c2410c', frame: { w: 37.8, h: 37.8 } });+ expect(addRefusal({ kind: 'icon', name: 'NotAnIcon' } as unknown as NewElement)).toBe('invalid_op');+ });++ it('BOOKEL-004: adds the travel kinds from the journey, and refuses them without its figures', () => {+ const map = added({ kind: 'map', scope: 'journey', style: 'dark' });+ expect(map).toMatchObject({ kind: 'map', style: 'dark', countries: ['IS', 'NO'] });+ const figures = added({ kind: 'stats', metrics: ['distance', 'days'] });+ expect(figures).toMatchObject({ kind: 'stats', metrics: ['distance', 'days'], values: { days: 14 } });+ expect(added({ kind: 'badge', variant: 'day', entryId: 7 })).toMatchObject({ text: 'DAY 1', style: 'chip' });+ expect(added({ kind: 'list', entryId: 7 })).toMatchObject({ kind: 'list', proLabel: 'Good', conLabel: 'Bad' });+ expect(addRefusal({ kind: 'badge', variant: 'mood', entryId: 7 })).toBe('text_required');+ const mood = added({ kind: 'badge', variant: 'mood', entryId: 7, text: 'Amazing' });+ expect(mood).toMatchObject({ code: 'amazing', text: 'Amazing' });+ expect(addRefusal({ kind: 'map', scope: 'journey' }, bare)).toBe('travel_unavailable');+ expect(addRefusal({ kind: 'badge', variant: 'day', entryId: 99 })).toBe('entry_not_found');+ expect(addRefusal({ kind: 'badge', variant: 'day', entryId: 7 }, bare)).toBe('travel_unavailable');+ expect(addRefusal({ kind: 'list', entryId: 7 }, bare)).toBe('travel_unavailable');+ expect(added({ kind: 'countries', codes: ['pt'] })).toMatchObject({ kind: 'countries', codes: ['PT'] });+ });+});++describe('style, lock, arrange', () => {+ const one = () => book([text('t-1', 'Hi')]);++ it('BOOKEL-005: restyles an element of its own kind, refuses another kind, a locked one and an empty set', () => {+ const doc = ok(run(one(), [{ op: 'style', elementId: 't-1', set: { kind: 'text', size: 14 } }]));+ expect(find(doc, 't-1')).toMatchObject({ size: 14 });+ const photoLook = { kind: 'photo' as const, fit: 'contain' as const };+ expect(refusal(run(one(), [{ op: 'style', elementId: 't-1', set: photoLook }]))).toBe('wrong_kind');+ const locked = book([text('t-1', 'Hi', undefined, { locked: true })]);+ const smaller = { kind: 'text' as const, size: 9 };+ expect(refusal(run(locked, [{ op: 'style', elementId: 't-1', set: smaller }]))).toBe('locked');+ expect(refusal(run(one(), [{ op: 'style', elementId: 't-1', set: { kind: 'text' } }]))).toBe('invalid_op');+ });++ it('BOOKEL-006: locks and unlocks, the one operation a locked element accepts', () => {+ const locked = ok(run(one(), [{ op: 'lock', elementIds: ['t-1'], locked: true }]));+ expect(find(locked, 't-1')?.locked).toBe(true);+ expect(refusal(run(locked, [{ op: 'frame', elementId: 't-1', x: 240 }]))).toBe('locked');+ const open = ok(run(locked, [{ op: 'lock', elementIds: ['t-1'], locked: false }]));+ expect(find(open, 't-1')?.locked).toBe(false);+ });++ it('BOOKEL-007: moves elements in the paint order, keeping their order among themselves', () => {+ const page = book([text('a', 'a'), text('b', 'b'), text('c', 'c'), text('d', 'd')]);+ type To = 'front' | 'back' | 'forward' | 'backward';+ const arranged = (elementIds: string[], to: To) => ids(ok(run(page, [{ op: 'arrange', elementIds, to }])));+ expect(arranged(['a', 'b'], 'front')).toEqual(['c', 'd', 'a', 'b']);+ expect(arranged(['d', 'c'], 'back')).toEqual(['c', 'd', 'a', 'b']);+ expect(arranged(['a', 'c'], 'forward')).toEqual(['b', 'a', 'd', 'c']);+ expect(arranged(['b', 'd'], 'backward')).toEqual(['b', 'a', 'd', 'c']);+ });+});++describe('align, distribute', () => {+ const three = () =>+ book([+ text('a', 'a', { x: 230, y: 20, w: 40, h: 10 }),+ text('b', 'b', { x: 250, y: 60, w: 20, h: 10 }),+ text('c', 'c', { x: 300, y: 100, w: 60, h: 10 }),+ ]);+ const xs = (doc: BookDocument) => ['a', 'b', 'c'].map((id) => find(doc, id)?.frame.x);+ const ys = (doc: BookDocument) => ['a', 'b', 'c'].map((id) => find(doc, id)?.frame.y);++ it('BOOKEL-008: aligns to the selection, to the page and to its safe area', () => {+ const left = ok(run(three(), [{ op: 'align', elementIds: ['a', 'b', 'c'], edge: 'left' }]));+ expect(xs(left)).toEqual([230, 230, 230]);+ const right = ok(run(three(), [{ op: 'align', elementIds: ['b'], edge: 'right', to: 'page' }]));+ expect(find(right, 'b')?.frame.x).toBe(400);+ const safe = ok(run(three(), [{ op: 'align', elementIds: ['c'], edge: 'top', to: 'safe' }]));+ expect(find(safe, 'c')?.frame.y).toBe(5);+ const middle = ok(run(three(), [{ op: 'align', elementIds: ['a', 'c'], edge: 'middle' }]));+ expect(find(middle, 'a')?.frame.y).toBe(60);+ });++ it('BOOKEL-009: spaces three elements evenly or by a gap, and needs three different ones', () => {+ const even = ok(run(three(), [{ op: 'distribute', elementIds: ['a', 'b', 'c'], axis: 'horizontal' }]));+ expect(xs(even)).toEqual([230, 275, 300]);+ const gap = ok(run(three(), [{ op: 'distribute', elementIds: ['c', 'a', 'b'], axis: 'vertical', gap: 5 }]));+ expect(ys(gap)).toEqual([20, 35, 50]);+ const twice = run(three(), [{ op: 'distribute', elementIds: ['a', 'a', 'b'], axis: 'vertical' }]);+ expect(refusal(twice)).toBe('not_enough_elements');+ });+});++describe('duplicate, fill, copy', () => {+ it('BOOKEL-010: duplicates with new ids, 4 mm down and right unless told otherwise', () => {+ const doc = ok(run(book([text('t-1', 'Hi')]), [{ op: 'duplicate', elementIds: ['t-1'] }]));+ expect(last(doc)).toMatchObject({ kind: 'text', text: 'Hi', frame: { x: 234, y: 124 } });+ expect(last(doc).id).not.toBe('t-1');+ const moved = ok(run(book([text('t-1', 'Hi')]), [{ op: 'duplicate', elementIds: ['t-1'], dx: -10, dy: 0 }]));+ expect(last(moved).frame).toMatchObject({ x: 220, y: 120 });+ });++ it('BOOKEL-011: fills a page or the spread to the bleed, unturned, at the back, as the inspector does', () => {+ const page = book([text('t-1', 'Hi'), photo('p-1', 1, { x: 300, y: 50, w: 50, h: 40 }, { rotation: 8 })]);+ const filled = ok(run(page, [{ op: 'fill', elementId: 'p-1', scope: 'page' }]));+ const back = inner(filled).elements[0];+ expect(back).toMatchObject({ id: 'p-1', rotation: 0, frame: { x: 207, y: -3, w: 216, h: 216 } });+ const spread = ok(run(page, [{ op: 'fill', elementId: 'p-1', scope: 'spread' }]));+ expect(inner(spread).elements[0]?.frame).toEqual({ x: -3, y: -3, w: 426, h: 216 });+ expect(refusal(run(page, [{ op: 'fill', elementId: 't-1', scope: 'page' }]))).toBe('wrong_kind');+ });++ it('BOOKEL-012: copies elements of another page with new ids, photos checked against the gallery', () => {+ const doc = book([]);+ const cover = doc.spreads[0] as BookSpread;+ doc.spreads[0] = { ...cover, elements: [text('t-c', 'Cover', { x: 20, y: 20, w: 100, h: 10 })] };+ const copied = ok(run(doc, [{ op: 'copy_from', spreadId: 'sp-cover', elementIds: ['t-c'] }]));+ expect(last(copied)).toMatchObject({ text: 'Cover', frame: { x: 230 } });+ expect(last(copied).id).not.toBe('t-c');+ doc.spreads[0] = { ...cover, elements: [photo('p-c', 99)] };+ const stranger = run(doc, [{ op: 'copy_from', spreadId: 'sp-cover', elementIds: ['p-c'] }]);+ expect(refusal(stranger)).toBe('photo_not_in_gallery');+ });+});++describe('travel figures, grids and the auto layout', () => {+ it('BOOKEL-013: refreshes the travel figures of a page to the journey, and refuses without its figures', () => {+ const placed = ok(run(book([]), [{ op: 'add', element: { kind: 'stats', metrics: ['days'] } }]));+ const later = { ...ctx, travel: { ...travel, stats: { ...stats, days: 20 } } };+ const fresh = ok(run(placed, [{ op: 'refresh_travel' }], later));+ expect(last(fresh)).toMatchObject({ values: { days: 20 }, stale: false });+ expect(refusal(run(placed, [{ op: 'refresh_travel' }], bare))).toBe('travel_unavailable');+ const named = run(book([text('t-1', 'Hi')]), [{ op: 'refresh_travel', elementIds: ['t-1'] }]);+ expect(refusal(named)).toBe('wrong_kind');+ });++ it('BOOKEL-014: drops a photo grid in as empty frames over the safe area', () => {+ const doc = ok(run(book([]), [{ op: 'add_grid', grid: 'grid-4' }]));+ const frames = inner(doc).elements.filter((e) => e.kind === 'photo');+ expect(frames).toHaveLength(4);+ expect(frames.every((f) => f.kind === 'photo' && f.photoId === null)).toBe(true);+ });++ it('BOOKEL-015: lays a page out again from its entry, keeping its id, its locks and what it parked', () => {+ const kept = text('t-lock', 'Kept', undefined, { locked: true });+ const page = book([kept], { entryId: 7, parked: [photo('p-p', 2)] });+ const doc = ok(run(page, [{ op: 'layout', auto: true }]));+ expect(inner(doc).id).toBe('sp-in');+ expect(find(doc, 't-lock')).toBeDefined();+ expect(inner(doc).parked.map((e) => e.id)).toEqual(['p-p']);+ expect(inner(doc).elements.some((e) => e.kind === 'photo' && e.photoId === 1)).toBe(true);+ expect(refusal(run(book([]), [{ op: 'layout', auto: true }]))).toBe('layout_not_found');+ expect(refusal(run(page, [{ op: 'layout', auto: true }], bare))).toBe('travel_unavailable');+ });++ it('BOOKEL-016: sets a text in italics, with its own leading and tracking', () => {+ const op = { op: 'text' as const, elementId: 't-1', italic: true, leading: 2, tracking: 0.1 };+ const doc = ok(run(book([text('t-1', 'Hi')]), [op]));+ expect(find(doc, 't-1')).toMatchObject({ italic: true, leading: 2, tracking: 0.1 });+ });+});diff --git a/shared/src/book/book-findings-design.spec.ts b/shared/src/book/book-findings-design.spec.tsnew file mode 100644index 000000000..18a689f4a--- /dev/null+++ b/shared/src/book/book-findings-design.spec.ts@@ -0,0 +1,166 @@+import { spreadFindings } from './book-findings';+import { bookBusyUnder, bookLevelFindings, bookVisiblePart, designFindings } from './book-findings-design';+import type { BookPhotoInfo } from './book-ops-core';+import type { BookFinding } from './book-ops.schema';+import { blankBook } from './book-pages';+import {+ bookBadgeElementSchema,+ bookPhotoElementSchema,+ bookShapeElementSchema,+ bookStatsElementSchema,+ bookTextElementSchema,+ type BookDocument,+ type BookElement,+ type BookPhotoElement,+ type BookSpread,+} from './book.schema';+import { describeSpread, pageFindings } from './describe-spread';++import { describe, expect, it } from 'vitest';++/**+ * The design checks on small fixture pages, each with one fault, on the+ * default square book (210 mm pages, the fold at 210).+ */++type Frame = { x: number; y: number; w: number; h: number };++const photo = (id: string, photoId: number, frame: Frame, over = {}) =>+ bookPhotoElementSchema.parse({ id, kind: 'photo', frame, photoId, ...over }) as BookPhotoElement;+const text = (id: string, words: string, frame: Frame, over = {}) =>+ bookTextElementSchema.parse({ id, kind: 'text', frame, text: words, size: 10, ...over }) as BookElement;+const shape = (id: string, frame: Frame, over = {}) =>+ bookShapeElementSchema.parse({ id, kind: 'shape', frame, ...over }) as BookElement;++/** A busy left half and a calm right half, row by row. */+const halves = Array.from({ length: 8 }, () => 'ffff0000').join('');++const gallery: BookPhotoInfo[] = [+ { photoId: 1, width: 4000, height: 3000, busy: halves, luma: 150 },+ { photoId: 2, width: 4000, height: 3000, salient: { x: 0.95, y: 0.5 } },+];++function spread(elements: BookElement[], over: Partial<BookSpread> = {}): BookSpread {+ return { id: 'sp-in', role: 'inner', background: null, elements, parked: [], entryId: null, ...over };+}+const page = blankBook({ title: 'T' }).page;+const codes = (list: BookFinding[]) => list.map((f) => `${f.severity}:${f.code}`);+const design = (elements: BookElement[], over: Partial<BookSpread> = {}) =>+ codes(designFindings(spread(elements, over), page, gallery));++const hero = photo('p-1', 1, { x: 230, y: 20, w: 160, h: 120 });++describe('design findings', () => {+ it('BOOKQA-001: finds words on the busy part of a picture, and none on its calm part or on a scrim', () => {+ expect(design([hero, text('t-1', 'Busy', { x: 235, y: 40, w: 60, h: 10 })])).toContain('warn:text_on_busy');+ expect(design([hero, text('t-2', 'Calm', { x: 330, y: 40, w: 50, h: 10 })])).not.toContain('warn:text_on_busy');+ const scrim = shape('s-1', { x: 232, y: 36, w: 70, h: 18 }, { fill: '#111111', opacity: 0.6 });+ const onScrim = text('t-3', 'Busy', { x: 235, y: 40, w: 60, h: 10 }, { color: '#ffffff' });+ expect(design([hero, scrim, onScrim])).toEqual([]);+ });++ it('BOOKQA-002: finds type that does not stand out, severe under 2:1, and lets large type through at 3:1', () => {+ const line = { x: 230, y: 20, w: 60, h: 10 };+ expect(design([text('t-1', 'Grey', line, { color: '#999999' })])).toContain('warn:contrast_low');+ expect(design([text('t-2', 'Pale', line, { color: '#eeeeee' })])).toContain('severe:contrast_low');+ const large = text('t-3', 'Large', { x: 230, y: 20, w: 120, h: 20 }, { color: '#888888', size: 24 });+ expect(design([large])).not.toContain('warn:contrast_low');+ const light = text('t-4', 'Light', { x: 235, y: 100, w: 60, h: 10 }, { color: '#ffffff' });+ expect(design([hero, light])).toContain('warn:contrast_low');+ });++ it('BOOKQA-003: reads figures in their ink, and leaves a mark that picks its own colour alone', () => {+ const stats = bookStatsElementSchema.parse({ id: 'st', kind: 'stats', frame: { x: 230, y: 20, w: 80, h: 30 } });+ expect(design([{ ...stats, color: '#dddddd' } as BookElement])).toContain('severe:contrast_low');+ const chip = bookBadgeElementSchema.parse({ id: 'bd', kind: 'badge', frame: { x: 230, y: 20, w: 30, h: 8 } });+ expect(design([{ ...chip, color: '#ffffff' } as BookElement])).toEqual([]);+ });++ it('BOOKQA-004: finds type too small to read, a body sooner than a caption', () => {+ const line = { x: 230, y: 20, w: 60, h: 10 };+ expect(design([text('t-1', 'Short', line, { size: 5 })])).toContain('warn:small_text');+ const long = 'A sentence that goes on for a while. '.repeat(4);+ const block = { x: 230, y: 20, w: 160, h: 40 };+ expect(design([text('t-2', long, block, { size: 6.5 })])).toContain('warn:small_text');+ expect(design([text('t-3', 'Caption', line, { size: 6 })])).not.toContain('warn:small_text');+ });++ it('BOOKQA-005: notes a packed page and two pictures all but touching, as context', () => {+ const tiles = Array.from({ length: 9 }, (_, i) =>+ photo(`p-${i}`, 1, { x: 215 + (i % 3) * 66, y: 5 + Math.floor(i / 3) * 67, w: 66, h: 67 }),+ );+ expect(design(tiles)).toContain('info:crowded');+ const a = photo('p-a', 1, { x: 230, y: 20, w: 60, h: 40 });+ const close = [a, photo('p-b', 1, { x: 291, y: 20, w: 60, h: 40 })];+ expect(design(close)).toContain('info:crowded');+ });++ it('BOOKQA-006: notes an edge just off the margin, and not one on it', () => {+ expect(design([text('t-1', 'Near', { x: 6.5, y: 40, w: 60, h: 10 })])).toContain('info:off_grid');+ expect(design([text('t-2', 'On', { x: 40, y: 40, w: 60, h: 10 })])).not.toContain('info:off_grid');+ expect(design([text('t-3', '.', { x: 40, y: 40, w: 2, h: 10 })])).not.toContain('info:off_grid');+ const bled = photo('p-9', 1, { x: -2, y: -2, w: 424, h: 214 });+ const thin = codes(designFindings(spread([bled]), { ...page, bleed: 2 }, gallery));+ expect(thin).not.toContain('info:off_grid');+ });++ it('BOOKQA-007: maps the busy grid through the crop, and says what part of the picture a frame shows', () => {+ const tall = photo('p-t', 1, { x: 230, y: 20, w: 60, h: 120 });+ const part = bookVisiblePart(tall, gallery[0]);+ expect(part?.w).toBeCloseTo(0.375, 3);+ expect(part?.x).toBeCloseTo(0.3125, 3);+ expect(bookBusyUnder(hero, gallery[0], { x: 230, y: 20, w: 80, h: 120 })).toBe(15);+ expect(bookBusyUnder(hero, gallery[0], { x: 310, y: 20, w: 80, h: 120 })).toBe(0);+ expect(bookBusyUnder(hero, { photoId: 1 }, { x: 230, y: 20, w: 80, h: 120 })).toBeNull();+ });++ it('BOOKQA-008: finds the picture detail cropped out of its frame, from its salient point', () => {+ const cut = photo('p-2', 2, { x: 230, y: 20, w: 60, h: 120 });+ expect(codes(spreadFindings(spread([cut]), page, gallery))).toContain('warn:focal_cut');+ const kept = photo('p-3', 2, { x: 230, y: 20, w: 60, h: 120 }, { focalX: 0.95 });+ expect(codes(spreadFindings(spread([kept]), page, gallery))).not.toContain('warn:focal_cut');+ });+});++describe('book level and the page in words', () => {+ function bookOf(spreads: BookElement[][]): BookDocument {+ const doc = blankBook({ title: 'T' });+ const inner = spreads.map((elements, i) => spread(elements, { id: `sp-${i}` }));+ return { ...doc, spreads: [doc.spreads[0] as BookSpread, ...inner, doc.spreads[4] as BookSpread] };+ }++ it('BOOKQA-009: finds more than two typefaces in a book, and says so once', () => {+ const fonts = ['sans', 'serif', 'bebas'].map((font, i) => [+ text(`t-${i}`, 'Hi', { x: 230, y: 20, w: 60, h: 10 }, { font }),+ ]);+ const list = bookLevelFindings(bookOf(fonts));+ expect(list.filter((f) => f.code === 'font_mix')).toHaveLength(1);+ expect(bookLevelFindings(bookOf(fonts.slice(0, 2)))).toEqual([]);+ });++ it('BOOKQA-010: notes colours outside the book own and the same page three times running', () => {+ const inks = ['#111111', '#121212', '#131313', '#141414', '#151515', '#161616', '#ff0000'];+ const page1 = inks.map((color, i) => text(`t-${i}`, 'Hi', { x: 230, y: 10 + i * 12, w: 60, h: 10 }, { color }));+ const same = [text('t-s', 'Same', { x: 230, y: 20, w: 60, h: 10 })];+ const list = codes(bookLevelFindings(bookOf([page1, same, same, same])));+ expect(list).toContain('info:palette_drift');+ expect(list).toContain('info:repeat_layout');+ const repeat = bookLevelFindings(bookOf([page1, same, same, same])).find((f) => f.code === 'repeat_layout');+ expect(repeat?.elementIds).toEqual([]);+ });++ it('BOOKQA-011: describes every kind in words, a crop with its face note, and adds the design findings', () => {+ const frame = { x: 230, y: 150, w: 30, h: 8 };+ const badge = bookBadgeElementSchema.parse({ id: 'bd', kind: 'badge', variant: 'day', text: 'DAY 3', frame });+ const crop = photo('p-c', 1, { x: 230, y: 20, w: 60, h: 120 });+ const grey = text('t-g', 'Grey', { x: 330, y: 160, w: 60, h: 10 }, { color: '#bbbbbb' });+ const doc = blankBook({ title: 'T', newId: (p) => `${p}-q` });+ const target = spread([crop, badge as BookElement, grey], { id: 'sp-x' });+ const withPage = { ...doc, spreads: [...doc.spreads.slice(0, 2), target, ...doc.spreads.slice(2)] };+ const d = describeSpread(withPage, 'sp-x', gallery);+ expect(d?.text).toMatch(/day mark "DAY 3", plain; sans bold/);+ expect(d?.text).toMatch(/no face detection/);+ expect(d?.findings.map((f) => f.code)).toContain('contrast_low');+ expect(pageFindings(target, page, gallery).map((f) => f.code)).toContain('contrast_low');+ });+});diff --git a/shared/src/book/book-findings-design.ts b/shared/src/book/book-findings-design.tsnew file mode 100644index 000000000..658874331--- /dev/null+++ b/shared/src/book/book-findings-design.ts@@ -0,0 +1,386 @@+import { contrastOfLuminance, deltaE, greyLuminance, luminance, parseHex, requiredContrast } from './book-colour';+import type { BookPhotoInfo } from './book-ops-core';+import { BOOK_OP_LIMITS, type BookFinding } from './book-ops.schema';+import type { BookDocument, BookElement, BookPageSetup, BookPhotoElement, BookSpread } from './book.schema';++/**+ * The checks a designer makes on a proof, beyond the print faults of+ * book-findings.ts: words over a busy part of a picture, words that do not+ * stand out from what they are set on, type too small to read, a page packed+ * edge to edge, edges that almost line up, and across the book more than two+ * typefaces, colours that wander from the book's own, the same page three+ * times running.+ *+ * Honest limits: no faces and no taste. A picture's busy areas, its mean+ * brightness and its salient point come from cheap pixel signals measured on+ * the server (an edge-density grid, a mean, an edge-energy centroid); without+ * them the checks that need them say nothing rather than guess.+ */++interface Box {+ x: number;+ y: number;+ w: number;+ h: number;+}++const mm = (v: number) => `${Math.round(v * 10) / 10}`;++function overlap(a: Box, b: Box): Box | null {+ const x = Math.max(a.x, b.x);+ const y = Math.max(a.y, b.y);+ const w = Math.min(a.x + a.w, b.x + b.w) - x;+ const h = Math.min(a.y + a.h, b.y + b.h) - y;+ return w > 0 && h > 0 ? { x, y, w, h } : null;+}++const centreIn = (b: Box, px: number, py: number) => px >= b.x && px <= b.x + b.w && py >= b.y && py <= b.y + b.h;++/**+ * Where a photo's picture lies in its frame: the drawn picture's box in page+ * millimetres, as `object-fit` and `object-position` place it (the focal point+ * is the position). Null when the picture's shape is unknown.+ */+export function bookPhotoCrop(el: BookPhotoElement, info: BookPhotoInfo | undefined): Box | null {+ if (!info?.width || !info.height) return null;+ const f = el.frame;+ const pick = el.fit === 'contain' ? Math.min : Math.max;+ const scale = pick(f.w / info.width, f.h / info.height);+ const w = info.width * scale;+ const h = info.height * scale;+ return { x: f.x + (f.w - w) * el.focalX, y: f.y + (f.h - h) * el.focalY, w, h };+}++/** The part of a picture (0..1 of each edge) its frame shows. */+export function bookVisiblePart(el: BookPhotoElement, info: BookPhotoInfo | undefined): Box | null {+ const crop = bookPhotoCrop(el, info);+ if (!crop) return null;+ const seen = overlap(crop, el.frame);+ if (!seen) return null;+ return { x: (seen.x - crop.x) / crop.w, y: (seen.y - crop.y) / crop.h, w: seen.w / crop.w, h: seen.h / crop.h };+}++/** How busy the part of a picture under a box is, 0 (calm) to 15, weighted by area; null when unknown. */+export function bookBusyUnder(el: BookPhotoElement, info: BookPhotoInfo | undefined, box: Box): number | null {+ const crop = bookPhotoCrop(el, info);+ const grid = info?.busy;+ if (!crop || !grid || grid.length !== 64) return null;+ const onPhoto = overlap(box, el.frame);+ const area = onPhoto && overlap(onPhoto, crop);+ if (!area) return null;+ const cw = crop.w / 8;+ const ch = crop.h / 8;+ let sum = 0;+ let weight = 0;+ for (let i = 0; i < 64; i++) {+ const cell = { x: crop.x + (i % 8) * cw, y: crop.y + Math.floor(i / 8) * ch, w: cw, h: ch };+ const part = overlap(cell, area);+ const value = Number.parseInt(grid.charAt(i), 16);+ if (!part || !Number.isFinite(value)) continue;+ sum += value * part.w * part.h;+ weight += part.w * part.h;+ }+ return weight > 0 ? sum / weight : null;+}++/** The kinds that carry words a reader has to read. */+const READ = new Set<BookElement['kind']>(['text', 'badge', 'stats', 'list']);++/** A shape that hides what is under it well enough for type: filled and at least half opaque. */+function scrimFill(el: BookElement): string | null {+ if (el.kind !== 'shape' || el.shape === 'line' || el.opacity < 0.5) return null;+ return el.fill;+}++/** What a text at index `i` is set on: a scrim, a picture, or the page. */+type Ground =+ | { kind: 'colour'; hex: string; label: string }+ | { kind: 'photo'; el: BookPhotoElement; info: BookPhotoInfo | undefined };++function groundOf(spread: BookSpread, i: number, box: Box, photos: readonly BookPhotoInfo[] | undefined): Ground {+ const cx = box.x + box.w / 2;+ const cy = box.y + box.h / 2;+ for (let j = i - 1; j >= 0; j--) {+ const under = spread.elements[j];+ if (!under || !centreIn(under.frame, cx, cy)) continue;+ const fill = scrimFill(under);+ if (fill) return { kind: 'colour', hex: fill, label: `shape ${under.id}` };+ if (under.kind === 'photo' && under.photoId != null) {+ return { kind: 'photo', el: under, info: photos?.find((p) => p.photoId === under.photoId) };+ }+ }+ const label = spread.background ? 'the page' : 'the paper';+ return { kind: 'colour', hex: spread.background ?? '#ffffff', label };+}++/** How light what the words are set on is, or null when a picture's brightness is unknown. */+function groundLuminance(ground: Ground): number | null {+ if (ground.kind === 'photo') return ground.info?.luma === undefined ? null : greyLuminance(ground.info.luma);+ const rgb = parseHex(ground.hex);+ return rgb ? luminance(rgb) : null;+}++/** The colour a reader sees the words in, or null when the element picks its own (an automatic mark). */+function inkOf(el: BookElement): { hex: string; size: number } | null {+ if (el.kind === 'text') return { hex: el.color, size: el.size };+ if (el.kind === 'badge') return el.autoColor ? null : { hex: el.color, size: 10 * el.textScale };+ if (el.kind === 'stats' || el.kind === 'list') return { hex: el.color, size: 10 * el.textScale };+ return null;+}++interface Ctx {+ spread: BookSpread;+ page: BookPageSetup;+ photos: readonly BookPhotoInfo[] | undefined;+ out: BookFinding[];+}++const add = (ctx: Ctx, f: BookFinding) => ctx.out.push({ ...f, message: f.message.slice(0, 300) });++function contrastAndBusy(ctx: Ctx): void {+ ctx.spread.elements.forEach((el, i) => {+ if (!READ.has(el.kind)) return;+ const ink = inkOf(el);+ const ground = groundOf(ctx.spread, i, el.frame, ctx.photos);+ if (ground.kind === 'photo') {+ const busy = bookBusyUnder(ground.el, ground.info, el.frame);+ if (busy !== null && busy >= 9) {+ add(ctx, {+ code: 'text_on_busy',+ severity: 'warn',+ elementIds: [el.id, ground.el.id],+ message: `${el.kind} ${el.id} sits on a busy part of photo ${ground.el.photoId} (${Math.round(busy)} of 15); put a scrim under it or move it to a calm area`,+ });+ }+ }+ const textRgb = ink ? parseHex(ink.hex) : null;+ const groundLum = groundLuminance(ground);+ if (!ink || !textRgb || groundLum === null) return;+ const ratio = contrastOfLuminance(luminance(textRgb), groundLum);+ const need = requiredContrast(ink.size);+ if (ratio >= need) return;+ const on = ground.kind === 'colour' ? ground.label : `photo ${ground.el.photoId}`;+ add(ctx, {+ code: 'contrast_low',+ severity: ratio < 2 ? 'severe' : 'warn',+ elementIds: [el.id],+ message: `${el.kind} ${el.id} in ${ink.hex} on ${on} has a contrast of ${ratio.toFixed(1)}:1, under the ${need}:1 type of that size needs`,+ });+ });+}++function smallText(ctx: Ctx): void {+ for (const el of ctx.spread.elements) {+ if (el.kind !== 'text' || !el.text.trim()) continue;+ const body = el.text.length > 80;+ const floor = body ? 7 : 5.5;+ if (el.size >= floor) continue;+ add(ctx, {+ code: 'small_text',+ severity: 'warn',+ elementIds: [el.id],+ message: `text ${el.id} is set at ${el.size} pt; ${body ? 'running text' : 'a caption or meta line'} reads from ${floor} pt`,+ });+ }+}++/** The page boxes of a spread: one page, or the two of a double spread. */+function pagesOf(ctx: Ctx): Box[] {+ const { pageWidth: w, pageHeight: h } = ctx.page;+ const first = { x: 0, y: 0, w, h };+ if (ctx.spread.role !== 'inner') return [first];+ return [first, { x: w, y: 0, w, h }];+}++const isContent = (el: BookElement) => el.kind !== 'shape' || el.frame.w > 2 || el.frame.h > 2;++/** How much of a page's live area (inside the safe margin) is covered, rastered in 4 mm cells. */+function coverage(page: Box, safe: number, els: readonly BookElement[]): number {+ const live = { x: page.x + safe, y: page.y + safe, w: page.w - safe * 2, h: page.h - safe * 2 };+ const step = 4;+ let cells = 0;+ let covered = 0;+ for (let x = live.x + step / 2; x < live.x + live.w; x += step) {+ for (let y = live.y + step / 2; y < live.y + live.h; y += step) {+ cells++;+ if (els.some((e) => centreIn(e.frame, x, y))) covered++;+ }+ }+ return cells ? covered / cells : 0;+}++function crowded(ctx: Ctx): void {+ const content = ctx.spread.elements.filter(isContent);+ for (const page of pagesOf(ctx)) {+ const on = content.filter((e) => overlap(e.frame, page));+ if (on.length < 9) continue;+ const share = coverage(page, ctx.page.safe, on);+ if (share <= 0.85) continue;+ add(ctx, {+ code: 'crowded',+ severity: 'info',+ elementIds: on.slice(0, 8).map((e) => e.id),+ message: `a page holds ${on.length} elements over ${Math.round(share * 100)}% of its live area; give it room`,+ });+ }+ const words = ctx.spread.elements.filter((e) => e.kind === 'photo' || READ.has(e.kind));+ for (let i = 0; i < words.length; i++) {+ for (let j = i + 1; j < words.length; j++) {+ const a = words[i] as BookElement;+ const b = words[j] as BookElement;+ const gap = gapBetween(a.frame, b.frame);+ if (gap === null || gap <= 0.05 || gap >= 2) continue;+ add(ctx, {+ code: 'crowded',+ severity: 'info',+ elementIds: [a.id, b.id],+ message: `${a.kind} ${a.id} and ${b.kind} ${b.id} are ${mm(gap)} mm apart; closer than 2 mm reads as touching`,+ });+ return;+ }+ }+}++/** The gap between two boxes side by side or one above the other, or null when they overlap or do not face. */+function gapBetween(a: Box, b: Box): number | null {+ const facingX = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y) > 0;+ const facingY = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x) > 0;+ if (facingX && facingY) return null;+ if (facingX) return Math.max(b.x - (a.x + a.w), a.x - (b.x + b.w));+ if (facingY) return Math.max(b.y - (a.y + a.h), a.y - (b.y + b.h));+ return null;+}++/**+ * Edges that almost line up: within 0.5 to 3 mm of the bleed, a margin, the+ * fold or another element's edge, a near miss. An element is measured against+ * the others only, so a small one is never off its own opposite edge.+ */+function offGrid(ctx: Ctx): void {+ const { pageWidth: PW, pageHeight: H, safe, bleed } = ctx.page;+ const inner = ctx.spread.role === 'inner';+ const W = inner ? PW * 2 : PW;+ const baseX = [-bleed, 0, safe, W - safe, W, W + bleed, ...(inner ? [PW, PW - safe, PW + safe] : [])];+ const baseY = [-bleed, 0, safe, H - safe, H, H + bleed];+ const content = ctx.spread.elements.filter((e) => e.kind !== 'shape' && !e.rotation);+ const near = (v: number, lines: number[]) => lines.some((l) => Math.abs(v - l) > 0.5 && Math.abs(v - l) < 3);+ const onLine = (v: number, lines: number[]) => lines.some((l) => Math.abs(v - l) <= 0.5);+ const misses = (edges: number[], lines: number[]) => edges.some((v) => near(v, lines) && !onLine(v, lines));+ let found = 0;+ for (const el of content) {+ if (found >= 3) return;+ const others = content.filter((o) => o !== el);+ const xs = [...baseX, ...others.flatMap((o) => [o.frame.x, o.frame.x + o.frame.w])];+ const ys = [...baseY, ...others.flatMap((o) => [o.frame.y, o.frame.y + o.frame.h])];+ const f = el.frame;+ if (!misses([f.x, f.x + f.w], xs) && !misses([f.y, f.y + f.h], ys)) continue;+ found++;+ add(ctx, {+ code: 'off_grid',+ severity: 'info',+ elementIds: [el.id],+ message: `an edge of ${el.kind} ${el.id} is a few millimetres off a margin, the fold or a neighbour; line it up or set it clearly apart`,+ });+ }+}++const SEVERITY_ORDER = { severe: 0, warn: 1, info: 2 } as const;++/** Severe first, in the order found, at most `BOOK_OP_LIMITS.findings`. */+export function sortBookFindings(list: readonly BookFinding[]): BookFinding[] {+ return list+ .map((f, i) => ({ f, i }))+ .sort((a, b) => SEVERITY_ORDER[a.f.severity] - SEVERITY_ORDER[b.f.severity] || a.i - b.i)+ .map(({ f }) => f)+ .slice(0, BOOK_OP_LIMITS.findings);+}++/** The design findings of one page, severe first. */+export function designFindings(+ spread: BookSpread,+ page: BookPageSetup,+ photos?: readonly BookPhotoInfo[],+): BookFinding[] {+ const ctx: Ctx = { spread, page, photos, out: [] };+ contrastAndBusy(ctx);+ smallText(ctx);+ crowded(ctx);+ offGrid(ctx);+ return sortBookFindings(ctx.out);+}++/** The typefaces a book is set in: its texts, its travel elements and its page numbers when shown. */+function familiesOf(doc: BookDocument): string[] {+ const used = new Set<string>();+ for (const spread of doc.spreads) {+ for (const el of spread.elements) {+ if ('font' in el && (el.kind !== 'text' || el.text.trim())) used.add(el.font);+ }+ }+ if (doc.page.pageNumbers.show) used.add(doc.page.pageNumbers.font);+ return [...used].sort();+}++/** The colours a book paints with: its type and its filled shapes, with how often each is used. */+function coloursOf(doc: BookDocument): Map<string, number> {+ const counts = new Map<string, number>();+ const count = (hex: string | null | undefined) => {+ if (hex) counts.set(hex.toLowerCase(), (counts.get(hex.toLowerCase()) ?? 0) + 1);+ };+ for (const spread of doc.spreads) {+ for (const el of spread.elements) {+ if (el.kind === 'text') count(el.color);+ if (el.kind === 'shape') count(el.fill);+ }+ }+ return counts;+}++const cm = (v: number) => Math.round(v / 10);++/** A page's arrangement as a short signature: which kinds sit where, to the nearest centimetre. */+function signatureOf(spread: BookSpread): string {+ return spread.elements.map((e) => `${e.kind}:${cm(e.frame.x)},${cm(e.frame.y)},${cm(e.frame.w)}`).join('|');+}++/** Findings about the book as a whole: typefaces, colours, and the same page three times running. */+export function bookLevelFindings(doc: BookDocument): BookFinding[] {+ const out: BookFinding[] = [];+ const families = familiesOf(doc);+ if (families.length > 2) {+ out.push({+ code: 'font_mix',+ severity: 'warn',+ elementIds: [],+ message: `the book is set in ${families.length} typefaces (${families.join(', ')}); keep to two`,+ });+ }+ const colours = [...coloursOf(doc)].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));+ const main = colours.slice(0, 6).map(([hex]) => hex);+ const stray = colours.slice(6).filter(([hex]) => main.every((m) => deltaE(hex, m) > 12));+ if (stray.length) {+ const named = stray.slice(0, 8).map(([hex]) => hex);+ out.push({+ code: 'palette_drift',+ severity: 'info',+ elementIds: [],+ message: `colours outside the book's own: ${named.join(', ')}`,+ });+ }+ const inner = doc.spreads.filter((s) => s.role === 'inner' && s.elements.length > 0);+ for (let i = 2; i < inner.length; i++) {+ const [a, b, c] = [inner[i - 2], inner[i - 1], inner[i]];+ if (!a || !b || !c) continue;+ const sig = signatureOf(c);+ if (signatureOf(a) !== sig || signatureOf(b) !== sig) continue;+ out.push({+ code: 'repeat_layout',+ severity: 'info',+ // Pages, not elements: the ids are in the message.+ elementIds: [],+ message: `pages ${a.id}, ${b.id} and ${c.id} are laid out the same way; vary one`,+ });+ break;+ }+ return sortBookFindings(out);+}diff --git a/shared/src/book/book-findings.ts b/shared/src/book/book-findings.tsindex 3973b809b..4cde98426 100644--- a/shared/src/book/book-findings.ts+++ b/shared/src/book/book-findings.ts@@ -1,3 +1,4 @@+import { bookVisiblePart } from './book-findings-design';import type { BookPhotoInfo } from './book-ops-core';import { BOOK_OP_LIMITS, type BookFinding } from './book-ops.schema';import type { BookElement, BookPageSetup, BookPhotoElement, BookSpread, BookTextElement } from './book.schema';@@ -80,7 +81,7 @@ const LETTER_EM: Record<BookTextElement['font'], number> = {const orDefault = (v: number | undefined, fallback: number) => (Number.isFinite(v) ? (v as number) : fallback);/** How many millimetres a text needs to be set at its frame's width, roughly. */-function textHeightNeeded(el: BookTextElement): number {+export function textHeightNeeded(el: BookTextElement): number {const sizeMm = (orDefault(el.size, 11) * 25.4) / 72;const tracking = orDefault(el.tracking, 0);const letter = sizeMm * ((LETTER_EM[el.font] ?? 0.5) * (el.weight >= 600 ? 1.06 : 1) + tracking);@@ -325,7 +326,28 @@ function focal(ctx: Ctx, el: BookPhotoElement, index: number): void {if (dx * dx + dy * dy > 1) return say('falls outside the ellipse mask');}const over = coveredBy(ctx.spread, index, px, py);- if (over) say(`is hidden under ${over.kind} ${over.id}`);+ if (over) return say(`is hidden under ${over.kind} ${over.id}`);+ salientCut(ctx, el);+}++/**+ * The picture's salient point (where its detail gathers, from the pixel+ * signals) cropped out of the frame. An estimate, not a face detector.+ */+function salientCut(ctx: Ctx, el: BookPhotoElement): void {+ const info = ctx.photos?.find((p) => p.photoId === el.photoId);+ const s = info?.salient;+ const seen = bookVisiblePart(el, info);+ if (!s || !seen) return;+ const inX = s.x >= seen.x - 0.02 && s.x <= seen.x + seen.w + 0.02;+ const inY = s.y >= seen.y - 0.02 && s.y <= seen.y + seen.h + 0.02;+ if (inX && inY) return;+ add(ctx, {+ code: 'focal_cut',+ severity: 'warn',+ elementIds: [el.id],+ message: `the detail of photo ${el.id} gathers at ${s.x.toFixed(2)}/${s.y.toFixed(2)} of the picture, outside what its frame shows; move focalX/focalY toward it`,+ });}function overflow(ctx: Ctx): void {diff --git a/shared/src/book/book-icons.ts b/shared/src/book/book-icons.tsnew file mode 100644index 000000000..4b1dde916--- /dev/null+++ b/shared/src/book/book-icons.ts@@ -0,0 +1,90 @@+/**+ * The drawings the assistant may put on a page, by their lucide names.+ *+ * The Studio's icon tab opens on this shelf (client/src/components/Studio/iconLibrary.ts+ * filters it against the lucide version it ships), and the book engine takes a+ * new icon only from it: an icon element stores a free name the renderer+ * resolves, and a model that names a drawing lucide does not have would place+ * the fallback glyph. A curated list keeps the assistant to drawings that exist+ * and that a travel page actually reaches for.+ */+export const BOOK_DESIGN_ICONS = [+ 'Plane',+ 'Train',+ 'TrainFront',+ 'Car',+ 'Bus',+ 'Ship',+ 'Bike',+ 'Footprints',+ 'Sailboat',+ 'MapPin',+ 'Map',+ 'Compass',+ 'Navigation',+ 'Route',+ 'Globe',+ 'Milestone',+ 'Signpost',+ 'Mountain',+ 'MountainSnow',+ 'Waves',+ 'TreePine',+ 'Palmtree',+ 'Flower2',+ 'Leaf',+ 'Bird',+ 'Fish',+ 'Sun',+ 'Sunrise',+ 'Sunset',+ 'Moon',+ 'Cloud',+ 'CloudRain',+ 'CloudLightning',+ 'Snowflake',+ 'Umbrella',+ 'Thermometer',+ 'Wind',+ 'Tent',+ 'Backpack',+ 'Luggage',+ 'BedDouble',+ 'Hotel',+ 'Key',+ 'Anchor',+ 'Coffee',+ 'UtensilsCrossed',+ 'Wine',+ 'Beer',+ 'IceCream',+ 'Croissant',+ 'Camera',+ 'Image',+ 'Film',+ 'Music',+ 'BookOpen',+ 'PenLine',+ 'Quote',+ 'Sticker',+ 'Heart',+ 'Star',+ 'Sparkles',+ 'Flag',+ 'Ticket',+ 'Gift',+ 'PartyPopper',+ 'Clock',+ 'CalendarDays',+ 'CreditCard',+ 'Wallet',+ 'ShoppingBag',+ 'Landmark',+ 'Church',+ 'Castle',+ 'Building2',+ 'Home',+ 'Binoculars',+ 'Telescope',+] as const;+export type BookDesignIcon = (typeof BOOK_DESIGN_ICONS)[number];diff --git a/shared/src/book/book-map-sources.ts b/shared/src/book/book-map-sources.tsnew file mode 100644index 000000000..afcadf6de--- /dev/null+++ b/shared/src/book/book-map-sources.ts@@ -0,0 +1,39 @@+/**+ * The imagery a book map may be drawn on, besides the bundled outlines.+ *+ * Two sources, chosen because they are honestly printable in a book somebody+ * might sell, and moved here from the Studio+ * (client/src/components/Studio/mapSources.ts) so the server's design tool+ * places the same tiles and the same credit the Travel panel does.+ *+ * - Relief: NASA's Blue Marble shaded relief and bathymetry through GIBS. US+ * government imagery whose capabilities document says `<ows:Fees>none` and+ * `<ows:AccessConstraints>none`. Level 8 at most, about 600 metres to the+ * pixel: a country or a continent, not a city. The path is `{z}/{y}/{x}`+ * because WMTS names its axes row then column.+ * - Satellite: EOX's Sentinel-2 cloudless mosaic, the 2016 layer, the one the+ * service releases under CC BY 4.0 (later years are non-commercial).+ * Attribution is part of the licence, so it travels into the document.+ *+ * Constants, not settings: the planner's own street tiles are not offered for+ * print at all (bulk fetching is against the OSM tile policy), so nothing here+ * depends on how an instance is configured.+ */++const GIBS = 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best';+const RELIEF_LAYER = 'BlueMarble_ShadedRelief_Bathymetry/default/GoogleMapsCompatible_Level8';+const EOX = 'https://tiles.maps.eox.at/wmts/1.0.0';++export const BOOK_RELIEF_TILES = `${GIBS}/${RELIEF_LAYER}/{z}/{y}/{x}.jpeg`;+export const BOOK_SATELLITE_TILES = `${EOX}/s2cloudless_3857/default/g/{z}/{y}/{x}.jpg`;++/** A map source the engine can place: the tile template and the credit the licence asks for. */+export interface BookMapSource {+ url: string;+ attribution: string;+}++export const BOOK_MAP_SOURCES: Record<'relief' | 'satellite', BookMapSource> = {+ relief: { url: BOOK_RELIEF_TILES, attribution: 'NASA EOSDIS GIBS' },+ satellite: { url: BOOK_SATELLITE_TILES, attribution: 'Sentinel-2 cloudless © EOX (CC BY 4.0)' },+};diff --git a/shared/src/book/book-op-ids.ts b/shared/src/book/book-op-ids.tsnew file mode 100644index 000000000..c428920c6--- /dev/null+++ b/shared/src/book/book-op-ids.ts@@ -0,0 +1,17 @@+import { BOOK_GRIDS } from './book-grids';++import { z } from 'zod';++/**+ * The ids a book edit names, as the document has them (`sp-...`, `p-...`):+ * never invented by the model, bounded. Kept apart from book-ops.schema.ts so+ * the element operations' own schema module can use them without a cycle;+ * book-ops.schema.ts re-exports them.+ */+export const bookSpreadIdSchema = z.string().regex(/^[\w-]{1,40}$/);+export const bookElementIdSchema = z.string().regex(/^[\w-]{1,40}$/);++const gridIds = BOOK_GRIDS.map((g) => g.id) as [string, ...string[]];++/** The photo grids, by id. */+export const bookGridIdSchema = z.enum(gridIds);diff --git a/shared/src/book/book-ops-core.ts b/shared/src/book/book-ops-core.tsindex cf39326b0..97f752212 100644--- a/shared/src/book/book-ops-core.ts+++ b/shared/src/book/book-ops-core.ts@@ -1,4 +1,13 @@-import { bookSpreadSchema, type BookDocument, type BookSpread } from './book.schema';+import type { BookTravelContext } from './book-travel';+import {+ MAX_SPREAD_ELEMENTS,+ MAX_TEXT_LENGTH,+ bookSpreadSchema,+ type BookDocument,+ type BookElement,+ type BookSpread,+ type BookTextElement,+} from './book.schema';import type { z } from 'zod';@@ -28,6 +37,10 @@ export const BOOK_OP_ERROR_CODES = ['caption_missing','text_required','no_cover',+ 'travel_unavailable',+ 'icon_unknown',+ 'not_enough_elements',+ 'layouts_full',] as const;export type BookOpErrorCode = (typeof BOOK_OP_ERROR_CODES)[number];@@ -49,6 +62,14 @@ export interface BookPhotoInfo {caption?: string | null;/** A photo by another contributor, drawn as an empty frame in a page image. */hidden?: boolean;+ /** Up to five `#rrggbb` or `#rrggbb:share` colours of the picture, most of it first. */+ palette?: readonly string[];+ /** An 8 x 8 grid of edge density, row by row, one hex nibble (0 calm to f busy) per cell. */+ busy?: string;+ /** Where the picture's detail gathers (an edge-energy centroid), 0..1 of each edge; not a face detector. */+ salient?: { x: number; y: number };+ /** The picture's mean brightness, 0..255, when known. */+ luma?: number;}/** The journey's words a text can be bound to. */@@ -56,6 +77,8 @@ export interface BookJourneyWords {title: string;subtitle?: string | null;entries?: readonly { id: number; title?: string | null; story?: string | null; location?: string | null }[];+ /** The cover photo the journey names, for a layout that rebuilds a page from its entry. */+ coverPhotoId?: number | null;}export interface BookOpsContext {@@ -64,6 +87,12 @@ export interface BookOpsContext {journey?: BookJourneyWords;/** Mints element and spread ids; tests pass a counter. */newId?: (prefix: string) => string;+ /**+ * The journey's figures, route and entries, for the travel elements (maps,+ * figures, countries, marks, lists) and for laying a page out again from its+ * entry. Without it those operations are refused with `travel_unavailable`.+ */+ travel?: BookTravelContext;}/**@@ -172,3 +201,59 @@ export function galleryPhoto(photoId: number, ctx: BookOpsContext, opIndex: numbif (!info) throw failOp('photo_not_in_gallery', `photo ${photoId} is not in this journey's gallery`, opIndex);return info;}++/** An element on the page by id; a parked one is named as parked. */+export function pageElement(spread: BookSpread, id: string, opIndex: number): BookElement {+ const el = spread.elements.find((e) => e.id === id);+ if (el) return el;+ const parked = spread.parked.some((e) => e.id === id);+ const message = parked+ ? `${id} is parked, not on the page; lay the page out again to bring it back`+ : `no element ${id} on this page`;+ throw failOp('element_not_found', message, opIndex, id);+}++/** The element itself, or a refusal when it is locked. */+export function unlockedElement<E extends BookElement>(el: E, opIndex: number): E {+ if (el.locked) throw failOp('locked', `${el.id} is locked; it is left as it is`, opIndex, el.id);+ return el;+}++/** A refusal when `add` more elements would not fit on the page. */+export function roomFor(spread: BookSpread, add: number, opIndex: number): void {+ if (spread.elements.length + add > MAX_SPREAD_ELEMENTS) {+ throw failOp('too_many_elements', `a page holds at most ${MAX_SPREAD_ELEMENTS} elements`, opIndex);+ }+}++type Binding = NonNullable<BookTextElement['binding']>;++/**+ * The words a binding reads, from what the context knows, or undefined.+ *+ * Dates and coordinates are set in a reader's language and notation, which the+ * engine does not know: those need their words given.+ */+export function bookBoundWords(binding: Binding, ctx: BookOpsContext): string | undefined {+ const j = ctx.journey;+ const pick = (v: string | null | undefined) => (v && v.trim() ? v.slice(0, MAX_TEXT_LENGTH) : undefined);+ switch (binding.source) {+ case 'journey.title':+ return pick(j?.title);+ case 'journey.subtitle':+ return pick(j?.subtitle);+ case 'photo.caption':+ return pick(ctx.photos?.find((p) => p.photoId === binding.photoId)?.caption);+ case 'entry.title':+ case 'entry.story':+ case 'entry.location': {+ if (binding.source === 'entry.location' && binding.format) return undefined;+ const entry = j?.entries?.find((e) => e.id === binding.entryId);+ if (!entry) return undefined;+ if (binding.source === 'entry.title') return pick(entry.title || entry.location);+ return pick(binding.source === 'entry.story' ? entry.story?.trim() : entry.location);+ }+ default:+ return undefined;+ }+}diff --git a/shared/src/book/book-ops-elements.ts b/shared/src/book/book-ops-elements.tsnew file mode 100644index 000000000..28a541b3c--- /dev/null+++ b/shared/src/book/book-ops-elements.ts@@ -0,0 +1,602 @@+import { relayoutSpread } from './auto/auto-book';+import type { AutoInput } from './auto/auto-types';+import { bookElementPropsSchema, type BOOK_ELEMENT_OP_SCHEMAS, type BookNewElement } from './book-element-ops.schema';+import { bookGridElements, defaultBookGridBox, findBookGrid } from './book-grids';+import {+ bookBoundWords,+ failOp,+ galleryPhoto,+ journeyEntry,+ pageElement,+ roomFor,+ round2,+ unlockedElement,+ type BookOpsContext,+} from './book-ops-core';+import {+ bookBadgeValue,+ bookEntryListItems,+ bookTravelBadge,+ bookTravelCountries,+ bookTravelList,+ bookTravelMap,+ bookTravelSize,+ bookTravelStats,+ refreshPatch,+ type BookTravelContext,+} from './book-travel';+import type {+ BookDocument,+ BookElement,+ BookFrame,+ BookPageSetup,+ BookPhotoElement,+ BookSpread,+ BookTextElement,+} from './book.schema';++import type { z } from 'zod';++/**+ * The element operations of the book engine: what `add`, `style`, `arrange`,+ * `align`, `distribute`, `lock`, `duplicate`, `fill`, `copy_from`,+ * `refresh_travel` and `add_grid` do to a page, and the `auto` layout. Called+ * from `applyBookOps` (book-ops.ts), which parses, runs a call all or nothing+ * and checks the page it hands back against the document's schema.+ *+ * Each does what the Studio's own control does: the sizes an element arrives+ * at are the panels', `fill` is the inspector's, `duplicate` offsets by 4 mm+ * like the Studio's. Where the assistant may do more than the Studio+ * (aligning and distributing a group), it is said in the operation's schema.+ */++interface ElementOpEnv {+ doc: BookDocument;+ page: BookPageSetup;+ ctx: BookOpsContext;+ newId: (prefix: string) => string;+ opIndex: number;+}++type ElementOp = z.infer<(typeof BOOK_ELEMENT_OP_SCHEMAS)[number]>;+type Op<K extends ElementOp['op']> = Extract<ElementOp, { op: K }>;++export function applyElementOp(spread: BookSpread, op: ElementOp, env: ElementOpEnv): BookSpread {+ switch (op.op) {+ case 'add':+ return opAdd(spread, op, env);+ case 'style':+ return opStyle(spread, op, env);+ case 'arrange':+ return opArrange(spread, op, env);+ case 'align':+ return opAlign(spread, op, env);+ case 'distribute':+ return opDistribute(spread, op, env);+ case 'lock':+ return opLock(spread, op, env);+ case 'duplicate':+ return opDuplicate(spread, op, env);+ case 'fill':+ return opFill(spread, op, env);+ case 'copy_from':+ return opCopyFrom(spread, op, env);+ case 'refresh_travel':+ return opRefreshTravel(spread, op, env);+ case 'add_grid':+ return opAddGrid(spread, op, env);+ }+}++// ── helpers ────────────────────────────────────────────────────────────────++const isInner = (spread: BookSpread) => spread.role === 'inner';++/** A size centred on the page: the right-hand page of a spread, so a new element never lands in the fold. */+function centred(spread: BookSpread, page: BookPageSetup, size: { w: number; h: number }): BookFrame {+ const origin = isInner(spread) ? page.pageWidth : 0;+ return {+ x: round2(origin + (page.pageWidth - size.w) / 2),+ y: round2((page.pageHeight - size.h) / 2),+ w: round2(size.w),+ h: round2(size.h),+ };+}++const roundFrame = (f: BookFrame): BookFrame => ({ x: round2(f.x), y: round2(f.y), w: round2(f.w), h: round2(f.h) });++/** The unlocked elements an operation names, each on the page, in the order named, each once. */+function namedElements(spread: BookSpread, ids: readonly string[], env: ElementOpEnv): BookElement[] {+ return [...new Set(ids)].map((id) => unlockedElement(pageElement(spread, id, env.opIndex), env.opIndex));+}++function replaceAll(spread: BookSpread, next: readonly BookElement[]): BookSpread {+ const byId = new Map(next.map((e) => [e.id, e]));+ return { ...spread, elements: spread.elements.map((e) => byId.get(e.id) ?? e) };+}++function travelOf(env: ElementOpEnv): BookTravelContext {+ const travel = env.ctx.travel;+ if (!travel) throw failOp('travel_unavailable', "the journey's figures are not available here", env.opIndex);+ return travel;+}++function statsOf(env: ElementOpEnv) {+ const stats = travelOf(env).stats;+ if (!stats) {+ throw failOp('travel_unavailable', 'this journey has no figures yet (no stops with places)', env.opIndex);+ }+ return stats;+}++/** The look fields a kind takes, from the props schema, so `add` and `style` set exactly what `style` may set. */+const PROP_KEYS = new Map(bookElementPropsSchema.options.map((o) => [o.shape.kind.value, lookKeys(o.shape)]));++function lookKeys(shape: object): string[] {+ return Object.keys(shape).filter((k) => k !== 'kind');+}++/** The element with the given look fields set; millimetre fields rounded as the document stores them. */+function withProps(el: BookElement, props: Record<string, unknown>): BookElement {+ const keys = PROP_KEYS.get(el.kind) ?? [];+ const next: Record<string, unknown> = { ...el };+ for (const key of keys) {+ const value = props[key];+ if (value === undefined) continue;+ next[key] = (key === 'radius' || key === 'strokeWidth') && typeof value === 'number' ? round2(value) : value;+ }+ return next as unknown as BookElement;+}++// ── add ────────────────────────────────────────────────────────────────────++function opAdd(spread: BookSpread, op: Op<'add'>, env: ElementOpEnv): BookSpread {+ roomFor(spread, 1, env.opIndex);+ const made = withProps(created(spread, op.element, op.frame ? roundFrame(op.frame) : null, env), lookOf(op.element));+ const el = op.rotation !== undefined ? { ...made, rotation: op.rotation } : made;+ const parked =+ el.kind === 'photo' && el.photoId != null+ ? spread.parked.filter((p) => !(p.kind === 'photo' && p.photoId === el.photoId))+ : spread.parked;+ return { ...spread, elements: [...spread.elements, el], parked };+}++/** The look fields of a new element. A shape's name is `created`'s: a rule arrives as a hairline rect, never `line`. */+function lookOf(spec: BookNewElement): Record<string, unknown> {+ const look: Record<string, unknown> = { ...spec };+ if (spec.kind === 'shape') delete look.shape;+ return look;+}++const BASE = { rotation: 0, opacity: 1, locked: false };++function created(spread: BookSpread, spec: BookNewElement, frame: BookFrame | null, env: ElementOpEnv): BookElement {+ const at = (size: { w: number; h: number }) => frame ?? centred(spread, env.page, size);+ switch (spec.kind) {+ case 'photo':+ return newPhotoFrame(spec, at, env);+ case 'text':+ return newText(spec, at, env);+ case 'shape':+ return newShape(spec, frame, spread, env);+ case 'icon': {+ const side = Math.min(env.page.pageWidth, env.page.pageHeight) * 0.18;+ return {+ ...BASE,+ id: env.newId('i'),+ kind: 'icon',+ frame: at({ w: side, h: side }),+ name: spec.name,+ color: '#111827',+ lineWidth: 2,+ };+ }+ default:+ return newTravel(spec, at, env);+ }+}++type At = (size: { w: number; h: number }) => BookFrame;++function newPhotoFrame(spec: Extract<BookNewElement, { kind: 'photo' }>, at: At, env: ElementOpEnv): BookPhotoElement {+ if (spec.photoId !== undefined) galleryPhoto(spec.photoId, env.ctx, env.opIndex);+ const side = Math.min(env.page.pageWidth, env.page.pageHeight) * 0.45;+ // A Polaroid is taller than it is wide, because of the chin.+ const frame = at({ w: side, h: spec.frameStyle === 'polaroid' ? side * 1.16 : side });+ return {+ ...BASE,+ id: env.newId('p'),+ kind: 'photo',+ frame,+ photoId: spec.photoId ?? null,+ fit: 'cover',+ focalX: 0.5,+ focalY: 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: 'none',+ };+}++/** The Studio's text presets: size, weight and the colour a caption and a quotation mark take. */+const TEXT_PRESETS = {+ heading: { size: 30, weight: 700 },+ subheading: { size: 16, weight: 600 },+ body: { size: 10, weight: 400 },+ caption: { size: 7.5, weight: 600, tracking: 0.14, color: '#8a8578' },+ quote: { size: 46, weight: 700, color: '#c9c2b4', leading: 0.9 },+} as const satisfies Record<string, Partial<BookTextElement>>;++function newText(spec: Extract<BookNewElement, { kind: 'text' }>, at: At, env: ElementOpEnv): BookTextElement {+ const binding = spec.binding ?? null;+ if (binding?.photoId !== undefined) galleryPhoto(binding.photoId, env.ctx, env.opIndex);+ if (binding?.entryId !== undefined) journeyEntry(binding.entryId, env.ctx, env.opIndex);+ const read = binding ? bookBoundWords(binding, env.ctx) : undefined;+ const words = spec.text ?? read;+ if (words === undefined || !words.trim()) {+ throw failOp('text_required', 'give the words for the new text; its binding cannot be read here', env.opIndex);+ }+ const preset: Partial<BookTextElement> = TEXT_PRESETS[spec.preset ?? 'body'];+ const size = preset.size ?? 10;+ return {+ ...BASE,+ id: env.newId('t'),+ kind: 'text',+ frame: at({ w: env.page.pageWidth * 0.7, h: size * 0.5 + 8 }),+ text: words,+ font: 'sans',+ size,+ weight: preset.weight ?? 400,+ italic: false,+ align: 'left',+ leading: preset.leading ?? (size > 16 ? 1.1 : 1.5),+ tracking: preset.tracking ?? (size > 16 ? -0.02 : 0),+ color: preset.color ?? '#1a1a1a',+ binding,+ overridden: binding !== null && spec.text !== undefined && read !== spec.text,+ };+}++const WIDE_SHAPES: readonly string[] = ['ticket', 'wave', 'arrow-right', 'arrow-left', 'arrow-both', 'capsule'];+const TALL_SHAPES: readonly string[] = ['pin', 'drop', 'arrow-up', 'arrow-down'];++/** Placed at a size that suits the shape: a banner wide, a pin tall, a rule a hairline across half a page. */+function newShape(+ spec: Extract<BookNewElement, { kind: 'shape' }>,+ frame: BookFrame | null,+ spread: BookSpread,+ env: ElementOpEnv,+): BookElement {+ const s = spec.shape;+ const side = Math.min(env.page.pageWidth, env.page.pageHeight) * 0.3;+ const wide = s.startsWith('banner') || WIDE_SHAPES.includes(s);+ const tall = TALL_SHAPES.includes(s);+ const rule = s === 'line';+ const size = rule+ ? { w: env.page.pageWidth * 0.5, h: 0.5 }+ : { w: wide ? side * 1.7 : side, h: tall ? side * 1.35 : wide ? side * 0.55 : side };+ return {+ ...BASE,+ id: env.newId('s'),+ kind: 'shape',+ frame: frame ?? centred(spread, env.page, size),+ // A rule is a hairline box rather than its own element type, as in the Studio.+ shape: rule ? 'rect' : s,+ fill: '#141414',+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 0,+ };+}++type TravelSpec = Extract<BookNewElement, { kind: 'map' | 'stats' | 'countries' | 'badge' | 'list' }>;++function newTravel(spec: TravelSpec, at: At, env: ElementOpEnv): BookElement {+ const id = env.newId(spec.kind === 'stats' ? 'st' : spec.kind.slice(0, 2));+ const page = env.page;+ switch (spec.kind) {+ case 'map': {+ const frame = at(bookTravelSize('map', page));+ const el = bookTravelMap(travelOf(env), statsOf(env), { id, frame, scope: spec.scope, source: spec.source });+ if (el.points.length === 0) {+ throw failOp('travel_unavailable', 'no stops of the journey fall in that scope', env.opIndex);+ }+ return el;+ }+ case 'stats':+ return bookTravelStats(statsOf(env), { id, frame: at(bookTravelSize('stats', page)), metrics: spec.metrics });+ case 'countries': {+ const travel = travelOf(env);+ const el = bookTravelCountries(travel, { id, frame: at(bookTravelSize('countries', page)), codes: spec.codes });+ if (el.codes.length === 0) {+ throw failOp('travel_unavailable', 'the journey has no countries to show', env.opIndex);+ }+ return el;+ }+ case 'badge':+ return newBadge(spec, id, at, env);+ case 'list':+ return newList(spec, id, at, env);+ }+}++/** The journey's figures when an entry is named (an entry needs them to be found), else whatever is known. */+const travelFor = (entryId: number | undefined, env: ElementOpEnv) =>+ entryId !== undefined ? travelOf(env) : env.ctx.travel;++function newBadge(spec: Extract<TravelSpec, { kind: 'badge' }>, id: string, at: At, env: ElementOpEnv): BookElement {+ const travel = travelFor(spec.entryId, env);+ const entry = spec.entryId !== undefined ? (travel?.entries.find((e) => e.id === spec.entryId) ?? null) : null;+ if (spec.entryId !== undefined && !entry) {+ throw failOp('entry_not_found', `entry ${spec.entryId} is not in this journey`, env.opIndex);+ }+ const resolved = travel ? bookBadgeValue(travel, spec.variant, entry) : null;+ const ownCode = spec.variant === 'mood' ? entry?.mood : spec.variant === 'weather' ? entry?.weather : undefined;+ const text = spec.text ?? resolved?.text;+ if (text === undefined || (!text && !resolved)) {+ const why = travel ? 'nothing in the journey says what it would show' : "the journey's figures are not available";+ throw failOp('text_required', `give the words for the ${spec.variant} mark; ${why}`, env.opIndex);+ }+ const value = {+ text,+ sub: spec.sub ?? resolved?.sub ?? '',+ code: spec.code ?? ownCode ?? resolved?.code ?? null,+ };+ const frame = at(bookTravelSize('badge', env.page, { variant: spec.variant }));+ return bookTravelBadge({ id, frame, variant: spec.variant, value });+}++function newList(spec: Extract<TravelSpec, { kind: 'list' }>, id: string, at: At, env: ElementOpEnv): BookElement {+ const travel = travelFor(spec.entryId, env);+ let items = spec.items ?? [];+ if (spec.entryId !== undefined) {+ const entry = travel?.entries.find((e) => e.id === spec.entryId);+ if (!entry) throw failOp('entry_not_found', `entry ${spec.entryId} is not in this journey`, env.opIndex);+ items = bookEntryListItems(entry);+ if (!items.length) {+ throw failOp('text_required', `entry ${spec.entryId} has no pros or cons; give the items`, env.opIndex);+ }+ }+ const labels = { pros: travel?.labels.pros ?? '', cons: travel?.labels.cons ?? '' };+ const rows = Math.max(items.filter((i) => i.tone === 'pro').length, items.filter((i) => i.tone !== 'pro').length);+ const frame = at(bookTravelSize('list', env.page, { rows }));+ return bookTravelList(labels, { id, frame, items });+}++// ── style, lock ────────────────────────────────────────────────────────────++function opStyle(spread: BookSpread, op: Op<'style'>, env: ElementOpEnv): BookSpread {+ const el = unlockedElement(pageElement(spread, op.elementId, env.opIndex), env.opIndex);+ if (op.set.kind !== el.kind) {+ throw failOp('wrong_kind', `${el.id} is a ${el.kind}; set.kind says ${op.set.kind}`, env.opIndex, el.id);+ }+ return replaceAll(spread, [withProps(el, op.set)]);+}++function opLock(spread: BookSpread, op: Op<'lock'>, env: ElementOpEnv): BookSpread {+ const els = [...new Set(op.elementIds)].map((id) => pageElement(spread, id, env.opIndex));+ return replaceAll(+ spread,+ els.map((e) => ({ ...e, locked: op.locked })),+ );+}++// ── arrange ────────────────────────────────────────────────────────────────++function opArrange(spread: BookSpread, op: Op<'arrange'>, env: ElementOpEnv): BookSpread {+ const chosen = new Set(namedElements(spread, op.elementIds, env).map((e) => e.id));+ const pick = (want: boolean) => spread.elements.filter((e) => chosen.has(e.id) === want);+ if (op.to === 'front') return { ...spread, elements: [...pick(false), ...pick(true)] };+ if (op.to === 'back') return { ...spread, elements: [...pick(true), ...pick(false)] };+ const els = spread.elements.slice();+ const step = op.to === 'forward' ? 1 : -1;+ const order = els.map((_, i) => i);+ if (step === 1) order.reverse();+ for (const i of order) {+ const here = els[i];+ const there = els[i + step];+ if (!here || !there || !chosen.has(here.id) || chosen.has(there.id)) continue;+ els[i] = there;+ els[i + step] = here;+ }+ return { ...spread, elements: els };+}++// ── align, distribute ──────────────────────────────────────────────────────++interface Box {+ x: number;+ y: number;+ w: number;+ h: number;+}++function boundsOf(frames: readonly Box[]): Box {+ const x = Math.min(...frames.map((f) => f.x));+ const y = Math.min(...frames.map((f) => f.y));+ const right = Math.max(...frames.map((f) => f.x + f.w));+ const bottom = Math.max(...frames.map((f) => f.y + f.h));+ return { x, y, w: right - x, h: bottom - y };+}++/** The page an element's centre is on, or its safe area. */+function pageBox(spread: BookSpread, page: BookPageSetup, f: Box, safe: boolean): Box {+ const onRight = isInner(spread) && f.x + f.w / 2 >= page.pageWidth;+ const x = onRight ? page.pageWidth : 0;+ const inset = safe ? page.safe : 0;+ return { x: x + inset, y: inset, w: page.pageWidth - inset * 2, h: page.pageHeight - inset * 2 };+}++function alignedFrame(f: Box, box: Box, edge: Op<'align'>['edge']): BookFrame {+ switch (edge) {+ case 'left':+ return { ...f, x: round2(box.x) };+ case 'center':+ return { ...f, x: round2(box.x + (box.w - f.w) / 2) };+ case 'right':+ return { ...f, x: round2(box.x + box.w - f.w) };+ case 'top':+ return { ...f, y: round2(box.y) };+ case 'middle':+ return { ...f, y: round2(box.y + (box.h - f.h) / 2) };+ case 'bottom':+ return { ...f, y: round2(box.y + box.h - f.h) };+ }+}++function opAlign(spread: BookSpread, op: Op<'align'>, env: ElementOpEnv): BookSpread {+ const els = namedElements(spread, op.elementIds, env);+ const selection = boundsOf(els.map((e) => e.frame));+ const next = els.map((e) => {+ const box = op.to === 'selection' ? selection : pageBox(spread, env.page, e.frame, op.to === 'safe');+ return { ...e, frame: alignedFrame(e.frame, box, op.edge) } as BookElement;+ });+ return replaceAll(spread, next);+}++function opDistribute(spread: BookSpread, op: Op<'distribute'>, env: ElementOpEnv): BookSpread {+ const els = namedElements(spread, op.elementIds, env);+ if (els.length < 3) throw failOp('not_enough_elements', 'distribute needs three different elements', env.opIndex);+ const across = op.axis === 'horizontal';+ const start = (f: Box) => (across ? f.x : f.y);+ const size = (f: Box) => (across ? f.w : f.h);+ const sorted = els.slice().sort((a, b) => start(a.frame) - start(b.frame));+ const first = sorted[0] as BookElement;+ const last = sorted[sorted.length - 1] as BookElement;+ const total = sorted.reduce((sum, e) => sum + size(e.frame), 0);+ const span = start(last.frame) + size(last.frame) - start(first.frame);+ const gap = op.gap ?? (span - total) / (sorted.length - 1);+ let cursor = start(first.frame);+ const next = sorted.map((e) => {+ const at = round2(cursor);+ cursor += size(e.frame) + gap;+ return { ...e, frame: across ? { ...e.frame, x: at } : { ...e.frame, y: at } } as BookElement;+ });+ return replaceAll(spread, next);+}++// ── duplicate, fill, copy_from ─────────────────────────────────────────────++const prefixOf = (el: BookElement) => el.kind.charAt(0);++function opDuplicate(spread: BookSpread, op: Op<'duplicate'>, env: ElementOpEnv): BookSpread {+ const els = [...new Set(op.elementIds)].map((id) => pageElement(spread, id, env.opIndex));+ roomFor(spread, els.length, env.opIndex);+ const dx = op.dx ?? 4;+ const dy = op.dy ?? 4;+ const copies = els.map((e) => {+ const frame = { ...e.frame, x: round2(e.frame.x + dx), y: round2(e.frame.y + dy) };+ return { ...e, id: env.newId(prefixOf(e)), frame } as BookElement;+ });+ return { ...spread, elements: [...spread.elements, ...copies] };+}++/** The inspector's fill: the photo to the bleed of the page its centre is on, or of the spread, at the back. */+function opFill(spread: BookSpread, op: Op<'fill'>, env: ElementOpEnv): BookSpread {+ const el = unlockedElement(pageElement(spread, op.elementId, env.opIndex), env.opIndex);+ if (el.kind !== 'photo') {+ throw failOp('wrong_kind', `${el.id} is a ${el.kind}; fill takes a photo`, env.opIndex, el.id);+ }+ const { bleed, pageWidth, pageHeight } = env.page;+ const onRight = isInner(spread) && op.scope === 'page' && el.frame.x + el.frame.w / 2 >= pageWidth;+ const spanning = op.scope === 'spread' && isInner(spread);+ const frame = {+ x: onRight ? pageWidth - bleed : -bleed,+ y: -bleed,+ w: (spanning ? 2 : 1) * pageWidth + 2 * bleed,+ h: pageHeight + 2 * bleed,+ };+ const filled: BookElement = { ...el, frame, rotation: 0, fit: 'cover' };+ return { ...spread, elements: [filled, ...spread.elements.filter((e) => e.id !== el.id)] };+}++/** Which page of its spread an element is on: the left (or only) page is 0, the right one starts at the fold. */+const pageOrigin = (spread: BookSpread, page: BookPageSetup, f: Box) =>+ isInner(spread) && f.x + f.w / 2 >= page.pageWidth ? page.pageWidth : 0;++function opCopyFrom(spread: BookSpread, op: Op<'copy_from'>, env: ElementOpEnv): BookSpread {+ const source = env.doc.spreads.find((s) => s.id === op.spreadId);+ if (!source) throw failOp('spread_not_found', `no page ${op.spreadId}`, env.opIndex);+ const els = [...new Set(op.elementIds)].map((id) => pageElement(source, id, env.opIndex));+ roomFor(spread, els.length, env.opIndex);+ const sameKind = isInner(source) === isInner(spread);+ const target = isInner(spread) ? env.page.pageWidth : 0;+ const copies = els.map((e) => {+ if (e.kind === 'photo' && e.photoId != null) galleryPhoto(e.photoId, env.ctx, env.opIndex);+ const x = sameKind ? e.frame.x : e.frame.x - pageOrigin(source, env.page, e.frame) + target;+ return { ...e, id: env.newId(prefixOf(e)), frame: { ...e.frame, x: round2(x) } } as BookElement;+ });+ return { ...spread, elements: [...spread.elements, ...copies] };+}++// ── refresh_travel, add_grid ───────────────────────────────────────────────++const carriesFigures = (el: BookElement) => el.kind === 'stats' || el.kind === 'countries' || el.kind === 'map';++function refreshTargets(spread: BookSpread, ids: readonly string[] | undefined, env: ElementOpEnv): BookElement[] {+ if (!ids) return spread.elements.filter((el) => carriesFigures(el) && !el.locked);+ const named = namedElements(spread, ids, env);+ const other = named.find((el) => !carriesFigures(el));+ if (other) {+ throw failOp('wrong_kind', `${other.id} is a ${other.kind}; it carries no journey figures`, env.opIndex, other.id);+ }+ return named;+}++function refreshed(el: BookElement, patch: Partial<BookElement> | null): BookElement {+ return { ...el, ...patch } as BookElement;+}++function opRefreshTravel(spread: BookSpread, op: Op<'refresh_travel'>, env: ElementOpEnv): BookSpread {+ const stats = statsOf(env);+ const next = refreshTargets(spread, op.elementIds, env).map((el) => refreshed(el, refreshPatch(el, stats)));+ return replaceAll(spread, next);+}++function opAddGrid(spread: BookSpread, op: Op<'add_grid'>, env: ElementOpEnv): BookSpread {+ const grid = findBookGrid(op.grid);+ if (!grid) throw failOp('layout_not_found', `no grid ${op.grid}`, env.opIndex);+ const box = op.box ?? defaultBookGridBox(env.page, !isInner(spread));+ const cells = bookGridElements(grid, box).map((c) => ({ ...c, id: env.newId('p'), frame: roundFrame(c.frame) }));+ roomFor(spread, cells.length, env.opIndex);+ return { ...spread, elements: [...spread.elements, ...cells] };+}++// ── layout auto ────────────────────────────────────────────────────────────++/**+ * The Studio's "lay this page out again": rebuilt from the entry the page was+ * made from, with the journey's figures. The page keeps its id and what it had+ * parked; the caller keeps locked elements where they were.+ */+export function autoRelayout(spread: BookSpread, env: ElementOpEnv): BookSpread {+ const travel = travelOf(env);+ if (spread.entryId == null || !isInner(spread)) {+ throw failOp('layout_not_found', 'this page was not made from an entry; auto layout needs one', env.opIndex);+ }+ if (!travel.entries.some((e) => e.id === spread.entryId)) {+ throw failOp('entry_not_found', `entry ${spread.entryId} is not in this journey`, env.opIndex);+ }+ const journey = env.ctx.journey;+ const input: AutoInput = {+ locale: travel.locale,+ title: journey?.title ?? env.doc.title,+ subtitle: journey?.subtitle ?? null,+ coverPhotoId: journey?.coverPhotoId ?? null,+ entries: [...travel.entries],+ page: env.page,+ stats: travel.stats,+ stationsLabel: travel.labels.stations,+ dayLabel: travel.labels.day,+ path: travel.path,+ summaryLabel: travel.labels.summary,+ countriesLabel: travel.labels.countries,+ newId: env.newId,+ };+ const next = relayoutSpread(spread, input);+ if (!next) throw failOp('layout_not_found', 'this page cannot be laid out again from its entry', env.opIndex);+ return { ...next, parked: spread.parked };+}diff --git a/shared/src/book/book-ops.schema.ts b/shared/src/book/book-ops.schema.tsindex 3845674be..16d3de28f 100644--- a/shared/src/book/book-ops.schema.ts+++ b/shared/src/book/book-ops.schema.ts@@ -1,10 +1,13 @@import { idSchema } from '../common/primitives.schema';-import { BOOK_GRIDS } from './book-grids';+import { BOOK_ELEMENT_OP_SCHEMAS, bindingNamesItsSource } from './book-element-ops.schema';import { BOOK_COVER_TEMPLATES, BOOK_TEMPLATES } from './book-layouts';+import { bookElementIdSchema, bookGridIdSchema, bookSpreadIdSchema } from './book-op-ids';import {MAX_BOOK_TITLE,MAX_SPREADS,MAX_SPREAD_ELEMENTS,+ bookLayoutSchema,+ bookPageNumbersSchema,bookPageSetupSchema,bookPhotoElementSchema,bookSpreadSchema,@@ -29,9 +32,7 @@ import { z } from 'zod';* double spread twice the page width with the fold at one page width.*/-/** Ids as the document has them (`sp-...`, `p-...`): never invented by the model, bounded. */-export const bookSpreadIdSchema = z.string().regex(/^[\w-]{1,40}$/);-export const bookElementIdSchema = z.string().regex(/^[\w-]{1,40}$/);+export { bookElementIdSchema, bookGridIdSchema, bookSpreadIdSchema };export const BOOK_OP_LIMITS = {/** Operations in one `edit_book_page` call. */@@ -56,7 +57,6 @@ export const bookTemplateIdSchema = z.enum(idsOf(BOOK_TEMPLATES));export const bookCoverTemplateIdSchema = z.enum(idsOf(BOOK_COVER_TEMPLATES));/** Either set: which one fits is the page's question, answered when the operation runs. */export const bookAnyTemplateIdSchema = z.enum([...idsOf(BOOK_TEMPLATES), ...idsOf(BOOK_COVER_TEMPLATES)]);-export const bookGridIdSchema = z.enum(idsOf(BOOK_GRIDS));const photo = bookPhotoElementSchema.shape;const text = bookTextElementSchema.shape;@@ -72,31 +72,25 @@ const has = (value: object, keys: readonly string[]) =>const LOOK_KEYS = ['fit', 'focalX', 'focalY', 'mask', 'frameStyle', 'filter', 'radius'] as const;const FRAME_KEYS = ['x', 'y', 'w', 'h', 'rotation'] as const;-const LAYOUT_KEYS = ['template', 'grid', 'saved'] as const;--/**- * An entry's words need the entry and a photo's caption needs the photo: a- * binding that names neither reads nothing, and the ids it names are checked- * against the journey when the engine runs.- */-function bindingNamesItsSource(b: { source: string; entryId?: number; photoId?: number } | null | undefined): boolean {- if (!b) return true;- if (b.source.startsWith('entry.') && b.entryId === undefined) return false;- return b.source !== 'photo.caption' || b.photoId !== undefined;-}+const LAYOUT_KEYS = ['template', 'grid', 'saved', 'auto'] as const;/** One edit of one page. Discriminated on `op`. */export const bookPageOpSchema = z.discriminatedUnion('op', [- /** Lay the page out again: a built-in layout, a photo grid, or one of the book's own layouts. */+ /**+ * Lay the page out again: a built-in layout, a photo grid, one of the book's+ * own layouts, or `auto`, the Studio's "this page again" from the entry the+ * page was made from.+ */z.strictObject({op: z.literal('layout'),template: bookAnyTemplateIdSchema.optional(),grid: bookGridIdSchema.optional(),saved: z.string().min(1).max(40).optional(),+ auto: z.literal(true).optional(),}).refine((v) => LAYOUT_KEYS.filter((k) => v[k] !== undefined).length === 1, {- message: 'give exactly one of template, grid or saved',+ message: 'give exactly one of template, grid, saved or auto',}),/** Put a gallery photo into a frame: by element id, by its place among the page's frames, or a new frame. */z.strictObject({@@ -150,7 +144,10 @@ export const bookPageOpSchema = z.discriminatedUnion('op', [font: text.font.unwrap().optional(),size: text.size.unwrap().optional(),weight: text.weight.unwrap().optional(),+ italic: text.italic.unwrap().optional(),align: text.align.unwrap().optional(),+ leading: text.leading.unwrap().optional(),+ tracking: text.tracking.unwrap().optional(),color: text.color.unwrap().optional(),}).refine((v) => v.elementId !== undefined || v.role !== undefined, { message: 'name an elementId or a role' })@@ -184,6 +181,7 @@ export const bookPageOpSchema = z.discriminatedUnion('op', [}),/** The page colour; null is the paper. */z.strictObject({ op: z.literal('background'), color: bookSpreadSchema.shape.background.unwrap() }),+ ...BOOK_ELEMENT_OP_SCHEMAS,]);export type BookPageOp = z.infer<typeof bookPageOpSchema>;export type BookPageOpInput = z.input<typeof bookPageOpSchema>;@@ -198,6 +196,8 @@ export type BookPageOpInput = z.input<typeof bookPageOpSchema>;*/const returnPrevious = z.boolean().optional();+/** Refuses the write (409) unless the book is still at this version; the assistant's undo sets it. */+const expectedVersion = z.number().int().nonnegative().optional();export const editBookPageArgs = {spreadId: bookSpreadIdSchema,@@ -218,10 +218,12 @@ export const moveBookPageArgs = {.int().min(0).max(MAX_SPREADS - 1),+ expectedVersion,};export const deleteBookPagesArgs = {spreadIds: z.array(bookSpreadIdSchema).min(1).max(BOOK_OP_LIMITS.pagesPerCall),returnPrevious,+ expectedVersion,};export const setBookCoverArgs = {template: bookCoverTemplateIdSchema.optional(),@@ -256,7 +258,10 @@ export const restoreBookPageArgs = {pages: z.array(bookPreviousSpreadSchema).min(1).max(BOOK_OP_LIMITS.pagesPerCall),expectedVersion: z.number().int().nonnegative(),};-export const describeBookPageArgs = { spreadId: bookSpreadIdSchema };+/** A design draft's id, as `design_book` answers it. */+export const bookDesignIdSchema = z.string().regex(/^[\w-]{1,40}$/);++export const describeBookPageArgs = { spreadId: bookSpreadIdSchema, designId: bookDesignIdSchema.optional() };export const listBookLayoutsArgs = { role: z.enum(['inner', 'single']).optional() };export const suggestBookPhotosArgs = {entryId: idSchema.optional(),@@ -268,6 +273,41 @@ export const suggestBookPhotosArgs = {limit: z.number().int().min(1).max(PHOTO_PICK.maxLimit).optional(),};+const pageNumbers = bookPageNumbersSchema.shape;++/**+ * The page format and the page numbers, as the Studio's setup sets them.+ * Elements are not rescaled when the size changes, as in the Studio; the+ * answer carries `previous_setup` to set it back.+ */+export const setBookSetupArgs = {+ preset: bookPageSetupSchema.shape.preset.unwrap().optional(),+ pageWidth: z.number().finite().min(60).max(500).optional(),+ pageHeight: z.number().finite().min(60).max(500).optional(),+ bleed: z.number().finite().min(0).max(20).optional(),+ safe: z.number().finite().min(0).max(50).optional(),+ pageNumbers: z+ .strictObject({+ show: pageNumbers.show.unwrap().optional(),+ startAt: pageNumbers.startAt.unwrap().optional(),+ position: pageNumbers.position.unwrap().optional(),+ margin: z.number().finite().min(0).max(60).optional(),+ size: pageNumbers.size.unwrap().optional(),+ autoColor: pageNumbers.autoColor.unwrap().optional(),+ color: pageNumbers.color.unwrap().optional(),+ font: pageNumbers.font.unwrap().optional(),+ })+ .optional(),+ /** The assistant's undo sets the setup back only while the book is still at the version the change left. */+ expectedVersion,+};+/** A copy of an inner page, with new ids, right after it. */+export const duplicateBookPageArgs = { spreadId: bookSpreadIdSchema };+/** Keep a page's arrangement as one of the book's own layouts. */+export const saveBookLayoutArgs = { spreadId: bookSpreadIdSchema, name: z.string().trim().min(1).max(60).optional() };+/** Take one of the book's own layouts away; the answer carries it in `previous_layout`. */+export const removeBookLayoutArgs = { layoutId: z.string().min(1).max(40), expectedVersion };+export const editBookPageRequestSchema = z.strictObject(editBookPageArgs);export const addBookPagesRequestSchema = z.strictObject(addBookPagesArgs);export const moveBookPageRequestSchema = z.strictObject(moveBookPageArgs);@@ -278,6 +318,10 @@ export const restoreBookPageRequestSchema = z.strictObject(restoreBookPageArgs);export const describeBookPageRequestSchema = z.strictObject(describeBookPageArgs);export const listBookLayoutsRequestSchema = z.strictObject(listBookLayoutsArgs);export const suggestBookPhotosRequestSchema = z.strictObject(suggestBookPhotosArgs);+export const setBookSetupRequestSchema = z.strictObject(setBookSetupArgs);+export const duplicateBookPageRequestSchema = z.strictObject(duplicateBookPageArgs);+export const saveBookLayoutRequestSchema = z.strictObject(saveBookLayoutArgs);+export const removeBookLayoutRequestSchema = z.strictObject(removeBookLayoutArgs);export type EditBookPageRequest = z.infer<typeof editBookPageRequestSchema>;export type AddBookPagesRequest = z.infer<typeof addBookPagesRequestSchema>;@@ -287,6 +331,10 @@ export type SetBookCoverRequest = z.infer<typeof setBookCoverRequestSchema>;export type CreateBookRequest = z.infer<typeof createBookRequestSchema>;export type RestoreBookPageRequest = z.infer<typeof restoreBookPageRequestSchema>;export type SuggestBookPhotosRequest = z.infer<typeof suggestBookPhotosRequestSchema>;+export type SetBookSetupRequest = z.infer<typeof setBookSetupRequestSchema>;+export type DuplicateBookPageRequest = z.infer<typeof duplicateBookPageRequestSchema>;+export type SaveBookLayoutRequest = z.infer<typeof saveBookLayoutRequestSchema>;+export type RemoveBookLayoutRequest = z.infer<typeof removeBookLayoutRequestSchema>;/** ── Answers ─────────────────────────────────────────────────────────────@@ -307,6 +355,14 @@ export const BOOK_FINDING_CODES = ['parked','hidden_photo','not_in_gallery',+ 'text_on_busy',+ 'contrast_low',+ 'small_text',+ 'crowded',+ 'off_grid',+ 'font_mix',+ 'palette_drift',+ 'repeat_layout',] as const;export type BookFindingCode = (typeof BOOK_FINDING_CODES)[number];@@ -384,5 +440,11 @@ export const bookWriteResultSchema = z.object({dropped: z.array(z.string()).max(MAX_SPREAD_ELEMENTS * 2),previous_spreads: z.array(bookPreviousSpreadSchema).optional(),from_index: z.number().int().nonnegative().optional(),+ /** From `set_book_setup`: the setup as it was, to set it back. */+ previous_setup: bookPageSetupSchema.optional(),+ /** From `remove_book_layout`: the layout as it was, to put it back. */+ previous_layout: bookLayoutSchema.optional(),+ /** From `save_book_layout`: the new layout's id, to take it away again. */+ layout_id: z.string().max(40).optional(),});export type BookWriteResult = z.infer<typeof bookWriteResultSchema>;diff --git a/shared/src/book/book-ops.ts b/shared/src/book/book-ops.tsindex ec29103d5..ae10590af 100644--- a/shared/src/book/book-ops.ts+++ b/shared/src/book/book-ops.ts@@ -2,6 +2,7 @@ import { bookGridElements, defaultBookGridBox, findBookGrid, type BookGridDef }import { bookElementId } from './book-ids';import { BOOK_TEXT_STYLES, applyBookTemplate, classifyBookTexts, findBookTemplate } from './book-layouts';import {+ bookBoundWords,caught,checkedSpread,createdIds,@@ -15,11 +16,11 @@ import {type BookOpsContext,type BookPhotoInfo,} from './book-ops-core';+import { applyElementOp, autoRelayout } from './book-ops-elements';import { BOOK_OP_LIMITS, bookPageOpSchema, type BookPageOp } from './book-ops.schema';import { applySavedBookLayout, bookLayoutRole } from './book-saved-layouts';import {MAX_SPREAD_ELEMENTS,- MAX_TEXT_LENGTH,type BookDocument,type BookElement,type BookPageSetup,@@ -115,6 +116,8 @@ function applyOne(spread: BookSpread, op: BookPageOp, env: Env): BookSpread {return opRemove(spread, op, env);case 'background':return { ...spread, background: op.color };+ default:+ return applyElementOp(spread, op, env);}}@@ -201,6 +204,7 @@ function layoutFree(spread: BookSpread, op: Op<'layout'>, env: Env): BookSpreadif (!grid) throw failOp('layout_not_found', `no grid ${op.grid}`, env.opIndex);return applyGridLayout(spread, grid, env.page);}+ if (op.auto) return autoRelayout(spread, env);const layout = (env.doc.layouts ?? []).find((l) => l.id === op.saved || l.name === op.saved);if (!layout) throw failOp('layout_not_found', `this book keeps no layout ${op.saved}`, env.opIndex);if (layout.role !== bookLayoutRole(spread)) {@@ -385,49 +389,22 @@ function opSwapPhotos(spread: BookSpread, op: Op<'swap_photos'>, env: Env): Booktype Binding = NonNullable<BookTextElement['binding']>;-/**- * The words a binding reads, from what the context knows, or undefined.- *- * Dates and coordinates are set in a reader's language and notation, which the- * engine does not know: those need their words given.- */-function boundWords(binding: Binding, ctx: BookOpsContext): string | undefined {- const j = ctx.journey;- const pick = (v: string | null | undefined) => (v && v.trim() ? v.slice(0, MAX_TEXT_LENGTH) : undefined);- switch (binding.source) {- case 'journey.title':- return pick(j?.title);- case 'journey.subtitle':- return pick(j?.subtitle);- case 'photo.caption':- return pick(ctx.photos?.find((p) => p.photoId === binding.photoId)?.caption);- case 'entry.title':- case 'entry.story':- case 'entry.location': {- if (binding.source === 'entry.location' && binding.format) return undefined;- const entry = j?.entries?.find((e) => e.id === binding.entryId);- if (!entry) return undefined;- if (binding.source === 'entry.title') return pick(entry.title || entry.location);- return pick(binding.source === 'entry.story' ? entry.story?.trim() : entry.location);- }- default:- return undefined;- }-}-/*** Words given to a bound text keep it bound only when they are what the* binding reads anyway; otherwise the text is the author's from now on, as when* somebody types into it in the Studio.*/const overriddenBy = (words: string, binding: Binding | null, ctx: BookOpsContext) =>- binding ? boundWords(binding, ctx) !== words : false;+ binding ? bookBoundWords(binding, ctx) !== words : false;const styleOf = (op: Op<'text'>): Partial<BookTextElement> => ({...(op.font !== undefined ? { font: op.font } : {}),...(op.size !== undefined ? { size: op.size } : {}),...(op.weight !== undefined ? { weight: op.weight } : {}),+ ...(op.italic !== undefined ? { italic: op.italic } : {}),...(op.align !== undefined ? { align: op.align } : {}),+ ...(op.leading !== undefined ? { leading: op.leading } : {}),+ ...(op.tracking !== undefined ? { tracking: op.tracking } : {}),...(op.color !== undefined ? { color: op.color } : {}),});@@ -469,7 +446,7 @@ function retext(el: BookTextElement, op: Op<'text'>, env: Env): BookTextElementel.id,);}- const words = op.text ?? boundWords(op.binding, env.ctx) ?? (el.text.trim() ? el.text : undefined);+ const words = op.text ?? bookBoundWords(op.binding, env.ctx) ?? (el.text.trim() ? el.text : undefined);if (words === undefined)throw failOp('text_required', `give the words for ${el.id}; the binding cannot be read here`, env.opIndex, el.id);// Bound without words of its own, the text follows its source: the Studio@@ -520,7 +497,7 @@ const TEXT_DEFAULTS: Pick<function newText(spread: BookSpread, op: Op<'text'>, env: Env): BookTextElement {const role = op.role ?? 'body';const binding = op.binding ?? null;- const words = op.text ?? (binding ? boundWords(binding, env.ctx) : undefined);+ const words = op.text ?? (binding ? bookBoundWords(binding, env.ctx) : undefined);if (!words) throw failOp('text_required', `the page has no ${role} text; give the words for a new one`, env.opIndex);return {id: env.newId('t'),diff --git a/shared/src/book/book-path.ts b/shared/src/book/book-path.tsnew file mode 100644index 000000000..2b05b1eda--- /dev/null+++ b/shared/src/book/book-path.ts@@ -0,0 +1,45 @@+import { MAX_PATH_POINTS, MAX_PATH_SEGMENTS } from './book.schema';++/**+ * A journey's tracks, thinned to what a printed line can show.+ *+ * A three-week drive is hundreds of thousands of GPS fixes. At the size a map+ * is printed, a point every fifteen metres and a point every kilometre are the+ * same picture, and only one of them fits in a document that has to be saved,+ * sent over a websocket and parsed on the other side. Moved here from the+ * Studio (client/src/pages/journeyStudio/useJourneyStudio.ts) so the server's+ * design tool draws the same line the editor does.+ *+ * Thinned by taking every nth point rather than by simplifying the geometry:+ * Douglas-Peucker would keep the shape better, and it is a hundred lines of+ * code to gain something nobody can see at 60mm across. The ends of every+ * segment are kept, because a track that stops short of where it ended reads+ * as a bug.+ */++/** Points one thinned segment keeps, under the document's own cap. */+const PER_SEGMENT = Math.min(600, MAX_PATH_POINTS);++export function bookPath(tracks: readonly { points: readonly (readonly unknown[])[] }[]): [number, number][][] {+ const out: [number, number][][] = [];+ for (const track of tracks.slice(0, MAX_PATH_SEGMENTS)) {+ // Normalised on the way in: the contract types a pair as a tuple, and Zod+ // infers that loosely enough that the pair has to be rebuilt to stay one.+ const pts = track.points+ .map((p): [number, number] => [Number(p[0]), Number(p[1])])+ .filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));+ if (pts.length < 2) continue;+ if (pts.length <= PER_SEGMENT) {+ out.push(pts);+ continue;+ }+ const step = (pts.length - 1) / (PER_SEGMENT - 1);+ const thinned: [number, number][] = [];+ for (let i = 0; i < PER_SEGMENT; i++) {+ const at = pts[Math.round(i * step)];+ if (at) thinned.push(at);+ }+ out.push(thinned);+ }+ return out;+}diff --git a/shared/src/book/book-text.spec.ts b/shared/src/book/book-text.spec.tsnew file mode 100644index 000000000..1a5e16c35--- /dev/null+++ b/shared/src/book/book-text.spec.ts@@ -0,0 +1,72 @@+import { bookPath } from './book-path';+import { bookCoordValue, formatBookCoords, formatBookDate } from './book-text';++import { describe, expect, it } from 'vitest';++/**+ * The words an entry lends to a page and the thinned route, moved from the+ * Studio: the characters must stay exactly what the Studio printed, or every+ * open of an old book rewrites its bound lines.+ */++describe('book text', () => {+ it('BOOKTXT-001: sets coordinates in degrees, minutes and seconds with hemisphere letters', () => {+ expect(formatBookCoords(52.5163, 13.3777)).toBe(`52° 30' 59" N 13° 22' 40" E`);+ expect(formatBookCoords(-33.8688, -70.6693)).toBe(`33° 52' 8" S 70° 40' 9" W`);+ });++ it('BOOKTXT-002: sets the decimal form to four places, with the hemisphere letter', () => {+ expect(formatBookCoords(52.5163, 13.3777, 'decimal')).toBe('52.5163° N 13.3777° E');+ expect(formatBookCoords(-33.8688, -70.6693, 'decimal')).toBe('33.8688° S 70.6693° W');+ });++ it('BOOKTXT-003: spells the date out in the given language, and answers nothing for no date or a bad one', () => {+ expect(formatBookDate('2026-06-12', 'de-DE')).toBe('12. Juni 2026');+ expect(formatBookDate('2026-06-12', 'en-GB')).toBe('12 June 2026');+ expect(formatBookDate(null, 'en')).toBe('');+ expect(formatBookDate('not a date', 'en')).toBe('');+ });++ it('BOOKTXT-004: keeps a point as the raw value a coordinates binding compares', () => {+ expect(bookCoordValue(63.4027, -19.0448)).toBe('63.4027,-19.0448');+ });+});++describe('book path', () => {+ it('BOOKTXT-005: keeps short tracks whole, drops tracks under two points and unreadable pairs', () => {+ const path = bookPath([+ {+ points: [+ [52.5, 13.4],+ [52.6, 'x'],+ [52.7, 13.6],+ ],+ },+ { points: [[1, 2]] },+ ]);+ expect(path).toEqual([+ [+ [52.5, 13.4],+ [52.7, 13.6],+ ],+ ]);+ });++ it('BOOKTXT-006: thins a long track to 600 points and keeps both of its ends', () => {+ const points = Array.from({ length: 5000 }, (_, i) => [i / 1000, i / 2000]);+ const [only] = bookPath([{ points }]);+ expect(only).toHaveLength(600);+ expect(only?.[0]).toEqual([0, 0]);+ expect(only?.[599]).toEqual([4.999, 2.4995]);+ });++ it('BOOKTXT-007: keeps at most 40 segments', () => {+ const track = {+ points: [+ [1, 1],+ [2, 2],+ ],+ };+ expect(bookPath(Array.from({ length: 50 }, () => track))).toHaveLength(40);+ });+});diff --git a/shared/src/book/book-text.ts b/shared/src/book/book-text.tsnew file mode 100644index 000000000..569e6461d--- /dev/null+++ b/shared/src/book/book-text.ts@@ -0,0 +1,68 @@+/**+ * The words a journal entry lends to a page.+ *+ * Several things print an entry's date or its point: the chips in the Studio's+ * Entries tab, the template filler, the auto layout, the binding resolver and+ * the server's design tool. They used to do it with private helpers that had+ * drifted apart, one printing degrees and minutes where the others printed+ * seconds, and a journey-wide mark and an entry mark on the same spread read as+ * a bug when they disagree by a notation. Moved here from the Studio+ * (client/src/components/Studio/entryText.ts) so the editor and the server set+ * the same characters.+ *+ * There is a second, harder reason for one implementation. A bound element is+ * re-read when the book is opened, and re-reading is only invisible while the+ * resolver produces exactly the string the chip produced. One character of+ * drift and every open rewrites the element, which the autosave then writes+ * back: a book that saves itself every time someone looks at it.+ */++export type BookCoordFormat = 'dms' | 'decimal';++/** One axis, as degrees, minutes and seconds. */+function dms(v: number, pos: string, neg: string): string {+ const hemisphere = v >= 0 ? pos : neg;+ const abs = Math.abs(v);+ const deg = Math.floor(abs);+ const min = Math.floor((abs - deg) * 60);+ const sec = Math.round(((abs - deg) * 60 - min) * 60);+ return `${deg}° ${min}' ${sec}" ${hemisphere}`;+}++/**+ * A point, set for print.+ *+ * Neither form carries a minus sign: a printed page says 33° 51' S, not+ * -33.8688, and the hemisphere letter is both shorter and unambiguous. Decimal+ * keeps four places, about eleven metres, which is finer than a book needs.+ */+export function formatBookCoords(lat: number, lng: number, format: BookCoordFormat = 'dms'): string {+ if (format === 'decimal') {+ const dec = (v: number, pos: string, neg: string) => `${Math.abs(v).toFixed(4)}° ${v >= 0 ? pos : neg}`;+ return `${dec(lat, 'N', 'S')} ${dec(lng, 'E', 'W')}`;+ }+ return `${dms(lat, 'N', 'S')} ${dms(lng, 'E', 'W')}`;+}++/**+ * The entry's day, spelled out.+ *+ * Parsed at local midnight rather than as UTC, because the date on a journal+ * entry is the day the writer had, not an instant: reading it as UTC moves it+ * a day backwards for anyone west of Greenwich. A page in a book that outlives+ * the year has to say which year it was, so the year is always printed.+ */+export function formatBookDate(iso: string | null, locale: string): string {+ if (!iso) return '';+ const d = new Date(`${iso}T00:00:00`);+ if (Number.isNaN(d.getTime())) return '';+ return d.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric' });+}++/**+ * What a point is, as one string: the raw value a coordinates binding keeps,+ * so re-reading it compares the fact behind the words and not the words.+ */+export function bookCoordValue(lat: number, lng: number): string {+ return `${lat},${lng}`;+}diff --git a/shared/src/book/book-travel.spec.ts b/shared/src/book/book-travel.spec.tsnew file mode 100644index 000000000..ca59aca41--- /dev/null+++ b/shared/src/book/book-travel.spec.ts@@ -0,0 +1,176 @@+import type { AutoEntry } from './auto/auto-types';+import {+ bookBadgeValue,+ bookCountryName,+ bookEntryListItems,+ bookTravelCountries,+ bookTravelMap,+ bookTravelSize,+ bookTravelStats,+ isStale,+ liveMetrics,+ refreshPatch,+ routeFor,+ type BookTravelContext,+} from './book-travel';+import { bookElementSchema, bookPageSetupSchema, type BookElement } from './book.schema';+import type { JourneyStats } from './journey-stats.schema';++import { describe, expect, it } from 'vitest';++/** The travel figures as elements, and keeping them in step with the journey. */++type Point = JourneyStats['points'][number];+const pt = (label: string, at: [number, number], country: string, tripId: number, entryId: number): Point => ({+ lat: at[0],+ lng: at[1],+ label,+ date: null,+ country,+ tripId,+ photoId: entryId === 1 ? 3 : null,+ entryId,+});++const stats: JourneyStats = {+ journeyId: 5,+ distance: 4_000_000,+ days: 21,+ steps: 6,+ photos: 40,+ places: 12,+ furthest: 3_000_000,+ countries: [+ { code: 'IS', name: 'Iceland', places: 2, firstVisit: '2026-06-02' },+ { code: 'PT', name: 'Portugal', places: 2, firstVisit: '2026-09-04' },+ ],+ points: [+ pt('Reykjavík', [64.14, -21.94], 'IS', 11, 1),+ pt('Akureyri', [65.68, -18.12], 'IS', 11, 2),+ pt('Lisboa', [38.72, -9.14], 'PT', 22, 3),+ ],+ trips: [],+ excluded: [],+ start: '2026-06-02',+ end: '2026-09-12',+};++const entry: AutoEntry = {+ id: 2,+ title: 'North',+ story: null,+ location: 'Akureyri',+ date: '2026-06-06',+ photos: [],+ lat: 65.68,+ lng: -18.12,+ country: 'IS',+ dayNumber: 5,+ dayCount: 21,+ pros: ['Whales'],+ cons: ['Rain', 'Wind'],+};++const ctx: BookTravelContext = {+ locale: 'en',+ stats,+ path: [+ [+ [64.1, -21.9],+ [65.6, -18.1],+ ],+ ],+ entries: [entry],+ labels: {+ day: 'DAY',+ stations: 'Stations',+ summary: 'Summary',+ countries: 'Countries',+ distance: 'Distance',+ pros: 'Pros',+ cons: 'Cons',+ },+};++const frame = { x: 230, y: 20, w: 120, h: 90 };+const valid = (el: BookElement) => bookElementSchema.safeParse(el).success;++describe('book travel', () => {+ it('BOOKTRV-001: resolves every metric from the journey, countries as a count', () => {+ expect(liveMetrics(stats)).toEqual({+ distance: 4_000_000,+ days: 21,+ steps: 6,+ photos: 40,+ countries: 2,+ places: 12,+ furthest: 3_000_000,+ });+ });++ it('BOOKTRV-002: narrows a route to one trip and keeps the whole journey for null', () => {+ expect(routeFor(stats, null)).toHaveLength(3);+ expect(routeFor(stats, 11).map((p) => p.label)).toEqual(['Reykjavík', 'Akureyri']);+ });++ it('BOOKTRV-003: places a map of the journey and of a trip, drawn, within the caps and current at once', () => {+ const whole = bookTravelMap(ctx, stats, { id: 'mp-1', frame, scope: 'journey' });+ expect(valid(whole)).toBe(true);+ expect(whole.points).toHaveLength(3);+ expect(whole.path).toHaveLength(1);+ expect(whole.countries).toEqual(['IS', 'PT']);+ expect(whole).toMatchObject({ routeStyle: 'drawn', routeArc: 'bow', source: 'vector', tripId: null });+ const trip = bookTravelMap(ctx, stats, { id: 'mp-2', frame, scope: { tripId: 22 }, source: 'satellite' });+ expect(trip).toMatchObject({ tripId: 22, source: 'tiles', accent: '#ffffff', countries: ['PT'], path: [] });+ expect(trip.attribution).toMatch(/EOX/);+ const north = bookTravelMap(ctx, stats, { id: 'mp-3', frame, scope: { tripId: 11 } });+ expect(north.points.map((p) => p.label)).toEqual(['Reykjavík', 'Akureyri']);+ expect(north.points[0]?.photoId).toBe(3);+ for (const placed of [whole, trip, north]) expect(isStale(placed, stats)).toBe(false);+ });++ it('BOOKTRV-004: places figures and country outlines named in the book language', () => {+ const figures = bookTravelStats(stats, { id: 'st-1', frame, metrics: ['distance', 'days'] });+ expect(valid(figures)).toBe(true);+ expect(figures.values.days).toBe(21);+ const outlines = bookTravelCountries({ ...ctx, locale: 'de' }, { id: 'co-1', frame });+ expect(outlines.codes).toEqual(['IS', 'PT']);+ expect(outlines.names).toEqual(['Island', 'Portugal']);+ expect(bookCountryName('is', 'en', stats)).toBe('Iceland');+ });++ it('BOOKTRV-005: resolves the small marks from an entry or the journey, and nothing it cannot say', () => {+ expect(bookBadgeValue(ctx, 'day', entry)).toEqual({ text: 'DAY 5', sub: '', code: null });+ expect(bookBadgeValue(ctx, 'date', entry)).toEqual({ text: '6', sub: 'JUNE', code: null });+ expect(bookBadgeValue(ctx, 'flag', entry)).toEqual({ text: '', sub: 'Iceland', code: 'IS' });+ expect(bookBadgeValue(ctx, 'coords', entry)?.sub).toBe('Akureyri');+ expect(bookBadgeValue(ctx, 'distance', null)).toEqual({ text: '4,000 km', sub: 'Distance', code: null });+ expect(bookBadgeValue(ctx, 'mood', entry)).toBeNull();+ expect(bookBadgeValue({ ...ctx, stats: null }, 'distance', null)).toBeNull();+ });++ it('BOOKTRV-006: lists an entry pros first, and sizes a list by its longer column', () => {+ expect(bookEntryListItems(entry)).toEqual([+ { text: 'Whales', tone: 'pro' },+ { text: 'Rain', tone: 'con' },+ { text: 'Wind', tone: 'con' },+ ]);+ const page = bookPageSetupSchema.parse({});+ expect(bookTravelSize('list', page, { rows: 2 }).h).toBeGreaterThan(bookTravelSize('list', page, { rows: 1 }).h);+ expect(bookTravelSize('badge', page, { variant: 'coords' }).w).toBeCloseTo(210 * 0.36, 5);+ });++ it('BOOKTRV-007: marks figures stale only when what they show moved, and refreshes them', () => {+ const figures = bookTravelStats(stats, { id: 'st-1', frame, metrics: ['days'] });+ expect(isStale(figures, stats)).toBe(false);+ expect(isStale(figures, { ...stats, photos: 41 })).toBe(false);+ const later = { ...stats, days: 22 };+ expect(isStale(figures, later)).toBe(true);+ expect(refreshPatch(figures, later)).toMatchObject({ stale: false, values: { days: 22 } });+ const map = bookTravelMap(ctx, stats, { id: 'mp-1', frame, scope: { tripId: 11 } });+ const moved = { ...stats, points: stats.points.map((p, i) => (i === 1 ? { ...p, photoId: 9 } : p)) };+ expect(isStale(map, moved)).toBe(true);+ expect(refreshPatch(map, moved)).toMatchObject({ countries: ['IS'] });+ expect(isStale(figures, null)).toBe(false);+ });+});diff --git a/shared/src/book/book-travel.ts b/shared/src/book/book-travel.tsnew file mode 100644index 000000000..760903b32--- /dev/null+++ b/shared/src/book/book-travel.ts@@ -0,0 +1,385 @@+import { statsValues } from './auto/auto-elements';+import type { AutoEntry } from './auto/auto-types';+import { BOOK_MAP_SOURCES } from './book-map-sources';+import { formatBookCoords } from './book-text';+import {+ MAX_BOOK_COUNTRIES,+ MAX_COUNTRY_NAME,+ MAX_MAP_POINTS,+ MAX_MAP_POINT_LABEL,+ MAX_PATH_POINTS,+ MAX_PATH_SEGMENTS,+ type BookBadgeElement,+ type BookCountriesElement,+ type BookElement,+ type BookFrame,+ type BookListElement,+ type BookMapElement,+ type BookMetric,+ type BookPageSetup,+ type BookStatsElement,+} from './book.schema';+import type { JourneyStats, JourneyStatsPoint } from './journey-stats.schema';++/**+ * The journey's own figures as things on a page, and keeping them in step.+ *+ * A travel element carries its own values (see the note in book.schema.ts),+ * which is what lets the print renderer work without a network. The cost is+ * that a journey edited afterwards leaves the page holding yesterday's+ * numbers: `isStale` says so and `refreshPatch` brings them up to date, never+ * behind anyone's back. Moved here from the Studio+ * (client/src/components/Studio/travelRefresh.ts) together with element+ * factories that build what the Studio's Travel panel places, so the book+ * engine's `add` and `refresh_travel` mean what the panel means.+ */++/** The metrics a stats element can show, resolved from live figures. */+export function liveMetrics(stats: JourneyStats): Record<BookMetric, number> {+ return statsValues(stats);+}++/**+ * The stops a map of this scope should draw: `null` is the journey entire, a+ * trip id narrows it to that trip's own stops, so two trips of one journey are+ * never joined by a leg nobody travelled.+ */+export function routeFor(stats: JourneyStats, tripId: number | null): JourneyStats['points'] {+ if (tripId == null) return stats.points;+ return stats.points.filter((p) => p.tripId === tripId);+}++const sameEnds = (a: readonly { lat: number; lng: number }[], b: readonly { lat: number; lng: number }[]) => {+ const [a0, b0, a1, b1] = [a[0], b[0], a[a.length - 1], b[b.length - 1]];+ if (!a0 || !b0 || !a1 || !b1) return a.length === b.length;+ return a0.lat === b0.lat && a0.lng === b0.lng && a1.lat === b1.lat && a1.lng === b1.lng;+};++/**+ * Whether an element's stored values still match the journey. Compared, not+ * tracked with a timestamp, and only the figures the element shows: a page of+ * distance and days does not go stale because a photograph was added. A map+ * compares its route by shape (length and ends) and its stop photographs in+ * full, since a photo added to the middle of a journey is the ordinary case.+ */+export function isStale(el: BookElement, stats: JourneyStats | null): boolean {+ if (!stats) return false;+ if (el.kind === 'stats') {+ const live = liveMetrics(stats);+ return el.metrics.some((m) => (el.values[m] ?? 0) !== live[m]);+ }+ if (el.kind === 'countries') return el.codes.join(',') !== stats.countries.map((c) => c.code).join(',');+ if (el.kind !== 'map') return false;+ const live = routeFor(stats, el.tripId);+ if (el.points.length !== live.length) return true;+ if (!el.points.length) return false;+ if (!sameEnds(el.points, live)) return true;+ const shown = el.points.map((p) => p.photoId ?? 0).join(',');+ const now = live.map((p) => p.photoId ?? 0).join(',');+ return shown !== now;+}++/** The countries a map outlines: the whole journey's, or only those its own stops fall in. */+function mapCountries(stats: JourneyStats, whole: boolean, route: readonly JourneyStatsPoint[]): string[] {+ if (whole) return stats.countries.map((c) => c.code);+ return [...new Set(route.map((p) => p.country).filter((c): c is string => !!c))];+}++const mapPoints = (route: readonly JourneyStatsPoint[]) =>+ route.map((p) => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: p.photoId ?? null }));++/**+ * The patch that takes an element's values from the journey as it stands now,+ * or null for an element that carries no journey figures. A country the+ * element already had keeps the name it was given (the book's language); a+ * new one takes the API's until someone places the element again.+ */+export function refreshPatch(el: BookElement, stats: JourneyStats): Partial<BookElement> | null {+ if (el.kind === 'stats') return { stale: false, values: liveMetrics(stats) };+ if (el.kind === 'countries') {+ const codes = stats.countries.map((c) => c.code);+ const names = codes.map((code, i) => {+ const had = el.codes.indexOf(code);+ return had >= 0 ? (el.names[had] ?? code) : (stats.countries[i]?.name ?? code);+ });+ return { stale: false, codes, names };+ }+ if (el.kind === 'map') {+ const live = routeFor(stats, el.tripId);+ return { stale: false, countries: mapCountries(stats, el.tripId == null, live), points: mapPoints(live) };+ }+ return null;+}++/*+ * ── Factories ───────────────────────────────────────────────────────────+ *+ * Each builds the finished element the Travel panel would place, with this+ * journey's values frozen into it, at the size the panel gives it. The caller+ * passes the frame (the engine centres it on a page) and the id.+ */++/** What the factories know about the journey, the words already in the book's language. */+export interface BookTravelLabels {+ day: string;+ stations: string;+ summary: string;+ countries: string;+ distance: string;+ pros: string;+ cons: string;+}++export interface BookTravelContext {+ locale: string;+ labels: BookTravelLabels;+ stats: JourneyStats | null;+ /** The recorded way, already thinned with `bookPath`. */+ path: [number, number][][];+ entries: readonly AutoEntry[];+}++/** The panel's sizes, in millimetres of the page each kind lands on. */+export function bookTravelSize(+ kind: 'map' | 'stats' | 'countries' | 'badge' | 'list',+ page: BookPageSetup,+ detail: { variant?: BookBadgeElement['variant']; rows?: number } = {},+): { w: number; h: number } {+ const side = Math.min(page.pageWidth, page.pageHeight) * 0.72;+ if (kind === 'map') return { w: side, h: side * 0.78 };+ if (kind === 'stats') return { w: page.pageWidth * 0.22, h: page.pageHeight * 0.13 };+ if (kind === 'countries') return { w: page.pageWidth * 0.34, h: 34 };+ if (kind === 'list') {+ const rows = Math.max(1, detail.rows ?? 1);+ return { w: page.pageWidth * 0.72, h: Math.min(page.pageHeight * 0.6, 6 * (0.86 + 1.7 * rows)) };+ }+ const [fw, fh] = MARK_SIZE[detail.variant ?? 'date'] ?? [0.24, 0.08];+ return { w: page.pageWidth * fw, h: page.pageHeight * fh };+}++/** A mark is placed at the size that suits what it holds, as fractions of the page. */+const MARK_SIZE: Partial<Record<BookBadgeElement['variant'], [number, number]>> = {+ flag: [0.25, 0.062],+ date: [0.16, 0.14],+ day: [0.17, 0.062],+ coords: [0.36, 0.05],+ country: [0.22, 0.078],+ distance: [0.26, 0.066],+ mood: [0.22, 0.062],+ weather: [0.22, 0.062],+};++/** What every travel element starts from, as the panel places it. */+const BASE = {+ rotation: 0,+ opacity: 1,+ locked: false,+ font: 'sans' as const,+ color: '#1a1a1a',+ accent: '#111111',+ textScale: 1,+ weight: 700 as const,+ stale: false,+};++/** A country's name in the book's language, from the same CLDR data Atlas uses. */+export function bookCountryName(code: string, locale: string, stats: JourneyStats | null): string {+ try {+ const name = new Intl.DisplayNames([locale], { type: 'region' }).of(code.toUpperCase());+ if (name) return name.slice(0, MAX_COUNTRY_NAME);+ } catch {+ // An unknown locale falls through to the API's own name.+ }+ const known = stats?.countries.find((c) => c.code === code)?.name;+ return (known || code.toUpperCase()).slice(0, MAX_COUNTRY_NAME);+}++/** Where a map is of: the whole journey or one trip, what a stored map's `tripId` can say. */+export type BookMapScope = 'journey' | { tripId: number };++/** A map of the journey or of a trip, drawn the way a new map is drawn. */+export function bookTravelMap(+ ctx: BookTravelContext,+ stats: JourneyStats,+ input: { id: string; frame: BookFrame; scope: BookMapScope; source?: 'vector' | 'relief' | 'satellite' },+): BookMapElement {+ const tripId = input.scope === 'journey' ? null : input.scope.tripId;+ const route = routeFor(stats, tripId);+ const imagery = input.source === 'relief' || input.source === 'satellite' ? BOOK_MAP_SOURCES[input.source] : null;+ const whole = input.scope === 'journey';+ const countries = mapCountries(stats, whole, route).slice(0, MAX_BOOK_COUNTRIES);+ const path = whole ? ctx.path.slice(0, MAX_PATH_SEGMENTS) : [];+ const points = mapPoints(route.slice(0, MAX_MAP_POINTS)).map((p) => ({+ ...p,+ label: p.label.slice(0, MAX_MAP_POINT_LABEL),+ }));+ return {+ ...BASE,+ id: input.id,+ kind: 'map',+ frame: input.frame,+ source: imagery ? 'tiles' : 'vector',+ tileUrl: imagery?.url ?? '',+ attribution: imagery?.attribution ?? '',+ zoom: null,+ style: 'minimal',+ // White over a photograph, ink on paper: the accent is the line.+ accent: imagery ? '#ffffff' : BASE.accent,+ showLand: true,+ showRoute: true,+ showPins: true,+ showLabels: false,+ routeStyle: 'drawn',+ routeArc: 'bow',+ routeDash: 'arcs',+ pinStyle: 'photo',+ countries,+ points,+ path: path.map((seg) => seg.slice(0, MAX_PATH_POINTS)),+ roads: [],+ fitPadding: 0.5,+ fitToCountries: true,+ clip: 'rect',+ tripId,+ };+}++/** Figures, one or a panel of them, with this journey's values. */+export function bookTravelStats(+ stats: JourneyStats,+ input: { id: string; frame: BookFrame; metrics: readonly BookMetric[] },+): BookStatsElement {+ return {+ ...BASE,+ id: input.id,+ kind: 'stats',+ frame: input.frame,+ metrics: [...input.metrics],+ layout: 'grid',+ showIcons: true,+ units: 'metric',+ values: liveMetrics(stats),+ };+}++/** Country outlines with their names in the book's language; the journey's countries unless codes are given. */+export function bookTravelCountries(+ ctx: BookTravelContext,+ input: { id: string; frame: BookFrame; codes?: readonly string[] },+): BookCountriesElement {+ const codes = (input.codes ?? ctx.stats?.countries.map((c) => c.code) ?? []).slice(0, MAX_BOOK_COUNTRIES);+ return {+ ...BASE,+ id: input.id,+ kind: 'countries',+ frame: input.frame,+ codes: codes.map((c) => c.toUpperCase()),+ names: codes.map((c) => bookCountryName(c, ctx.locale, ctx.stats)),+ layout: 'list',+ showOutline: true,+ showFlag: false,+ showName: true,+ align: 'center',+ };+}++/** The words a mark carries, resolved from an entry or the journey; null when nothing says what it would show. */+export function bookBadgeValue(+ ctx: BookTravelContext,+ variant: BookBadgeElement['variant'],+ entry: AutoEntry | null,+): { text: string; sub: string; code: string | null } | null {+ const stats = ctx.stats;+ const point = stats?.points[0];+ const lat = entry ? entry.lat : point?.lat;+ const lng = entry ? entry.lng : point?.lng;+ const country = entry ? (entry.country ?? null) : (stats?.countries[0]?.code ?? null);+ const date = entry ? entry.date : (stats?.start ?? null);+ switch (variant) {+ case 'day': {+ const day = entry ? entry.dayNumber : 1;+ return day ? { text: `${ctx.labels.day} ${day}`, sub: '', code: null } : null;+ }+ case 'date': {+ const d = date ? new Date(`${date}T00:00:00`) : null;+ if (!d || Number.isNaN(d.getTime())) return null;+ const month = d.toLocaleDateString(ctx.locale, { month: 'long' }).toUpperCase();+ return { text: String(d.getDate()), sub: month, code: null };+ }+ case 'coords': {+ if (lat == null || lng == null) return null;+ const sub = entry ? (entry.location ?? '') : (point?.label ?? '');+ return { text: formatBookCoords(lat, lng), sub, code: null };+ }+ case 'flag':+ case 'country':+ return country ? { text: '', sub: bookCountryName(country, ctx.locale, stats), code: country } : null;+ case 'distance':+ if (!stats) return null;+ return { text: formatDistance(stats.distance, ctx.locale), sub: ctx.labels.distance, code: null };+ default:+ return null;+ }+}++/** Kilometres, grouped for the reader's locale. */+function formatDistance(metres: number, locale: string): string {+ return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(metres / 1000)} km`;+}++/** The style the panel gives each mark. */+const MARK_STYLE: Partial<Record<BookBadgeElement['variant'], BookBadgeElement['style']>> = {+ date: 'stacked',+ day: 'chip',+ distance: 'outline',+};++/** A small mark: a flag, a date numeral, a day chip, coordinates, a distance, a mood or the weather. */+export function bookTravelBadge(input: {+ id: string;+ frame: BookFrame;+ variant: BookBadgeElement['variant'];+ value: { text: string; sub: string; code: string | null };+}): BookBadgeElement {+ return {+ ...BASE,+ id: input.id,+ kind: 'badge',+ frame: input.frame,+ variant: input.variant,+ text: input.value.text.slice(0, 200),+ sub: input.value.sub.slice(0, 200),+ code: input.value.code,+ style: MARK_STYLE[input.variant] ?? 'plain',+ autoColor: true,+ showIcon: true,+ showLabel: true,+ autoIconColor: true,+ iconColor: '#111111',+ };+}++/** An entry's pros and cons as two marked columns, headed in the book's language. */+export function bookTravelList(+ labels: { pros: string; cons: string },+ input: { id: string; frame: BookFrame; items: BookListElement['items'] },+): BookListElement {+ return {+ ...BASE,+ id: input.id,+ kind: 'list',+ frame: input.frame,+ items: input.items.slice(0, 60),+ layout: 'columns',+ showMarks: true,+ proLabel: labels.pros.slice(0, 80),+ conLabel: labels.cons.slice(0, 80),+ };+}++/** The lines of an entry's pros and cons, pros first. */+export function bookEntryListItems(entry: AutoEntry): BookListElement['items'] {+ const pros = (entry.pros ?? []).map((text) => ({ text: text.slice(0, 400), tone: 'pro' as const }));+ const cons = (entry.cons ?? []).map((text) => ({ text: text.slice(0, 400), tone: 'con' as const }));+ return [...pros, ...cons];+}diff --git a/shared/src/book/describe-spread.ts b/shared/src/book/describe-spread.tsindex b3df0e47c..01d2994bc 100644--- a/shared/src/book/describe-spread.ts+++ b/shared/src/book/describe-spread.ts@@ -1,4 +1,5 @@import { photoDpi, spreadFindings } from './book-findings';+import { designFindings, sortBookFindings } from './book-findings-design';import { BOOK_GRIDS } from './book-grids';import { BOOK_COVER_TEMPLATES, BOOK_TEMPLATES, type BookTemplate } from './book-layouts';import type { BookPhotoInfo } from './book-ops-core';@@ -61,7 +62,10 @@ function photoWords(el: BookPhotoElement, info: BookPhotoInfo | undefined): striparts.push(`${pic} ${info.width} x ${info.height} px in a ${frame} frame`);const ratio = info.width / info.height / (el.frame.w / el.frame.h);const shown = Math.min(ratio, 1 / ratio);- if (el.fit === 'cover' && shown < 0.9) parts.push(`cover shows ${Math.round(shown * 100)}% of the picture`);+ if (el.fit === 'cover' && shown < 0.9) {+ const crop = `cover shows ${Math.round(shown * 100)}% of the picture (no face detection: check people in the page image)`;+ parts.push(crop);+ }}parts.push(`${el.fit}, focal ${el.focalX.toFixed(2)}/${el.focalY.toFixed(2)}`);const dpi = photoDpi(el, info);@@ -86,19 +90,50 @@ function elementWords(el: BookElement, photos: readonly BookPhotoInfo[] | undefireturn `${style}: "${head(el.text, 80)}"${bound}`;}case 'shape':- return `${el.shape}, fill ${el.fill ?? 'none'}${el.stroke ? `, stroke ${el.stroke}` : ''}`;- case 'map':- return `${el.source} map, ${el.points.length} points, ${el.countries.length} countries`;- case 'stats':- return `figures: ${el.metrics.join(', ')}`;+ return shapeWords(el);+ case 'icon':+ return `icon ${el.name}, ${el.color}, line ${n(el.lineWidth)}`;+ default:+ return travelWords(el);+ }+}++function shapeWords(el: Extract<BookElement, { kind: 'shape' }>): string {+ const parts = [`${el.shape}, fill ${el.fill ?? 'none'}`];+ if (el.gradient !== 'none') parts.push(`fading ${el.gradient}`);+ if (el.stroke) parts.push(`stroke ${el.stroke} ${n(el.strokeWidth)} mm ${el.strokeStyle}`);+ if (el.radius > 0) parts.push(`radius ${n(el.radius)}`);+ return parts.join(', ');+}++type TravelElement = Extract<BookElement, { kind: 'map' | 'stats' | 'countries' | 'badge' | 'list' }>;++/** What a travel element shows, and how it is set: its face, ink, accent and size. */+function travelWords(el: TravelElement): string {+ const set = `${el.font} ${el.weight >= 600 ? 'bold' : 'regular'}, ink ${el.color}, accent ${el.accent}, type x${n(el.textScale)}`;+ const stale = el.stale ? '; its figures are out of date with the journey' : '';+ return `${travelWhat(el)}; ${set}${stale}`;+}++function travelWhat(el: TravelElement): string {+ switch (el.kind) {+ case 'map': {+ const scope = el.tripId != null ? `trip ${el.tripId}` : 'the whole journey';+ const line = el.path.length ? `, a recorded track of ${el.path.length} segments` : '';+ return `${el.style} ${el.source} map of ${scope}, ${el.points.length} stops, ${el.countries.length} countries${line}`;+ }+ case 'stats': {+ const figures = el.metrics.map((m) => `${m} ${el.values[m] ?? 0}`).join(', ');+ return `figures (${el.layout}): ${figures}`;+ }case 'countries':- return `${el.codes.length} countries`;+ return `${el.codes.length} countries (${el.codes.slice(0, 8).join(', ')}), ${el.layout}`;case 'badge':- return `${el.variant} mark "${head(el.text, 40)}"`;- case 'list':- return `list of ${el.items.length}`;- case 'icon':- return `icon ${el.name}`;+ return `${el.variant} mark "${head(el.text, 40)}"${el.sub ? ` over "${head(el.sub, 40)}"` : ''}, ${el.style}`;+ case 'list': {+ const pros = el.items.filter((i) => i.tone === 'pro').length;+ return `list of ${el.items.length} (${pros} pros, ${el.items.length - pros} others), ${el.layout}`;+ }}}@@ -156,6 +191,18 @@ function elementSummary(el: BookElement): BookElementSummary {};}+/**+ * Every finding of one page, the print faults and the design checks+ * (book-findings-design.ts) together, severe first, at most the cap.+ */+export function pageFindings(+ spread: BookSpread,+ page: BookPageSetup,+ photos?: readonly BookPhotoInfo[],+): BookFinding[] {+ return sortBookFindings([...spreadFindings(spread, page, photos), ...designFindings(spread, page, photos)]);+}+/*** One page in words, with its findings and its elements. Null when the book* has no page with that id.@@ -171,7 +218,7 @@ export function describeSpread(const index = doc.spreads.findIndex((s) => s.id === spreadId);const spread = doc.spreads[index];if (!spread) return null;- const findings = spreadFindings(spread, doc.page, photos);+ const findings = pageFindings(spread, doc.page, photos);const lines = [pageLine(doc, spread, index)];if (spread.elements.length) {lines.push('Elements, back to front (frame in mm: x, y, w x h):');diff --git a/shared/src/book/design/design-book.fixtures.json b/shared/src/book/design/design-book.fixtures.jsonnew file mode 100644index 000000000..c1b41798e--- /dev/null+++ b/shared/src/book/design/design-book.fixtures.json@@ -0,0 +1,2812 @@+{+ "rich": {+ "input": {+ "locale": "en-GB",+ "title": "Atlantic coast",+ "subtitle": "Two weeks north",+ "coverPhotoId": 100,+ "entries": [+ {+ "id": 1,+ "title": "Day 1 in Lisboa",+ "story": null,+ "location": "Lisboa",+ "date": "2026-05-01",+ "photos": [],+ "lat": 38.72,+ "lng": -9.14,+ "country": "PT",+ "dayNumber": 1,+ "dayCount": 14+ },+ {+ "id": 2,+ "title": "Day 2 in Lisboa",+ "story": "Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while r",+ "location": "Lisboa",+ "date": "2026-05-02",+ "photos": [+ {+ "photoId": 100,+ "width": 4000,+ "height": 3000,+ "caption": "Tram 28"+ }+ ],+ "lat": 38.72,+ "lng": -9.14,+ "country": "PT",+ "dayNumber": 2,+ "dayCount": 14+ },+ {+ "id": 3,+ "title": "Day 3 in Porto",+ "story": "Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for the north coast stopped light enough at while. Good look a road along and wherever was to for the north coast stopped. While ran the we the good look a road along and wherever was to for.\n Coast stopped light enough at while ran the we the good look a road along and. Was to for the north coast stopped light. A road along and wherever was to for the. The we the good look a road along and wherever. Light enough at while ran the we the good look a.\n For the north coast stopped light enough at while ran the we. Along and wherever was to for the north coast stopped light enough at. The good look a road along and wherever was to for the north coast. At while ran the we the good look a road along and wherever was to. North coast stopped light enough at while ran the we the good look a road along.\n Wherever was to for the north coast stopped. Look a road along and wherever was to for.",+ "location": "Porto",+ "date": "2026-05-03",+ "photos": [+ {+ "photoId": 101,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 102,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 41.15,+ "lng": -8.61,+ "country": "PT",+ "dayNumber": 3,+ "dayCount": 14,+ "pros": [+ "The light"+ ],+ "cons": [+ "The wind"+ ]+ },+ {+ "id": 4,+ "title": "Day 4 in Porto",+ "story": "A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a r",+ "location": "Porto",+ "date": "2026-05-04",+ "photos": [+ {+ "photoId": 103,+ "width": 6000,+ "height": 2000,+ "caption": "The bridge"+ },+ {+ "photoId": 104,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 41.15,+ "lng": -8.61,+ "country": "PT",+ "dayNumber": 4,+ "dayCount": 14+ },+ {+ "id": 5,+ "title": null,+ "story": null,+ "location": "Santiago",+ "date": "2026-05-05",+ "photos": [+ {+ "photoId": 105,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 106,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 107,+ "width": 3000,+ "height": 4000,+ "caption": null+ }+ ],+ "lat": 42.88,+ "lng": -8.54,+ "country": "ES",+ "dayNumber": 5,+ "dayCount": 14+ },+ {+ "id": 6,+ "title": "Day 6 in Santiago",+ "story": "Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for t",+ "location": "Santiago",+ "date": "2026-05-06",+ "photos": [+ {+ "photoId": 108,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 109,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 110,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 111,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 42.88,+ "lng": -8.54,+ "country": "ES",+ "dayNumber": 6,+ "dayCount": 14+ },+ {+ "id": 7,+ "title": "Day 7 in Oviedo",+ "story": "For the north coast stopped light enough at. Along and where",+ "location": "Oviedo",+ "date": "2026-05-07",+ "photos": [+ {+ "photoId": 112,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 113,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 114,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 115,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 116,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 43.36,+ "lng": -5.85,+ "country": "ES",+ "dayNumber": 7,+ "dayCount": 14+ },+ {+ "id": 8,+ "title": "Day 8 in Oviedo",+ "story": "Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for the north coast stopped light enough at while. Good look a road along and wherever was to for the north coast stopped. While ran the we the good look a road along and wherever was to for.\n Coast stopped light enough at while ran the we the good look a road along and. Was to for the north coast stopped light. A road along and wherever was to for the. The we the good look a road along and wherever. Light enough at while ran the we the good look a.\n For the north coast stopped light enough at while ran the we. Along and wherever was to for the north coast stopped light enough at. The good look a road along and wherever was to for the north coast. At while ran the we the good look a road along and wherever was to. Nort",+ "location": "Oviedo",+ "date": "2026-05-08",+ "photos": [+ {+ "photoId": 117,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 118,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 119,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 120,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 121,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 122,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 123,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 124,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 43.36,+ "lng": -5.85,+ "country": "ES",+ "dayNumber": 8,+ "dayCount": 14+ },+ {+ "id": 9,+ "title": "Day 9 in Bilbao",+ "story": null,+ "location": "Bilbao",+ "date": "2026-05-09",+ "photos": [+ {+ "photoId": 125,+ "width": null,+ "height": null,+ "caption": null+ }+ ],+ "lat": 43.26,+ "lng": -2.93,+ "country": "ES",+ "dayNumber": 9,+ "dayCount": 14+ },+ {+ "id": 10,+ "title": "Day 10 in Bilbao",+ "story": "At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wh",+ "location": "Bilbao",+ "date": "2026-05-10",+ "photos": [+ {+ "photoId": 126,+ "width": 4000,+ "height": 3000,+ "caption": "Dusk"+ }+ ],+ "lat": 43.26,+ "lng": -2.93,+ "country": "ES",+ "dayNumber": 10,+ "dayCount": 14+ },+ {+ "id": 11,+ "title": "Day 11 in Biarritz",+ "story": null,+ "location": "Biarritz",+ "date": "2026-05-11",+ "photos": [+ {+ "photoId": 127,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 128,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 129,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ],+ "lat": 43.48,+ "lng": -1.56,+ "country": "FR",+ "dayNumber": 11,+ "dayCount": 14+ },+ {+ "id": 12,+ "title": "Day 12 in Biarritz",+ "story": null,+ "location": "Biarritz",+ "date": "2026-05-12",+ "photos": [],+ "lat": 43.48,+ "lng": -1.56,+ "country": "FR",+ "dayNumber": 12,+ "dayCount": 14+ }+ ],+ "page": {+ "preset": "square-210",+ "pageWidth": 210,+ "pageHeight": 210,+ "bleed": 3,+ "safe": 5,+ "pageNumbers": {+ "show": false,+ "startAt": 2,+ "position": "outer",+ "margin": 12,+ "size": 8,+ "autoColor": true,+ "color": "#8a8578",+ "font": "sans"+ }+ },+ "stats": {+ "journeyId": 1,+ "distance": 1420000,+ "days": 14,+ "steps": 12,+ "photos": 41,+ "places": 12,+ "furthest": 980000,+ "countries": [+ {+ "code": "PT",+ "name": "Portugal",+ "places": 4,+ "firstVisit": "2026-05-01"+ },+ {+ "code": "ES",+ "name": "Spain",+ "places": 5,+ "firstVisit": "2026-05-05"+ },+ {+ "code": "FR",+ "name": "France",+ "places": 3,+ "firstVisit": "2026-05-11"+ }+ ],+ "points": [+ {+ "lat": 38.72,+ "lng": -9.14,+ "label": "Lisboa",+ "date": "2026-05-01",+ "country": "PT",+ "tripId": null,+ "photoId": 100,+ "entryId": 1+ },+ {+ "lat": 41.15,+ "lng": -8.61,+ "label": "Porto",+ "date": "2026-05-03",+ "country": "PT",+ "tripId": null,+ "photoId": null,+ "entryId": 2+ },+ {+ "lat": 42.88,+ "lng": -8.54,+ "label": "Santiago",+ "date": "2026-05-05",+ "country": "ES",+ "tripId": null,+ "photoId": 102,+ "entryId": 3+ },+ {+ "lat": 43.36,+ "lng": -5.85,+ "label": "Oviedo",+ "date": "2026-05-07",+ "country": "ES",+ "tripId": null,+ "photoId": null,+ "entryId": 4+ },+ {+ "lat": 43.26,+ "lng": -2.93,+ "label": "Bilbao",+ "date": "2026-05-09",+ "country": "ES",+ "tripId": null,+ "photoId": 104,+ "entryId": 5+ },+ {+ "lat": 43.48,+ "lng": -1.56,+ "label": "Biarritz",+ "date": "2026-05-11",+ "country": "FR",+ "tripId": null,+ "photoId": null,+ "entryId": 6+ },+ {+ "lat": 44.84,+ "lng": -0.58,+ "label": "Bordeaux",+ "date": "2026-05-13",+ "country": "FR",+ "tripId": null,+ "photoId": 106,+ "entryId": 7+ }+ ],+ "trips": [],+ "excluded": [],+ "start": "2026-05-01",+ "end": "2026-05-14"+ },+ "path": [+ [+ [+ 38.72,+ -9.14+ ],+ [+ 39.5,+ -9+ ],+ [+ 41.15,+ -8.61+ ]+ ],+ [+ [+ 42.88,+ -8.54+ ],+ [+ 43.3,+ -6+ ],+ [+ 43.36,+ -5.85+ ],+ [+ 43.26,+ -2.93+ ]+ ]+ ],+ "stationsLabel": "Stations",+ "dayLabel": "DAY",+ "summaryLabel": "Trip summary",+ "countriesLabel": "Countries",+ "distanceLabel": "Distance",+ "prosLabel": "Pros",+ "consLabel": "Cons",+ "candidates": [+ {+ "photoId": 100,+ "takenAt": "2026-05-02T12:10:00",+ "lat": 38.72,+ "lng": -9.14,+ "width": 4000,+ "height": 3000,+ "caption": "Tram 28",+ "entryIds": [+ 2+ ],+ "inBook": false,+ "signals": {+ "phash": "a6f096b17fa1630e",+ "sharpness": 120,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 101,+ "takenAt": "2026-05-03T12:11:00",+ "lat": 41.15,+ "lng": -8.61,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 3+ ],+ "inBook": false,+ "signals": {+ "phash": "56984de1216e0955",+ "sharpness": 121,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 102,+ "takenAt": "2026-05-03T12:12:00",+ "lat": 41.15,+ "lng": -8.61,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 3+ ],+ "inBook": false,+ "signals": {+ "phash": "f8cf19356da23ad9",+ "sharpness": 122,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 103,+ "takenAt": "2026-05-04T12:13:00",+ "lat": 41.15,+ "lng": -8.61,+ "width": 6000,+ "height": 2000,+ "caption": "The bridge",+ "entryIds": [+ 4+ ],+ "inBook": false,+ "signals": {+ "phash": "a7d8b4d113fccc86",+ "sharpness": 123,+ "clipped": 0.01,+ "origWidth": 6000,+ "origHeight": 2000+ }+ },+ {+ "photoId": 104,+ "takenAt": "2026-05-04T12:14:00",+ "lat": 41.15,+ "lng": -8.61,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 4+ ],+ "inBook": false,+ "signals": {+ "phash": "49005149c25eda2a",+ "sharpness": 124,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 105,+ "takenAt": "2026-05-05T12:15:00",+ "lat": 42.88,+ "lng": -8.54,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 5+ ],+ "inBook": false,+ "signals": {+ "phash": "fb37226c4e17184b",+ "sharpness": 125,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 106,+ "takenAt": "2026-05-05T12:16:00",+ "lat": 42.88,+ "lng": -8.54,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 5+ ],+ "inBook": false,+ "signals": {+ "phash": "a6318983ddb88e37",+ "sharpness": 126,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 107,+ "takenAt": "2026-05-05T12:17:00",+ "lat": 42.88,+ "lng": -8.54,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 5+ ],+ "inBook": false,+ "signals": {+ "phash": "48697291581b8b06",+ "sharpness": 127,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 108,+ "takenAt": "2026-05-06T12:18:00",+ "lat": 42.88,+ "lng": -8.54,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 6+ ],+ "inBook": false,+ "signals": {+ "phash": "fa913c6f28dd3f28",+ "sharpness": 128,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 109,+ "takenAt": "2026-05-06T12:19:00",+ "lat": 42.88,+ "lng": -8.54,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 6+ ],+ "inBook": false,+ "signals": {+ "phash": "9cb80945b71aacac",+ "sharpness": 129,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 110,+ "takenAt": "2026-05-06T12:20:00",+ "lat": 42.88,+ "lng": -8.54,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 6+ ],+ "inBook": false,+ "signals": {+ "phash": "4ee0d27af914b205",+ "sharpness": 130,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 111,+ "takenAt": "2026-05-06T12:21:00",+ "lat": 42.88,+ "lng": -8.54,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 6+ ],+ "inBook": false,+ "signals": {+ "phash": "e016da31c64c8d54",+ "sharpness": 131,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 112,+ "takenAt": "2026-05-07T12:22:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 7+ ],+ "inBook": false,+ "signals": {+ "phash": "924ddc543da61f9d",+ "sharpness": 132,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 113,+ "takenAt": "2026-05-07T12:23:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 7+ ],+ "inBook": false,+ "signals": {+ "phash": "447739db76fdf0cd",+ "sharpness": 133,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 114,+ "takenAt": "2026-05-07T12:24:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 7+ ],+ "inBook": false,+ "signals": {+ "phash": "e69ef452f0536314",+ "sharpness": 134,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 115,+ "takenAt": "2026-05-07T12:25:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 7+ ],+ "inBook": false,+ "signals": {+ "phash": "98c6c0bec8613247",+ "sharpness": 135,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 116,+ "takenAt": "2026-05-07T12:26:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 7+ ],+ "inBook": false,+ "signals": {+ "phash": "3ad488ef7faa2a76",+ "sharpness": 136,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 117,+ "takenAt": "2026-05-08T12:27:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "ec254f670baa6262",+ "sharpness": 137,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 118,+ "takenAt": "2026-05-08T12:28:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "8e4d24c09a4d8bae",+ "sharpness": 138,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 119,+ "takenAt": "2026-05-08T12:29:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "8e4d24c09a4d8bae",+ "sharpness": 139,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 120,+ "takenAt": "2026-05-08T12:30:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "e2aa2a58885625e5",+ "sharpness": 140,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 121,+ "takenAt": "2026-05-08T12:31:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "83d48702dc4e60fb",+ "sharpness": 141,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 122,+ "takenAt": "2026-05-08T12:32:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "35e24da0d14ead56",+ "sharpness": 142,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 123,+ "takenAt": "2026-05-08T12:33:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "d723022d8cfb4349",+ "sharpness": 143,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 124,+ "takenAt": "2026-05-08T12:34:00",+ "lat": 43.36,+ "lng": -5.85,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 8+ ],+ "inBook": false,+ "signals": {+ "phash": "895bea3b17e957d3",+ "sharpness": 144,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 125,+ "takenAt": "2026-05-09T12:35:00",+ "lat": 43.26,+ "lng": -2.93,+ "width": null,+ "height": null,+ "caption": null,+ "entryIds": [+ 9+ ],+ "inBook": false,+ "signals": null+ },+ {+ "photoId": 126,+ "takenAt": "2026-05-10T12:36:00",+ "lat": 43.26,+ "lng": -2.93,+ "width": 4000,+ "height": 3000,+ "caption": "Dusk",+ "entryIds": [+ 10+ ],+ "inBook": false,+ "signals": {+ "phash": "d403c04d5361c843",+ "sharpness": 146,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 127,+ "takenAt": "2026-05-11T12:37:00",+ "lat": 43.48,+ "lng": -1.56,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 11+ ],+ "inBook": false,+ "signals": {+ "phash": "863a80379227d012",+ "sharpness": 147,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 128,+ "takenAt": "2026-05-11T12:38:00",+ "lat": 43.48,+ "lng": -1.56,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 11+ ],+ "inBook": false,+ "signals": {+ "phash": "2849617c9cbf73b1",+ "sharpness": 148,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 129,+ "takenAt": "2026-05-11T12:39:00",+ "lat": 43.48,+ "lng": -1.56,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 11+ ],+ "inBook": false,+ "signals": {+ "phash": "da8a401815615cf3",+ "sharpness": 149,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ }+ ],+ "photos": [+ {+ "photoId": 100,+ "width": 4000,+ "height": 3000,+ "caption": "Tram 28",+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad",+ "luma": 90,+ "salient": {+ "x": 0.3,+ "y": 0.4+ }+ },+ {+ "photoId": 101,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "7ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be14",+ "luma": 127,+ "salient": {+ "x": 0.7,+ "y": 0.55+ }+ },+ {+ "photoId": 102,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "e147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258b",+ "luma": 164,+ "salient": {+ "x": 0.35,+ "y": 0.45+ }+ },+ {+ "photoId": 103,+ "width": 6000,+ "height": 2000,+ "caption": "The bridge",+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "58be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf2",+ "luma": 201,+ "salient": {+ "x": 0.65,+ "y": 0.4+ }+ },+ {+ "photoId": 104,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369",+ "luma": 118,+ "salient": {+ "x": 0.3,+ "y": 0.55+ }+ },+ {+ "photoId": 105,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0",+ "luma": 155,+ "salient": {+ "x": 0.7,+ "y": 0.45+ }+ },+ {+ "photoId": 106,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147",+ "luma": 192,+ "salient": {+ "x": 0.35,+ "y": 0.4+ }+ },+ {+ "photoId": 107,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be",+ "luma": 109,+ "salient": {+ "x": 0.65,+ "y": 0.55+ }+ },+ {+ "photoId": 108,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "8be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf25",+ "luma": 146,+ "salient": {+ "x": 0.3,+ "y": 0.45+ }+ },+ {+ "photoId": 109,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "f258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369c",+ "luma": 183,+ "salient": {+ "x": 0.7,+ "y": 0.4+ }+ },+ {+ "photoId": 110,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "69cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad03",+ "luma": 100,+ "salient": {+ "x": 0.35,+ "y": 0.55+ }+ },+ {+ "photoId": 111,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "d0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147a",+ "luma": 137,+ "salient": {+ "x": 0.65,+ "y": 0.45+ }+ },+ {+ "photoId": 112,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "47ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be1",+ "luma": 174,+ "salient": {+ "x": 0.3,+ "y": 0.4+ }+ },+ {+ "photoId": 113,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258",+ "luma": 91,+ "salient": {+ "x": 0.7,+ "y": 0.55+ }+ },+ {+ "photoId": 114,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf",+ "luma": 128,+ "salient": {+ "x": 0.35,+ "y": 0.45+ }+ },+ {+ "photoId": 115,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "9cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad036",+ "luma": 165,+ "salient": {+ "x": 0.65,+ "y": 0.4+ }+ },+ {+ "photoId": 116,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad",+ "luma": 202,+ "salient": {+ "x": 0.3,+ "y": 0.55+ }+ },+ {+ "photoId": 117,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "7ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be14",+ "luma": 119,+ "salient": {+ "x": 0.7,+ "y": 0.45+ }+ },+ {+ "photoId": 118,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "e147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258b",+ "luma": 156,+ "salient": {+ "x": 0.35,+ "y": 0.4+ }+ },+ {+ "photoId": 119,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "58be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf2",+ "luma": 193,+ "salient": {+ "x": 0.65,+ "y": 0.55+ }+ },+ {+ "photoId": 120,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369",+ "luma": 110,+ "salient": {+ "x": 0.3,+ "y": 0.45+ }+ },+ {+ "photoId": 121,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0",+ "luma": 147,+ "salient": {+ "x": 0.7,+ "y": 0.4+ }+ },+ {+ "photoId": 122,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147",+ "luma": 184,+ "salient": {+ "x": 0.35,+ "y": 0.55+ }+ },+ {+ "photoId": 123,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be",+ "luma": 101,+ "salient": {+ "x": 0.65,+ "y": 0.45+ }+ },+ {+ "photoId": 124,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "8be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf25",+ "luma": 138,+ "salient": {+ "x": 0.3,+ "y": 0.4+ }+ },+ {+ "photoId": 125,+ "width": null,+ "height": null,+ "caption": null+ },+ {+ "photoId": 126,+ "width": 4000,+ "height": 3000,+ "caption": "Dusk",+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "69cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad03",+ "luma": 92,+ "salient": {+ "x": 0.35,+ "y": 0.45+ }+ },+ {+ "photoId": 127,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "d0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147a",+ "luma": 129,+ "salient": {+ "x": 0.65,+ "y": 0.4+ }+ },+ {+ "photoId": 128,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "47ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be1",+ "luma": 166,+ "salient": {+ "x": 0.3,+ "y": 0.55+ }+ },+ {+ "photoId": 129,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258",+ "luma": 203,+ "salient": {+ "x": 0.7,+ "y": 0.45+ }+ }+ ]+ }+ },+ "sparse": {+ "input": {+ "locale": "pt-PT",+ "title": "Algarve",+ "subtitle": null,+ "coverPhotoId": 902,+ "entries": [+ {+ "id": 501,+ "title": "Arrival",+ "story": "We landed late and found the house by torchlight.",+ "location": "Faro",+ "date": "2026-03-01",+ "photos": [+ {+ "photoId": 900,+ "width": 1600,+ "height": 1200,+ "caption": null+ }+ ]+ },+ {+ "id": 502,+ "title": "Stop",+ "story": null,+ "location": "Tavira",+ "date": "2026-03-02",+ "photos": []+ },+ {+ "id": 503,+ "title": null,+ "story": null,+ "location": "Olhao",+ "date": "2026-03-03",+ "photos": []+ },+ {+ "id": 504,+ "title": "Cliffs",+ "story": "Wind all day.",+ "location": "Sagres",+ "date": "2026-03-04",+ "photos": [+ {+ "photoId": 901,+ "width": null,+ "height": null,+ "caption": "Edge"+ },+ {+ "photoId": 902,+ "width": 3000,+ "height": 4000,+ "caption": null+ }+ ]+ }+ ],+ "page": {+ "preset": "square-210",+ "pageWidth": 210,+ "pageHeight": 210,+ "bleed": 3,+ "safe": 5,+ "pageNumbers": {+ "show": false,+ "startAt": 2,+ "position": "outer",+ "margin": 12,+ "size": 8,+ "autoColor": true,+ "color": "#8a8578",+ "font": "sans"+ }+ },+ "stats": {+ "journeyId": 3,+ "distance": 210000,+ "days": 4,+ "steps": 3,+ "photos": 3,+ "places": 4,+ "furthest": 120000,+ "countries": [+ {+ "code": "PT",+ "name": "Portugal",+ "places": 4,+ "firstVisit": "2026-03-01"+ }+ ],+ "points": [+ {+ "lat": 37.02,+ "lng": -7.93,+ "label": "Faro",+ "date": "2026-03-01",+ "country": "PT",+ "tripId": null,+ "photoId": 900,+ "entryId": 501+ },+ {+ "lat": 37.13,+ "lng": -7.65,+ "label": "Tavira",+ "date": "2026-03-02",+ "country": "PT",+ "tripId": null,+ "photoId": null,+ "entryId": 502+ },+ {+ "lat": 37,+ "lng": -8.94,+ "label": "Sagres",+ "date": "2026-03-04",+ "country": "PT",+ "tripId": null,+ "photoId": 902,+ "entryId": 504+ }+ ],+ "trips": [],+ "excluded": [],+ "start": "2026-03-01",+ "end": "2026-03-04"+ },+ "stationsLabel": "Paragens",+ "dayLabel": "DIA",+ "summaryLabel": "Resumo",+ "countriesLabel": "Paises",+ "distanceLabel": "Distance",+ "prosLabel": "Pros",+ "consLabel": "Cons",+ "candidates": [+ {+ "photoId": 900,+ "takenAt": "2026-03-01T12:10:00",+ "lat": null,+ "lng": null,+ "width": 1600,+ "height": 1200,+ "caption": null,+ "entryIds": [+ 501+ ],+ "inBook": false,+ "signals": {+ "phash": "a6f096b17fa1630e",+ "sharpness": 120,+ "clipped": 0.01,+ "origWidth": 1600,+ "origHeight": 1200+ }+ },+ {+ "photoId": 901,+ "takenAt": "2026-03-04T12:11:00",+ "lat": null,+ "lng": null,+ "width": null,+ "height": null,+ "caption": "Edge",+ "entryIds": [+ 504+ ],+ "inBook": false,+ "signals": null+ },+ {+ "photoId": 902,+ "takenAt": "2026-03-04T12:12:00",+ "lat": null,+ "lng": null,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [+ 504+ ],+ "inBook": false,+ "signals": {+ "phash": "f8cf19356da23ad9",+ "sharpness": 122,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ }+ ],+ "photos": [+ {+ "photoId": 900,+ "width": 1600,+ "height": 1200,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad",+ "luma": 90,+ "salient": {+ "x": 0.3,+ "y": 0.4+ }+ },+ {+ "photoId": 901,+ "width": null,+ "height": null,+ "caption": "Edge"+ },+ {+ "photoId": 902,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "e147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258b",+ "luma": 164,+ "salient": {+ "x": 0.35,+ "y": 0.45+ }+ }+ ]+ }+ },+ "nostats": {+ "input": {+ "locale": "fr-FR",+ "title": "Carnet",+ "subtitle": "Automne",+ "coverPhotoId": null,+ "entries": [+ {+ "id": 301,+ "title": "Chapter 1",+ "story": "And wherever was to for the north coast stopped. Good look a road along and wherever was to for. While ran the we the good look a road along and. Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light e",+ "location": null,+ "date": "2026-10-01",+ "photos": []+ },+ {+ "id": 302,+ "title": "Chapter 2",+ "story": "Good look a road along and wherever was to for. While ran the we the good look a road along and. Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along a",+ "location": null,+ "date": "2026-10-02",+ "photos": [+ {+ "photoId": 149,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 150,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 151,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 152,+ "width": 4000,+ "height": 3000,+ "caption": null+ }+ ]+ },+ {+ "id": 303,+ "title": "Chapter 3",+ "story": "While ran the we the good look a road along and. Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and where",+ "location": null,+ "date": "2026-10-03",+ "photos": []+ },+ {+ "id": 304,+ "title": "Chapter 4",+ "story": "Coast stopped light enough at while ran the we the good look. Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good",+ "location": null,+ "date": "2026-10-04",+ "photos": []+ },+ {+ "id": 305,+ "title": "Chapter 5",+ "story": "Was to for the north coast stopped light enough at while ran the.\n A road along and wherever was to for the north coast stopped light enough. The we the good look a road along and wherever was to for the north. Light enough at while ran the we the good look a road along and wherever was. For the north coast stopped light enough at. Along and wherever was to for the north coast.\n The good look a road along and wherever was to. At while ran the we the good look a road along. North coast stopped light enough at while ran the we the good. Wherever was to for the north coast stopped light enough at while ran. Look a road along and wherever was to for the north coast stopped light.\n Ran the we the good look a road along and wherever was to for the. Stopped light enough at while ran the we the good look a road along and wherever. To for the north coast stopped light enough. Road along and wherever was to for the north. We the good look a road along and wherever was.\n Enough at while ran the we the good look a road. The north coast stopped light enough at while ran the we the. And wherever was to for the north coast stopped light enough at while. Good look a road along and wherever was to for the north coast stopped. While ran the we the",+ "location": null,+ "date": "2026-10-05",+ "photos": []+ }+ ],+ "page": {+ "preset": "a4-portrait",+ "pageWidth": 210,+ "pageHeight": 297,+ "bleed": 3,+ "safe": 5,+ "pageNumbers": {+ "show": false,+ "startAt": 2,+ "position": "outer",+ "margin": 12,+ "size": 8,+ "autoColor": true,+ "color": "#8a8578",+ "font": "sans"+ }+ },+ "stats": null,+ "stationsLabel": "Stations",+ "dayLabel": "DAY",+ "summaryLabel": "Trip summary",+ "countriesLabel": "Countries",+ "distanceLabel": "Distance",+ "prosLabel": "Pros",+ "consLabel": "Cons",+ "candidates": [+ {+ "photoId": 149,+ "takenAt": "2026-10-02T12:10:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 302+ ],+ "inBook": false,+ "signals": {+ "phash": "a6f096b17fa1630e",+ "sharpness": 120,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 150,+ "takenAt": "2026-10-02T12:11:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 302+ ],+ "inBook": false,+ "signals": {+ "phash": "56984de1216e0955",+ "sharpness": 121,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 151,+ "takenAt": "2026-10-02T12:12:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 302+ ],+ "inBook": false,+ "signals": {+ "phash": "f8cf19356da23ad9",+ "sharpness": 122,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 152,+ "takenAt": "2026-10-02T12:13:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [+ 302+ ],+ "inBook": false,+ "signals": {+ "phash": "a7d8b4d113fccc86",+ "sharpness": 123,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 132,+ "takenAt": "2026-05-20T12:14:00",+ "lat": null,+ "lng": null,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 0",+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "49005149c25eda2a",+ "sharpness": 124,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 133,+ "takenAt": "2026-05-20T12:15:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "fb37226c4e17184b",+ "sharpness": 125,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 134,+ "takenAt": "2026-05-20T12:16:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "a6318983ddb88e37",+ "sharpness": 126,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 135,+ "takenAt": "2026-05-20T12:17:00",+ "lat": null,+ "lng": null,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "48697291581b8b06",+ "sharpness": 127,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 136,+ "takenAt": "2026-05-20T12:18:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 4",+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "fa913c6f28dd3f28",+ "sharpness": 128,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 137,+ "takenAt": "2026-05-20T12:19:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "9cb80945b71aacac",+ "sharpness": 129,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 138,+ "takenAt": "2026-05-20T12:20:00",+ "lat": null,+ "lng": null,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "4ee0d27af914b205",+ "sharpness": 130,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 139,+ "takenAt": "2026-05-20T12:21:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "e016da31c64c8d54",+ "sharpness": 131,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 140,+ "takenAt": "2026-05-20T12:22:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 8",+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "924ddc543da61f9d",+ "sharpness": 132,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 141,+ "takenAt": "2026-05-20T12:23:00",+ "lat": null,+ "lng": null,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "447739db76fdf0cd",+ "sharpness": 133,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 142,+ "takenAt": "2026-05-20T12:24:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "e69ef452f0536314",+ "sharpness": 134,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 143,+ "takenAt": "2026-05-20T12:25:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "98c6c0bec8613247",+ "sharpness": 135,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 144,+ "takenAt": "2026-05-20T12:26:00",+ "lat": null,+ "lng": null,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 12",+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "3ad488ef7faa2a76",+ "sharpness": 136,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 145,+ "takenAt": "2026-05-20T12:27:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "ec254f670baa6262",+ "sharpness": 137,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 146,+ "takenAt": "2026-05-20T12:28:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "8e4d24c09a4d8bae",+ "sharpness": 138,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ },+ {+ "photoId": 147,+ "takenAt": "2026-05-20T12:29:00",+ "lat": null,+ "lng": null,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "30560be83fb513b3",+ "sharpness": 139,+ "clipped": 0.01,+ "origWidth": 3000,+ "origHeight": 4000+ }+ },+ {+ "photoId": 148,+ "takenAt": "2026-05-20T12:30:00",+ "lat": null,+ "lng": null,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 16",+ "entryIds": [],+ "inBook": false,+ "signals": {+ "phash": "e2aa2a58885625e5",+ "sharpness": 140,+ "clipped": 0.01,+ "origWidth": 4000,+ "origHeight": 3000+ }+ }+ ],+ "photos": [+ {+ "photoId": 149,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad",+ "luma": 90,+ "salient": {+ "x": 0.3,+ "y": 0.4+ }+ },+ {+ "photoId": 150,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "7ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be14",+ "luma": 127,+ "salient": {+ "x": 0.7,+ "y": 0.55+ }+ },+ {+ "photoId": 151,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "e147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258b",+ "luma": 164,+ "salient": {+ "x": 0.35,+ "y": 0.45+ }+ },+ {+ "photoId": 152,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "58be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf2",+ "luma": 201,+ "salient": {+ "x": 0.65,+ "y": 0.4+ }+ },+ {+ "photoId": 132,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 0",+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369",+ "luma": 118,+ "salient": {+ "x": 0.3,+ "y": 0.55+ }+ },+ {+ "photoId": 133,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0",+ "luma": 155,+ "salient": {+ "x": 0.7,+ "y": 0.45+ }+ },+ {+ "photoId": 134,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147",+ "luma": 192,+ "salient": {+ "x": 0.35,+ "y": 0.4+ }+ },+ {+ "photoId": 135,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be",+ "luma": 109,+ "salient": {+ "x": 0.65,+ "y": 0.55+ }+ },+ {+ "photoId": 136,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 4",+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "8be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf25",+ "luma": 146,+ "salient": {+ "x": 0.3,+ "y": 0.45+ }+ },+ {+ "photoId": 137,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "f258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369c",+ "luma": 183,+ "salient": {+ "x": 0.7,+ "y": 0.4+ }+ },+ {+ "photoId": 138,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "69cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad03",+ "luma": 100,+ "salient": {+ "x": 0.35,+ "y": 0.55+ }+ },+ {+ "photoId": 139,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "d0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147a",+ "luma": 137,+ "salient": {+ "x": 0.65,+ "y": 0.45+ }+ },+ {+ "photoId": 140,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 8",+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "47ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be1",+ "luma": 174,+ "salient": {+ "x": 0.3,+ "y": 0.4+ }+ },+ {+ "photoId": 141,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258",+ "luma": 91,+ "salient": {+ "x": 0.7,+ "y": 0.55+ }+ },+ {+ "photoId": 142,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf",+ "luma": 128,+ "salient": {+ "x": 0.35,+ "y": 0.45+ }+ },+ {+ "photoId": 143,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "9cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad036",+ "luma": 165,+ "salient": {+ "x": 0.65,+ "y": 0.4+ }+ },+ {+ "photoId": 144,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 12",+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad",+ "luma": 202,+ "salient": {+ "x": 0.3,+ "y": 0.55+ }+ },+ {+ "photoId": 145,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "7ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be14",+ "luma": 119,+ "salient": {+ "x": 0.7,+ "y": 0.45+ }+ },+ {+ "photoId": 146,+ "width": 4000,+ "height": 3000,+ "caption": null,+ "palette": [+ "#c0392b:0.35",+ "#f2e8d5:0.4",+ "#2c3e50:0.25"+ ],+ "busy": "e147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258b",+ "luma": 156,+ "salient": {+ "x": 0.35,+ "y": 0.4+ }+ },+ {+ "photoId": 147,+ "width": 3000,+ "height": 4000,+ "caption": null,+ "palette": [+ "#2e86ab:0.5",+ "#f6f5f0:0.3",+ "#3b3b3b:0.2"+ ],+ "busy": "58be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369cf2",+ "luma": 193,+ "salient": {+ "x": 0.65,+ "y": 0.55+ }+ },+ {+ "photoId": 148,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 16",+ "palette": [+ "#6a994e:0.45",+ "#e9d8a6:0.35",+ "#1f1f1f:0.2"+ ],+ "busy": "cf258be147ad0369cf258be147ad0369cf258be147ad0369cf258be147ad0369",+ "luma": 110,+ "salient": {+ "x": 0.3,+ "y": 0.45+ }+ }+ ],+ "gallery": [+ {+ "photoId": 132,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 0"+ },+ {+ "photoId": 133,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 134,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 135,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 136,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 4"+ },+ {+ "photoId": 137,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 138,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 139,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 140,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 8"+ },+ {+ "photoId": 141,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 142,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 143,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 144,+ "width": 3000,+ "height": 4000,+ "caption": "Gallery 12"+ },+ {+ "photoId": 145,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 146,+ "width": 4000,+ "height": 3000,+ "caption": null+ },+ {+ "photoId": 147,+ "width": 3000,+ "height": 4000,+ "caption": null+ },+ {+ "photoId": 148,+ "width": 4000,+ "height": 3000,+ "caption": "Gallery 16"+ }+ ]+ }+ }+}diff --git a/shared/src/book/design/design-book.spec.ts b/shared/src/book/design/design-book.spec.tsnew file mode 100644index 000000000..2e69a7048--- /dev/null+++ b/shared/src/book/design/design-book.spec.ts@@ -0,0 +1,305 @@+import { bookLevelFindings } from '../book-findings-design';+import { blankBook } from '../book-pages';+import {+ MAX_SPREADS,+ MAX_SPREAD_ELEMENTS,+ bookDocumentSchema,+ bookTextElementSchema,+ type BookDocument,+ type BookElement,+ type BookSpread,+} from '../book.schema';+import { pageFindings } from '../describe-spread';+import { designBook, type BookDesignInput, type BookDesignResult } from './design-book';+import type { BookDesignDirectivesInput } from './design-directives.schema';++import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';++/**+ * The whole-book design engine on three journeys (rich, sparse, no figures)+ * and a set of directives: every style, both densities, a page budget, a+ * scope, chapters by day and by place, a palette from the photos, captions+ * and excerpts, chapter maps, a locked page kept. Each design is checked for+ * its structure (the framing in order, every chapter there, the rhythm, the+ * budget, the caps, a document the save route takes) and for being clean:+ * no severe and no warn finding left on any page or on the book.+ */++type Name = 'rich' | 'sparse' | 'nostats';++const here = (file: string) => fileURLToPath(new URL(file, import.meta.url));+const fixtures = JSON.parse(readFileSync(here('./design-book.fixtures.json'), 'utf8')) as Record<+ Name,+ { input: BookDesignInput }+>;++/** The journey with ids minted by a counter, so a design is the same every run. */+function input(name: Name): BookDesignInput {+ let n = 0;+ return { ...fixtures[name].input, newId: (p) => `${p}-${++n}` };+}++const VARIANTS: [string, Name, BookDesignDirectivesInput][] = [+ ['minimal', 'rich', { style: 'minimal' }],+ ['editorial', 'rich', { style: 'editorial' }],+ ['journal', 'rich', { style: 'journal' }],+ ['bold', 'rich', { style: 'bold' }],+ ['scrapbook', 'rich', { style: 'scrapbook' }],+ ['airy', 'rich', { style: 'minimal', density: 'airy' }],+ ['dense', 'rich', { style: 'editorial', density: 'rich' }],+ ['budget', 'rich', { style: 'journal', pages: { min: 6, max: 10 } }],+ ['grow', 'rich', { style: 'minimal', pages: { min: 30 } }],+ ['scope', 'rich', { style: 'editorial', scope: { entryIds: [3, 4, 5, 6] } }],+ ['days', 'rich', { style: 'minimal', chapters: 'day' }],+ ['places', 'rich', { style: 'bold', chapters: 'place' }],+ ['palette', 'rich', { style: 'classic', palette: 'from_photos', type: { scale: 0.8 } }],+ ['captions', 'rich', { style: 'journal', text: { captions: 'photo', story: 'excerpt', excerptChars: 300 } }],+ ['maps', 'rich', { style: 'editorial', travel: { chapterMaps: true, dayBadges: false } }],+ ['sparse', 'sparse', { style: 'scrapbook' }],+ ['sparse-all', 'sparse', { style: 'minimal', photos: { pick: 'all' } }],+ ['nostats', 'nostats', { style: 'editorial' }],+ ['nostats-a5', 'nostats', { style: 'bold', preset: 'a5-landscape' }],+];++const FRAMING_ROLES = ['cover', 'first', 'last', 'back'];+const inner = (doc: BookDocument) => doc.spreads.filter((s) => s.role === 'inner');+const notInfo = (list: { severity: string }[]) => list.filter((f) => f.severity !== 'info');++/** Everything a design must be, whatever was asked of it. */+function checkStructure(result: BookDesignResult): void {+ const roles = result.doc.spreads.map((s) => s.role);+ expect(roles.slice(0, 2)).toEqual(['cover', 'first']);+ expect(roles.slice(-2)).toEqual(['last', 'back']);+ expect(roles.slice(2, -2).every((r) => r === 'inner')).toBe(true);+ expect(bookDocumentSchema.safeParse(result.doc).success).toBe(true);+ expect(result.doc.spreads.every((s) => s.elements.length <= MAX_SPREAD_ELEMENTS)).toBe(true);+ expect(new Set(result.doc.spreads.map((s) => s.id)).size).toBe(result.doc.spreads.length);+}++/** No severe and no warn finding, on any page or on the book, measured afresh. */+function checkClean(result: BookDesignResult, photos: BookDesignInput['photos']): void {+ expect(notInfo(result.findings)).toEqual([]);+ expect(result.plan.every((r) => r.findings.severe === 0 && r.findings.warn === 0)).toBe(true);+ for (const spread of result.doc.spreads) {+ const left = notInfo(pageFindings(spread, result.doc.page, photos));+ expect({ spread: spread.id, left }).toEqual({ spread: spread.id, left: [] });+ }+ expect(notInfo(bookLevelFindings(result.doc))).toEqual([]);+}++/** A loud spread (a hero, a panorama) is followed by a calm one, and heroes are four spreads apart. */+function checkRhythm(result: BookDesignResult): void {+ const beats = result.plan.filter((r) => r.action !== 'drop').map((r) => r.beat);+ const loud = (b: string) => b === 'hero' || b === 'pano';+ beats.forEach((b, i) => {+ if (i > 0 && loud(b)) expect(loud(beats[i - 1] as string)).toBe(false);+ });+ const heroes = beats.flatMap((b, i) => (b === 'hero' ? [i] : []));+ heroes.forEach((at, i) => {+ if (i > 0) expect(at - (heroes[i - 1] as number)).toBeGreaterThanOrEqual(4);+ });+}++/** Every entry with something to show opens a spread of its own (or is listed among the stations). */+function checkCoverage(result: BookDesignResult, entryIds: readonly number[]): void {+ const told = new Set<number>();+ for (const spread of result.doc.spreads) {+ if (spread.entryId != null) told.add(spread.entryId);+ for (const el of spread.elements) if (el.kind === 'text' && el.binding?.entryId) told.add(el.binding.entryId);+ }+ expect(entryIds.filter((id) => !told.has(id))).toEqual([]);+}++const substantive = (name: Name, ids?: readonly number[]) =>+ fixtures[name].input.entries+ .filter((e) => !ids || ids.includes(e.id))+ .filter((e) => e.photos.length > 0 || (e.story ?? '').trim())+ .map((e) => e.id);++describe('design_book', () => {+ for (const [label, name, directives] of VARIANTS) {+ it(`BOOKDSN-001: designs the ${label} variant with its framing in order, its pages valid and none left with a fault`, () => {+ const fx = input(name);+ const result = designBook(null, fx, directives);+ checkStructure(result);+ checkRhythm(result);+ checkClean(result, fx.photos);+ });+ }++ it('BOOKDSN-002: gives every entry with photos or words a spread, in the order of the journey', () => {+ for (const style of ['minimal', 'editorial', 'scrapbook'] as const) {+ checkCoverage(designBook(null, input('rich'), { style }), substantive('rich'));+ }+ checkCoverage(designBook(null, input('rich'), { style: 'minimal', chapters: 'day' }), substantive('rich'));+ checkCoverage(designBook(null, input('sparse'), { style: 'journal' }), substantive('sparse'));+ const scoped = designBook(null, input('rich'), { style: 'editorial', scope: { entryIds: [3, 4, 5, 6] } });+ checkCoverage(scoped, substantive('rich', [3, 4, 5, 6]));+ const others = scoped.doc.spreads.filter((s) => s.entryId != null && ![3, 4, 5, 6].includes(s.entryId));+ expect(others).toEqual([]);+ });++ it('BOOKDSN-003: keeps to the page budget, and grows when more pages are asked for', () => {+ const tight = designBook(null, input('rich'), { style: 'journal', pages: { min: 6, max: 10 } });+ expect(inner(tight.doc).length).toBeLessThanOrEqual(10);+ expect(tight.photos.left_out.some((p) => p.reason === 'page_budget')).toBe(true);+ const natural = inner(designBook(null, input('rich'), { style: 'minimal' }).doc).length;+ const grown = inner(designBook(null, input('rich'), { style: 'minimal', pages: { min: 30 } }).doc).length;+ expect(grown).toBeGreaterThan(natural);+ });++ it('BOOKDSN-004: sets every page in two typefaces at most, and colours from the photos when asked', () => {+ const result = designBook(null, input('rich'), { style: 'editorial' });+ expect(result.style).toMatchObject({ heading: 'playfair', body: 'garamond', paper: '#faf8f4' });+ const fonts = new Set(result.doc.spreads.flatMap((s) => s.elements.flatMap((e) => ('font' in e ? [e.font] : []))));+ expect([...fonts].sort()).toEqual(['garamond', 'playfair']);+ const tinted = designBook(null, input('rich'), { style: 'minimal', palette: 'from_photos' });+ expect(tinted.style.accent).not.toBe(result.style.accent);+ const given = (accent: string) =>+ designBook(null, input('sparse'), { style: 'minimal', palette: { paper: '#ffffff', ink: '#111111', accent } });+ expect(given('#C2410C').style.accent).toBe('#c2410c');+ expect(given('#fafafa').style.accent).toBe('#111111');+ });++ it('BOOKDSN-005: binds the words the journey owns, and the cover and title page to the journey', () => {+ const result = designBook(null, input('rich'), { style: 'editorial' });+ const texts = result.doc.spreads.flatMap((s) => s.elements.filter((e) => e.kind === 'text'));+ const sources = new Set(texts.flatMap((t) => (t.kind === 'text' && t.binding ? [t.binding.source] : [])));+ expect([...sources]).toEqual(expect.arrayContaining(['journey.title', 'entry.title', 'entry.date', 'entry.story']));+ const cover = result.doc.spreads[0] as BookSpread;+ expect(cover.elements.some((e) => e.kind === 'photo')).toBe(true);+ const own = designBook(null, input('rich'), { style: 'minimal', cover: { title: 'Our coast' } });+ const title = (own.doc.spreads[0] as BookSpread).elements.find((e) => e.kind === 'text');+ expect(title).toMatchObject({ text: 'Our coast', binding: null });+ expect(own.doc.title).toBe('Our coast');+ });++ it('BOOKDSN-006: leaves a near duplicate out and says why, and keeps every photo with pick all', () => {+ const best = designBook(null, input('rich'), { style: 'minimal' });+ expect(best.photos.left_out.some((p) => p.reason === 'near_duplicate_of')).toBe(true);+ const sparse = designBook(null, input('sparse'), { style: 'minimal', photos: { pick: 'all' } });+ expect(sparse.photos.used.sort()).toEqual([900, 901, 902]);+ const without = designBook(null, input('sparse'), { style: 'minimal', photos: { exclude: [902] } });+ expect(without.photos.used).not.toContain(902);+ expect(without.photos.left_out).toContainEqual({ photoId: 902, reason: 'excluded' });+ });++ it('BOOKDSN-007: keeps a locked page as it is, takes the place of the stored pages of its entries, drops the rest', () => {+ const stored = storedBook();+ const result = designBook(stored, input('rich'), { style: 'minimal' });+ const locked = result.doc.spreads.find((s) => s.id === 'sp-locked');+ expect(locked).toEqual(stored.spreads[2]);+ expect(result.plan.find((r) => r.spreadId === 'sp-locked')?.action).toBe('keep');+ expect(result.plan.find((r) => r.spreadId === 'sp-entry')?.action).toBe('replace');+ expect(result.plan.find((r) => r.spreadId === 'sp-hand')?.action).toBe('drop');+ expect(result.doc.spreads[0]?.id).toBe('sp-cover');+ checkClean(result, input('rich').photos);+ const edited = designBook(stored, input('rich'), { style: 'minimal', keep: 'edited' });+ expect(edited.plan.find((r) => r.spreadId === 'sp-hand')?.action).toBe('keep');+ });++ it('BOOKDSN-008: lays the classic style over a stored book as the Auto layout, keeping the locked page', () => {+ const stored = storedBook();+ const result = designBook(stored, input('rich'), { style: 'classic' });+ expect(result.doc.spreads.find((s) => s.id === 'sp-locked')).toEqual(stored.spreads[2]);+ expect(result.plan.find((r) => r.spreadId === 'sp-cover')?.action).toBe('replace');+ checkStructure(result);+ });++ it('BOOKDSN-009: designs the same book twice from the same journey and seed', () => {+ const a = designBook(null, input('rich'), { style: 'editorial', seed: 7 });+ const b = designBook(null, input('rich'), { style: 'editorial', seed: 7 });+ expect(JSON.stringify(b)).toBe(JSON.stringify(a));+ const c = designBook(null, input('rich'), { style: 'editorial', seed: 8 });+ expect(JSON.stringify(c.doc)).not.toBe(JSON.stringify(a.doc));+ });++ it('BOOKDSN-010: honours a new format only for a book with nothing on it yet', () => {+ const fresh = designBook(null, input('nostats'), { style: 'bold', preset: 'a5-landscape' });+ expect(fresh.doc.page).toMatchObject({ preset: 'a5-landscape', pageWidth: 210, pageHeight: 148 });+ const kept = designBook(storedBook(), input('rich'), { style: 'bold', preset: 'a5-landscape' });+ expect(kept.doc.page.preset).toBe('square-210');+ });++ it('BOOKDSN-011: runs classic as the Auto layout only when nothing more is asked, and measures its pages', () => {+ const photos = input('rich').photos;+ const auto = designBook(null, input('rich'), { style: 'classic' });+ expect(inner(auto.doc).length).toBeGreaterThan(4);+ for (const row of auto.plan) {+ const spread = auto.doc.spreads.find((s) => s.id === row.spreadId) as BookSpread;+ const left = pageFindings(spread, auto.doc.page, photos);+ expect(row.findings.severe).toBe(left.filter((f) => f.severity === 'severe').length);+ expect(row.findings.warn).toBe(left.filter((f) => f.severity === 'warn').length);+ }+ const budgeted = designBook(null, input('rich'), { style: 'classic', pages: { max: 4 } });+ expect(inner(budgeted.doc).length).toBeLessThanOrEqual(4);+ expect(budgeted.style).toMatchObject({ heading: 'sans', body: 'sans', paper: '#ffffff' });+ const titled = designBook(null, input('rich'), { style: 'classic', cover: { title: 'Our coast' } });+ const title = (titled.doc.spreads[0] as BookSpread).elements.find((e) => e.kind === 'text');+ expect(title).toMatchObject({ text: 'Our coast', binding: null });+ });++ it('BOOKDSN-012: holds a small page budget as a hard limit, the framing pages counted in it', () => {+ for (const style of ['editorial', 'bold'] as const) {+ const result = designBook(null, input('rich'), { style, pages: { max: 2 } });+ checkStructure(result);+ expect(inner(result.doc).length).toBeLessThanOrEqual(2);+ expect(result.notes.some((n) => n.includes('no room for'))).toBe(true);+ }+ const one = designBook(null, input('rich'), { style: 'minimal', pages: { min: 5, max: 1 } });+ expect(inner(one.doc).length).toBeLessThanOrEqual(1);+ });++ it('BOOKDSN-013: lays the cover out by the cover layout asked for, the same way every time', () => {+ const banded = designBook(null, input('rich'), { style: 'minimal', cover: { template: 'cover-band' } });+ const cover = banded.doc.spreads[0] as BookSpread;+ const photo = cover.elements.find((e) => e.kind === 'photo');+ expect(photo).toBeDefined();+ expect((photo?.frame.y ?? 0) + (photo?.frame.h ?? 0)).toBeLessThan(banded.doc.page.pageHeight);+ const bound = cover.elements.some((e) => e.kind === 'text' && e.binding?.source === 'journey.title');+ expect(bound).toBe(true);+ const again = designBook(null, input('rich'), { style: 'minimal', cover: { template: 'cover-band' } });+ expect(JSON.stringify(again.doc)).toBe(JSON.stringify(banded.doc));+ });++ it('BOOKDSN-014: stays within the spread cap beside many kept pages, the closing pages kept', () => {+ const stored = storedBook();+ const lockedPage = stored.spreads[2] as BookSpread;+ const many = Array.from({ length: MAX_SPREADS - 6 }, (_, i): BookSpread => ({+ ...lockedPage,+ id: `sp-l${i}`,+ elements: lockedPage.elements.map((e) => ({ ...e, id: `t-l${i}` })),+ }));+ const [cover, first] = stored.spreads;+ const full: BookDocument = {+ ...stored,+ spreads: [cover as BookSpread, first as BookSpread, ...many, ...stored.spreads.slice(-2)],+ };+ for (const style of ['minimal', 'classic'] as const) {+ const result = designBook(full, input('rich'), { style });+ checkStructure(result);+ expect(result.doc.spreads.length).toBeLessThanOrEqual(MAX_SPREADS);+ expect(inner(result.doc).length).toBeLessThanOrEqual(MAX_SPREADS - 4);+ expect(many.every((p) => result.doc.spreads.some((s) => s.id === p.id))).toBe(true);+ expect(result.notes.length).toBeGreaterThan(0);+ }+ });+});++/** A stored book: a page locked by hand, a page of entry 3, and a page made by hand. */+function storedBook(): BookDocument {+ const doc = blankBook({ title: 'Atlantic coast', newId: (p) => `${p}-s` });+ const ids = ['sp-cover', 'sp-first', 'sp-locked', 'sp-last', 'sp-back'];+ const spreads = doc.spreads.map((s, i) => ({ ...s, id: ids[i] as string }));+ const frame = { x: 230, y: 30, w: 150, h: 12 };+ const words = { kind: 'text', frame, text: 'Kept', font: 'inter', locked: true };+ const lockedText = bookTextElementSchema.parse({ id: 't-locked', ...words }) as BookElement;+ spreads[2] = { ...(spreads[2] as BookSpread), elements: [lockedText], entryId: 6 };+ const note = bookTextElementSchema.parse({ id: 't-hand', kind: 'text', frame, text: 'Ours', font: 'inter' });+ const entryPage = { ...(spreads[2] as BookSpread), id: 'sp-entry', elements: [], entryId: 3 };+ const handPage = { ...(spreads[2] as BookSpread), id: 'sp-hand', elements: [note as BookElement], entryId: null };+ spreads.splice(3, 0, entryPage, handPage);+ return { ...doc, spreads };+}diff --git a/shared/src/book/design/design-book.ts b/shared/src/book/design/design-book.tsnew file mode 100644index 000000000..f108f1766--- /dev/null+++ b/shared/src/book/design/design-book.ts@@ -0,0 +1,280 @@+import { buildBook, distributeGallery } from '../auto/auto-book';+import type { AutoEntry, AutoInput, AutoPhoto } from '../auto/auto-types';+import { bookLevelFindings, sortBookFindings } from '../book-findings-design';+import { bookElementId } from '../book-ids';+import type { BookPhotoInfo } from '../book-ops-core';+import type { BookFinding } from '../book-ops.schema';+import { bookPageSetupForPreset } from '../book-pages';+import type { BookTravelContext } from '../book-travel';+import { MAX_BOOK_TITLE, MAX_SPREADS, type BookDocument, type BookPageSetup, type BookSpread } from '../book.schema';+import { pageFindings } from '../describe-spread';+import type { PhotoPickCandidate } from '../photo-pick';+import type { ComposeCtx } from './design-compose';+import {+ bookDesignDirectivesSchema,+ type BookDesignDirectives,+ type BookDesignDirectivesInput,+} from './design-directives.schema';+import { composeBack, composeCover, composeTitlePage, stationsPerSpread } from './design-framing';+import { composeDesignedInner, type FramingNeeds } from './design-inner';+import { keepsStored, mergeDesign, type BookDesignPlanRow, type DesignedSpread } from './design-merge';+import type { BookDesignBeat } from './design-pacing';+import { choosePhotos, type BookDesignLeftOut } from './design-photos';+import { repairSpread } from './design-repair';+import { designGrid, designLook, paperBackground, type BookDesignLook } from './design-style';++/**+ * The assistant designs the whole photo book.+ *+ * Pure and deterministic for the same book, journey, directives and seed: the+ * server's `design_book` runs it and keeps the result as a draft until the+ * person approves it. `style: 'classic'` asking nothing the Auto layout cannot+ * do is the Studio's own Auto layout (`buildBook`) over the stored pages;+ * every other design composes the book from chapters, pacing, a page+ * grid, the photos' own palette and type, repairs every page against the+ * findings and answers what is left.+ */++export interface BookDesignInput extends AutoInput {+ /** The gallery's photos with their pixel signals, for the picker and the place chapters. */+ candidates: readonly PhotoPickCandidate[];+ /** The gallery as the book engine knows it: original sizes, palette, busy grid, salient point. */+ photos: readonly BookPhotoInfo[];+ /** Photos of the journey on no entry, shared out to the entries as the Studio does. */+ gallery?: readonly AutoPhoto[];+ distanceLabel?: string;+ prosLabel?: string;+ consLabel?: string;+}++export interface BookDesignResult {+ doc: BookDocument;+ plan: BookDesignPlanRow[];+ style: Pick<BookDesignLook, 'paper' | 'ink' | 'accent' | 'heading' | 'body'>;+ photos: { used: number[]; left_out: BookDesignLeftOut[] };+ /** What the repair passes could not fix, severe first. */+ findings: BookFinding[];+ notes: string[];+}++/** The entries the directives' scope names, in the order they came. */+function inScope(entries: readonly AutoEntry[], scope: BookDesignDirectives['scope']): AutoEntry[] {+ const ids = scope?.entryIds ? new Set(scope.entryIds) : null;+ return entries.filter((e) => {+ if (ids && !ids.has(e.id)) return false;+ if (scope?.from && (!e.date || e.date < scope.from)) return false;+ return !(scope?.to && (!e.date || e.date > scope.to));+ });+}++/** Entries in date order, the undated ones last as they came. */+function byDate(entries: readonly AutoEntry[]): AutoEntry[] {+ const dated = entries.filter((e) => e.date).sort((a, b) => (a.date ?? '').localeCompare(b.date ?? ''));+ return [...dated, ...entries.filter((e) => !e.date)];+}++/** A book with nothing on its pages yet: a new format may still be chosen for it. */+const isBlank = (doc: BookDocument | null) => !doc || doc.spreads.every((s) => !s.elements.length);++function pageFor(doc: BookDocument | null, input: BookDesignInput, directives: BookDesignDirectives): BookPageSetup {+ const base = doc?.page ?? input.page;+ if (!directives.preset || !isBlank(doc)) return base;+ return { ...bookPageSetupForPreset(directives.preset), pageNumbers: base.pageNumbers };+}++/**+ * Whether the classic style may run as the Studio's own Auto layout: only when+ * nothing is asked that `buildBook` cannot do. A page budget, a cover of the+ * person's, chapters by day or place, another density, caption, story or+ * travel choices go through the composer in the classic look, so no directive+ * is dropped without a word. Scope, keep, format and seed the Auto path honours.+ */+function classicOnly(d: BookDesignDirectives): boolean {+ if (d.style !== 'classic' || d.photos || d.palette || d.type) return false;+ if (d.pages || d.cover || d.text || d.travel) return false;+ return d.chapters === 'entry' && d.density === 'balanced';+}++/**+ * The designed pages within the spread cap: inner pages past `room` are left+ * off the end (the framing pages always stay), and the note says how many.+ */+function withinRoom(designed: readonly DesignedSpread[], room: number, notes: string[]): DesignedSpread[] {+ const inner = designed.filter((d) => d.spread.role === 'inner');+ const over = inner.length - Math.max(0, room);+ if (over <= 0) return [...designed];+ const cut = new Set(inner.slice(inner.length - over).map((d) => d.spread.id));+ notes.push(`the book holds ${MAX_SPREADS} spreads, so the last ${over} designed pages are left out`);+ return designed.filter((d) => !cut.has(d.spread.id));+}++/** Inner spreads the book has room for once the stored pages it keeps are counted. */+const roomFor = (doc: BookDocument | null, keep: BookDesignDirectives['keep']) =>+ MAX_SPREADS - 4 - (doc?.spreads ?? []).filter((s) => s.role === 'inner' && keepsStored(s, keep)).length;++/** The travel context the travel elements read: the journey's figures, route, entries and labels. */+function travelOf(input: BookDesignInput, entries: readonly AutoEntry[]): BookTravelContext {+ return {+ locale: input.locale,+ stats: input.stats,+ path: input.path ?? [],+ entries,+ labels: {+ day: input.dayLabel,+ stations: input.stationsLabel,+ summary: input.summaryLabel,+ countries: input.countriesLabel,+ distance: input.distanceLabel ?? '',+ pros: input.prosLabel ?? '',+ cons: input.consLabel ?? '',+ },+ };+}++/** The beat a page of the Auto layout plays, read from what it holds. */+function classicBeat(spread: BookSpread): BookDesignBeat {+ if (spread.role !== 'inner') return spread.role;+ if (spread.entryId != null) return 'opener';+ const has = (kind: BookSpread['elements'][number]['kind']) => spread.elements.some((e) => e.kind === kind);+ if (has('stats') && has('map')) return 'summary';+ if (spread.elements.some((e) => e.kind === 'countries' && e.codes.length > 1)) return 'countries';+ return 'stations';+}++function classicDesign(+ doc: BookDocument | null,+ input: BookDesignInput,+ directives: BookDesignDirectives,+ entries: AutoEntry[],+): BookDesignResult {+ const newId = input.newId ?? bookElementId;+ const placed = input.gallery ? distributeGallery(entries, input.gallery) : entries;+ const page = pageFor(doc, input, directives);+ const built = buildBook({ ...input, entries: placed, page, newId });+ const notes: string[] = [];+ // The Auto layout is not repaired (it is the Studio's own, page for page),+ // but every page is measured, so the plan and the findings say what it left.+ const all = built.spreads.map((spread): DesignedSpread => ({+ spread,+ beat: classicBeat(spread),+ chapter: entries.find((e) => e.id === spread.entryId)?.title ?? null,+ findings: pageFindings(spread, page, input.photos),+ }));+ const designed = withinRoom(all, roomFor(doc, directives.keep), notes);+ const merged = mergeDesign(doc, designed, directives.keep);+ const finalDoc: BookDocument = {+ ...built,+ spreads: merged.spreads,+ ...(doc?.layouts ? { layouts: doc.layouts } : {}),+ };+ const residual = designed.flatMap((d) => d.findings.filter((f) => f.severity !== 'info'));+ return {+ doc: finalDoc,+ plan: merged.plan,+ style: { paper: '#ffffff', ink: '#1a1a1a', accent: '#c2410c', heading: 'sans', body: 'sans' },+ photos: { used: [...new Set(merged.plan.flatMap((r) => (r.action === 'drop' ? [] : r.photoIds)))], left_out: [] },+ findings: sortBookFindings([...residual, ...bookLevelFindings(finalDoc)]),+ notes,+ };+}++/** The photo the cover takes: the one asked for, else the journey's cover, else the first photo the book uses. */+function coverPhoto(+ input: BookDesignInput,+ directives: BookDesignDirectives,+ used: readonly AutoPhoto[],+): AutoPhoto | null {+ const want = directives.photos?.coverPhotoId ?? input.coverPhotoId;+ const excluded = want != null && (directives.photos?.exclude ?? []).includes(want);+ const info = want == null || excluded ? undefined : input.photos.find((p) => p.photoId === want);+ if (info) return { photoId: info.photoId, width: info.width ?? null, height: info.height ?? null };+ return used[0] ?? null;+}++/**+ * Design the whole book. `doc` is the stored book (null for a journey with+ * none); the result is a complete document laid over it, page ids kept where+ * a designed page takes a stored one's place.+ */+export function designBook(+ doc: BookDocument | null,+ input: BookDesignInput,+ raw: BookDesignDirectivesInput,+): BookDesignResult {+ const directives = bookDesignDirectivesSchema.parse(raw);+ const entries = inScope(input.entries, directives.scope);+ if (classicOnly(directives)) return classicDesign(doc, input, directives, entries);++ const newId = input.newId ?? bookElementId;+ const page = pageFor(doc, input, directives);+ const ordered = byDate(entries);+ const placed = input.gallery ? distributeGallery(ordered, input.gallery) : ordered;+ const choice = choosePhotos(placed, input.candidates, directives, input.photos);+ const usedPhotos = [...choice.byEntry.values()].flat();+ const usedInfos = input.photos.filter((p) => usedPhotos.some((u) => u.photoId === p.photoId));+ const look = designLook(directives, page, usedInfos);+ const c: ComposeCtx = {+ look,+ page,+ grid: designGrid(page),+ newId,+ locale: input.locale,+ infos: new Map(input.photos.map((p) => [p.photoId, p])),+ travel: travelOf(input, placed),+ directives,+ notes: [],+ };+ const needs: FramingNeeds = { room: roomFor(doc, directives.keep), perStations: stationsPerSpread(c) };+ const inner = composeDesignedInner(c, placed, choice, input, needs);++ const words = {+ title: input.title,+ subtitle: input.subtitle,+ ownTitle: directives.cover?.title,+ ownSubtitle: directives.cover?.subtitle,+ };+ const cover = coverPhoto(input, directives, usedPhotos);+ const titlePage = directives.style === 'editorial' || directives.style === 'journal';+ const first = titlePage ? composeTitlePage(c, words, placed) : blank(c, 'first');+ const framing: DesignedSpread[] = [+ { spread: composeCover(c, words, cover), beat: 'cover', chapter: null, findings: [] },+ { spread: first, beat: 'first', chapter: null, findings: [] },+ ];+ const closing: DesignedSpread[] = [+ { spread: blank(c, 'last'), beat: 'last', chapter: null, findings: [] },+ { spread: composeBack(c, words, placed), beat: 'back', chapter: null, findings: [] },+ ];+ const repairCtx = { page, photos: input.photos, look, newId };+ const designed = [...framing, ...inner.spreads, ...closing].map((d): DesignedSpread => {+ const fixed = repairSpread(d.spread, repairCtx);+ return { ...d, spread: fixed.spread, findings: fixed.findings };+ });++ const merged = mergeDesign(doc, designed, directives.keep);+ const title = (directives.cover?.title ?? input.title).slice(0, MAX_BOOK_TITLE);+ const pageNumbers = { ...page.pageNumbers, font: look.body };+ const result: BookDocument = {+ version: 1,+ title,+ page: { ...page, pageNumbers: { ...pageNumbers, startAt: 1 } },+ spreads: merged.spreads,+ ...(doc?.layouts ? { layouts: doc.layouts } : {}),+ };+ const residual = designed.flatMap((d) => d.findings.filter((f) => f.severity !== 'info'));+ return {+ doc: result,+ plan: merged.plan,+ style: { paper: look.paper, ink: look.ink, accent: look.accent, heading: look.heading, body: look.body },+ photos: {+ used: [...new Set(merged.plan.flatMap((r) => (r.action === 'drop' ? [] : r.photoIds)))],+ left_out: [...choice.leftOut, ...inner.leftOut],+ },+ findings: sortBookFindings([...residual, ...bookLevelFindings(result)]),+ notes: [...new Set([...c.notes, ...inner.notes])],+ };+}++/** An empty single page of a role, on the book's paper. */+function blank(c: ComposeCtx, role: 'first' | 'last'): BookSpread {+ return { id: c.newId('sp'), role, background: paperBackground(c.look), elements: [], parked: [], entryId: null };+}diff --git a/shared/src/book/design/design-compose.ts b/shared/src/book/design/design-compose.tsnew file mode 100644index 000000000..9bab360c8--- /dev/null+++ b/shared/src/book/design/design-compose.ts@@ -0,0 +1,346 @@+import type { AutoEntry, AutoPhoto } from '../auto/auto-types';+import { MIN_PRINT_DPI, textHeightNeeded } from '../book-findings';+import type { BookPhotoInfo } from '../book-ops-core';+import { formatBookDate } from '../book-text';+import { bookBadgeValue, bookTravelBadge, type BookTravelContext } from '../book-travel';+import type {+ BookElement,+ BookFrame,+ BookPageSetup,+ BookPhotoElement,+ BookShapeElement,+ BookTextElement,+} from '../book.schema';+import type { BookDesignDirectives } from './design-directives.schema';+import { dpiIn } from './design-photos';+import type { BookDesignGrid, BookDesignLook } from './design-style';++/**+ * The parts a designed page is built from, on the book's grid and in its+ * look: photos placed at print resolution with their focal point on the+ * detail, texts measured before they are set (a frame is as tall as its words+ * need), the title block of a chapter, a story that continues or is cut at a+ * sentence when it does not fit.+ *+ * Everything sits inside the margins or runs exactly to the bleed: nothing+ * stops a few millimetres short of an edge, no words cross the fold, nothing+ * lies on top of a picture except words on a scrim.+ */++export interface ComposeCtx {+ look: BookDesignLook;+ page: BookPageSetup;+ grid: BookDesignGrid;+ newId: (prefix: string) => string;+ locale: string;+ infos: ReadonlyMap<number, BookPhotoInfo>;+ travel: BookTravelContext;+ directives: BookDesignDirectives;+ notes: string[];+}++export type Side = 'left' | 'right' | 'single';++const r2 = (v: number) => Math.round(v * 100) / 100;++export const frameOf = (x: number, y: number, w: number, h: number): BookFrame => ({+ x: r2(x),+ y: r2(y),+ w: r2(w),+ h: r2(h),+});++/** Millimetres scaled from a 210 mm page to this one. */+export const scaled = (c: ComposeCtx, v: number) => (v * c.grid.pageWidth) / 210;++/** Where a page starts on its spread. */+export const pageX = (c: ComposeCtx, side: Side) => (side === 'right' ? c.grid.pageWidth : 0);++/** A page's live area: inside the margins. */+export function liveBox(c: ComposeCtx, side: Side): BookFrame {+ const { margin: m, pageWidth: PW, pageHeight: H } = c.grid;+ return frameOf(pageX(c, side) + m, m, PW - m * 2, H - m * 2);+}++/** A whole page to the bleed, stopping at the fold on a spread. */+export function bleedPage(c: ComposeCtx, side: Side): BookFrame {+ const { bleed: b, pageWidth: PW, pageHeight: H } = c.grid;+ if (side === 'single') return frameOf(-b, -b, PW + b * 2, H + b * 2);+ return frameOf(side === 'left' ? -b : PW, -b, PW + b, H + b * 2);+}++/** The whole spread to the bleed. */+export function bleedSpread(c: ComposeCtx): BookFrame {+ const { bleed: b, pageWidth: PW, pageHeight: H } = c.grid;+ return frameOf(-b, -b, PW * 2 + b * 2, H + b * 2);+}++export const other = (side: 'left' | 'right'): 'left' | 'right' => (side === 'left' ? 'right' : 'left');++// ── photos ─────────────────────────────────────────────────────────────────++/** A frame at least `MIN_PRINT_DPI` for this photo: the frame itself, or a smaller one centred in it. */+function printable(c: ComposeCtx, photo: AutoPhoto, frame: BookFrame): BookFrame {+ const dpi = dpiIn(photo, c.infos.get(photo.photoId), frame);+ if (dpi === null || dpi >= MIN_PRINT_DPI) return frame;+ const k = (dpi / MIN_PRINT_DPI) * 0.98;+ const w = frame.w * k;+ const h = frame.h * k;+ return frameOf(frame.x + (frame.w - w) / 2, frame.y + (frame.h - h) / 2, w, h);+}++/** Whether a photo prints sharply in this frame (or its size is unknown). */+export function printsAt(c: ComposeCtx, photo: AutoPhoto, frame: BookFrame): boolean {+ const dpi = dpiIn(photo, c.infos.get(photo.photoId), frame);+ return dpi === null || dpi >= MIN_PRINT_DPI;+}++interface PhotoOpts {+ /** Runs to the bleed: never decorated or turned, and moved into the margins when it would print soft. */+ bleed?: { side: Side };+ /** The focal point across, when the frame crosses the fold and the detail must stay off it. */+ focalX?: number;+ turn?: number;+}++/** A photo element: its focal point on the picture's detail when known, the style's frame around it. */+export function photoEl(c: ComposeCtx, photo: AutoPhoto, frame: BookFrame, opts: PhotoOpts = {}): BookPhotoElement {+ const info = c.infos.get(photo.photoId);+ let placed = frame;+ if (opts.bleed && !printsAt(c, photo, frame)) placed = printable(c, photo, liveBox(c, opts.bleed.side));+ else if (!opts.bleed) placed = printable(c, photo, frame);+ const framed = !opts.bleed || placed !== frame;+ return {+ id: c.newId('p'),+ kind: 'photo',+ frame: placed,+ rotation: framed ? (opts.turn ?? 0) : 0,+ opacity: 1,+ locked: false,+ photoId: photo.photoId,+ fit: 'cover',+ focalX: opts.focalX ?? info?.salient?.x ?? 0.5,+ focalY: info?.salient?.y ?? 0.5,+ radius: 0,+ filter: 'none',+ mask: null,+ frameStyle: framed ? c.look.frameStyle : 'none',+ };+}++/** A scrapbook's slight turn, alternating; nothing for the other styles. */+export const turnOf = (c: ComposeCtx, i: number) => (c.look.tilt ? (i % 2 === 0 ? -c.look.tilt : c.look.tilt) : 0);++// ── texts ──────────────────────────────────────────────────────────────────++type TextRole = 'heading' | 'sub' | 'body' | 'caption' | 'meta';++const WEIGHT: Record<TextRole, BookTextElement['weight']> = {+ heading: 700,+ sub: 600,+ body: 400,+ caption: 500,+ meta: 600,+};+const LEADING: Record<TextRole, number> = { heading: 1.1, sub: 1.25, body: 1.5, caption: 1.35, meta: 1.3 };++interface TextOpts {+ binding?: BookTextElement['binding'];+ overridden?: boolean;+ color?: string;+ align?: BookTextElement['align'];+ size?: number;+}++/** A text in the book's look, its frame as tall as its words need. */+export function textEl(+ c: ComposeCtx,+ at: { x: number; y: number; w: number },+ words: string,+ role: TextRole,+ opts: TextOpts = {},+): BookTextElement {+ const defaultColour = role === 'caption' || role === 'meta' ? c.look.muted : c.look.ink;+ const el: BookTextElement = {+ id: c.newId('t'),+ kind: 'text',+ frame: frameOf(at.x, at.y, at.w, 10),+ rotation: 0,+ opacity: 1,+ locked: false,+ text: words,+ font: role === 'heading' || role === 'sub' ? c.look.heading : c.look.body,+ size: opts.size ?? c.look.sizes[role],+ weight: WEIGHT[role],+ italic: false,+ align: opts.align ?? 'left',+ leading: LEADING[role],+ tracking: role === 'meta' ? 0.08 : 0,+ color: opts.color ?? defaultColour,+ binding: opts.binding ?? null,+ overridden: opts.overridden ?? false,+ };+ return { ...el, frame: frameOf(at.x, at.y, at.w, textHeightNeeded(el) + 1.2) };+}++/** A heading that fits `maxH`: set smaller, down to the sub size, until it does. */+export function headingEl(+ c: ComposeCtx,+ at: { x: number; y: number; w: number },+ words: string,+ maxH: number,+ opts: TextOpts = {},+): BookTextElement {+ let size = c.look.sizes.heading;+ let el = textEl(c, at, words, 'heading', { ...opts, size });+ while (el.frame.h > maxH && size > c.look.sizes.sub) {+ size = Math.max(c.look.sizes.sub, size - 2);+ el = textEl(c, at, words, 'heading', { ...opts, size });+ }+ return el;+}++const NEWLINE = String.fromCharCode(10);++/** Where the last sentence of `head` ends, or -1. */+function sentenceEnd(head: string): number {+ return Math.max(...['. ', '! ', '? ', NEWLINE].map((mark) => head.lastIndexOf(mark)));+}++/** A start of `words` at most `n` characters long, cut at a sentence end where one is near, else at a word. */+export function cutWords(words: string, n: number): string {+ if (words.length <= n) return words;+ const head = words.slice(0, n);+ const sentence = sentenceEnd(head);+ if (sentence > n * 0.5) return head.slice(0, sentence + 1).trimEnd();+ const space = head.lastIndexOf(' ');+ return space > 0 ? `${head.slice(0, space).trimEnd()}…` : '';+}++/** The longest start of `words` that fits a box at body size, cut at a sentence end where one is near. */+function cutToFit(c: ComposeCtx, words: string, box: { w: number; h: number }): string {+ const fits = (s: string) => textEl(c, { x: 0, y: 0, w: box.w }, s, 'body').frame.h <= box.h;+ if (fits(words)) return words;+ let lo = 0;+ let hi = words.length;+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ if (fits(`${words.slice(0, mid)}…`)) lo = mid;+ else hi = mid - 1;+ }+ return cutWords(words, lo);+}++// ── the title block ────────────────────────────────────────────────────────++interface TitleOpts {+ /** Words on a scrim over a photo: set in the scrim's colour. */+ onScrim?: boolean;+}++/**+ * A chapter's title block, top down in a box: the day chip, the date, the+ * title, the place, a short rule in the accent. Returns the elements and+ * where the block ends.+ */+export function titleBlock(+ c: ComposeCtx,+ entry: AutoEntry,+ box: BookFrame,+ opts: TitleOpts = {},+): { els: BookElement[]; bottom: number } {+ const els: BookElement[] = [];+ const colour = opts.onScrim ? c.look.onScrim : undefined;+ const captions = c.directives.text?.captions ?? 'entry';+ let y = box.y;+ if ((c.directives.travel?.dayBadges ?? true) && entry.dayNumber) {+ const value = bookBadgeValue(c.travel, 'day', entry);+ if (value) {+ const chip = frameOf(box.x, y, scaled(c, 24), scaled(c, 7));+ const badge = bookTravelBadge({ id: c.newId('bd'), frame: chip, variant: 'day', value });+ els.push({ ...badge, font: c.look.heading, accent: c.look.accent });+ y += chip.h + 4;+ }+ }+ if (captions !== 'none' && entry.date) {+ const words = formatBookDate(entry.date, c.locale);+ const binding = { source: 'entry.date' as const, entryId: entry.id, value: entry.date };+ if (words) {+ const date = textEl(c, { x: box.x, y, w: box.w }, words, 'meta', { binding, color: colour });+ els.push(date);+ y += date.frame.h + 2;+ }+ }+ const heading = entry.title || entry.location || '';+ if (heading) {+ const binding = { source: 'entry.title' as const, entryId: entry.id };+ const title = headingEl(c, { x: box.x, y, w: box.w }, heading, box.h * 0.45, { binding, color: colour });+ els.push(title);+ y += title.frame.h + 3;+ }+ if (captions !== 'none' && entry.title && entry.location) {+ const binding = { source: 'entry.location' as const, entryId: entry.id };+ const place = textEl(c, { x: box.x, y, w: box.w }, entry.location, 'caption', { binding, color: colour });+ els.push(place);+ y += place.frame.h + 3;+ }+ els.push(ruleEl(c, box.x, y + 1));+ return { els, bottom: y + 6 };+}++/** A short rule in the accent. */+export function ruleEl(c: ComposeCtx, x: number, y: number): BookShapeElement {+ return {+ id: c.newId('s'),+ kind: 'shape',+ frame: frameOf(x, y, scaled(c, 14), 0.5),+ rotation: 0,+ opacity: 1,+ locked: false,+ shape: 'rect',+ fill: c.look.accent,+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 0,+ };+}++/** A fading panel under words set on a photograph. */+export function scrimEl(c: ComposeCtx, frame: BookFrame): BookShapeElement {+ return {+ ...ruleEl(c, 0, 0),+ frame,+ fill: c.look.scrim,+ gradient: 'up',+ opacity: c.look.scrimOpacity,+ };+}++// ── the story ──────────────────────────────────────────────────────────────++/**+ * An entry's story in a box: bound when it fits whole; cut at a sentence+ * when it does not (no longer bound, said in the notes), with the rest handed+ * back for a quiet page when the story is to be set in full.+ */+export function storyEl(+ c: ComposeCtx,+ entry: AutoEntry,+ words: string,+ box: BookFrame,+ whole: boolean,+): { el: BookTextElement | null; rest: string } {+ const mode = c.directives.text?.story ?? 'full';+ const limit = mode === 'excerpt' ? (c.directives.text?.excerptChars ?? 600) : Infinity;+ const binding = { source: 'entry.story' as const, entryId: entry.id };+ if (!words || mode === 'none' || box.h < c.look.sizes.body * 1.6) return { el: null, rest: words };+ const fitting = cutToFit(c, cutWords(words, limit), box);+ if (!fitting) return { el: null, rest: words };+ const bound = whole && fitting === words;+ if (!bound) c.notes.push(`the story of entry ${entry.id} is cut to fit its page and no longer follows the journal`);+ const el = textEl(c, box, fitting, 'body', { binding, overridden: !bound });+ const rest = mode === 'full' && !bound ? words.slice(fitting.replace(/…$/, '').length).trim() : '';+ return { el, rest };+}diff --git a/shared/src/book/design/design-directives.schema.ts b/shared/src/book/design/design-directives.schema.tsnew file mode 100644index 000000000..90b438002--- /dev/null+++ b/shared/src/book/design/design-directives.schema.ts@@ -0,0 +1,80 @@+import { idSchema } from '../../common/primitives.schema';+import { bookCoverTemplateIdSchema } from '../book-ops.schema';+import { BOOK_FONTS_IDS, BOOK_METRICS, MAX_BOOK_TITLE, bookPageSetupSchema } from '../book.schema';++import { z } from 'zod';++/**+ * What the person wants of a whole-book design, as the assistant's+ * `design_book` takes it. The model maps free words ("calm, lots of white",+ * "like a magazine", "only Portugal") to these fields; the engine takes no free+ * text it would have to interpret. Every field is optional and bounded.+ */++const hex = z.string().regex(/^#[0-9a-fA-F]{6}$/, 'expected #rrggbb');+const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);+const pageCount = z.number().int().min(1).max(146);+const ids300 = z.array(idSchema).max(300);+const ids200 = z.array(idSchema).max(200);++export const BOOK_DESIGN_STYLES = ['classic', 'minimal', 'editorial', 'journal', 'bold', 'scrapbook'] as const;+export type BookDesignStyle = (typeof BOOK_DESIGN_STYLES)[number];++export const bookDesignDirectivesSchema = z.strictObject({+ style: z.enum(BOOK_DESIGN_STYLES).default('classic'),+ /** Photos per spread: airy 1 to 2, balanced 2 to 4, rich 4 to 6. */+ density: z.enum(['airy', 'balanced', 'rich']).default('balanced'),+ /** Inner spreads, the covers and the first and last page not counted. */+ pages: z.strictObject({ min: pageCount.optional(), max: pageCount.optional() }).optional(),+ scope: z.strictObject({ entryIds: ids200.optional(), from: isoDate.optional(), to: isoDate.optional() }).optional(),+ chapters: z.enum(['entry', 'day', 'place']).default('entry'),+ photos: z+ .strictObject({+ /** best: the photo-pick groups' best, near duplicates and blurry ones left out; all: every photo. */+ pick: z.enum(['best', 'all']).default('best'),+ perChapterMax: z.number().int().min(1).max(24).optional(),+ include: ids300.optional(),+ exclude: ids300.optional(),+ coverPhotoId: idSchema.optional(),+ })+ .optional(),+ cover: z+ .strictObject({+ template: bookCoverTemplateIdSchema.optional(),+ title: z.string().max(MAX_BOOK_TITLE).optional(),+ subtitle: z.string().max(MAX_BOOK_TITLE).optional(),+ })+ .optional(),+ type: z+ .strictObject({+ heading: z.enum(BOOK_FONTS_IDS).optional(),+ body: z.enum(BOOK_FONTS_IDS).optional(),+ scale: z.number().min(0.8).max(1.3).optional(),+ })+ .optional(),+ /** The book's colours: taken from the photos, ink only, or given; the style's own when absent. */+ palette: z.union([z.enum(['from_photos', 'ink']), z.strictObject({ paper: hex, ink: hex, accent: hex })]).optional(),+ text: z+ .strictObject({+ captions: z.enum(['none', 'entry', 'photo']).default('entry'),+ story: z.enum(['full', 'excerpt', 'none']).default('full'),+ excerptChars: z.number().int().min(80).max(1200).optional(),+ })+ .optional(),+ travel: z+ .strictObject({+ summary: z.boolean().default(true),+ countries: z.boolean().default(true),+ chapterMaps: z.boolean().default(false),+ dayBadges: z.boolean().default(true),+ metrics: z.array(z.enum(BOOK_METRICS)).min(1).max(7).optional(),+ })+ .optional(),+ /** What stays: pages holding a locked element, also hand-made pages, or nothing (a fresh book). */+ keep: z.enum(['nothing', 'locked', 'edited']).default('locked'),+ /** Only honoured for a blank or a new book. */+ preset: bookPageSetupSchema.shape.preset.unwrap().optional(),+ seed: z.number().int().min(0).max(2147483647).optional(),+});+export type BookDesignDirectives = z.infer<typeof bookDesignDirectivesSchema>;+export type BookDesignDirectivesInput = z.input<typeof bookDesignDirectivesSchema>;diff --git a/shared/src/book/design/design-framing.ts b/shared/src/book/design/design-framing.tsnew file mode 100644index 000000000..bdd420d57--- /dev/null+++ b/shared/src/book/design/design-framing.ts@@ -0,0 +1,263 @@+import type { AutoEntry, AutoPhoto } from '../auto/auto-types';+import { BOOK_COVER_TEMPLATES, applyBookTemplate } from '../book-layouts';+import { formatBookDate } from '../book-text';+import { bookTravelCountries, bookTravelMap, bookTravelStats } from '../book-travel';+import type { BookElement, BookMetric, BookSpread, BookTextElement } from '../book.schema';+import type { JourneyStats } from '../journey-stats.schema';+import {+ bleedPage,+ frameOf,+ headingEl,+ liveBox,+ photoEl,+ ruleEl,+ scaled,+ scrimEl,+ textEl,+ type ComposeCtx,+} from './design-compose';+import { paperBackground } from './design-style';++/**+ * The pages around the chapters: the cover, the title page, the journey at a+ * glance, its countries, the closing totals, the list of bare stops and the+ * back cover. Words the journey owns are bound to it (the title, the+ * subtitle, an entry's date and name) unless the person gave their own.+ */++const single = (c: ComposeCtx, role: BookSpread['role'], elements: BookElement[]): BookSpread => ({+ id: c.newId('sp'),+ role,+ background: paperBackground(c.look),+ elements,+ parked: [],+ entryId: null,+});++/** A title the journey owns, bound to it, or the person's own words, not bound. */+function titleWords(own: string | undefined, journey: string): { words: string; bound: boolean } {+ return own !== undefined && own.trim() ? { words: own, bound: false } : { words: journey, bound: true };+}++interface CoverWords {+ title: string;+ subtitle: string | null;+ ownTitle?: string;+ ownSubtitle?: string;+}++/** The cover: a photo to the bleed with the title on a scrim at its foot, or the title alone on the paper. */+export function composeCover(c: ComposeCtx, words: CoverWords, photo: AutoPhoto | null): BookSpread {+ const { pageWidth: PW, pageHeight: H, bleed: b, margin: m } = c.grid;+ const els: BookElement[] = [];+ const title = titleWords(words.ownTitle, words.title);+ const sub = titleWords(words.ownSubtitle, words.subtitle ?? '');+ const top = H * 0.6;+ if (photo) {+ els.push(photoEl(c, photo, bleedPage(c, 'single'), { bleed: { side: 'single' } }));+ els.push(scrimEl(c, frameOf(-b, top, PW + b * 2, H - top + b)));+ }+ const colour = photo ? c.look.onScrim : c.look.ink;+ const box = photo ? frameOf(m, top + m * 0.6, PW - m * 2, H - top - m * 1.6) : liveBox(c, 'single');+ const y = photo ? box.y : box.y + box.h * 0.35;+ if (title.words.trim()) {+ const binding = title.bound ? { source: 'journey.title' as const } : null;+ const head = headingEl(c, { x: box.x, y, w: box.w }, title.words, box.h * 0.6, { binding, color: colour });+ els.push(head);+ if (sub.words.trim()) {+ const subBinding = sub.bound ? { source: 'journey.subtitle' as const } : null;+ const at = { x: box.x, y: head.frame.y + head.frame.h + 3, w: box.w };+ els.push(textEl(c, at, sub.words, 'sub', { binding: subBinding, color: colour }));+ }+ }+ return withCoverTemplate(c, single(c, 'cover', els));+}++/**+ * The cover laid out by the cover layout the person asked for (`cover.template`),+ * its photo and its words carried over as the Templates panel carries them. The+ * words keep the book's typeface and take its ink; the repair pass puts a scrim+ * or the light ink under any that land on a busy photo. Ids come from the+ * design's own counter, so the same journey designs the same cover.+ */+function withCoverTemplate(c: ComposeCtx, cover: BookSpread): BookSpread {+ const wanted = c.directives.cover?.template;+ const tpl = wanted ? BOOK_COVER_TEMPLATES.find((t) => t.id === wanted) : undefined;+ if (!tpl) return cover;+ const laid = applyBookTemplate(cover, tpl, c.page);+ const elements = laid.elements.map((e): BookElement => {+ if (e.kind === 'text') return { ...e, id: c.newId('t'), color: c.look.ink };+ return { ...e, id: c.newId(e.kind.charAt(0)) };+ });+ return { ...laid, elements, parked: [] };+}++/** The dates a journey ran, as two lines (the first day and the last), or none. */+function spanLines(entries: readonly AutoEntry[], locale: string): string[] {+ const dated = entries.map((e) => e.date).filter((d): d is string => !!d);+ const dates = [...dated].sort();+ const first = dates[0];+ const last = dates[dates.length - 1];+ if (!first || !last) return [];+ const out = [formatBookDate(first, locale)];+ if (last !== first) out.push(formatBookDate(last, locale));+ return out.filter(Boolean);+}++/** Lines of small text stacked from `y`, each under the one before. */+function stack(c: ComposeCtx, lines: readonly string[], at: { x: number; y: number; w: number }): BookTextElement[] {+ const out: BookTextElement[] = [];+ let y = at.y;+ for (const line of lines) {+ const el = textEl(c, { x: at.x, y, w: at.w }, line, 'meta', { align: 'center' });+ out.push(el);+ y += el.frame.h + 1.5;+ }+ return out;+}++/** The title page an editorial or journal book opens on: the title, the subtitle and when it was. */+export function composeTitlePage(c: ComposeCtx, words: CoverWords, entries: readonly AutoEntry[]): BookSpread {+ const box = liveBox(c, 'single');+ const title = titleWords(words.ownTitle, words.title);+ const els: BookElement[] = [];+ if (!title.words.trim()) return single(c, 'first', els);+ const binding = title.bound ? { source: 'journey.title' as const } : null;+ const at = { x: box.x, y: box.y + box.h * 0.38, w: box.w };+ const head = headingEl(c, at, title.words, box.h * 0.3, { binding, align: 'center' });+ els.push(head);+ const lines = spanLines(entries, c.locale);+ els.push(...stack(c, lines, { x: box.x, y: head.frame.y + head.frame.h + 4, w: box.w }));+ return single(c, 'first', els);+}++/** The figures worth printing: the ones asked for, else everything the journey actually has, at most six. */+function metricsOf(c: ComposeCtx, stats: JourneyStats): BookMetric[] {+ const asked = c.directives.travel?.metrics;+ if (asked) return [...asked];+ const all: [BookMetric, number][] = [+ ['distance', stats.distance],+ ['days', stats.days],+ ['steps', stats.steps],+ ['photos', stats.photos],+ ['countries', stats.countries.length],+ ['furthest', stats.furthest],+ ];+ return all+ .filter(([, v]) => v > 0)+ .map(([k]) => k)+ .slice(0, 6);+}++/** A label over a page: small, in the ink, with a rule in the accent above it. */+function label(c: ComposeCtx, words: string, side: 'left' | 'right'): { els: BookElement[]; bottom: number } {+ const box = liveBox(c, side);+ const head = textEl(c, { x: box.x, y: box.y + 4, w: box.w }, words, 'sub');+ return { els: [ruleEl(c, box.x, box.y), head], bottom: head.frame.y + head.frame.h + scaled(c, 6) };+}++/** The route drawn and what it came to: the map on one page, the figures on the other. */+export function composeSummary(+ c: ComposeCtx,+ stats: JourneyStats,+ words: string,+ mapSide: 'left' | 'right',+): BookElement[] {+ const textSide = mapSide === 'left' ? 'right' : 'left';+ const els: BookElement[] = [];+ const map = bookTravelMap(c.travel, stats, { id: c.newId('mp'), frame: liveBox(c, mapSide), scope: 'journey' });+ els.push({ ...map, style: c.look.mapStyle, font: c.look.heading, color: c.look.ink, accent: c.look.accent });+ const head = label(c, words, textSide);+ els.push(...head.els);+ const metrics = metricsOf(c, stats);+ if (metrics.length) {+ const box = liveBox(c, textSide);+ const frame = frameOf(box.x, head.bottom, box.w, Math.min(box.h * 0.6, box.y + box.h - head.bottom));+ const figures = bookTravelStats(stats, { id: c.newId('st'), frame, metrics });+ els.push({ ...figures, font: c.look.heading, color: c.look.ink, accent: c.look.accent });+ }+ return els;+}++/** The countries, outlined and named in the book's language, beside their label. */+export function composeCountries(c: ComposeCtx, words: string): BookElement[] {+ const head = label(c, words, 'left');+ const box = liveBox(c, 'right');+ const countries = bookTravelCountries(c.travel, { id: c.newId('co'), frame: box });+ return [...head.els, { ...countries, font: c.look.heading, color: c.look.ink, accent: c.look.accent }];+}++/**+ * The stops nobody wrote about, as a list: the date and the name of each, a+ * column per page, in the order they happened. Answers how many it placed;+ * the rest go on the next stations spread.+ */+export function composeStations(+ c: ComposeCtx,+ entries: readonly AutoEntry[],+ words: string,+): { elements: BookElement[]; placed: number } {+ const head = label(c, words, 'left');+ const els: BookElement[] = [...head.els];+ let placed = 0;+ for (const side of ['left', 'right'] as const) {+ const box = liveBox(c, side);+ let y = side === 'left' ? head.bottom : box.y;+ while (placed < entries.length && els.length + 2 <= STATION_ELEMENT_CAP) {+ const row = stationRow(c, entries[placed] as AutoEntry, { x: box.x, y, w: box.w });+ if (row.bottom > box.y + box.h) break;+ els.push(...row.els);+ y = row.bottom + scaled(c, 4);+ placed++;+ }+ }+ return { elements: els, placed };+}++/** Elements a stations spread may hold: two a stop, under the 90 a spread may hold. */+const STATION_ELEMENT_CAP = 88;++/** One stop of the list: its date over its name, both bound to the entry. */+function stationRow(+ c: ComposeCtx,+ entry: AutoEntry,+ at: { x: number; y: number; w: number },+): { els: BookElement[]; bottom: number } {+ const els: BookElement[] = [];+ let y = at.y;+ if (entry.date) {+ const binding = { source: 'entry.date' as const, entryId: entry.id, value: entry.date };+ const date = textEl(c, { ...at, y }, formatBookDate(entry.date, c.locale), 'meta', { binding });+ els.push(date);+ y += date.frame.h + 1;+ }+ const name = entry.title || entry.location || '';+ if (name) {+ const line = textEl(c, { ...at, y }, name, 'body', { binding: { source: 'entry.title', entryId: entry.id } });+ els.push(line);+ y += line.frame.h;+ }+ return { els, bottom: y };+}++/** About how many stops one stations spread holds, for the page budget. */+export function stationsPerSpread(c: ComposeCtx): number {+ const box = liveBox(c, 'left');+ const row = textEl(c, box, 'May', 'meta').frame.h + 1 + textEl(c, box, 'Stop', 'body').frame.h + scaled(c, 4);+ return Math.max(2, Math.floor((box.h * 2 - scaled(c, 16)) / row));+}++/** The back cover: the title and when it was, small and centred, a full stop. */+export function composeBack(c: ComposeCtx, words: CoverWords, entries: readonly AutoEntry[]): BookSpread {+ const box = liveBox(c, 'single');+ const title = titleWords(words.ownTitle, words.title);+ const els: BookElement[] = [];+ if (title.words.trim()) {+ const binding = title.bound ? { source: 'journey.title' as const } : null;+ const at = { x: box.x, y: box.y + box.h * 0.45, w: box.w };+ const head = textEl(c, at, title.words, 'sub', { binding, align: 'center' });+ const below = { x: box.x, y: head.frame.y + head.frame.h + 3, w: box.w };+ els.push(head, ...stack(c, spanLines(entries, c.locale), below));+ }+ return single(c, 'back', els);+}diff --git a/shared/src/book/design/design-inner.ts b/shared/src/book/design/design-inner.tsnew file mode 100644index 000000000..2b25422f0--- /dev/null+++ b/shared/src/book/design/design-inner.ts@@ -0,0 +1,220 @@+import type { AutoEntry } from '../auto/auto-types';+import type { BookElement, BookSpread } from '../book.schema';+import type { BookDesignInput } from './design-book';+import type { ComposeCtx } from './design-compose';+import { composeCountries, composeStations, composeSummary } from './design-framing';+import type { DesignedSpread } from './design-merge';+import {+ buildChapters,+ fitChapters,+ naturalSpreads,+ newRhythm,+ planChapter,+ shareSpreads,+ type DesignChapter,+ type PlannedSpread,+} from './design-pacing';+import type { BookDesignLeftOut, DesignPhotoChoice } from './design-photos';+import {+ composeDuo,+ composeGrid,+ composeHero,+ composeOpener,+ composePano,+ composeQuiet,+ composeTrio,+ innerSpread,+ panoFits,+ type Composed,+} from './design-spreads';++/**+ * The inner pages of a designed book: the journey at a glance and its+ * countries, the chapters paced to the page budget, the closing totals.+ */++export interface FramingNeeds {+ /** Inner spreads the book has room for, the kept stored pages taken off. */+ room: number;+ /** Bare stops one stations spread holds. */+ perStations: number;+}++interface InnerResult {+ spreads: DesignedSpread[];+ leftOut: BookDesignLeftOut[];+ notes: string[];+}++type FramingKind = 'summary' | 'countries' | 'closing';++const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));++/** The inner framing pages the journey has something for: the summary, the countries, the closing totals. */+function framingInner(c: ComposeCtx): FramingKind[] {+ const stats = c.travel.stats;+ const travel = c.directives.travel;+ const out: FramingKind[] = [];+ if (!stats) return out;+ if ((travel?.summary ?? true) && stats.points.length >= 2) out.push('summary');+ if ((travel?.countries ?? true) && stats.countries.length >= 2) out.push('countries');+ const closes = c.directives.style === 'editorial' || c.directives.style === 'bold';+ if (closes && stats.points.length >= 2) out.push('closing');+ return out;+}++/** The most inner spreads the design may make: `pages.max`, and never past the room the book has. */+const innerCap = (c: ComposeCtx, needs: FramingNeeds) =>+ Math.max(0, Math.min(c.directives.pages?.max ?? needs.room, needs.room));++/**+ * The framing pages that fit beside at least one chapter spread: past the cap+ * the closing totals go first, then the countries, then the summary.+ */+function fittingFraming(all: readonly FramingKind[], cap: number): FramingKind[] {+ let out = [...all];+ for (const drop of ['closing', 'countries', 'summary'] as const) {+ if (out.length + 1 <= cap) break;+ out = out.filter((k) => k !== drop);+ }+ return out;+}++/** Spreads for the chapters, within the page budget the directives set (framing pages count as pages). */+function chapterBudget(c: ComposeCtx, natural: number, framing: number, cap: number): number {+ const lo = Math.min(c.directives.pages?.min ?? 1, cap);+ return Math.max(1, clamp(natural + framing, lo, Math.max(lo, cap)) - framing);+}++/**+ * The chapter pages within the cap. Stations pages take what their stops need+ * and a chapter may round up, so the end is cut here; the photos of a page cut+ * are said to be left out for the budget.+ */+function withinCap(body: DesignedSpread[], room: number, leftOut: BookDesignLeftOut[], notes: string[]) {+ const keep = Math.max(0, room);+ if (body.length <= keep) return body;+ const cut = body.slice(keep);+ for (const d of cut) {+ for (const e of d.spread.elements) {+ if (e.kind === 'photo' && e.photoId != null) leftOut.push({ photoId: e.photoId, reason: 'page_budget' });+ }+ }+ notes.push(`${cut.length} pages past the page budget are left out`);+ return body.slice(0, keep);+}++function framingElements(c: ComposeCtx, kind: FramingKind, input: BookDesignInput): BookElement[] {+ const stats = c.travel.stats;+ if (kind === 'countries') return composeCountries(c, input.countriesLabel);+ if (!stats) return [];+ return composeSummary(c, stats, input.summaryLabel, kind === 'summary' ? 'left' : 'right');+}++function framingSpread(c: ComposeCtx, kind: FramingKind, input: BookDesignInput): DesignedSpread {+ return { spread: innerSpread(c, framingElements(c, kind, input), null), beat: kind, chapter: null, findings: [] };+}++/** The pages of a list of bare stops: as many stations spreads as the stops need. */+function stationsSpreads(c: ComposeCtx, chapter: DesignChapter, input: BookDesignInput): DesignedSpread[] {+ const out: DesignedSpread[] = [];+ let rest = chapter.entries;+ while (rest.length) {+ const set = composeStations(c, rest, input.stationsLabel);+ if (!set.placed) break;+ out.push({ spread: innerSpread(c, set.elements, null), beat: 'stations', chapter: null, findings: [] });+ rest = rest.slice(set.placed);+ }+ return out;+}++const chapterName = (chapter: DesignChapter) => chapter.label ?? chapter.entries[0]?.title ?? null;++/** One planned spread, composed; the story still to set is carried from the opener to its quiet page. */+function composePlanned(c: ComposeCtx, plan: PlannedSpread, hand: 'left' | 'right', carry: string): Composed {+ const entry = plan.entry;+ const entryId = plan.chapter.entries[0]?.id ?? null;+ const [first, ...more] = plan.photos;+ switch (plan.beat) {+ case 'hero':+ if (entry && first) return composeHero(c, entry, first, hand);+ break;+ case 'pano':+ if (entry && first && panoFits(c, first)) return composePano(c, entry, first, more, hand);+ break;+ case 'quiet':+ return composeQuiet(c, entry, carry, first ?? null, hand);+ case 'duo':+ return composeDuo(c, plan.photos, hand, entryId);+ case 'trio':+ return composeTrio(c, plan.photos, hand, entryId);+ case 'grid':+ return composeGrid(c, plan.photos, hand, entryId);+ default:+ break;+ }+ if (entry) return composeOpener(c, entry, first ?? null, hand);+ return composeGrid(c, plan.photos, hand, entryId);+}++/** A chapter's spreads, composed from its plan, the photo page alternating across the book. */+function chapterSpreads(c: ComposeCtx, chapter: DesignChapter, plans: readonly PlannedSpread[], start: number) {+ const out: DesignedSpread[] = [];+ let carry = '';+ plans.forEach((plan, i) => {+ // A quiet page with no words left to set and no photo would be an empty spread: it is left out.+ if (plan.beat === 'quiet' && !carry && !plan.photos.length) return;+ const hand = (start + i + (c.directives.seed ?? 0)) % 2 === 0 ? 'left' : 'right';+ const done = composePlanned(c, plan, hand, carry);+ carry = done.rest;+ const spread: BookSpread = innerSpread(c, done.elements, chapter.entries[0]?.id ?? null);+ out.push({ spread, beat: plan.beat, chapter: chapterName(chapter), findings: [] });+ });+ const entry = chapter.entries[0];+ if (carry && entry && (c.directives.text?.story ?? 'full') === 'full') {+ c.notes.push(`part of the story of entry ${entry.id} found no page within the budget and is left out`);+ }+ return out;+}++/** Every inner page of the designed book, in order. */+export function composeDesignedInner(+ c: ComposeCtx,+ entries: readonly AutoEntry[],+ choice: DesignPhotoChoice,+ input: BookDesignInput,+ needs: FramingNeeds,+): InnerResult {+ const notes: string[] = [];+ const leftOut: BookDesignLeftOut[] = [];+ const cap = innerCap(c, needs);+ const wanted = framingInner(c);+ const framing = fittingFraming(wanted, cap);+ if (framing.length < wanted.length) {+ notes.push(`the page budget leaves no room for: ${wanted.slice(framing.length).join(', ')}`);+ }+ const naturalOf = (ch: DesignChapter) => naturalSpreads(ch, c.directives, needs.perStations);+ let chapters = buildChapters(entries, choice.byEntry, c.directives, input.candidates);+ const natural = chapters.map(naturalOf).reduce((a, b) => a + b, 0);+ const budget = chapterBudget(c, natural, framing.length, cap);+ if (budget < chapters.length) {+ notes.push(`${chapters.length} chapters share ${budget} spreads, so neighbouring chapters are combined`);+ chapters = fitChapters(chapters, budget);+ }+ const shares = shareSpreads(chapters, chapters.map(naturalOf), budget);+ const rhythm = newRhythm();+ const plan = { directives: c.directives, page: c.page, infos: c.infos };+ const body: DesignedSpread[] = [];+ chapters.forEach((chapter, i) => {+ if (chapter.stations) {+ body.push(...stationsSpreads(c, chapter, input));+ return;+ }+ const plans = planChapter(chapter, shares[i] ?? 1, rhythm, plan, leftOut);+ body.push(...chapterSpreads(c, chapter, plans, body.length));+ });+ const head = framing.filter((k) => k !== 'closing').map((k) => framingSpread(c, k, input));+ const tail = framing.filter((k) => k === 'closing').map((k) => framingSpread(c, k, input));+ const fitted = withinCap(body, cap - head.length - tail.length, leftOut, notes);+ return { spreads: [...head, ...fitted, ...tail], leftOut, notes };+}diff --git a/shared/src/book/design/design-merge.ts b/shared/src/book/design/design-merge.tsnew file mode 100644index 000000000..fa4929f67--- /dev/null+++ b/shared/src/book/design/design-merge.ts@@ -0,0 +1,150 @@+import type { BookFinding } from '../book-ops.schema';+import type { BookSpread } from '../book.schema';+import type { BookDesignDirectives } from './design-directives.schema';+import type { BookDesignBeat } from './design-pacing';++/**+ * A designed book laid over the stored one: which stored pages stay as they+ * are, which designed pages take a stored page's place (and its id, so the+ * Studio keeps its page), which are new, and which stored pages go. The plan+ * says it page by page, for the proposal card and the apply.+ */++export const BOOK_DESIGN_ACTIONS = ['keep', 'replace', 'insert', 'drop'] as const;+export type BookDesignAction = (typeof BOOK_DESIGN_ACTIONS)[number];++export interface BookDesignPlanRow {+ spreadId: string;+ /** Where the page sits in the designed book; a dropped page keeps its stored index. */+ index: number;+ action: BookDesignAction;+ beat: BookDesignBeat;+ chapter: string | null;+ entryId: number | null;+ photoIds: number[];+ findings: { severe: number; warn: number };+}++export interface DesignedSpread {+ spread: BookSpread;+ beat: BookDesignBeat;+ chapter: string | null;+ findings: BookFinding[];+}++const photoIdsOf = (spread: BookSpread) =>+ spread.elements.flatMap((e) => (e.kind === 'photo' && e.photoId != null ? [e.photoId] : []));++const hasLock = (spread: BookSpread) => spread.elements.some((e) => e.locked);++/**+ * Whether a stored page stays as it is: one holding a locked element (an+ * inner page only while the person keeps locked pages); with `edited` also a+ * page made by hand (no entry behind it, not blank).+ */+export function keepsStored(spread: BookSpread, keep: BookDesignDirectives['keep']): boolean {+ if (spread.role !== 'inner') return hasLock(spread);+ if (keep === 'nothing') return false;+ if (hasLock(spread)) return true;+ return keep === 'edited' && spread.entryId == null && spread.elements.length > 0;+}++interface Placed {+ spread: BookSpread;+ action: BookDesignAction;+ beat: BookDesignBeat;+ chapter: string | null;+ findings: BookFinding[];+}++const placedOf = (d: DesignedSpread, action: BookDesignAction, id?: string): Placed => ({+ spread: id ? { ...d.spread, id } : d.spread,+ action,+ beat: d.beat,+ chapter: d.chapter,+ findings: d.findings,+});++const keptOf = (spread: BookSpread, beat: BookDesignBeat): Placed => ({+ spread,+ action: 'keep',+ beat,+ chapter: null,+ findings: [],+});++/** The framing page of a role: the stored one when it holds a lock, else the designed one in its place. */+function framing(stored: readonly BookSpread[], designed: DesignedSpread, keep: BookDesignDirectives['keep']): Placed {+ const own = stored.find((s) => s.role === designed.spread.role);+ if (own && keepsStored(own, keep)) return keptOf(own, designed.beat);+ return own ? placedOf(designed, 'replace', own.id) : placedOf(designed, 'insert');+}++/** The inner pages: designed ones taking the place of the stored pages of their entry, kept ones where they were. */+function innerPages(+ stored: readonly BookSpread[],+ designed: readonly DesignedSpread[],+ keep: BookDesignDirectives['keep'],+): { pages: Placed[]; dropped: BookSpread[] } {+ const inner = stored.filter((s) => s.role === 'inner');+ const kept = new Set(inner.filter((s) => keepsStored(s, keep)).map((s) => s.id));+ const taken = new Map<string, number>();+ const free = (s: BookSpread) => !kept.has(s.id) && !taken.has(s.id);+ const pages = designed.map((d, i): Placed => {+ const match = inner.find((s) => free(s) && s.entryId != null && s.entryId === d.spread.entryId);+ if (!match) return placedOf(d, 'insert');+ taken.set(match.id, i);+ return placedOf(d, 'replace', match.id);+ });+ let lastTaken = -1;+ const after = new Map<number, BookSpread[]>();+ for (const s of inner) {+ const at = taken.get(s.id);+ if (at !== undefined) lastTaken = at;+ if (kept.has(s.id)) after.set(lastTaken, [...(after.get(lastTaken) ?? []), s]);+ }+ const ordered = [...(after.get(-1) ?? []).map((s) => keptOf(s, 'opener'))];+ pages.forEach((p, i) => ordered.push(p, ...(after.get(i) ?? []).map((s) => keptOf(s, 'opener'))));+ const dropped = inner.filter((s) => !kept.has(s.id) && !taken.has(s.id));+ return { pages: ordered, dropped };+}++const count = (findings: readonly BookFinding[], severity: BookFinding['severity']) =>+ findings.filter((f) => f.severity === severity).length;++/** The designed book over the stored one (or as a new book), and its plan. */+export function mergeDesign(+ doc: { spreads: readonly BookSpread[] } | null,+ designed: readonly DesignedSpread[],+ keep: BookDesignDirectives['keep'],+): { spreads: BookSpread[]; plan: BookDesignPlanRow[] } {+ const stored = doc?.spreads ?? [];+ const role = (r: BookSpread['role']) => designed.filter((d) => d.spread.role === r);+ const head = [...role('cover'), ...role('first')].map((d) => framing(stored, d, keep));+ const tail = [...role('last'), ...role('back')].map((d) => framing(stored, d, keep));+ const { pages, dropped } = innerPages(stored, role('inner'), keep);+ const all = [...head, ...pages, ...tail];+ const plan = all.map((p, index): BookDesignPlanRow => ({+ spreadId: p.spread.id,+ index,+ action: doc ? p.action : 'insert',+ beat: p.beat,+ chapter: p.chapter,+ entryId: p.spread.entryId,+ photoIds: photoIdsOf(p.spread),+ findings: { severe: count(p.findings, 'severe'), warn: count(p.findings, 'warn') },+ }));+ for (const s of dropped) {+ plan.push({+ spreadId: s.id,+ index: stored.indexOf(s),+ action: 'drop',+ beat: 'opener',+ chapter: null,+ entryId: s.entryId,+ photoIds: photoIdsOf(s),+ findings: { severe: 0, warn: 0 },+ });+ }+ return { spreads: all.map((p) => p.spread), plan };+}diff --git a/shared/src/book/design/design-pacing.ts b/shared/src/book/design/design-pacing.tsnew file mode 100644index 000000000..bbedbd474--- /dev/null+++ b/shared/src/book/design/design-pacing.ts@@ -0,0 +1,339 @@+import type { AutoEntry, AutoPhoto } from '../auto/auto-types';+import type { BookPhotoInfo } from '../book-ops-core';+import type { BookPageSetup } from '../book.schema';+import { pickBookPhotos, type PhotoPickCandidate } from '../photo-pick';+import type { BookDesignDirectives } from './design-directives.schema';+import { hasBurst, heroWorthy, isPanorama, pickEntriesOf, type BookDesignLeftOut } from './design-photos';++/**+ * The story of the book before its pages: which chapters, how many spreads+ * each gets, and the beat of every spread (opener or hero, a quiet page for a+ * long story, two, three or a grid of photos, a panorama), paced so the book+ * breathes: never one beat three times running, a loud spread followed by a+ * calm one, at most one hero in four spreads.+ */++export const BOOK_DESIGN_BEATS = [+ 'cover',+ 'first',+ 'summary',+ 'countries',+ 'opener',+ 'hero',+ 'story',+ 'quiet',+ 'grid',+ 'duo',+ 'trio',+ 'pano',+ 'map',+ 'stations',+ 'closing',+ 'last',+ 'back',+] as const;+export type BookDesignBeat = (typeof BOOK_DESIGN_BEATS)[number];++export interface DesignChapter {+ key: string;+ /** The place or day a chapter is of, when it is not one entry's. */+ label: string | null;+ /** The entries it tells, the first one opening it. */+ entries: AutoEntry[];+ photos: AutoPhoto[];+ /** Runs of bare stops, set as a list. */+ stations: boolean;+ burst: boolean;+}++export interface PlannedSpread {+ beat: BookDesignBeat;+ chapter: DesignChapter;+ /** The entry whose words the spread sets, when it sets any. */+ entry: AutoEntry | null;+ photos: AutoPhoto[];+}++const storyChars = (entries: readonly AutoEntry[]) => entries.reduce((n, e) => n + (e.story ?? '').trim().length, 0);++function entryChapter(entry: AutoEntry, photos: AutoPhoto[], pool: readonly PhotoPickCandidate[]): DesignChapter {+ const burst = hasBurst(photos, pool);+ return { key: `e${entry.id}`, label: null, entries: [entry], photos, stations: false, burst };+}++/** A run of bare stops, set as a list. */+const stationsChapter = (run: AutoEntry[]): DesignChapter => ({+ key: `s${run[0]?.id ?? 0}`,+ label: null,+ entries: run,+ photos: [],+ stations: true,+ burst: false,+});++/** Entries with substance each open a chapter; runs of bare ones become a list of stations. */+function byEntry(+ entries: readonly AutoEntry[],+ photosOf: (e: AutoEntry) => AutoPhoto[],+ candidates: readonly PhotoPickCandidate[],+): DesignChapter[] {+ const out: DesignChapter[] = [];+ let run: AutoEntry[] = [];+ const flush = () => {+ if (run.length) out.push(stationsChapter(run));+ run = [];+ };+ for (const entry of entries) {+ const photos = photosOf(entry);+ if (!photos.length && !(entry.story ?? '').trim()) {+ run.push(entry);+ continue;+ }+ flush();+ out.push(entryChapter(entry, photos, candidates));+ }+ flush();+ return out;+}++/** The entries of one date merged into a chapter, in date order. */+function byDay(+ entries: readonly AutoEntry[],+ photosOf: (e: AutoEntry) => AutoPhoto[],+ candidates: readonly PhotoPickCandidate[],+): DesignChapter[] {+ const days = new Map<string, AutoEntry[]>();+ for (const entry of entries) {+ const key = entry.date ?? `undated-${entry.id}`;+ days.set(key, [...(days.get(key) ?? []), entry]);+ }+ return [...days].map(([day, list]): DesignChapter => {+ const photos = list.flatMap(photosOf);+ const substance = photos.length > 0 || storyChars(list) > 0;+ return {+ key: `d${day}`,+ label: day,+ entries: list,+ photos,+ stations: !substance,+ burst: hasBurst(photos, candidates),+ };+ });+}++/**+ * Chapters by place: the photo picker's groups (photos within 250 m of each+ * other), each labelled by its nearest entry. Entries with words and no+ * photos of their own keep a chapter of their own, in date order.+ */+function byPlace(+ entries: readonly AutoEntry[],+ photosOf: (e: AutoEntry) => AutoPhoto[],+ candidates: readonly PhotoPickCandidate[],+): DesignChapter[] {+ const all = new Map(entries.flatMap(photosOf).map((p) => [p.photoId, p]));+ const result = pickBookPhotos(candidates, pickEntriesOf(entries, candidates), { limit: 60 });+ const out: { day: string; chapter: DesignChapter }[] = [];+ const placed = new Set<number>();+ for (const group of result.groups) {+ const photos = group.picks.flatMap((p) => all.get(p.photoId) ?? []).filter((p) => !placed.has(p.photoId));+ if (!photos.length) continue;+ photos.forEach((p) => placed.add(p.photoId));+ const entry = entries.find((e) => e.id === group.entryId);+ const chapter = {+ key: `p${out.length}`,+ label: group.place,+ entries: entry ? [entry] : [],+ photos,+ stations: false,+ burst: hasBurst(photos, candidates),+ };+ out.push({ day: group.day, chapter });+ }+ for (const entry of entries) {+ const rest = photosOf(entry).filter((p) => !placed.has(p.photoId));+ rest.forEach((p) => placed.add(p.photoId));+ const told = out.some((o) => o.chapter.entries.includes(entry));+ if (told && !rest.length) continue;+ if (!rest.length && !(entry.story ?? '').trim()) continue;+ out.push({ day: entry.date ?? '9999', chapter: entryChapter(entry, rest, candidates) });+ }+ return out.sort((a, b) => a.day.localeCompare(b.day)).map((o) => o.chapter);+}++/** The book's chapters, as the directives ask. */+export function buildChapters(+ entries: readonly AutoEntry[],+ byEntryPhotos: ReadonlyMap<number, AutoPhoto[]>,+ directives: BookDesignDirectives,+ candidates: readonly PhotoPickCandidate[],+): DesignChapter[] {+ const photosOf = (e: AutoEntry) => byEntryPhotos.get(e.id) ?? [];+ if (directives.chapters === 'day') return byDay(entries, photosOf, candidates);+ if (directives.chapters === 'place' && candidates.length) return byPlace(entries, photosOf, candidates);+ return byEntry(entries, photosOf, candidates);+}++/** Photos per spread the density aims at, and the most a spread takes. */+const DENSITY = { airy: { aim: 1.5, max: 2 }, balanced: { aim: 3, max: 4 }, rich: { aim: 5, max: 6 } } as const;++/** Characters an opener's text page holds before the story needs a page of its own. */+const OPENER_STORY_CHARS = 1400;++/** The spreads a chapter wants with nothing holding it back. */+export function naturalSpreads(chapter: DesignChapter, directives: BookDesignDirectives, perStations: number): number {+ if (chapter.stations) return Math.max(1, Math.ceil(chapter.entries.length / perStations));+ const aim = DENSITY[directives.density].aim;+ const rest = Math.max(0, chapter.photos.length - 1);+ const words = storyChars(chapter.entries) > OPENER_STORY_CHARS && directives.text?.story !== 'excerpt' ? 1 : 0;+ return 1 + Math.ceil(rest / aim) + words;+}++/** The most spreads a chapter can fill: one photo each, a quiet page for its words. */+const fullest = (chapter: DesignChapter) => (chapter.stations ? 1 : 1 + Math.max(0, chapter.photos.length - 1) + 1);++/**+ * Spreads per chapter for a total, by largest remainder on the chapters'+ * weight (photos and words), every chapter at least one, none more than it+ * can fill.+ */+export function shareSpreads(chapters: readonly DesignChapter[], natural: readonly number[], total: number): number[] {+ const want = natural.reduce((a, b) => a + b, 0);+ if (total === want) return [...natural];+ const weight = chapters.map((c) => c.photos.length + storyChars(c.entries) / 600 + 1);+ const sum = weight.reduce((a, b) => a + b, 0) || 1;+ const floor = chapters.map(() => 1);+ const room = Math.max(0, total - chapters.length);+ const raw = weight.map((w) => (room * w) / sum);+ const out = raw.map((r, i) => Math.min((floor[i] ?? 1) + Math.floor(r), fullest(chapters[i] as DesignChapter)));+ const order = raw.map((r, i) => ({ i, rem: r - Math.floor(r) })).sort((a, b) => b.rem - a.rem || a.i - b.i);+ let left = total - out.reduce((a, b) => a + b, 0);+ for (let pass = 0; left > 0 && pass < 4; pass++) {+ for (const { i } of order) {+ const chapter = chapters[i] as DesignChapter;+ if (left <= 0) break;+ if ((out[i] ?? 0) >= fullest(chapter)) continue;+ out[i] = (out[i] ?? 0) + 1;+ left--;+ }+ }+ return out;+}++/** Merge the two smallest neighbouring chapters until the book has no more chapters than spreads. */+export function fitChapters(chapters: readonly DesignChapter[], total: number): DesignChapter[] {+ const list = [...chapters];+ while (list.length > Math.max(1, total)) {+ let best = 0;+ let bestSize = Infinity;+ for (let i = 0; i + 1 < list.length; i++) {+ const a = list[i] as DesignChapter;+ const b = list[i + 1] as DesignChapter;+ const size = a.photos.length + b.photos.length + a.entries.length + b.entries.length;+ if (size < bestSize) {+ best = i;+ bestSize = size;+ }+ }+ const a = list[best] as DesignChapter;+ const b = list[best + 1] as DesignChapter;+ const merged = {+ key: `${a.key}+${b.key}`,+ label: a.label,+ entries: [...a.entries, ...b.entries],+ photos: [...a.photos, ...b.photos],+ stations: a.stations && b.stations,+ burst: a.burst || b.burst,+ };+ list.splice(best, 2, merged);+ }+ return list;+}++interface Rhythm {+ beats: BookDesignBeat[];+ lastHero: number;+}++const LOUD = new Set<BookDesignBeat>(['hero', 'pano']);++/** Whether a loud beat may come now: the spread before it was calm, and no hero in the last three. */+function loudAllowed(rhythm: Rhythm, beat: BookDesignBeat): boolean {+ const last = rhythm.beats[rhythm.beats.length - 1];+ if (last && (LOUD.has(last) || last === 'grid')) return false;+ return beat !== 'hero' || rhythm.beats.length - rhythm.lastHero >= 4;+}++/** The beat a run of photos makes on its own spread. */+function photoBeat(count: number): BookDesignBeat {+ if (count <= 1) return 'quiet';+ if (count === 2) return 'duo';+ if (count === 3) return 'trio';+ return 'grid';+}++interface PlanInput {+ directives: BookDesignDirectives;+ page: BookPageSetup;+ infos: ReadonlyMap<number, BookPhotoInfo>;+}++/** The chapter's opening spread: a hero when it has a photo for one and the rhythm allows, else the opener. */+function opening(chapter: DesignChapter, photos: AutoPhoto[], rhythm: Rhythm, input: PlanInput): PlannedSpread {+ const entry = chapter.entries[0] ?? null;+ const hero = photos.find((p) => heroWorthy(p, input.infos.get(p.photoId), input.page));+ if (entry && hero && loudAllowed(rhythm, 'hero')) {+ photos.splice(photos.indexOf(hero), 1);+ return { beat: 'hero', chapter, entry, photos: [hero] };+ }+ const pano = photos[0] && isPanorama(photos[0]) && loudAllowed(rhythm, 'pano') ? photos[0] : null;+ if (entry && pano) return { beat: 'pano', chapter, entry, photos: photos.splice(0, 3) };+ const first = photos.shift();+ return { beat: first ? 'opener' : 'story', chapter, entry, photos: first ? [first] : [] };+}++/**+ * The spreads of one chapter for its share of the budget: the opening, a+ * quiet page when the words run long, then the photos spread evenly over+ * what is left, at most the density's maximum a spread; photos that find no+ * spread are left out and said.+ */+export function planChapter(+ chapter: DesignChapter,+ spreads: number,+ rhythm: Rhythm,+ input: PlanInput,+ leftOut: BookDesignLeftOut[],+): PlannedSpread[] {+ if (chapter.stations) return [{ beat: 'stations', chapter, entry: null, photos: [] }];+ const photos = [...chapter.photos];+ const out: PlannedSpread[] = [];+ const push = (s: PlannedSpread) => {+ out.push(s);+ if (s.beat === 'hero') rhythm.lastHero = rhythm.beats.length;+ rhythm.beats.push(s.beat);+ };+ push(opening(chapter, photos, rhythm, input));+ const long = storyChars(chapter.entries.slice(0, 1)) > OPENER_STORY_CHARS || out[0]?.beat === 'hero';+ const wantsWords = long && (input.directives.text?.story ?? 'full') === 'full';+ let left = spreads - 1;+ if (wantsWords && left > 0 && storyChars(chapter.entries.slice(0, 1)) > 0) {+ push({ beat: 'quiet', chapter, entry: chapter.entries[0] ?? null, photos: photos.splice(0, left > 1 ? 0 : 1) });+ left--;+ }+ const max = DENSITY[input.directives.density].max;+ while (left > 0 && photos.length) {+ const count = Math.min(max, Math.ceil(photos.length / left));+ let take = count >= 6 && !loudAllowed(rhythm, 'grid') ? 5 : count;+ const prev = rhythm.beats.slice(-2);+ if (take > 1 && prev.length === 2 && prev.every((b) => b === photoBeat(take))) take = Math.max(1, take - 1);+ push({ beat: photoBeat(take), chapter, entry: null, photos: photos.splice(0, take) });+ left--;+ }+ for (const p of photos) leftOut.push({ photoId: p.photoId, reason: 'page_budget' });+ return out;+}++export function newRhythm(): Rhythm {+ return { beats: [], lastHero: -10 };+}diff --git a/shared/src/book/design/design-photos.ts b/shared/src/book/design/design-photos.tsnew file mode 100644index 000000000..1df975024--- /dev/null+++ b/shared/src/book/design/design-photos.ts@@ -0,0 +1,183 @@+import { isPano } from '../auto/auto-elements';+import type { AutoEntry, AutoPhoto } from '../auto/auto-types';+import { MIN_PRINT_DPI, photoDpi } from '../book-findings';+import type { BookPhotoInfo } from '../book-ops-core';+import type { BookPageSetup, BookPhotoElement } from '../book.schema';+import {+ PHOTO_PICK,+ pickBookPhotos,+ type PhotoPickCandidate,+ type PhotoPickDropped,+ type PhotoPickEntry,+} from '../photo-pick';+import type { BookDesignDirectives } from './design-directives.schema';++/**+ * Which photos a designed book uses, chapter by chapter, and why the others+ * were left out. `best` takes the photo-pick ranking (near duplicates and+ * possibly blurry ones out, with the reason); `include` forces a photo in,+ * `exclude` takes one out; a chapter keeps at most `perChapterMax`.+ */++export type BookDesignLeftOutReason = PhotoPickDropped['reason'] | 'excluded' | 'chapter_max' | 'page_budget';++export interface BookDesignLeftOut {+ photoId: number;+ reason: BookDesignLeftOutReason;+}++export interface DesignPhotoChoice {+ /** The photos each entry keeps, best first. */+ byEntry: Map<number, AutoPhoto[]>;+ leftOut: BookDesignLeftOut[];+}++/** The entries as the photo picker reads them. */+export function pickEntriesOf(+ entries: readonly AutoEntry[],+ candidates: readonly PhotoPickCandidate[],+): PhotoPickEntry[] {+ const at = new Map(candidates.flatMap((c) => c.entryIds.map((id): [number, PhotoPickCandidate] => [id, c])));+ return entries.map((e) => ({+ id: e.id,+ date: e.date ?? '',+ title: e.title,+ location: e.location,+ lat: e.lat ?? at.get(e.id)?.lat ?? null,+ lng: e.lng ?? at.get(e.id)?.lng ?? null,+ }));+}++/** An entry's photos in the order the picker ranks them, and the ones it left out. */+function ranked(+ entry: AutoEntry,+ candidates: readonly PhotoPickCandidate[],+ pickEntries: readonly PhotoPickEntry[],+): { order: AutoPhoto[]; dropped: PhotoPickDropped[] } {+ const own = new Map(entry.photos.map((p) => [p.photoId, p]));+ const result = pickBookPhotos(candidates, pickEntries, { entryId: entry.id, limit: PHOTO_PICK.maxLimit });+ const pickedIds = result.groups.flatMap((g) => g.picks.map((p) => p.photoId)).filter((id) => own.has(id));+ const dropped = result.groups.flatMap((g) => g.dropped).filter((d) => own.has(d.photoId));+ const out = new Set(dropped.map((d) => d.photoId));+ const seen = new Set(pickedIds);+ const rest = entry.photos.filter((p) => !seen.has(p.photoId) && !out.has(p.photoId));+ const order = [...pickedIds.map((id) => own.get(id) as AutoPhoto), ...rest];+ return { order, dropped };+}++/** An entry's photos as they are, for `pick: 'all'` or a journey without measured photos. */+function unranked(entry: AutoEntry): { order: AutoPhoto[]; dropped: PhotoPickDropped[] } {+ return { order: [...entry.photos], dropped: [] };+}++/** The entry an included photo belongs to: the one it is linked to, else the one of its day, else the first. */+function homeOf(photoId: number, entries: readonly AutoEntry[], candidates: readonly PhotoPickCandidate[]) {+ const c = candidates.find((x) => x.photoId === photoId);+ const linked = entries.find((e) => c?.entryIds.includes(e.id));+ const day = c?.takenAt?.slice(0, 10);+ return linked ?? entries.find((e) => day && e.date === day) ?? entries[0];+}++/** The photos each entry of the design keeps. */+export function choosePhotos(+ entries: readonly AutoEntry[],+ candidates: readonly PhotoPickCandidate[],+ directives: BookDesignDirectives,+ gallery: readonly BookPhotoInfo[],+): DesignPhotoChoice {+ const opts = directives.photos;+ const pick = opts?.pick ?? 'best';+ const exclude = new Set(opts?.exclude ?? []);+ const include = new Set(opts?.include ?? []);+ const pickEntries = pickEntriesOf(entries, candidates);+ const leftOut: BookDesignLeftOut[] = [];+ const byEntry = new Map<number, AutoPhoto[]>();+ const used = new Set<number>();++ for (const entry of entries) {+ const best = pick === 'best' && candidates.length > 0;+ const { order, dropped } = best ? ranked(entry, candidates, pickEntries) : unranked(entry);+ for (const d of dropped) {+ if (include.has(d.photoId)) order.push(entry.photos.find((p) => p.photoId === d.photoId) as AutoPhoto);+ else leftOut.push({ photoId: d.photoId, reason: d.reason });+ }+ const kept: AutoPhoto[] = [];+ for (const p of order) {+ if (used.has(p.photoId)) continue;+ if (exclude.has(p.photoId)) {+ leftOut.push({ photoId: p.photoId, reason: 'excluded' });+ continue;+ }+ if (opts?.perChapterMax !== undefined && kept.length >= opts.perChapterMax && !include.has(p.photoId)) {+ leftOut.push({ photoId: p.photoId, reason: 'chapter_max' });+ continue;+ }+ used.add(p.photoId);+ kept.push(p);+ }+ byEntry.set(entry.id, kept);+ }++ for (const photoId of include) {+ const info = gallery.find((g) => g.photoId === photoId);+ const home = homeOf(photoId, entries, candidates);+ if (!info || used.has(photoId) || exclude.has(photoId) || !home) continue;+ used.add(photoId);+ const list = byEntry.get(home.id) ?? [];+ list.push({ photoId, width: info.width ?? null, height: info.height ?? null, caption: info.caption ?? null });+ byEntry.set(home.id, list);+ }+ return { byEntry, leftOut };+}++/** The resolution a photo prints at in a frame, from what the gallery knows of it; null when its size is unknown. */+export function dpiIn(+ photo: AutoPhoto,+ info: BookPhotoInfo | undefined,+ frame: BookPhotoElement['frame'],+): number | null {+ const width = info?.width ?? photo.width;+ const height = info?.height ?? photo.height;+ if (!width || !height) return null;+ const el = { frame, fit: 'cover' } as BookPhotoElement;+ return photoDpi(el, { photoId: photo.photoId, width, height });+}++/** Clearly wider than tall: a picture that can run across a spread. */+export const isLandscape = (p: AutoPhoto) => !!(p.width && p.height && p.width >= p.height * 1.2);++/** A panorama: more than twice as wide as tall. */+export const isPanorama = (p: AutoPhoto) => isPano(p);++/** A picture wide and sharp enough to run across a whole spread at print resolution, its detail off the fold. */+export function heroWorthy(photo: AutoPhoto, info: BookPhotoInfo | undefined, page: BookPageSetup): boolean {+ if (!isLandscape(photo)) return false;+ const frame = {+ x: -page.bleed,+ y: -page.bleed,+ w: page.pageWidth * 2 + page.bleed * 2,+ h: page.pageHeight + page.bleed * 2,+ };+ const dpi = dpiIn(photo, info, frame);+ if (dpi === null || dpi < MIN_PRINT_DPI) return false;+ const sx = info?.salient?.x;+ return sx === undefined || sx < 0.4 || sx > 0.6;+}++/**+ * Whether a chapter has a burst: four or more photos taken within fifteen+ * minutes of each other, which reads best as a grid.+ */+export function hasBurst(photos: readonly AutoPhoto[], candidates: readonly PhotoPickCandidate[]): boolean {+ const times = photos+ .map((p) => candidates.find((c) => c.photoId === p.photoId)?.takenAt ?? null)+ .map((t) => (t ? Date.parse(t) : Number.NaN))+ .filter((t) => Number.isFinite(t))+ .sort((a, b) => a - b);+ for (let i = 0; i + 3 < times.length; i++) {+ const a = times[i] as number;+ const b = times[i + 3] as number;+ if (b - a <= 15 * 60 * 1000) return true;+ }+ return false;+}diff --git a/shared/src/book/design/design-repair.ts b/shared/src/book/design/design-repair.tsnew file mode 100644index 000000000..bcc91789e--- /dev/null+++ b/shared/src/book/design/design-repair.ts@@ -0,0 +1,204 @@+import { readableInk } from '../book-colour';+import { MIN_PRINT_DPI, photoDpi, textHeightNeeded } from '../book-findings';+import type { BookPhotoInfo } from '../book-ops-core';+import type { BookFinding } from '../book-ops.schema';+import {+ MAX_SPREAD_ELEMENTS,+ type BookElement,+ type BookFrame,+ type BookPageSetup,+ type BookShapeElement,+ type BookSpread,+ type BookTextElement,+} from '../book.schema';+import { pageFindings } from '../describe-spread';+import { cutWords } from './design-compose';+import { designGrid, type BookDesignLook } from './design-style';++/**+ * The engine checks its own pages before anyone sees them: every finding a+ * page has (book-findings.ts and book-findings-design.ts) is fixed where a+ * rule says how, at most three passes, the same way every time. What is left+ * is answered with the design, for the model to look at.+ *+ * The fixes, in order: words set smaller to their tier's floor and then cut at+ * a sentence; a photo that prints soft made smaller (never enlarged), moved+ * into the margins when it ran to the bleed; a focal point moved onto the+ * picture's detail or off the fold; a scrim put under words on a busy part of+ * a picture, or the words set in the ink that reads; empty frames taken out;+ * words pulled inside the margins and back onto their page.+ */++interface RepairCtx {+ page: BookPageSetup;+ photos: readonly BookPhotoInfo[];+ look: BookDesignLook;+ newId: (prefix: string) => string;+}++const r2 = (v: number) => Math.round(v * 100) / 100;+const MAX_PASSES = 3;+const fixable = (f: BookFinding) => f.severity !== 'info';++/** Run the repair passes on one page; the page as fixed and what is left. */+export function repairSpread(spread: BookSpread, ctx: RepairCtx): { spread: BookSpread; findings: BookFinding[] } {+ let current = spread;+ for (let pass = 0; pass < MAX_PASSES; pass++) {+ const open = pageFindings(current, ctx.page, ctx.photos).filter(fixable);+ if (!open.length) break;+ const next = open.reduce((s, f) => fixOne(s, f, ctx), current);+ if (next === current) break;+ current = next;+ }+ return { spread: current, findings: pageFindings(current, ctx.page, ctx.photos) };+}++function fixOne(spread: BookSpread, f: BookFinding, ctx: RepairCtx): BookSpread {+ const el = spread.elements.find((e) => e.id === f.elementIds[0]);+ switch (f.code) {+ case 'empty_frame':+ return dropIds(spread, new Set(f.elementIds));+ case 'text_overflow':+ return el?.kind === 'text' ? replace(spread, fitText(el, ctx)) : spread;+ case 'low_dpi':+ return el?.kind === 'photo' ? replace(spread, sharper(el, ctx)) : spread;+ case 'focal_cut':+ case 'fold':+ return el ? replace(spread, onPage(el, ctx)) : spread;+ case 'text_on_busy':+ case 'contrast_low':+ return el ? readable(spread, el, ctx) : spread;+ case 'trim':+ return el && el.kind !== 'photo' && el.kind !== 'shape' ? replace(spread, inside(el, ctx)) : spread;+ case 'small_text':+ return el?.kind === 'text' ? replace(spread, { ...el, size: el.text.length > 80 ? 7.5 : 6 }) : spread;+ case 'overlap':+ return separate(spread, f, ctx);+ default:+ return spread;+ }+}++const replace = (spread: BookSpread, next: BookElement): BookSpread => ({+ ...spread,+ elements: spread.elements.map((e) => (e.id === next.id ? next : e)),+});++const dropIds = (spread: BookSpread, ids: ReadonlySet<string>): BookSpread => ({+ ...spread,+ elements: spread.elements.filter((e) => !ids.has(e.id)),+});++/** A text that overflows: half a point smaller down to its floor, then its words cut to the frame. */+function fitText(el: BookTextElement, ctx: RepairCtx): BookTextElement {+ const floor = el.text.length > 80 ? ctx.look.sizes.body * 0.9 : ctx.look.sizes.caption;+ if (el.size - 0.5 >= floor) return { ...el, size: r2(el.size - 0.5) };+ let lo = 0;+ let hi = el.text.length;+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ const tried = { ...el, text: cutWords(el.text, mid) };+ if (textHeightNeeded(tried) <= el.frame.h) lo = mid;+ else hi = mid - 1;+ }+ const text = cutWords(el.text, lo);+ return { ...el, text: text || el.text.slice(0, 1), overridden: el.binding ? true : el.overridden };+}++/** The page an element's centre is on: its frame there, or the live area inside its margins. */+function liveOf(el: BookElement, spread: BookSpread | null, ctx: RepairCtx): BookFrame {+ const grid = designGrid(ctx.page);+ const onRight = (spread?.role ?? 'inner') === 'inner' && el.frame.x + el.frame.w / 2 >= ctx.page.pageWidth;+ const x = (onRight ? ctx.page.pageWidth : 0) + grid.margin;+ return { x, y: grid.margin, w: ctx.page.pageWidth - grid.margin * 2, h: ctx.page.pageHeight - grid.margin * 2 };+}++/** A photo that prints soft: made smaller to print at 200 dpi, inside the margins when it ran to the bleed. */+function sharper(el: Extract<BookElement, { kind: 'photo' }>, ctx: RepairCtx): BookElement {+ const info = ctx.photos.find((p) => p.photoId === el.photoId);+ const bleeding = el.frame.x < 0 || el.frame.y < 0;+ const base = bleeding ? liveOf(el, null, ctx) : el.frame;+ const dpi = photoDpi({ ...el, frame: base }, info);+ const k = dpi === null || dpi >= MIN_PRINT_DPI ? 1 : (dpi / MIN_PRINT_DPI) * 0.98;+ const w = base.w * k;+ const h = base.h * k;+ const frame = { x: r2(base.x + (base.w - w) / 2), y: r2(base.y + (base.h - h) / 2), w: r2(w), h: r2(h) };+ return { ...el, frame, rotation: 0 };+}++/** A focal point on the picture's detail when known, and never in the fold of a photo across it. */+function onPage(el: BookElement, ctx: RepairCtx): BookElement {+ if (el.kind !== 'photo') return el;+ const salient = ctx.photos.find((p) => p.photoId === el.photoId)?.salient;+ let focalX = salient?.x ?? 0.5;+ const focalY = salient?.y ?? 0.5;+ const px = el.frame.x + focalX * el.frame.w;+ if (Math.abs(px - ctx.page.pageWidth) < 14 && el.frame.w > ctx.page.pageWidth) focalX = focalX < 0.5 ? 0.36 : 0.64;+ return { ...el, focalX, focalY };+}++/** The colour behind an element's centre: a scrim or the page, or null when it is a photograph. */+function groundUnder(spread: BookSpread, el: BookElement): string | null {+ const index = spread.elements.indexOf(el);+ const cx = el.frame.x + el.frame.w / 2;+ const cy = el.frame.y + el.frame.h / 2;+ for (let j = index - 1; j >= 0; j--) {+ const under = spread.elements[j];+ if (!under) continue;+ const f = under.frame;+ if (cx < f.x || cx > f.x + f.w || cy < f.y || cy > f.y + f.h) continue;+ if (under.kind === 'shape' && under.fill && under.opacity >= 0.5 && under.shape !== 'line') return under.fill;+ if (under.kind === 'photo' && under.photoId != null) return null;+ }+ return spread.background ?? '#ffffff';+}++/** Words that do not read: a scrim under them on a photograph, else the ink that reads on what they are on. */+function readable(spread: BookSpread, el: BookElement, ctx: RepairCtx): BookSpread {+ if (el.kind !== 'text' && el.kind !== 'stats' && el.kind !== 'list' && el.kind !== 'badge') return spread;+ const ground = groundUnder(spread, el);+ if (ground) return replace(spread, { ...el, color: readableInk(ground, ctx.look.ink) } as BookElement);+ const recoloured = { ...el, color: ctx.look.onScrim } as BookElement;+ // A page already at the element cap takes no scrim: the light ink alone, and what is left is answered.+ if (spread.elements.length >= MAX_SPREAD_ELEMENTS) return replace(spread, recoloured);+ const pad = 3;+ const { x, y, w, h } = el.frame;+ const scrim: BookShapeElement = {+ id: ctx.newId('s'),+ kind: 'shape',+ frame: { x: r2(x - pad), y: r2(y - pad), w: r2(w + pad * 2), h: r2(h + pad * 2) },+ rotation: 0,+ opacity: ctx.look.scrimOpacity,+ locked: false,+ shape: 'rect',+ fill: ctx.look.scrim,+ gradient: 'none',+ stroke: null,+ strokeWidth: 0,+ strokeStyle: 'solid',+ radius: 1.5,+ };+ const index = spread.elements.indexOf(el);+ const elements = [...spread.elements.slice(0, index), scrim, recoloured, ...spread.elements.slice(index + 1)];+ return { ...spread, elements };+}++/** Words pulled inside the margins of the page their centre is on. */+function inside(el: BookElement, ctx: RepairCtx): BookElement {+ const live = liveOf(el, null, ctx);+ const w = Math.min(el.frame.w, live.w);+ const h = Math.min(el.frame.h, live.h);+ const x = Math.min(Math.max(el.frame.x, live.x), live.x + live.w - w);+ const y = Math.min(Math.max(el.frame.y, live.y), live.y + live.h - h);+ return { ...el, frame: { x: r2(x), y: r2(y), w: r2(w), h: r2(h) } } as BookElement;+}++/** Two texts on top of each other: the later one moved under the earlier, or taken out when there is no room. */+function separate(spread: BookSpread, f: BookFinding, ctx: RepairCtx): BookSpread {+ const [a, b] = f.elementIds.map((id) => spread.elements.find((e) => e.id === id));+ if (!a || !b || f.severity !== 'severe') return spread;+ const y = a.frame.y + a.frame.h + 2;+ const live = liveOf(b, spread, ctx);+ if (y + b.frame.h > live.y + live.h) return dropIds(spread, new Set([b.id]));+ return replace(spread, { ...b, frame: { ...b.frame, y: r2(y) } } as BookElement);+}diff --git a/shared/src/book/design/design-spreads.ts b/shared/src/book/design/design-spreads.tsnew file mode 100644index 000000000..7e19088a5--- /dev/null+++ b/shared/src/book/design/design-spreads.ts@@ -0,0 +1,273 @@+import type { AutoEntry, AutoPhoto } from '../auto/auto-types';+import type { BookElement, BookFrame, BookSpread } from '../book.schema';+import {+ bleedPage,+ bleedSpread,+ frameOf,+ liveBox,+ other,+ pageX,+ photoEl,+ printsAt,+ scaled,+ scrimEl,+ storyEl,+ textEl,+ titleBlock,+ turnOf,+ type ComposeCtx,+ type Side,+} from './design-compose';+import { isLandscape } from './design-photos';+import { paperBackground } from './design-style';++/**+ * The spreads of a chapter, one composer per beat: the opener, the hero, a+ * quiet page for a long story, two, three and four to six photos, and a+ * panorama across the fold. Each takes the photos the plan gave it and the+ * page (left or right) its photos lead on, and hands back the elements and+ * whatever of the story it could not set.+ */++export interface Composed {+ elements: BookElement[];+ /** The part of the story still to be set, for the next quiet page. */+ rest: string;+}++type Hand = 'left' | 'right';++/** A photo's caption under it, when the directives ask for photo captions and it has one. */+function captionFor(c: ComposeCtx, photo: AutoPhoto, frame: BookFrame, entryId: number | null): BookElement | null {+ if ((c.directives.text?.captions ?? 'entry') !== 'photo' || !photo.caption?.trim()) return null;+ const binding = { source: 'photo.caption' as const, photoId: photo.photoId, ...(entryId ? { entryId } : {}) };+ const at = { x: frame.x, y: frame.y + frame.h + 2, w: frame.w };+ return textEl(c, at, photo.caption.trim(), 'caption', { binding });+}++/** The room a caption takes under a photo, when one will be set. */+function captionRoom(c: ComposeCtx, photos: readonly AutoPhoto[]): number {+ if ((c.directives.text?.captions ?? 'entry') !== 'photo') return 0;+ return photos.some((p) => p.caption?.trim()) ? scaled(c, 9) : 0;+}++/** Photos in a page's live area: one, two (stacked or side by side by their shape) or three. */+function pagePhotos(c: ComposeCtx, photos: readonly AutoPhoto[], side: Side, entryId: number | null): BookElement[] {+ const box = liveBox(c, side);+ const g = c.grid.gutter;+ const room = captionRoom(c, photos);+ const cells = cellsFor(photos, box, g, room);+ const out: BookElement[] = [];+ photos.forEach((p, i) => {+ const cell = cells[i];+ if (!cell) return;+ const el = photoEl(c, p, cell, { turn: turnOf(c, i) });+ out.push(el);+ const caption = captionFor(c, p, el.frame, entryId);+ if (caption) out.push(caption);+ });+ return out;+}++/** Cells for up to three photos in a box, the gutter between them and room under each for a caption. */+function cellsFor(photos: readonly AutoPhoto[], box: BookFrame, g: number, room: number): BookFrame[] {+ const n = Math.min(3, photos.length);+ const sideBySide = photos.slice(0, 2).every((p) => !isLandscape(p));+ if (n === 1) return [frameOf(box.x, box.y, box.w, box.h - room)];+ if (n === 2 && sideBySide) {+ const w = (box.w - g) / 2;+ return [frameOf(box.x, box.y, w, box.h - room), frameOf(box.x + w + g, box.y, w, box.h - room)];+ }+ if (n === 2) {+ const h = (box.h - g - room * 2) / 2;+ return [frameOf(box.x, box.y, box.w, h), frameOf(box.x, box.y + h + room + g, box.w, h)];+ }+ const top = (box.h - g - room * 2) * 0.58;+ const low = box.h - g - room * 2 - top;+ const w = (box.w - g) / 2;+ const y2 = box.y + top + room + g;+ return [frameOf(box.x, box.y, box.w, top), frameOf(box.x, y2, w, low), frameOf(box.x + w + g, y2, w, low)];+}++/**+ * The chapter opens: the title block and the story on one page, a photo to+ * the bleed on the other. Without a photo the story runs on across both pages.+ */+export function composeOpener(c: ComposeCtx, entry: AutoEntry, photo: AutoPhoto | null, hand: Hand): Composed {+ const textSide = photo ? other(hand) : 'left';+ const box = liveBox(c, textSide);+ const head = titleBlock(c, entry, box);+ const els: BookElement[] = [...head.els];+ let bottom = box.y + box.h;+ const map = chapterMap(c, entry, box);+ if (map) {+ els.push(map);+ bottom = map.frame.y - c.grid.gutter;+ }+ const storyBox = frameOf(box.x, head.bottom + 2, box.w, bottom - head.bottom - 2);+ const first = storyEl(c, entry, (entry.story ?? '').trim(), storyBox, true);+ if (first.el) els.push(first.el);+ let rest = first.el ? first.rest : (entry.story ?? '').trim();+ if (photo) {+ els.unshift(photoEl(c, photo, bleedPage(c, hand), { bleed: { side: hand } }));+ } else if (rest) {+ const next = storyEl(c, entry, rest, liveBox(c, 'right'), false);+ if (next.el) els.push(next.el);+ rest = next.el ? next.rest : rest;+ }+ return { elements: els, rest };+}++/** A small map of the chapter's stop at the foot of the title page, when the directives ask for one. */+function chapterMap(c: ComposeCtx, entry: AutoEntry, box: BookFrame): BookElement | null {+ const stats = c.travel.stats;+ if (!c.directives.travel?.chapterMaps || !stats || entry.lat == null || entry.lng == null) return null;+ const h = box.h * 0.3;+ const point = { lat: entry.lat, lng: entry.lng, label: (entry.location ?? '').slice(0, 120), photoId: null };+ return {+ id: c.newId('mp'),+ kind: 'map',+ frame: frameOf(box.x, box.y + box.h - h, box.w, h),+ rotation: 0,+ opacity: 1,+ locked: false,+ font: c.look.heading,+ color: c.look.ink,+ accent: c.look.accent,+ textScale: 1,+ weight: 700,+ stale: false,+ source: 'vector',+ tileUrl: '',+ attribution: '',+ zoom: null,+ style: c.look.mapStyle,+ showLand: true,+ showRoute: false,+ showPins: true,+ showLabels: false,+ routeStyle: 'plain',+ routeArc: 'straight',+ routeDash: 'solid',+ pinStyle: 'dot',+ countries: entry.country ? [entry.country] : [],+ points: [point],+ path: [],+ roads: [],+ fitPadding: 0.5,+ fitToCountries: true,+ clip: 'rect',+ tripId: null,+ };+}++/**+ * One photo across the whole spread, the title on a scrim at the foot of a+ * page. The detail is kept off the fold; the story goes to the next page.+ */+export function composeHero(c: ComposeCtx, entry: AutoEntry, photo: AutoPhoto, hand: Hand): Composed {+ const { pageWidth: PW, pageHeight: H, bleed: b, margin: m } = c.grid;+ const sx = c.infos.get(photo.photoId)?.salient?.x;+ const focalX = sx !== undefined && (sx < 0.4 || sx > 0.6) ? sx : 0.62;+ const els: BookElement[] = [photoEl(c, photo, bleedSpread(c), { bleed: { side: 'left' }, focalX })];+ const top = H * 0.55;+ const textSide = other(hand);+ els.push(scrimEl(c, frameOf(textSide === 'left' ? -b : PW, top, PW + b, H - top + b)));+ const box = frameOf(pageX(c, textSide) + m, top + m * 0.6, PW - m * 2, H - top - m * 1.6);+ els.push(...titleBlock(c, entry, box, { onScrim: true }).els);+ return { elements: els, rest: (entry.story ?? '').trim() };+}++/** A long story's next page: the words in a narrow column, a photo on the other page when there is one. */+export function composeQuiet(+ c: ComposeCtx,+ entry: AutoEntry | null,+ words: string,+ photo: AutoPhoto | null,+ hand: Hand,+): Composed {+ const textSide = photo ? other(hand) : 'left';+ const box = liveBox(c, textSide);+ const inset = box.w * 0.08;+ const column = frameOf(box.x + inset, box.y, box.w - inset * 2, box.h);+ const els: BookElement[] = [];+ let rest = words;+ if (entry && words) {+ const set = storyEl(c, entry, words, column, false);+ if (set.el) els.push(set.el);+ rest = set.el ? set.rest : words;+ }+ if (photo) els.push(...pagePhotos(c, [photo], hand, entry?.id ?? null));+ return { elements: els, rest };+}++/** Two photos: one to the bleed of its page, the other framed on the facing page. */+export function composeDuo(c: ComposeCtx, list: readonly AutoPhoto[], hand: Hand, entryId: number | null): Composed {+ const [a, ...rest] = list;+ const els: BookElement[] = [];+ if (a) els.push(photoEl(c, a, bleedPage(c, hand), { bleed: { side: hand } }));+ els.push(...pagePhotos(c, rest.slice(0, 1), other(hand), entryId));+ return { elements: els, rest: '' };+}++/** Three photos: one to the bleed of its page, two framed on the facing page. */+export function composeTrio(c: ComposeCtx, list: readonly AutoPhoto[], hand: Hand, entryId: number | null): Composed {+ const [a, ...rest] = list;+ const els: BookElement[] = [];+ if (a) els.push(photoEl(c, a, bleedPage(c, hand), { bleed: { side: hand } }));+ els.push(...pagePhotos(c, rest.slice(0, 2), other(hand), entryId));+ return { elements: els, rest: '' };+}++/** Four to six photos, framed on both pages, the fuller page on the leading side. */+export function composeGrid(c: ComposeCtx, list: readonly AutoPhoto[], hand: Hand, entryId: number | null): Composed {+ const lead = Math.min(3, Math.ceil(list.length / 2));+ const els = [+ ...pagePhotos(c, list.slice(0, lead), hand, entryId),+ ...pagePhotos(c, list.slice(lead, lead + 3), other(hand), entryId),+ ];+ return { elements: els, rest: '' };+}++/**+ * A panorama across the top of the spread, the title and the story under it+ * on one page, up to two photos under it on the other.+ */+export function composePano(+ c: ComposeCtx,+ entry: AutoEntry,+ pano: AutoPhoto,+ others: readonly AutoPhoto[],+ hand: Hand,+): Composed {+ const { pageWidth: PW, pageHeight: H, bleed: b, margin: m, gutter: g } = c.grid;+ const band = frameOf(-b, -b, PW * 2 + b * 2, H * 0.5 + b);+ const els: BookElement[] = [photoEl(c, pano, band, { bleed: { side: 'left' }, focalX: 0.35 })];+ const top = H * 0.5 + g;+ const textSide = other(hand);+ const box = frameOf(pageX(c, textSide) + m, top, PW - m * 2, H - m - top);+ const head = titleBlock(c, entry, box);+ els.push(...head.els);+ const storyBox = frameOf(box.x, head.bottom + 2, box.w, box.y + box.h - head.bottom - 2);+ const set = storyEl(c, entry, (entry.story ?? '').trim(), storyBox, true);+ if (set.el) els.push(set.el);+ const row = others.slice(0, 2);+ const cell = frameOf(pageX(c, hand) + m, top, PW - m * 2, H - m - top);+ const w = row.length > 1 ? (cell.w - g) / 2 : cell.w;+ row.forEach((p, i) => {+ const frame = frameOf(cell.x + i * (w + g), cell.y, w, cell.h);+ els.push(photoEl(c, p, frame, { turn: turnOf(c, i) }));+ });+ return { elements: els, rest: set.el ? set.rest : (entry.story ?? '').trim() };+}++/** Whether a panorama can run across the top of the spread at print resolution. */+export function panoFits(c: ComposeCtx, pano: AutoPhoto): boolean {+ const { pageWidth: PW, pageHeight: H, bleed: b } = c.grid;+ return printsAt(c, pano, frameOf(-b, -b, PW * 2 + b * 2, H * 0.5 + b));+}++/** An inner spread holding the composed elements, on the book's paper. */+export function innerSpread(c: ComposeCtx, elements: BookElement[], entryId: number | null): BookSpread {+ return { id: c.newId('sp'), role: 'inner', background: paperBackground(c.look), elements, parked: [], entryId };+}diff --git a/shared/src/book/design/design-style.ts b/shared/src/book/design/design-style.tsnew file mode 100644index 000000000..82cb3073b--- /dev/null+++ b/shared/src/book/design/design-style.ts@@ -0,0 +1,215 @@+import { accentFromPalettes, contrastRatio, parseHex, readPalette, readableInk, toHex } from '../book-colour';+import type { BookPhotoInfo } from '../book-ops-core';+import type { BookFontFamily, BookPageSetup, BookPhotoElement } from '../book.schema';+import type { BookDesignDirectives, BookDesignStyle } from './design-directives.schema';++/**+ * The look of a designed book: its paper, ink, accent, the two typefaces,+ * the type sizes and the page grid, from the style and the directives.+ *+ * At most two families per book; badges, figures, maps and lists take the+ * heading face. Sizes are set for a 210 mm page and scale with the page+ * width, times `type.scale`, never under what a reader can read. Every+ * colour a text is set in is checked against the paper to WCAG contrast;+ * a pair that fails falls back to the ink.+ */++export interface BookDesignLook {+ style: BookDesignStyle;+ paper: string;+ ink: string;+ /** Captions and meta lines: lighter than the ink, still 4.5:1 on the paper. */+ muted: string;+ accent: string;+ /** What goes under words set on a photograph, at `scrimOpacity`. */+ scrim: string;+ scrimOpacity: number;+ /** The colour words take on the scrim. */+ onScrim: string;+ heading: BookFontFamily;+ body: BookFontFamily;+ sizes: { heading: number; sub: number; body: number; caption: number; meta: number };+ /** The frame decoration and the slight turn a scrapbook gives its pictures. */+ frameStyle: BookPhotoElement['frameStyle'];+ tilt: number;+ /** The map style that reads on this paper. */+ mapStyle: 'minimal' | 'outline' | 'dark' | 'paper';+}++interface StylePreset {+ paper: string;+ ink: string;+ accent: string;+ heading: BookFontFamily;+ body: BookFontFamily;+ frameStyle: BookPhotoElement['frameStyle'];+ tilt: number;+ mapStyle: BookDesignLook['mapStyle'];+}++const PRESETS: Record<BookDesignStyle, StylePreset> = {+ classic: {+ paper: '#ffffff',+ ink: '#1a1a1a',+ accent: '#c2410c',+ heading: 'sans',+ body: 'sans',+ frameStyle: 'none',+ tilt: 0,+ mapStyle: 'minimal',+ },+ minimal: {+ paper: '#ffffff',+ ink: '#1f1f1f',+ accent: '#3d3d3d',+ heading: 'inter',+ body: 'inter',+ frameStyle: 'none',+ tilt: 0,+ mapStyle: 'outline',+ },+ editorial: {+ paper: '#faf8f4',+ ink: '#161616',+ accent: '#8c2f1b',+ heading: 'playfair',+ body: 'garamond',+ frameStyle: 'none',+ tilt: 0,+ mapStyle: 'paper',+ },+ journal: {+ paper: '#f6f1e7',+ ink: '#2a241c',+ accent: '#6b4f2a',+ heading: 'serif',+ body: 'garamond',+ frameStyle: 'white',+ tilt: 0,+ mapStyle: 'paper',+ },+ bold: {+ paper: '#111111',+ ink: '#f5f2ec',+ accent: '#e4572e',+ heading: 'bebas',+ body: 'inter',+ frameStyle: 'none',+ tilt: 0,+ mapStyle: 'dark',+ },+ scrapbook: {+ paper: '#f3ede2',+ ink: '#2b2620',+ accent: '#c0392b',+ heading: 'display',+ body: 'sans',+ frameStyle: 'polaroid',+ tilt: 2,+ mapStyle: 'paper',+ },+};++/** Type sizes on a 210 mm page, in points. */+const BASE_SIZES = { heading: 28, sub: 14, body: 10, caption: 7.5, meta: 7 };+/** Never under these: running text reads from 7 pt, a caption or meta line from 5.5 pt (with room to spare). */+const FLOOR = { heading: 14, sub: 9, body: 8, caption: 7, meta: 6 };++const round1 = (v: number) => Math.round(v * 10) / 10;++/** A colour part way from `a` to `b`. */+function mix(a: string, b: string, t: number): string {+ const ca = parseHex(a);+ const cb = parseHex(b);+ if (!ca || !cb) return a;+ return toHex({ r: ca.r + (cb.r - ca.r) * t, g: ca.g + (cb.g - ca.g) * t, b: ca.b + (cb.b - ca.b) * t });+}++/** The ink, unless it reads under 4.5:1 on the paper, then whichever of near black and white reads better. */+function readableOn(paper: string, ink: string): string {+ return contrastRatio(ink, paper) >= 4.5 ? ink : readableInk(paper);+}++/** The paper, ink and accent the palette directive asks for. */+function paletteOf(+ preset: StylePreset,+ palette: BookDesignDirectives['palette'],+ photos: readonly BookPhotoInfo[],+): { paper: string; ink: string; accent: string } {+ if (palette === 'ink') return { paper: preset.paper, ink: preset.ink, accent: preset.ink };+ if (palette === 'from_photos') {+ const accent = accentFromPalettes(photos.map((p) => readPalette(p.palette)));+ return { paper: preset.paper, ink: preset.ink, accent: accent ?? preset.accent };+ }+ if (palette) {+ const paper = palette.paper.toLowerCase();+ const ink = palette.ink.toLowerCase();+ // An accent of the person's own still has to show on their paper: 3:1, the line for marks and large type.+ const accent = contrastRatio(palette.accent, paper) >= 3 ? palette.accent.toLowerCase() : readableOn(paper, ink);+ return { paper, ink, accent };+ }+ return { paper: preset.paper, ink: preset.ink, accent: preset.accent };+}++/** The look of the book, from its style, its directives, its page and the photos it uses. */+export function designLook(+ directives: BookDesignDirectives,+ page: BookPageSetup,+ usedPhotos: readonly BookPhotoInfo[],+): BookDesignLook {+ const preset = PRESETS[directives.style];+ const colours = paletteOf(preset, directives.palette, usedPhotos);+ const ink = readableOn(colours.paper, colours.ink);+ const softer = mix(ink, colours.paper, 0.3);+ const muted = contrastRatio(softer, colours.paper) >= 4.6 ? softer : ink;+ const scale = (page.pageWidth / 210) * (directives.type?.scale ?? 1);+ const size = (role: keyof typeof BASE_SIZES) => Math.max(FLOOR[role], round1(BASE_SIZES[role] * scale));+ const heading = directives.type?.heading ?? preset.heading;+ return {+ style: directives.style,+ paper: colours.paper,+ ink,+ muted,+ accent: colours.accent,+ scrim: '#111111',+ scrimOpacity: 0.6,+ onScrim: '#ffffff',+ heading,+ body: directives.type?.body ?? preset.body,+ sizes: {+ heading: size('heading'),+ sub: size('sub'),+ body: size('body'),+ caption: size('caption'),+ meta: size('meta'),+ },+ frameStyle: preset.frameStyle,+ tilt: preset.tilt,+ mapStyle: preset.mapStyle,+ };+}++/** The page grid: margin and gutter in millimetres, as fractions of the page width over the safe area. */+export interface BookDesignGrid {+ pageWidth: number;+ pageHeight: number;+ bleed: number;+ safe: number;+ margin: number;+ gutter: number;+}++export function designGrid(page: BookPageSetup): BookDesignGrid {+ const margin = Math.max(page.safe + 6, 0.075 * page.pageWidth);+ return {+ pageWidth: page.pageWidth,+ pageHeight: page.pageHeight,+ bleed: page.bleed,+ safe: page.safe,+ margin: Math.round(margin * 100) / 100,+ gutter: Math.round(0.025 * page.pageWidth * 100) / 100,+ };+}++/** The background a spread takes: none for white paper (the paper itself), else the paper colour. */+export const paperBackground = (look: BookDesignLook): string | null => (look.paper === '#ffffff' ? null : look.paper);diff --git a/shared/src/index.ts b/shared/src/index.tsindex 258a827fb..f01e4251d 100644--- a/shared/src/index.ts+++ b/shared/src/index.ts@@ -138,6 +138,26 @@ export * from './book/book-page-ops';export * from './book/book-findings';export * from './book/describe-spread';export * from './book/photo-pick';+export * from './book/book-element-ops.schema';+export * from './book/book-doc-ops';+export * from './book/book-travel';+export * from './book/book-text';+export * from './book/book-path';+export * from './book/book-icons';+export * from './book/book-map-sources';+export * from './book/book-colour';+export * from './book/book-findings-design';+export * from './book/auto/auto-types';+export * from './book/auto/auto-book';+export * from './book/auto/auto-templates.data';+export * from './book/auto/auto-template-apply';+export * from './book/design/design-directives.schema';+export * from './book/design/design-book';+export * from './book/design/design-merge';+export { BOOK_DESIGN_BEATS, type BookDesignBeat } from './book/design/design-pacing';+export type { BookDesignLeftOut, BookDesignLeftOutReason } from './book/design/design-photos';+export type { BookDesignLook } from './book/design/design-style';+export * from './book/book-design-tools.schema';export * from './share/share.schema';export * from './storage/storage.schema';export * from './settings/settings.schema';@@ -153,6 +173,8 @@ export * from './ai/ai-connections.schema';export * from './assistant/assistant.schema';export * from './assistant/cards';export * from './assistant/assistant-share.schema';+export * from './assistant/assistant-scope.schema';+export * from './assistant/assistant-vision.schema';// Realtime WS event contract registry (event names + payload schemas)export * from './realtime/events.schema';