diff --git a/shared/src/book/design/design-template-pick.spec.ts b/shared/src/book/design/design-template-pick.spec.ts new file mode 100644 index 000000000..c79d143cf --- /dev/null +++ b/shared/src/book/design/design-template-pick.spec.ts @@ -0,0 +1,212 @@ +import type { AutoPhoto } from '../auto/auto-types'; +import { BOOK_COVER_ARCHETYPES } from '../book-archetypes'; +import { bookPageSetupForPreset } from '../book-pages'; +import { decoratedTemplatesFor, findDecoratedTemplate } from '../templates/template-catalogue'; +import { templatePhotoSlots, templateRoles, type BookDecoratedTemplate } from '../templates/template-format'; +import { bookThemeOf } from '../theme/book-theme'; +import { BOOK_THEME_IDS } from '../theme/book-theme.schema'; +import { + ARCHETYPE_KIN, + THEME_ARCHETYPE, + archetypeOfTheme, + bodyCapacity, + chunkPhotos, + chunkSizesOf, + innerPool, + pickCoverTemplate, + pickInnerTemplate, + templateEnergy, + type TemplateChunk, + type TemplatePickCtx, +} from './design-template-pick'; + +import { describe, expect, it } from 'vitest'; + +/** Picking a decorated spread for a page's photos and words. */ + +const page = bookPageSetupForPreset('square-210'); +const wide = (photoId: number): AutoPhoto => ({ photoId, width: 4000, height: 3000 }); +const tall = (photoId: number): AutoPhoto => ({ photoId, width: 3000, height: 4000 }); +const photos = (n: number, at = 1) => Array.from({ length: n }, (_, i) => (i % 3 === 2 ? tall(at + i) : wide(at + i))); +const STORY = 'We walked up from the harbour in the morning and found the old town still asleep. '; + +const ctxOf = (over: Partial = {}): TemplatePickCtx => ({ + archetype: 'spine-band', + page, + theme: bookThemeOf('fabric-classic'), + history: [], + calm: false, + seed: 7, + key: 'k', + ...over, +}); + +const chunk = (n: number, story = '', mappable = false): TemplateChunk => ({ photos: photos(n), story, mappable }); +const roles = (t: BookDecoratedTemplate) => templateRoles(t) as readonly string[]; + +/** A book of pages picked one after the other, as the auto layout picks them. */ +function book(chunks: readonly TemplateChunk[], over: Partial = {}): BookDecoratedTemplate[] { + const out: BookDecoratedTemplate[] = []; + chunks.forEach((c, i) => { + const pick = pickInnerTemplate(c, ctxOf({ ...over, history: out.map((t) => t.id), key: `e${i}` })); + if (pick) out.push(pick); + }); + return out; +} + +const varied = Array.from({ length: 20 }, (_, i) => + chunk(i % 9, i % 3 === 0 ? STORY.repeat(1 + (i % 4)) : '', i % 5 === 0), +); + +describe('the template picker', () => { + it('AUTOTPL-001: never picks a template that would leave a photo frame empty', () => { + for (const archetype of BOOK_COVER_ARCHETYPES) { + for (let n = 0; n <= 9; n++) { + for (const story of ['', STORY]) { + const pick = pickInnerTemplate(chunk(n, story), ctxOf({ archetype })); + if (pick) expect(templatePhotoSlots(pick), `${archetype} ${n}`).toBeLessThanOrEqual(n); + } + } + } + }); + + it('AUTOTPL-002: a story always lands on a template with a story frame', () => { + for (const archetype of BOOK_COVER_ARCHETYPES) { + for (let n = 0; n <= 8; n++) { + const pick = pickInnerTemplate(chunk(n, STORY), ctxOf({ archetype })); + expect(pick, `${archetype} ${n}`).toBeDefined(); + expect(roles(pick as BookDecoratedTemplate)).toContain('body'); + } + } + }); + + it('AUTOTPL-003: a map template only where there is a place to draw', () => { + for (const archetype of BOOK_COVER_ARCHETYPES) { + for (let n = 1; n <= 8; n++) { + const pick = pickInnerTemplate(chunk(n), ctxOf({ archetype })); + if (pick) expect(roles(pick), `${archetype} ${n}`).not.toContain('map'); + } + } + const mapped = [1, 2, 3, 4, 5].map((n) => + pickInnerTemplate(chunk(n, '', true), ctxOf({ archetype: 'field-notes' })), + ); + expect(mapped.every((t) => t !== undefined)).toBe(true); + }); + + it('AUTOTPL-004: never the same template twice running, never loud after loud or lively', () => { + for (const archetype of BOOK_COVER_ARCHETYPES) { + const picks = book(varied, { archetype, theme: null }); + picks.forEach((t, i) => { + const before = picks[i - 1]; + if (!before) return; + expect(t.id, `${archetype} at ${i}`).not.toBe(before.id); + if (templateEnergy(t) === 'loud') expect(['loud', 'lively']).not.toContain(templateEnergy(before)); + }); + } + }); + + it('AUTOTPL-005: twenty varied entries are laid on at least eight different templates', () => { + for (const archetype of BOOK_COVER_ARCHETYPES) { + const picks = book(varied, { archetype }); + expect(new Set(picks.map((t) => t.id)).size, archetype).toBeGreaterThanOrEqual(8); + } + }); + + it("AUTOTPL-006: the theme's own archetype wins over a kin one that fits as well", () => { + for (const archetype of BOOK_COVER_ARCHETYPES) { + for (const tpl of decoratedTemplatesFor('inner', archetype)) { + if (roles(tpl).includes('map')) continue; + const n = templatePhotoSlots(tpl); + const pick = pickInnerTemplate( + { photos: photos(n), story: '', mappable: true }, + ctxOf({ archetype, theme: null }), + ); + expect(pick?.archetype, `${archetype} ${n}`).toBe(archetype); + } + } + }); + + it('AUTOTPL-007: the same seed picks the same templates, another seed others', () => { + const one = book(varied, { seed: 1 }).map((t) => t.id); + expect(book(varied, { seed: 1 }).map((t) => t.id)).toEqual(one); + const others = [2, 3, 4, 5, 6].map((seed) => + book(varied, { seed }) + .map((t) => t.id) + .join(), + ); + expect(others.some((o) => o !== one.join())).toBe(true); + }); + + it('AUTOTPL-008: every theme has an archetype, and every archetype kin of its own kind', () => { + for (const id of BOOK_THEME_IDS) expect(BOOK_COVER_ARCHETYPES).toContain(THEME_ARCHETYPE[id]); + expect(THEME_ARCHETYPE).toMatchObject({ + riso: 'riso', + magazine: 'editorial', + 'retro-travel': 'vintage-poster', + midnight: 'night-film', + 'field-notes': 'field-notes', + }); + for (const a of BOOK_COVER_ARCHETYPES) { + expect(ARCHETYPE_KIN[a].length).toBeGreaterThan(0); + expect(ARCHETYPE_KIN[a]).not.toContain(a); + } + expect(ARCHETYPE_KIN['night-film']).toEqual(['editorial', 'minimal-serif']); + }); + + it('AUTOTPL-009: a story frame holds more the larger it is drawn', () => { + const base = findDecoratedTemplate('story-quote') as BookDecoratedTemplate; + const grown = (k: number): BookDecoratedTemplate => ({ + ...base, + id: `story-quote-x${k}`, + elements: base.elements.map((e) => (e.role === 'body' ? { ...e, frame: { ...e.frame, h: e.frame.h * k } } : e)), + }); + const sizes = [0.5, 1, 1.5, 2].map((k) => bodyCapacity(grown(k), page)); + for (let i = 1; i < sizes.length; i++) expect(sizes[i] as number).toBeGreaterThanOrEqual(sizes[i - 1] as number); + expect(sizes[3] as number).toBeGreaterThan(sizes[0] as number); + expect(bodyCapacity(findDecoratedTemplate('grid-tight') as BookDecoratedTemplate, page)).toBe(0); + }); + + it('AUTOTPL-010: photos are cut into pages that leave no frame empty and park as few as there can be', () => { + const sizes = { any: new Set([0, 1, 2, 3, 4, 5, 6, 7, 8]), story: new Set([0, 1, 2, 3, 4, 6]) }; + for (let n = 1; n <= 20; n++) { + for (const story of [false, true]) { + const cut = chunkPhotos(n, story, sizes); + expect(cut.sizes.reduce((a, b) => a + b, 0) + cut.parked).toBe(n); + expect(cut.parked, `${n}`).toBe(0); + if (story) expect(sizes.story.has(cut.sizes[0] as number)).toBe(true); + } + } + expect(chunkPhotos(12, false, sizes).sizes).toEqual([6, 6]); + expect(chunkPhotos(5, true, sizes).sizes).toEqual([2, 3]); + // A story too long for a small page's frame goes on a page of words of its own. + expect(chunkPhotos(2, true, { ...sizes, storyCost: (s) => (s > 0 ? 30 : 0) }).sizes).toEqual([0, 2]); + expect(chunkPhotos(3, false, { any: new Set([2]), story: new Set() })).toEqual({ sizes: [2], parked: 1 }); + }); + + it('AUTOTPL-011: a cover template never leaves a frame empty, and with no photo only one drawn for none', () => { + for (const archetype of BOOK_COVER_ARCHETYPES) { + for (let n = 0; n <= 5; n++) { + const pick = pickCoverTemplate({ archetype, photos: n, portrait: false, seed: 3 }); + if (pick) expect(templatePhotoSlots(pick)).toBeLessThanOrEqual(n); + if (n >= 4) expect(pick, `${archetype} ${n}`).toBeDefined(); + } + } + expect(pickCoverTemplate({ archetype: 'postcard', photos: 0, portrait: false, seed: 1 })?.id).toBe( + 'postcard-coast', + ); + expect(pickCoverTemplate({ archetype: 'riso', photos: 0, portrait: false, seed: 1 })).toBeUndefined(); + expect(pickCoverTemplate({ archetype: 'minimal-serif', photos: 1, portrait: true, seed: 1 })?.id).toBe( + 'minimal-serif-portrait', + ); + }); + + it("AUTOTPL-012: a theme of the book's own takes the archetype of the theme it still sets the faces of", () => { + expect(archetypeOfTheme({ ...bookThemeOf('midnight'), id: null })).toBe('night-film'); + const odd = bookThemeOf('riso'); + const own = { ...odd, id: null, fonts: { ...odd.fonts, display: { font: 'bodoni' }, heading: { font: 'bodoni' } } }; + expect(archetypeOfTheme(own)).toBe('spine-band'); + expect(archetypeOfTheme(null)).toBe('spine-band'); + expect(innerPool('riso').every((t) => ['riso', 'poster-pop', 'cutout'].includes(t.archetype))).toBe(true); + expect([...chunkSizesOf(innerPool('riso')).story]).toContain(0); + }); +}); diff --git a/shared/src/book/design/design-template-pick.ts b/shared/src/book/design/design-template-pick.ts new file mode 100644 index 000000000..fb456156a --- /dev/null +++ b/shared/src/book/design/design-template-pick.ts @@ -0,0 +1,370 @@ +import { isPortrait } from '../auto/auto-elements'; +import type { AutoPhoto } from '../auto/auto-types'; +import type { BookCoverArchetype } from '../book-archetypes'; +import { DESIGN_TEXT_HEADROOM, textHeightNeeded } from '../book-findings'; +import type { BookPageSetup, BookTextElement } from '../book.schema'; +import { layDecoratedTemplate } from '../templates/template-apply'; +import { decoratedTemplatesFor } from '../templates/template-catalogue'; +import { templatePhotoSlots, templateRoles, type BookDecoratedTemplate } from '../templates/template-format'; +import { themedElement } from '../theme/book-theme-apply'; +import type { BookTheme, BookThemeId } from '../theme/book-theme.schema'; +import { BOOK_THEME_PRESETS } from '../theme/book-themes.data'; +import { isLandscape } from './design-photos'; +import { designRng } from './design-random'; + +/** + * Which decorated template a page of the auto layout is laid on. + * + * A book is in a theme, and a theme belongs to one of the twelve archetypes + * the templates are drawn in (`THEME_ARCHETYPE`). Its pages are picked from + * that archetype's templates and from those of the archetypes that sit well + * beside it (`ARCHETYPE_KIN`), by what a page holds: how many photos, whether + * a story has to fit, whether the stop can draw a map. Templates that would + * leave an empty frame, lose the story or repeat the page before are never + * candidates; of the rest the best is taken, the theme's own first, its + * story fitting its body, its first frame the shape of the first photo, not + * one used a few pages back, and calm where the book should breathe. Equal + * ones are chosen by the design's seed, so the same journey and seed give the + * same book and another seed another. + */ + +/** The archetype each built-in theme's pages are drawn in. */ +export const THEME_ARCHETYPE: Readonly> = { + 'poster-pop': 'poster-pop', + tropical: 'poster-pop', + cutout: 'cutout', + postcard: 'postcard', + riviera: 'postcard', + 'fabric-classic': 'spine-band', + alpine: 'spine-band', + 'minimal-serif': 'minimal-serif', + nordic: 'minimal-serif', + 'grid-badge': 'grid-badge', + 'scrapbook-script': 'stamp-collage', + 'india-stamp': 'stamp-collage', + riso: 'riso', + magazine: 'editorial', + 'retro-travel': 'vintage-poster', + midnight: 'night-film', + 'field-notes': 'field-notes', +}; + +/** The archetypes whose spreads sit well in a book of another, nearest first. */ +export const ARCHETYPE_KIN: Readonly> = { + 'spine-band': ['minimal-serif', 'postcard'], + 'poster-pop': ['cutout', 'stamp-collage'], + cutout: ['poster-pop', 'riso'], + postcard: ['vintage-poster', 'spine-band'], + 'grid-badge': ['minimal-serif', 'stamp-collage'], + 'minimal-serif': ['editorial', 'spine-band'], + 'stamp-collage': ['field-notes', 'postcard'], + riso: ['poster-pop', 'cutout'], + editorial: ['minimal-serif', 'grid-badge'], + 'vintage-poster': ['postcard', 'stamp-collage'], + 'night-film': ['editorial', 'minimal-serif'], + 'field-notes': ['stamp-collage', 'spine-band'], +}; + +/** The archetype a book without a recognisable theme takes. */ +const FALLBACK_ARCHETYPE: BookCoverArchetype = 'spine-band'; + +/** + * The archetype of a book's theme: a built-in theme's own; a theme of the + * book's own (no id) that of the built-in one whose faces it still sets, + * else the calm bookish one. + */ +export function archetypeOfTheme(theme: BookTheme | null | undefined): BookCoverArchetype { + if (!theme) return FALLBACK_ARCHETYPE; + if (theme.id) return THEME_ARCHETYPE[theme.id]; + const kin = BOOK_THEME_PRESETS.find( + (p) => p.fonts.display.font === theme.fonts.display.font && p.fonts.heading.font === theme.fonts.heading.font, + ); + return kin ? THEME_ARCHETYPE[kin.id] : FALLBACK_ARCHETYPE; +} + +/** How loud a template is, from its tags: a loud poster, a lively collage, a graphic grid, a calm page. */ +export type TemplateEnergy = 'loud' | 'lively' | 'medium' | 'calm'; + +/** A template's energy. Graphic pages, and the few drawn without a word for it, count as medium. */ +export function templateEnergy(tpl: Pick): TemplateEnergy { + if (tpl.tags.includes('loud')) return 'loud'; + if (tpl.tags.includes('lively')) return 'lively'; + if (tpl.tags.includes('calm') && !tpl.tags.includes('graphic')) return 'calm'; + return 'medium'; +} + +const isLoud = (e: TemplateEnergy | undefined) => e === 'loud'; +const isBusy = (e: TemplateEnergy | undefined) => e === 'loud' || e === 'lively'; + +/** A page format and theme as a cache key: what a laid template's measures depend on. */ +const formatKey = (page: BookPageSetup, theme: BookTheme | null | undefined) => + `${page.pageWidth}x${page.pageHeight}|${theme?.fonts.body.font ?? '-'}|${theme?.fonts.body.weight ?? '-'}`; + +/** Words of an ordinary length, to measure a body frame by. */ +const FILLER = + 'We left early and walked along the water while the town woke up, stopped for coffee, ' + + 'and found the road that runs up the hill to the old walls and the view over the bay. '; + +const laidBodies = new Map(); + +/** The body text of a template as it is laid on this format in this theme, empty; null without one. */ +function laidBody(tpl: BookDecoratedTemplate, page: BookPageSetup, theme: BookTheme | null | undefined) { + const key = `${tpl.id}|${formatKey(page, theme)}`; + if (laidBodies.has(key)) return laidBodies.get(key) ?? null; + let n = 0; + const laid = layDecoratedTemplate(tpl, page, theme ?? null, (p) => `${p}${++n}`); + const found = laid.find((l) => l.role === 'body' && l.el.kind === 'text')?.el; + const body = found?.kind === 'text' ? (theme ? themedElement(found, theme) : found) : null; + laidBodies.set(key, body); + return body; +} + +/** Whether these words fit a laid body frame as it is set. */ +function fitsBody(body: BookTextElement, words: string): boolean { + return textHeightNeeded({ ...body, text: words }, DESIGN_TEXT_HEADROOM) <= body.frame.h; +} + +const capacities = new Map(); + +/** + * How many characters of ordinary running text a template's story frame + * holds on this page format in this theme's body face: 0 for a template + * without one. Measured once per template, format and face. + */ +export function bodyCapacity(tpl: BookDecoratedTemplate, page: BookPageSetup, theme?: BookTheme | null): number { + const key = `${tpl.id}|${formatKey(page, theme)}`; + const known = capacities.get(key); + if (known !== undefined) return known; + const body = laidBody(tpl, page, theme); + let lo = 0; + if (body) { + let hi = 4000; + while (lo < hi) { + const mid = Math.ceil((lo + hi) / 2); + if (fitsBody(body, FILLER.repeat(Math.ceil(mid / FILLER.length)).slice(0, mid))) lo = mid; + else hi = mid - 1; + } + } + capacities.set(key, lo); + return lo; +} + +/** The parts a page of photos is cut into: how many photos each takes, the first one carrying the words. */ +export interface PhotoChunking { + sizes: number[]; + /** Photos that find no frame: noted and parked, never lost. */ + parked: number; +} + +/** What a chunking may use: the photo counts of the templates there are, those with a story frame apart. */ +export interface ChunkSizes { + any: ReadonlySet; + story: ReadonlySet; + /** What setting the words on a first page of this many photos costs beyond a page: its story cut short. */ + storyCost?: (size: number) => number; +} + +/** A spread costs this much, and every photo left without a frame more. */ +const SPREAD_COST = 10; +const PARKED_COST = 15; +/** The most spreads one entry's photos are cut into. */ +const MOST_CHUNKS = 3; + +/** + * An entry's photos cut into page-sized parts that leave no frame empty, + * as few pages and as few photos without a frame as there can be: every + * spread costs 10, every photo left over 15, and the first part, which + * carries the story, is one a story template takes. Of two equal cuts the + * more even one is kept, so twelve photos make six and six rather than ten + * and two. + */ +export function chunkPhotos(n: number, hasStory: boolean, sizes: ChunkSizes): PhotoChunking { + type Plan = { sizes: number[]; cost: number; parked: number }; + const firsts = [...(hasStory ? sizes.story : sizes.any)].filter((s) => s <= n); + const rest = [...sizes.any].filter((s) => s > 0); + let best: Plan = { sizes: [], cost: Infinity, parked: n }; + const better = (a: Plan, b: Plan) => + a.cost < b.cost || + (a.cost === b.cost && Math.max(...a.sizes) - Math.min(...a.sizes) < Math.max(...b.sizes) - Math.min(...b.sizes)); + const walk = (taken: number[], left: number, cost: number) => { + const plan: Plan = { sizes: taken, cost: cost + left * PARKED_COST, parked: left }; + if (taken.length && (!best.sizes.length || better(plan, best))) best = plan; + if (taken.length >= MOST_CHUNKS) return; + const options = taken.length ? rest : firsts; + for (const s of options) { + if (s > left || (taken.length && s === 0)) continue; + const extra = !taken.length && hasStory ? (sizes.storyCost?.(s) ?? 0) : 0; + walk([...taken, s], left - s, cost + SPREAD_COST + extra); + } + }; + walk([], n, 0); + return best.sizes.length ? { sizes: best.sizes, parked: best.parked } : { sizes: [], parked: n }; +} + +/** What a page to be laid holds, as the picker reads it. */ +export interface TemplateChunk { + photos: readonly AutoPhoto[]; + /** The words a story frame must take; empty when the page sets none. */ + story: string; + /** The stop or the journey has a place a map can draw. */ + mappable: boolean; +} + +/** What the picker knows of the book around the page. */ +export interface TemplatePickCtx { + archetype: BookCoverArchetype; + page: BookPageSetup; + theme: BookTheme | null | undefined; + /** Template ids of the spreads laid so far, in order. */ + history: readonly string[]; + /** The book's energy for template choice: a calm book keeps its busy pages few. */ + calm: boolean; + seed: number; + /** Names the decision for the seed: the same page of the same journey picks the same. */ + key: string; + /** Ids never to take here (the page's own on "this spread", its neighbours'). */ + avoid?: readonly string[]; +} + +const hasRole = (tpl: BookDecoratedTemplate, role: string) => (templateRoles(tpl) as readonly string[]).includes(role); + +const slotsOf = new Map(); +const slots = (tpl: BookDecoratedTemplate) => { + const known = slotsOf.get(tpl.id); + if (known !== undefined) return known; + const n = templatePhotoSlots(tpl); + slotsOf.set(tpl.id, n); + return n; +}; + +/** The inner templates of an archetype and of its kin, the own ones first. */ +export function innerPool(archetype: BookCoverArchetype): BookDecoratedTemplate[] { + return [archetype, ...ARCHETYPE_KIN[archetype]].flatMap((a) => decoratedTemplatesFor('inner', a)); +} + +/** The photo counts a pool of templates takes, and those of its templates with a story frame. */ +export function chunkSizesOf(pool: readonly BookDecoratedTemplate[]): { any: Set; story: Set } { + return { + any: new Set(pool.map(slots)), + story: new Set(pool.filter((t) => hasRole(t, 'body')).map(slots)), + }; +} + +/** Whether a template can take this page at all, after the one before it. */ +function admits( + tpl: BookDecoratedTemplate, + chunk: TemplateChunk, + ctx: TemplatePickCtx, + before: TemplateEnergy | undefined, +) { + if (tpl.kind !== 'inner' || slots(tpl) > chunk.photos.length) return false; + if (chunk.story && !hasRole(tpl, 'body')) return false; + if (hasRole(tpl, 'map') && !chunk.mappable) return false; + if (ctx.history[ctx.history.length - 1] === tpl.id || ctx.avoid?.includes(tpl.id)) return false; + return !(isLoud(templateEnergy(tpl)) && isBusy(before)); +} + +/** The orientation of a template's first frame on this format: wide, tall or square. */ +function firstFrameShape(tpl: BookDecoratedTemplate, page: BookPageSetup): 'wide' | 'tall' | 'square' { + const el = tpl.elements.find((e) => e.role === 'photo:1'); + if (!el) return 'square'; + const across = el.frame.w * page.pageWidth; + const down = el.frame.h * page.pageHeight; + if (across >= down * 1.2) return 'wide'; + return down >= across * 1.1 ? 'tall' : 'square'; +} + +/** Points for the story: it fits the frame, or it loses in proportion to how far it runs over. */ +function storyScore(tpl: BookDecoratedTemplate, chunk: TemplateChunk, ctx: TemplatePickCtx): number { + if (!chunk.story) return 0; + const room = bodyCapacity(tpl, ctx.page, ctx.theme); + if (room >= chunk.story.length) return 10; + return -Math.min(40, (20 * (chunk.story.length - room)) / Math.max(room, 1)); +} + +/** How well a template suits the page, the higher the better. */ +function scoreOf( + tpl: BookDecoratedTemplate, + chunk: TemplateChunk, + ctx: TemplatePickCtx, + before: TemplateEnergy | undefined, +) { + let score = 100 - 12 * (chunk.photos.length - slots(tpl)); + if (tpl.archetype === ctx.archetype) score += 20; + else if (ARCHETYPE_KIN[ctx.archetype].includes(tpl.archetype)) score += 8; + const first = chunk.photos[0]; + const shape = firstFrameShape(tpl, ctx.page); + if (first && ((shape === 'wide' && isLandscape(first)) || (shape === 'tall' && isPortrait(first)))) score += 6; + score += storyScore(tpl, chunk, ctx); + const recent = ctx.history.slice(-3); + if (recent.includes(tpl.id)) score -= 40; + score -= 8 * ctx.history.slice(0, -3).filter((id) => id === tpl.id).length; + const energy = templateEnergy(tpl); + if ((ctx.calm || isBusy(before)) && isBusy(energy)) score -= 30; + return score; +} + +/** Scores this close count as equal, and the seed chooses among them. */ +const TIE = 5; + +/** The best of scored templates, equals chosen by the seed. */ +function bestOf(scored: { tpl: BookDecoratedTemplate; score: number }[], seed: number, key: string) { + if (!scored.length) return undefined; + const top = Math.max(...scored.map((s) => s.score)); + const near = scored.filter((s) => s.score >= top - TIE).map((s) => s.tpl); + return designRng(seed, key).pick(near); +} + +/** The energy of the template a page was laid on, by its id. */ +function energyOfId(pool: readonly BookDecoratedTemplate[], id: string | undefined): TemplateEnergy | undefined { + const tpl = id ? pool.find((t) => t.id === id) : undefined; + return tpl ? templateEnergy(tpl) : undefined; +} + +/** + * The template a page is laid on, of the archetype's and its kin's; any + * archetype's when none of those can take it; undefined when none at all can + * (a page of words with no words template anywhere). + */ +export function pickInnerTemplate(chunk: TemplateChunk, ctx: TemplatePickCtx): BookDecoratedTemplate | undefined { + const all = decoratedTemplatesFor('inner'); + const before = energyOfId(all, ctx.history[ctx.history.length - 1]); + for (const pool of [innerPool(ctx.archetype), all]) { + const scored = pool + .filter((t) => admits(t, chunk, ctx, before)) + .map((tpl) => ({ tpl, score: scoreOf(tpl, chunk, ctx, before) })); + const pick = bestOf(scored, ctx.seed, ctx.key); + if (pick) return pick; + } + return undefined; +} + +/** What a cover may be laid with: how many photos there are, and whether the cover photo stands tall. */ +export interface CoverPick { + archetype: BookCoverArchetype; + photos: number; + portrait: boolean; + seed: number; + /** Ids never to take (the cover on screen, on "this spread"). */ + avoid?: readonly string[]; +} + +const PORTRAIT_COVER = /-portrait$|^cutout-/; + +/** + * The cover template of an archetype for the photos there are: one that + * leaves no frame empty and fills the most of them, a tall one for a tall + * cover photo, equals chosen by the seed. Undefined when the archetype has + * none to take them, for the composed cover to stand in. + */ +export function pickCoverTemplate(p: CoverPick): BookDecoratedTemplate | undefined { + const scored = decoratedTemplatesFor('single', p.archetype) + .filter((t) => slots(t) <= p.photos && !p.avoid?.includes(t.id)) + // Without a photo only a cover drawn for none stands; a photo frame left empty does not. + .filter((t) => p.photos > 0 || slots(t) === 0) + .map((tpl) => { + const tall = PORTRAIT_COVER.test(tpl.id); + return { tpl, score: slots(tpl) * 10 + (tall === p.portrait ? 8 : 0) }; + }); + return bestOf(scored, p.seed, `cover:${p.archetype}`); +}