feat(studio): text effects, fit to frame and 24 lockups in a Text styles shelf

- A text can be cased (capitals, lower case, small caps), placed at the top,
  middle or foot of its frame, outlined, given a hard shadow or a marker band,
  bent on an arc or round a circle, filled with a gallery photo or left
  hollow, and shrunk to fit its frame. Every effect prints as vector: copies
  and strokes for HTML type, textPath and a clip over an <image> for SVG.
- Fitting is solved when the text is edited, in the Studio and in the edit
  engine, and stored; the chosen size is kept as the ceiling.
- Text sizes reach 400 pt and tracking 1.5 em.
- The Elements panel opens on a Text tab: the plain styles and 24 lockups
  (titles, badges and stamps, chapter marks, quotes, captions, places), each
  drawn with the book's own title and placed as one group.
- The assistant sets every effect through style and add, places a lockup with
  add_lockup, reads the effects in describe_book_page and gets two new
  findings (curve_overflow, effect_heavy) beside photo-fill and band checks.
- Book format revision 6.
This commit is contained in:
Maurice
2026-10-23 21:43:09 +02:00
parent 82b8eb1067
commit 75d0593198
125 changed files with 6469 additions and 51 deletions
+6 -2
View File
@@ -32,6 +32,7 @@ import { bookElementIdSchema, bookGridIdSchema, bookSpreadIdSchema } from './boo
import { bookPaintInSchema } from './book-paint.schema';
import { BOOK_PHOTO_LOOK_PROPS } from './book-photo-look.schema';
import { bookStickerIdSchema } from './book-sticker';
import { TEXT_EFFECT_PROPS, bookAddLockupOpSchema } from './book-text-ops.schema';
import {
MAX_BOOK_COUNTRIES,
bookBadgeElementSchema,
@@ -51,7 +52,7 @@ import { z } from 'zod';
/**
* The element operations of a book page: create any of the ten 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
* page, refresh the travel figures, drop in a photo grid, set a lockup. 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.
*
@@ -116,7 +117,8 @@ export const TEXT_STYLE_FIELDS = {
tracking: text.tracking.unwrap().optional(),
color: text.color.unwrap().optional(),
};
const TEXT_PROPS = { ...COMMON, ...TEXT_STYLE_FIELDS, ...THEMED_TEXT_IN };
/** A text's look for `style` and `add`: its setting, its theme links and its effects (book-text-ops.schema.ts). */
const TEXT_PROPS = { ...COMMON, ...TEXT_STYLE_FIELDS, ...THEMED_TEXT_IN, ...TEXT_EFFECT_PROPS };
const SHAPE_PROPS = {
...COMMON,
fill: shape.fill.unwrap().optional(),
@@ -379,4 +381,6 @@ export const BOOK_ELEMENT_OP_SCHEMAS = [
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() }),
/** A lockup: a set title, badge, postmark, quote, caption or chapter mark (book-text-ops.schema.ts). */
bookAddLockupOpSchema,
] as const;
+3
View File
@@ -5,6 +5,7 @@ import { visibleSpread } from './book-groups';
import type { BookPhotoInfo } from './book-ops-core';
import { BOOK_OP_LIMITS, type BookFinding } from './book-ops.schema';
import { photoZoomBox, photoZoomOf } from './book-photo-look';
import { bookTextHasOwnGround } from './book-text-findings';
import type { BookDocument, BookElement, BookFrame, BookPageSetup, BookPhotoElement, BookSpread } from './book.schema';
/**
@@ -142,6 +143,8 @@ const add = (ctx: Ctx, f: BookFinding) => ctx.out.push({ ...f, message: f.messag
function contrastAndBusy(ctx: Ctx): void {
ctx.spread.elements.forEach((el, i) => {
if (!READ.has(el.kind)) return;
// A band, an outline or a picture in the letters is the text's own ground (book-text-findings.ts).
if (el.kind === 'text' && bookTextHasOwnGround(el)) return;
const ink = inkOf(el);
const ground = groundOf(ctx.spread, i, el.frame, ctx.photos);
if (ground.kind === 'photo') {
+23 -4
View File
@@ -7,6 +7,8 @@ import { visibleSpread } from './book-groups';
import type { BookPhotoInfo } from './book-ops-core';
import type { BookFinding } from './book-ops.schema';
import { photoZoomOf } from './book-photo-look';
import { bookTextIsDrawn } from './book-text-effects.schema';
import { textEffectFindings } from './book-text-findings';
import type { BookElement, BookPageSetup, BookPhotoElement, BookSpread, BookTextElement } from './book.schema';
/**
@@ -110,6 +112,21 @@ function wrappedLines(para: string, perLine: number): number {
return lines;
}
/** How much wider capitals set than the family's average letter; a capitals-only face is set in them already. */
const CASE_WIDTH: Record<string, number> = { upper: 1.18, smallcaps: 1.08 };
/**
* The average advance of one letter of a text in millimetres, its tracking
* included: the family's letter width at the text's size, a little more when
* bold, and more again when it is set in capitals.
*/
export function bookLetterMm(el: BookTextElement, headroom = 1): number {
const sizeMm = (orDefault(el.size, 11) * 25.4) / 72;
const tracking = orDefault(el.tracking, 0);
const caps = bookFontFace(el.font)?.caps ? 1 : (CASE_WIDTH[el.transform ?? 'none'] ?? 1);
return sizeMm * (letterEm(el.font) * (el.weight >= 600 ? 1.06 : 1) * caps * headroom + tracking);
}
/**
* How many millimetres a text needs to be set at its frame's width, roughly:
* its words wrapped at the family's average letter width times `headroom`,
@@ -119,8 +136,7 @@ function wrappedLines(para: string, perLine: number): number {
*/
export function textHeightNeeded(el: BookTextElement, headroom = 1): number {
const sizeMm = (orDefault(el.size, 11) * 25.4) / 72;
const tracking = orDefault(el.tracking, 0);
const letter = sizeMm * (letterEm(el.font) * (el.weight >= 600 ? 1.06 : 1) * headroom + tracking);
const letter = bookLetterMm(el, headroom);
const perLine = Math.max(1, Math.floor(el.frame.w / Math.max(letter, 0.1)));
const lines = el.text.split('\n').reduce((sum, para) => sum + wrappedLines(para.trimEnd(), perLine), 0);
return lines * sizeMm * orDefault(el.leading, 1.45);
@@ -240,7 +256,8 @@ function overlapFinding(a: BookElement, b: BookElement, ba: Box, bb: Box, shared
* to the cap, so pairs layered on purpose never crowd out an accident.
*/
function overlaps(ctx: Ctx): void {
const content = ctx.spread.elements.filter((e) => e.kind === 'photo' || e.kind === 'text');
// A curved text's ink is its curve, not its frame: a badge's rim runs round what it holds.
const content = ctx.spread.elements.filter((e) => e.kind === 'photo' || (e.kind === 'text' && !e.curve));
const found: BookFinding[] = [];
for (let i = 0; i < content.length; i++) {
for (let j = i + 1; j < content.length; j++) {
@@ -461,7 +478,8 @@ function salientCut(ctx: Ctx, el: BookPhotoElement): void {
function overflow(ctx: Ctx): void {
for (const el of ctx.spread.elements) {
if (el.kind !== 'text' || !el.text.trim()) continue;
// A curved or photo-filled text is set as written, unwrapped: its own check measures it.
if (el.kind !== 'text' || !el.text.trim() || bookTextIsDrawn(el)) continue;
const need = textHeightNeeded(el);
if (need <= el.frame.h * 1.1 + 0.5) continue;
add(ctx, {
@@ -512,5 +530,6 @@ export function spreadFindings(
parked(ctx);
for (const f of stickerFindings(spread)) add(ctx, f);
for (const f of strokeFindings(spread)) add(ctx, f);
ctx.out.push(...textEffectFindings(spread, photos));
return sortBookFindings(ctx.out);
}
+589
View File
@@ -0,0 +1,589 @@
import type {
BookLockup,
BookLockupRole,
BookLockupShapePart,
BookLockupTextPart,
BookLockupTone,
} from './book-lockups';
/**
* The 24 lockups, in the units of a box 100 wide (book-lockups.ts).
*
* Type sizes are chosen against the share of the page a lockup takes, so the
* printed sizes land where the type scale wants them on a 210 mm page: a cover
* title between 70 and 180 pt, spaced capitals at 8 to 11 pt with a quarter to
* half an em of tracking, a title at least three times its subtitle. Every
* frame is a little taller than its line, and the parts never touch unless
* they are meant to layer, so a lockup placed as it comes has no severe finding.
*
* The faces are the book's own (book-fonts.data.ts): condensed and heavy
* poster faces for titles, Montserrat for spaced capitals, a thin serif and its
* italic for quiet titles and quotes, a script for the word laid over a title,
* DM Mono for coordinates.
*/
/** A line of spaced capitals: a date line, a kicker, a year. */
function spaced(
role: BookLockupRole,
y: number,
size: number,
tone: BookLockupTone = 'muted',
more: Partial<BookLockupTextPart> = {},
): BookLockupTextPart {
return {
kind: 'text',
role,
x: 0,
y,
w: 100,
h: size * 2,
font: 'montserrat',
size,
weight: 600,
tracking: 0.4,
transform: 'upper',
tone,
...more,
};
}
/** A filled bar: a rule when it is thin, a band when it is not. */
function bar(x: number, y: number, w: number, h: number, fill: BookLockupTone = 'ink'): BookLockupShapePart {
return { kind: 'shape', shape: 'rect', x, y, w, h, fill };
}
/** A circle drawn as a line only. */
function ring(inset: number, stroke: BookLockupTone, strokeWidth: number, size = 100): BookLockupShapePart {
const side = size - inset * 2;
return { kind: 'shape', shape: 'ellipse', x: inset, y: inset, w: side, h: side, fill: null, stroke, strokeWidth };
}
/** A condensed poster face, Bebas unless the part says another: capitals, tight lines. */
function poster(
role: BookLockupRole,
y: number,
size: number,
more: Partial<BookLockupTextPart> = {},
): BookLockupTextPart {
return {
kind: 'text',
role,
x: 0,
y,
w: 100,
h: size * 1.05,
font: 'bebas',
size,
leading: 0.9,
tracking: 0.02,
transform: 'upper',
tone: 'ink',
...more,
};
}
export const BOOK_LOCKUPS: readonly BookLockup[] = [
{
id: 'poster-stack',
descr: 'Heavy poster title with a hard accent shadow, a subtitle on an accent band, the year under it',
height: 62,
share: 0.8,
parts: [
poster('title', 0, 34, { font: 'anton', shadow: { dx: 0.9, dy: 0.9, tone: 'accent' } }),
poster('subtitle', 38, 7.5, {
h: 11,
tracking: 0.3,
tone: 'paper',
highlight: { tone: 'accent', padX: 2.4, padY: 0.5 },
}),
spaced('year', 54, 2.4, 'ink', { h: 6 }),
],
},
{
id: 'spaced-date',
descr: 'A spaced date line over a condensed title, a short accent rule and the place',
height: 50,
share: 0.75,
parts: [
spaced('dates', 0, 2.4, 'muted', { h: 6 }),
poster('title', 7, 30, { font: 'league', tracking: 0.04 }),
bar(42, 40.5, 16, 0.5, 'accent'),
spaced('place', 43.5, 2.4, 'ink', { h: 6, tracking: 0.3 }),
],
},
{
id: 'serif-sun',
descr: 'A large thin serif title, an italic subtitle, a sun between two hairlines and the year',
height: 64,
share: 0.8,
parts: [
{
kind: 'text',
role: 'title',
x: 0,
y: 0,
w: 100,
h: 28,
font: 'cormorant',
size: 26,
weight: 300,
leading: 1,
tracking: -0.01,
tone: 'ink',
},
{
kind: 'text',
role: 'subtitle',
x: 0,
y: 29,
w: 100,
h: 10,
font: 'cormorant',
size: 7.5,
italic: true,
tone: 'ink',
},
bar(18, 46.8, 26, 0.3),
{ kind: 'shape', shape: 'sun', x: 46, y: 43, w: 8, h: 8, fill: 'accent' },
bar(56, 46.8, 26, 0.3),
spaced('year', 55, 2.2, 'muted', { h: 6, tracking: 0.5 }),
],
},
{
id: 'title-script-year',
descr: 'A bold serif title, an accent script subtitle turned across its foot, the year in spaced capitals',
height: 50,
share: 0.75,
parts: [
{
kind: 'text',
role: 'title',
x: 0,
y: 0,
w: 100,
h: 25,
font: 'playfair',
size: 22,
weight: 700,
leading: 0.95,
tone: 'ink',
},
{
kind: 'text',
role: 'subtitle',
x: 12,
y: 24,
w: 76,
h: 13,
rotation: -4,
font: 'vibes',
size: 12,
italic: false,
tone: 'accent',
},
spaced('year', 42, 2.4, 'muted', { h: 6, tracking: 0.45 }),
],
},
{
id: 'circle-badge',
descr: 'A round accent badge: a kicker run round its rim inside a paper ring, the title and the year in the middle',
height: 100,
share: 0.45,
parts: [
{ kind: 'shape', shape: 'ellipse', x: 0, y: 0, w: 100, h: 100, fill: 'accent' },
ring(5, 'paper', 0.7),
spaced('kicker', 0, 6, 'paper', {
x: 7,
y: 7,
w: 86,
h: 86,
tracking: 0.25,
curve: { type: 'circle', bend: 0, start: 0 },
}),
poster('title', 36, 22, { x: 16, w: 68, h: 24, tone: 'paper', tracking: 0.04 }),
spaced('year', 62, 4.4, 'paper', { x: 25, w: 50, h: 8, tracking: 0.3 }),
],
},
{
id: 'postmark',
descr: 'A round postmark: the place round its rim between two rings, the date in the middle over a cancel wave',
height: 100,
share: 0.42,
parts: [
ring(0.5, 'ink', 1),
ring(14, 'ink', 0.5),
poster('place', 0, 12, {
x: 1,
y: 1,
w: 98,
h: 98,
tracking: 0.16,
curve: { type: 'circle', bend: 0, start: 0 },
}),
poster('dates', 38, 10, { x: 20, w: 60, h: 11, tracking: 0.08 }),
{ kind: 'shape', shape: 'wave', x: 22, y: 53, w: 56, h: 8, fill: 'ink' },
spaced('year', 63, 4.4, 'ink', { x: 25, w: 50, h: 8, tracking: 0.3 }),
],
},
{
id: 'script-overlay',
descr: 'A spaced poster title with a large accent script word turned over it, outlined in paper',
height: 58,
share: 0.8,
parts: [
poster('title', 22, 32, { tracking: 0.1 }),
{
kind: 'text',
role: 'overlay',
x: 8,
y: 0,
w: 84,
h: 30,
rotation: -6,
font: 'yellowtail',
size: 24,
weight: 400,
italic: false,
tone: 'accent',
outline: { tone: 'paper', width: 0.6 },
},
],
},
{
id: 'photo-word',
descr: 'A huge poster word filled with a photo, a spaced kicker over it',
height: 50,
share: 0.85,
parts: [
spaced('kicker', 0, 2.4, 'ink', { h: 6, tracking: 0.45 }),
poster('title', 7, 40, { h: 42, font: 'anton', fill: 'photo' }),
],
},
{
id: 'fabric-band',
descr: 'A poster title in paper on a full accent band, a script subtitle under it',
height: 44,
share: 0.8,
parts: [
bar(0, 0, 100, 26, 'accent'),
poster('title', 4, 18, { h: 18, tracking: 0.14, tone: 'paper' }),
{
kind: 'text',
role: 'subtitle',
x: 0,
y: 29,
w: 100,
h: 13,
font: 'satisfy',
size: 7,
italic: false,
tone: 'ink',
},
],
},
{
id: 'quote-classic',
descr:
'A large accent quotation mark, the quote in a serif italic, an accent rule and the source in spaced capitals',
height: 56,
share: 0.6,
parts: [
{
kind: 'text',
role: 'quote',
literal: '“',
x: 0,
y: 0,
w: 22,
h: 22,
font: 'playfair',
size: 26,
weight: 700,
leading: 0.8,
align: 'left',
tone: 'accent',
},
{
kind: 'text',
role: 'quote',
x: 0,
y: 23,
w: 100,
h: 24,
font: 'cormorant',
size: 6.5,
italic: true,
leading: 1.3,
align: 'left',
tone: 'ink',
},
bar(0, 50.8, 9, 0.4, 'accent'),
spaced('caption', 48, 2.8, 'muted', { x: 12, w: 88, h: 6, align: 'left', tracking: 0.3 }),
],
},
{
id: 'quote-band',
descr: 'A quote set in paper on ink bands behind each line, the source under it',
height: 42,
share: 0.7,
parts: [
{
kind: 'text',
role: 'quote',
x: 0,
y: 0,
w: 100,
h: 32,
font: 'sans',
size: 5,
weight: 600,
leading: 1.6,
align: 'left',
tone: 'paper',
highlight: { tone: 'ink', padX: 1.4, padY: 0.4 },
},
spaced('caption', 35, 2.6, 'muted', { h: 6, align: 'left', tracking: 0.3 }),
],
},
{
id: 'caption-rule',
descr: 'A caption in spaced capitals after a short rule',
height: 8,
share: 0.5,
parts: [
bar(0, 3.85, 8, 0.3),
spaced('caption', 0, 3.1, 'ink', { x: 11, w: 89, h: 8, align: 'left', tracking: 0.3 }),
],
},
{
id: 'caption-number',
descr: 'An accent figure beside a caption in a serif italic',
height: 16,
share: 0.5,
parts: [
poster('number', 0, 14, { w: 16, h: 16, align: 'left', tone: 'accent' }),
{
kind: 'text',
role: 'caption',
x: 18,
y: 1,
w: 82,
h: 14,
font: 'cormorant',
size: 4.8,
italic: true,
leading: 1.3,
align: 'left',
tone: 'ink',
},
],
},
{
id: 'ticket',
descr: 'A ticket outline holding a kicker, the place in poster capitals and the dates',
height: 40,
share: 0.55,
parts: [
{ kind: 'shape', shape: 'ticket', x: 0, y: 0, w: 100, h: 40, fill: null, stroke: 'ink', strokeWidth: 0.5 },
spaced('kicker', 7, 2.8, 'muted', { x: 12, w: 76, h: 5 }),
poster('place', 12, 15, { x: 12, w: 76, h: 16, tracking: 0.08 }),
spaced('dates', 28.5, 2.8, 'ink', { x: 12, w: 76, h: 5, font: 'mono', weight: 500, tracking: 0.12 }),
],
},
{
id: 'coords-pin',
descr: 'Coordinates in spaced figures after an accent map pin',
height: 10,
share: 0.5,
parts: [
{ kind: 'shape', shape: 'pin', x: 0, y: 1, w: 6, h: 8, fill: 'accent' },
spaced('coords', 0, 3.2, 'ink', {
x: 9,
w: 91,
h: 10,
align: 'left',
font: 'mono',
weight: 400,
tracking: 0.12,
transform: 'none',
}),
],
},
{
id: 'coords-stack',
descr: 'The place in poster capitals, an accent rule and the coordinates under it',
height: 30,
share: 0.5,
parts: [
poster('place', 0, 15, { h: 16, tracking: 0.1 }),
bar(42, 17.5, 16, 0.4, 'accent'),
spaced('coords', 21, 3, 'muted', { h: 7, font: 'mono', weight: 400, tracking: 0.08, transform: 'none' }),
],
},
{
id: 'chapter-outline',
descr: 'A huge hollow outlined figure, a spaced accent label under it and the title in a serif italic',
height: 62,
share: 0.45,
parts: [
poster('number', 0, 42, { h: 42, fill: { tone: 'ink', alpha: 0 }, outline: { tone: 'accent', width: 0.5 } }),
spaced('label', 43, 3.6, 'accent', { h: 7, tracking: 0.5 }),
{
kind: 'text',
role: 'title',
x: 0,
y: 51,
w: 100,
h: 11,
font: 'cormorant',
size: 8,
italic: true,
tone: 'ink',
},
],
},
{
id: 'chapter-rules',
descr: 'A serif figure between two hairlines, the title in spaced capitals under it',
height: 34,
share: 0.5,
parts: [
bar(0, 12.8, 32, 0.35),
{ kind: 'text', role: 'number', x: 34, y: 2, w: 32, h: 22, font: 'bodoni', size: 17, leading: 1, tone: 'ink' },
bar(68, 12.8, 32, 0.35),
spaced('title', 26, 3.4, 'ink', { h: 7 }),
],
},
{
id: 'day-opener',
descr: 'A spaced label, a huge accent serif figure and the place in poster capitals, set flush left',
height: 58,
share: 0.5,
parts: [
spaced('label', 0, 3.4, 'muted', { h: 7, align: 'left', tracking: 0.5 }),
{
kind: 'text',
role: 'number',
x: 0,
y: 7,
w: 100,
h: 37,
font: 'fraunces',
size: 40,
weight: 800,
leading: 0.85,
align: 'left',
tone: 'accent',
},
poster('place', 46, 10, { h: 11, align: 'left', tracking: 0.14 }),
],
},
{
id: 'stamp',
descr: 'A rubber stamp set at an angle: a double accent frame round the place and the dates',
height: 44,
share: 0.45,
rotation: -7,
parts: [
{
kind: 'shape',
shape: 'rect',
x: 0,
y: 0,
w: 100,
h: 44,
fill: null,
stroke: 'accent',
strokeWidth: 1,
radius: 2,
},
{
kind: 'shape',
shape: 'rect',
x: 3.5,
y: 3.5,
w: 93,
h: 37,
fill: null,
stroke: 'accent',
strokeWidth: 0.35,
radius: 1,
},
poster('place', 8, 17, { x: 7, w: 86, h: 18, tracking: 0.12, tone: 'accent' }),
spaced('dates', 28, 3.4, 'accent', { x: 7, w: 86, h: 7, tracking: 0.35 }),
],
},
{
id: 'arched-title',
descr: 'A poster title arched over a script subtitle, a sparkle at each side',
height: 58,
share: 0.75,
parts: [
poster('title', 0, 20, { h: 42, tracking: 0.08, curve: { type: 'arc', bend: 42, start: 0 } }),
{ kind: 'shape', shape: 'sparkle', x: 6, y: 43, w: 7, h: 7, fill: 'accent' },
{
kind: 'text',
role: 'subtitle',
x: 16,
y: 41,
w: 68,
h: 12,
font: 'dancing',
size: 7,
italic: false,
weight: 500,
tone: 'ink',
},
{ kind: 'shape', shape: 'sparkle', x: 87, y: 43, w: 7, h: 7, fill: 'accent' },
],
},
{
id: 'retro-shadow',
descr: 'A heavy retro title in the accent, outlined in ink with a hard ink shadow, a subtitle and the year',
height: 48,
share: 0.75,
parts: [
{
kind: 'text',
role: 'title',
x: 0,
y: 0,
w: 100,
h: 28,
font: 'shrikhand',
size: 21,
weight: 400,
leading: 0.95,
tracking: -0.01,
tone: 'accent',
outline: { tone: 'ink', width: 0.5 },
shadow: { dx: 1.3, dy: 1.3, tone: 'ink' },
},
spaced('subtitle', 32, 2.8, 'ink', { h: 7, tracking: 0.35 }),
spaced('year', 40, 2.4, 'muted', { h: 7, tracking: 0.35 }),
],
},
{
id: 'outline-echo',
descr: 'The title three times in poster capitals: two hollow outlines over the solid word, the year under it',
height: 66,
share: 0.7,
parts: [
poster('title', 0, 17, { h: 18, fill: { tone: 'ink', alpha: 0 }, outline: { tone: 'ink', width: 0.3 } }),
poster('title', 19, 17, { h: 18, fill: { tone: 'ink', alpha: 0 }, outline: { tone: 'ink', width: 0.3 } }),
poster('title', 38, 17, { h: 18 }),
spaced('year', 59, 2.6, 'muted', { h: 6, tracking: 0.45 }),
],
},
{
id: 'minimal-caps',
descr: 'A title in widely spaced light capitals, a hairline and the year: quiet and elegant',
height: 30,
share: 0.7,
parts: [
spaced('title', 0, 8, 'ink', { h: 13, weight: 300, tracking: 0.55 }),
bar(44, 16.5, 12, 0.3),
spaced('year', 21, 2.6, 'muted', { h: 7, weight: 400, tracking: 0.5 }),
],
},
];
+181
View File
@@ -0,0 +1,181 @@
import { contrastRatio } from './book-colour';
import {
BOOK_LOCKUP_PALETTE,
addBookLockup,
buildBookLockup,
bookLockupBox,
findBookLockup,
type BookLockupWords,
} from './book-lockups';
import { BOOK_LOCKUPS } from './book-lockups.data';
import { formatBookCoords } from './book-text';
import { bookTextFits } from './book-text-fit';
import { bookElementSchema, bookPageSetupSchema, type BookSpread, type BookTextElement } from './book.schema';
import { pageFindings } from './describe-spread';
import { describe, expect, it } from 'vitest';
/**
* The lockups: every one builds into elements the document reads, its words
* fitted into their frames, and placed as it comes on a blank page it has no
* finding worth fixing, with a short title and with a long one.
*/
const page = bookPageSetupSchema.parse({});
const WORDS: BookLockupWords = {
title: 'Lisbon',
subtitle: 'A summer by the sea',
kicker: 'Travel journal',
overlay: 'travel',
year: '2026',
place: 'Portugal',
dates: '12 to 26 August',
quote: 'The best views come after the hardest climbs.',
caption: 'Alfama at first light',
number: '01',
label: 'Day',
coords: formatBookCoords(38.7139, -9.1334),
};
const LONG: BookLockupWords = {
...WORDS,
title: 'Two weeks along the Portuguese coast',
place: 'Sintra and the coast',
};
let seq = 0;
const newId = (p: string) => `${p}-${++seq}`;
const spreadOf = (elements: BookSpread['elements']): BookSpread => ({
id: 'sp',
role: 'inner',
background: null,
elements,
parked: [],
entryId: null,
});
describe('the lockup catalogue', () => {
it('BKLCK-001: holds 24 lockups with unique ids, each described and drawn inside its own box', () => {
expect(BOOK_LOCKUPS).toHaveLength(24);
expect(new Set(BOOK_LOCKUPS.map((l) => l.id)).size).toBe(24);
for (const l of BOOK_LOCKUPS) {
expect(l.descr.length, l.id).toBeGreaterThan(20);
expect(l.share, l.id).toBeGreaterThan(0);
expect(l.share, l.id).toBeLessThanOrEqual(1);
for (const p of l.parts) {
expect(p.x, `${l.id} x`).toBeGreaterThanOrEqual(0);
expect(p.x + p.w, `${l.id} right`).toBeLessThanOrEqual(100.01);
expect(p.y, `${l.id} y`).toBeGreaterThanOrEqual(0);
expect(p.y + p.h, `${l.id} foot`).toBeLessThanOrEqual(l.height + 0.01);
}
}
expect(findBookLockup('postmark')?.id).toBe('postmark');
expect(findBookLockup('nope')).toBeUndefined();
});
it('BKLCK-002: sets its small lines in a grey that still reads on white paper', () => {
expect(contrastRatio(BOOK_LOCKUP_PALETTE.muted, BOOK_LOCKUP_PALETTE.paper)).toBeGreaterThanOrEqual(4.5);
});
for (const [name, words] of [
['short', WORDS],
['long', LONG],
] as const) {
it(`BKLCK-003 (${name} words): builds every lockup into readable, fitted elements with no severe or warning finding`, () => {
for (const l of BOOK_LOCKUPS) {
const els = buildBookLockup(l, bookLockupBox(l, page, false), { words, newId, photoId: 5 });
expect(els.length, l.id).toBeGreaterThan(0);
for (const el of els) expect(bookElementSchema.safeParse(el).success, `${l.id} ${el.id}`).toBe(true);
for (const el of els.filter((e): e is BookTextElement => e.kind === 'text')) {
expect(bookTextFits(el), `${l.id} "${el.text}"`).toBe(true);
expect(el.fit).toBe('shrink');
}
const found = pageFindings(spreadOf(els), page, [{ photoId: 5, width: 4000, height: 3000 }]);
expect(
found.filter((f) => f.severity !== 'info').map((f) => `${f.code}: ${f.message}`),
l.id,
).toEqual([]);
}
});
}
});
describe('building a lockup', () => {
const poster = findBookLockup('poster-stack');
if (!poster) throw new Error('poster-stack is missing');
it('BKLCK-004: scales its units onto the box it is placed in, centred in it, keeping its proportions', () => {
const els = buildBookLockup(poster, { x: 0, y: 0, w: 200, h: 400 }, { words: WORDS, newId });
const title = els[0];
expect(title?.frame.w).toBeCloseTo(200, 1);
// 62 units tall at 2 mm a unit, centred in a 400 mm box.
expect(title?.frame.y).toBeCloseTo((400 - 124) / 2, 1);
});
it('BKLCK-005: leaves out the parts that were given no words, and builds nothing from no words at all', () => {
const els = buildBookLockup(poster, { x: 0, y: 0, w: 100, h: 62 }, { words: { title: 'Porto' }, newId });
expect(els.map((e) => (e.kind === 'text' ? e.text : e.kind))).toEqual(['Porto']);
expect(buildBookLockup(poster, { x: 0, y: 0, w: 100, h: 62 }, { words: {}, newId })).toEqual([]);
const quote = findBookLockup('quote-classic');
if (!quote) throw new Error('quote-classic is missing');
// The quotation mark is fixed words: alone, it is not a lockup anybody placed.
expect(buildBookLockup(quote, { x: 0, y: 0, w: 100, h: 56 }, { words: {}, newId })).toEqual([]);
});
it('BKLCK-006: takes its colours from the palette it is given', () => {
const els = buildBookLockup(
poster,
{ x: 0, y: 0, w: 100, h: 62 },
{
words: WORDS,
newId,
palette: { ink: '#202020', accent: '#0f766e' },
},
);
const [title, subtitle] = els as BookTextElement[];
expect(title?.color).toBe('#202020');
expect(title?.shadow?.color).toBe('#0f766e');
expect(subtitle?.highlight?.color).toBe('#0f766e');
});
it('BKLCK-007: fills a photo word with the photo it is given, and with the accent without one', () => {
const word = findBookLockup('photo-word');
if (!word) throw new Error('photo-word is missing');
const box = { x: 0, y: 0, w: 100, h: 50 };
const withPhoto = buildBookLockup(word, box, { words: WORDS, newId, photoId: 9 }).find(
(e) => e.kind === 'text' && e.fillPaint,
);
expect(withPhoto?.kind === 'text' && withPhoto.fillPaint).toMatchObject({ type: 'photo', photoId: 9 });
const title = buildBookLockup(word, box, { words: WORDS, newId }).at(-1) as BookTextElement;
expect(title.fillPaint).toBeUndefined();
expect(title.color).toBe(BOOK_LOCKUP_PALETTE.accent);
});
it('BKLCK-008: turns a stamp as a whole, about its own centre', () => {
const stamp = findBookLockup('stamp');
if (!stamp) throw new Error('stamp is missing');
const els = buildBookLockup(stamp, { x: 0, y: 0, w: 100, h: 44 }, { words: WORDS, newId });
for (const el of els) expect(el.rotation).toBe(-7);
const outer = els[0];
expect((outer?.frame.x ?? 0) + (outer?.frame.w ?? 0) / 2).toBeCloseTo(50, 1);
expect((outer?.frame.y ?? 0) + (outer?.frame.h ?? 0) / 2).toBeCloseTo(22, 1);
});
it('BKLCK-009: is placed on the right-hand page of a double spread and on the page of a single one', () => {
const inner = bookLockupBox(poster, page, false);
expect(inner.x).toBeGreaterThan(page.pageWidth);
const single = bookLockupBox(poster, page, true);
expect(single.x + single.w).toBeLessThan(page.pageWidth);
expect(single.w).toBeCloseTo(page.pageWidth * poster.share, 1);
});
it('BKLCK-010: lays a lockup in front of the page as one group, and a single element without one', () => {
const els = buildBookLockup(poster, { x: 0, y: 0, w: 100, h: 62 }, { words: WORDS, newId });
const sp = addBookLockup(spreadOf([]), els, 'g-1');
expect(sp.elements.map((e) => e.group)).toEqual(['g-1', 'g-1', 'g-1']);
const one = buildBookLockup(poster, { x: 0, y: 0, w: 100, h: 62 }, { words: { title: 'Porto' }, newId });
const alone = addBookLockup(spreadOf([]), one, 'g-2');
expect(alone.elements[0]?.group).toBeUndefined();
});
});
+329
View File
@@ -0,0 +1,329 @@
import { groupElements } from './book-groups';
import { BOOK_LOCKUPS } from './book-lockups.data';
import type { BookTextCurve, BookTextTransform } from './book-text-effects.schema';
import { solveBookTextFit } from './book-text-fit';
import type {
BookElement,
BookFontFamily,
BookFrame,
BookPageSetup,
BookSpread,
BookShapeElement,
BookShapeId,
BookTextElement,
} from './book.schema';
/**
* Lockups: titles, date lines, badges, postmarks, quotes and chapter marks set
* as a few texts and shapes that belong together, the way the covers of the
* reference books are composed.
*
* ── How a lockup is described ───────────────────────────────────────────────
*
* In the units of a box 100 wide and `height` tall, every size and position in
* those units and every colour a tone (ink, accent, paper, muted) rather than a
* value. `buildBookLockup` scales the units onto the box it is placed in and
* the tones onto the palette it is given, so one description sets a cover
* title on a large square book and a chapter mark on a small landscape one.
*
* ── The words ───────────────────────────────────────────────────────────────
*
* A text part names the role its words play (title, year, place …), and the
* words arrive with the placement: the Studio passes the book's own title and
* translated samples, the assistant the words it was asked for. A part whose
* role has no words is left out, so a lockup asked for only a title is a
* title. Every text part is set to fit its frame, so a long title shrinks into
* its place instead of running out of it.
*
* ── What it builds ──────────────────────────────────────────────────────────
*
* Ordinary elements, back to front, which move, restyle, undo and print like
* any other, placed as one group (`addBookLockup`) so the set moves as one and
* a double click still reaches a single part.
*/
export const BOOK_LOCKUP_ROLES = [
'title',
'subtitle',
'kicker',
'overlay',
'year',
'place',
'dates',
'quote',
'caption',
'number',
'label',
'coords',
] as const;
export type BookLockupRole = (typeof BOOK_LOCKUP_ROLES)[number];
export type BookLockupWords = Partial<Record<BookLockupRole, string>>;
/** The colours a lockup is set in, by what they do. */
export type BookLockupTone = 'ink' | 'accent' | 'paper' | 'muted';
export type BookLockupPalette = Record<BookLockupTone, string>;
/**
* Ink black, a warm terracotta accent, white paper, and a warm grey a shade
* darker than the Studio's captions, so the small spaced lines it sets still
* read at the 4.5:1 small type needs.
*/
export const BOOK_LOCKUP_PALETTE: BookLockupPalette = {
ink: '#1a1a1a',
accent: '#b4532a',
paper: '#ffffff',
muted: '#7a7468',
};
interface PartBox {
x: number;
y: number;
w: number;
h: number;
/** Degrees, turned about the part's own centre. */
rotation?: number;
}
export interface BookLockupTextPart extends PartBox {
kind: 'text';
/** Where the words come from. */
role: BookLockupRole;
/** Fixed words, for a mark such as a quotation mark: set whatever the words given. */
literal?: string;
font: BookFontFamily;
size: number;
weight?: BookTextElement['weight'];
italic?: boolean;
align?: BookTextElement['align'];
leading?: number;
tracking?: number;
tone: BookLockupTone;
transform?: BookTextTransform;
outline?: { tone: BookLockupTone; width: number };
shadow?: { dx: number; dy: number; tone: BookLockupTone; alpha?: number };
highlight?: { tone: BookLockupTone; padX: number; padY: number; radius?: number; alpha?: number };
curve?: BookTextCurve;
/** `photo` fills the letters with the photo the placement names, else with the accent; a tone with alpha 0 leaves them hollow. */
fill?: 'photo' | { tone: BookLockupTone; alpha: number };
}
export interface BookLockupShapePart extends PartBox {
kind: 'shape';
shape: BookShapeId;
fill: BookLockupTone | null;
stroke?: BookLockupTone;
strokeWidth?: number;
strokeStyle?: BookShapeElement['strokeStyle'];
radius?: number;
}
export type BookLockupPart = BookLockupTextPart | BookLockupShapePart;
export interface BookLockup {
id: string;
/** The box is 100 units wide and this tall. */
height: number;
/** How much of a page's width it takes when placed without a box. */
share: number;
/** The whole lockup turned about its centre, in degrees: a stamp set at an angle. */
rotation?: number;
/** What it is, for the assistant's schema and the shelf's tooltips. */
descr: string;
parts: readonly BookLockupPart[];
}
export function findBookLockup(id: string): BookLockup | undefined {
return BOOK_LOCKUPS.find((l) => l.id === id);
}
const r2 = (v: number) => Math.round(v * 100) / 100;
/**
* Where a lockup goes when no box is named: its share of the page width,
* centred on the page, or on the right-hand page of a double spread so it never
* lands in the fold.
*/
export function bookLockupBox(lockup: BookLockup, page: BookPageSetup, single: boolean): BookFrame {
const w = Math.min(page.pageWidth * lockup.share, ((page.pageHeight * 0.8) / lockup.height) * 100);
const h = (w / 100) * lockup.height;
const origin = single ? 0 : page.pageWidth;
return { x: r2(origin + (page.pageWidth - w) / 2), y: r2((page.pageHeight - h) / 2), w: r2(w), h: r2(h) };
}
/** The lockup's own proportions, as large as the box allows and centred in it. */
function fitted(lockup: BookLockup, box: BookFrame): { x: number; y: number; scale: number } {
const scale = Math.min(box.w / 100, box.h / lockup.height);
return {
x: box.x + (box.w - 100 * scale) / 2,
y: box.y + (box.h - lockup.height * scale) / 2,
scale,
};
}
interface Placement {
origin: { x: number; y: number; scale: number };
centre: { x: number; y: number };
turn: number;
}
/** A part's frame on the page and its rotation, the lockup's own turn applied about the lockup's centre. */
function placed(part: PartBox, at: Placement): { frame: BookFrame; rotation: number } {
const { x, y, scale } = at.origin;
const w = part.w * scale;
const h = part.h * scale;
let cx = x + (part.x + part.w / 2) * scale;
let cy = y + (part.y + part.h / 2) * scale;
if (at.turn) {
const rad = (at.turn * Math.PI) / 180;
const dx = cx - at.centre.x;
const dy = cy - at.centre.y;
cx = at.centre.x + dx * Math.cos(rad) - dy * Math.sin(rad);
cy = at.centre.y + dx * Math.sin(rad) + dy * Math.cos(rad);
}
const frame = { x: r2(cx - w / 2), y: r2(cy - h / 2), w: r2(Math.max(0.5, w)), h: r2(Math.max(0.3, h)) };
return { frame, rotation: r2((part.rotation ?? 0) + at.turn) };
}
/** Units to points at a scale of `scale` millimetres a unit, inside the document's range. */
const unitsToPt = (units: number, scale: number) =>
Math.min(400, Math.max(4, Math.round(((units * scale * 72) / 25.4) * 10) / 10));
export interface BuildLockupOptions {
words: BookLockupWords;
palette?: Partial<BookLockupPalette>;
/** The photo a photo-filled part is filled with; without one it is filled with the accent. */
photoId?: number | null;
newId: (prefix: string) => string;
}
const BASE = { opacity: 1, locked: false };
function textFill(part: BookLockupTextPart, tones: BookLockupPalette, photoId: number | null | undefined) {
if (part.fill === 'photo') {
return photoId ? { type: 'photo' as const, photoId, focalX: 0.5, focalY: 0.5, zoom: 1 } : null;
}
return part.fill ? { type: 'solid' as const, color: tones[part.fill.tone], alpha: part.fill.alpha } : null;
}
function textPart(
part: BookLockupTextPart,
words: string,
at: Placement,
opts: BuildLockupOptions,
tones: BookLockupPalette,
) {
const { frame, rotation } = placed(part, at);
const s = at.origin.scale;
const size = unitsToPt(part.size, s);
const fillPaint = textFill(part, tones, opts.photoId);
const el: BookTextElement = {
...BASE,
id: opts.newId('t'),
kind: 'text',
frame,
rotation,
text: words,
font: part.font,
size,
weight: part.weight ?? 400,
italic: part.italic ?? false,
align: part.align ?? 'center',
leading: part.leading ?? 1.1,
tracking: part.tracking ?? 0,
// A photo fill that found no photo falls back to the accent, so the word still carries colour.
color: part.fill === 'photo' && !fillPaint ? tones.accent : tones[part.tone],
binding: null,
overridden: false,
vAlign: 'middle',
fit: 'shrink',
fitMax: size,
...(part.transform ? { transform: part.transform } : {}),
...(fillPaint ? { fillPaint } : {}),
...(part.outline ? { outline: { color: tones[part.outline.tone], width: r2(part.outline.width * s) } } : {}),
...(part.shadow
? {
shadow: {
dx: r2(part.shadow.dx * s),
dy: r2(part.shadow.dy * s),
color: tones[part.shadow.tone],
alpha: part.shadow.alpha ?? 1,
},
}
: {}),
...(part.highlight
? {
highlight: {
color: tones[part.highlight.tone],
alpha: part.highlight.alpha ?? 1,
padX: r2(part.highlight.padX * s),
padY: r2(part.highlight.padY * s),
radius: r2((part.highlight.radius ?? 0) * s),
},
}
: {}),
...(part.curve ? { curve: part.curve } : {}),
};
return { ...el, size: solveBookTextFit(el, size) };
}
function shapePart(part: BookLockupShapePart, at: Placement, opts: BuildLockupOptions, tones: BookLockupPalette) {
const { frame, rotation } = placed(part, at);
const s = at.origin.scale;
const el: BookShapeElement = {
...BASE,
id: opts.newId('s'),
kind: 'shape',
frame,
rotation,
shape: part.shape,
fill: part.fill ? tones[part.fill] : null,
gradient: 'none',
stroke: part.stroke ? tones[part.stroke] : null,
strokeWidth: part.stroke ? r2(Math.max(0.1, (part.strokeWidth ?? 0.4) * s)) : 0,
strokeStyle: part.strokeStyle ?? 'solid',
radius: r2((part.radius ?? 0) * s),
};
return el;
}
/**
* The lockup's elements in `box`, back to front, its parts without words left
* out. Empty when no text part has words: a lockup of ornaments alone is not
* what anybody placed.
*/
export function buildBookLockup(lockup: BookLockup, box: BookFrame, opts: BuildLockupOptions): BookElement[] {
const tones = { ...BOOK_LOCKUP_PALETTE, ...opts.palette };
const origin = fitted(lockup, box);
const at: Placement = {
origin,
centre: { x: origin.x + 50 * origin.scale, y: origin.y + (lockup.height / 2) * origin.scale },
turn: lockup.rotation ?? 0,
};
const out: BookElement[] = [];
let words = 0;
for (const part of lockup.parts) {
if (part.kind === 'shape') {
out.push(shapePart(part, at, opts, tones));
continue;
}
const text = (part.literal ?? opts.words[part.role] ?? '').trim();
if (!text) continue;
if (!part.literal) words += 1;
out.push(textPart(part, text, at, opts, tones));
}
return words ? out : [];
}
/**
* A lockup's elements laid on a spread in front of what is there, made one
* group under `groupId` when there is more than one of them.
*/
export function addBookLockup(spread: BookSpread, made: readonly BookElement[], groupId: string): BookSpread {
const placed = { ...spread, elements: [...spread.elements, ...made] };
if (made.length < 2) return placed;
return groupElements(
placed,
made.map((e) => e.id),
groupId,
);
}
+8 -2
View File
@@ -17,6 +17,7 @@ import {
type BookOpsContext,
} from './book-ops-core';
import { bookLineStyled, bookNewLine } from './book-ops-line';
import { checkTextFillPhoto, opAddLockup } from './book-ops-lockup';
import { newStickerElement } from './book-ops-sticker';
import { withShapePaint } from './book-paint';
import type { BookPaint } from './book-paint.schema';
@@ -54,7 +55,7 @@ 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
* `refresh_travel`, `add_grid` and `add_lockup` 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.
*
@@ -99,6 +100,8 @@ export function applyElementOp(spread: BookSpread, op: ElementOp, env: ElementOp
return opRefreshTravel(spread, op, env);
case 'add_grid':
return opAddGrid(spread, op, env);
case 'add_lockup':
return opAddLockup(spread, op, env);
}
}
@@ -195,6 +198,7 @@ function opAdd(spread: BookSpread, op: Op<'add'>, env: ElementOpEnv): BookSpread
roomFor(spread, 1, env.opIndex);
const blank = created(spread, op.element, op.frame ? roundFrame(op.frame) : null, env);
const made = withProps(blank, lookOf(op.element), env.doc.theme);
checkTextFillPhoto(made, env);
const el = op.rotation !== undefined ? { ...made, rotation: op.rotation } : made;
const parked =
el.kind === 'photo' && el.photoId != null
@@ -435,7 +439,9 @@ function opStyle(spread: BookSpread, op: Op<'style'>, env: ElementOpEnv): BookSp
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, env.doc.theme)]);
const styled = withProps(el, op.set, env.doc.theme);
checkTextFillPhoto(styled, env);
return replaceAll(spread, [styled]);
}
function opLock(spread: BookSpread, op: Op<'lock'>, env: ElementOpEnv): BookSpread {
+40
View File
@@ -0,0 +1,40 @@
import { addBookLockup, buildBookLockup, bookLockupBox, findBookLockup } from './book-lockups';
import { failOp, galleryPhoto, roomFor, type BookOpsContext } from './book-ops-core';
import type { BookAddLockupOp } from './book-text-ops.schema';
import type { BookElement, BookPageSetup, BookSpread } from './book.schema';
/**
* `add_lockup`: the Studio's Text styles shelf, for the assistant. The same
* builder sets the same lockup from the same words, so a lockup the assistant
* placed looks exactly like one somebody picked from the shelf.
*/
interface LockupEnv {
page: BookPageSetup;
ctx: BookOpsContext;
newId: (prefix: string) => string;
opIndex: number;
}
export function opAddLockup(spread: BookSpread, op: BookAddLockupOp, env: LockupEnv): BookSpread {
const lockup = findBookLockup(op.lockup);
if (!lockup) throw failOp('invalid_op', `no lockup ${op.lockup}`, env.opIndex);
if (op.photoId !== undefined) galleryPhoto(op.photoId, env.ctx, env.opIndex);
const box = op.box ?? bookLockupBox(lockup, env.page, spread.role !== 'inner');
const made = buildBookLockup(lockup, box, {
words: op.words,
palette: { ...(op.ink ? { ink: op.ink } : {}), ...(op.accent ? { accent: op.accent } : {}) },
photoId: op.photoId ?? null,
newId: env.newId,
});
if (!made.length) {
throw failOp('text_required', `give the words for at least one of the texts of ${lockup.id}`, env.opIndex);
}
roomFor(spread, made.length, env.opIndex);
return addBookLockup(spread, made, env.newId('g'));
}
/** A text's photo fill names a gallery photo, checked as a photo frame's photo is. */
export function checkTextFillPhoto(el: BookElement, env: { ctx: BookOpsContext; opIndex: number }): void {
if (el.kind === 'text' && el.fillPaint?.type === 'photo') galleryPhoto(el.fillPaint.photoId, env.ctx, env.opIndex);
}
+2
View File
@@ -415,6 +415,8 @@ export const BOOK_FINDING_CODES = [
'raster_effect',
'hairline',
'edge_unused',
'curve_overflow',
'effect_heavy',
] as const;
export type BookFindingCode = (typeof BOOK_FINDING_CODES)[number];
+3
View File
@@ -26,6 +26,7 @@ import { applyGroupOp, isGroupOp } from './book-ops-groups';
import { BOOK_OP_LIMITS, bookPageOpSchema, type BookPageOp } from './book-ops.schema';
import { withSpreadPaint } from './book-paint';
import { applySavedBookLayout, bookLayoutRole } from './book-saved-layouts';
import { fitSpreadTexts } from './book-text-fit';
import {
MAX_SPREAD_ELEMENTS,
type BookDocument,
@@ -92,6 +93,8 @@ export function applyBookOps(
});
// A removal or a layout can leave a group with one member: it goes, with its name.
spread = tidyGroups(spread);
// A text set to fit its frame is solved once the page's operations are done (book-text-fit.ts).
spread = fitSpreadTexts(spread, original);
checkedSpread(spread, null);
const spreads = doc.spreads.slice();
spreads[index] = spread;
+4 -1
View File
@@ -40,8 +40,11 @@ import type { BookDocument } from './book.schema';
* book-shapes-more.ts) and the line kind (book-line.schema.ts).
* - 8: themes (the document's `theme`, and the `token`, `strokeToken`, `accentToken`,
* `fontRole` and `backgroundToken` links, theme/book-theme.schema.ts).
* - 9: text effects and fitting (`transform`, `vAlign`, `outline`, `shadow`, `highlight`,
* `curve`, `fillPaint`, `fit`, `fitMax`, book-text-effects.schema.ts), text up to 400 pt and
* tracking up to 1.5 em.
*/
export const BOOK_SCHEMA_REV = 8;
export const BOOK_SCHEMA_REV = 9;
/** The `code` a refused save carries in its body when the stored book is newer than the writer. */
export const BOOK_SCHEMA_NEWER_CODE = 'book_schema_newer';
+46
View File
@@ -0,0 +1,46 @@
import { bookTextCurvePath } from './book-text-curve';
import { describe, expect, it } from 'vitest';
/** The line a curved text runs along, in the millimetres of its frame. */
describe('the path of a curved text', () => {
it('BKCRV-001: runs a flat arc as a straight line across the frame, inset by half an em', () => {
const p = bookTextCurvePath({ type: 'arc', bend: 0, start: 0 }, 100, 40, 10);
expect(p.d).toBe('M 5 23.5 L 95 23.5');
expect(p.length).toBe(90);
});
it('BKCRV-002: arches clockwise over the top for a positive bend and dips anticlockwise for a negative one', () => {
const up = bookTextCurvePath({ type: 'arc', bend: 50, start: 0 }, 100, 60, 10);
const down = bookTextCurvePath({ type: 'arc', bend: -50, start: 0 }, 100, 60, 10);
expect(up.d).toMatch(/ 0 0 1 95 /);
expect(down.d).toMatch(/ 0 0 0 95 /);
// Longer than the chord, the same either way.
expect(up.length).toBeGreaterThan(90);
expect(up.length).toBeCloseTo(down.length, 6);
});
it('BKCRV-003: bends a half circle at 100, whose length is half the circumference of the chord', () => {
const p = bookTextCurvePath({ type: 'arc', bend: 100, start: 0 }, 120, 80, 10);
expect(p.length).toBeCloseTo((Math.PI * 110) / 2, 4);
});
it('BKCRV-004: keeps a bend past the bounds to a half circle', () => {
const half = bookTextCurvePath({ type: 'arc', bend: 100, start: 0 }, 120, 80, 10);
expect(bookTextCurvePath({ type: 'arc', bend: 300, start: 0 }, 120, 80, 10)).toEqual(half);
});
it('BKCRV-005: runs a circle round the inscribed circle, brought in by the letters, starting half a turn before its centre', () => {
const p = bookTextCurvePath({ type: 'circle', bend: 0, start: 0 }, 100, 100, 8);
const r = 50 - 8 * 0.75;
expect(p.length).toBeCloseTo(2 * Math.PI * r, 6);
// From the bottom of the circle, so the middle of the words lands at the top.
expect(p.d.startsWith(`M 50 ${50 + r}`)).toBe(true);
expect(p.d.match(/ A /g)).toHaveLength(2);
});
it('BKCRV-006: never draws a circle smaller than a millimetre, whatever the letters', () => {
expect(bookTextCurvePath({ type: 'circle', bend: 0, start: 90 }, 4, 4, 30).length).toBeCloseTo(2 * Math.PI, 6);
});
});
+71
View File
@@ -0,0 +1,71 @@
import type { BookTextCurve } from './book-text-effects.schema';
/**
* The line a curved text runs along, in the millimetres of its frame.
*
* Both the page and the checks read it: the page lays the words on it with SVG
* `textPath`, the checks compare its length with what the words need. It is
* computed here rather than in the renderer so the two can never disagree on
* how long a line is.
*
* The frame's SVG is drawn with a viewBox of its own size in millimetres, so a
* user unit is a millimetre in both directions and an arc command means a
* circle, never the ellipse it would turn into under a non-uniform scale.
*/
export interface BookTextCurvePath {
/** SVG path data, in millimetres from the frame's top left. */
d: string;
/** The length of the line in millimetres. */
length: number;
}
const r2 = (v: number) => Math.round(v * 100) / 100;
/** A point on a circle at `deg` degrees, 0 at the top and clockwise, as the page draws it. */
function onCircle(cx: number, cy: number, r: number, deg: number): string {
const rad = (deg * Math.PI) / 180;
return `${r2(cx + r * Math.sin(rad))} ${r2(cy - r * Math.cos(rad))}`;
}
/**
* Where a curved text is laid.
*
* `arc`: a chord across the frame, inset by half an em on each side so the
* first and last letter stay inside it, bowed by `bend` percent of half the
* chord (a half circle at 100). Up is the arch of a rainbow, down a smile; the
* letters always stand on the outside of the bow as read left to right, so
* neither direction prints a word upside down. The bow is centred in the frame
* with room for the letters above and below it.
*
* `circle`: the frame's inscribed circle, its radius brought in by the cap
* height so the letters stand inside the frame, starting half a turn before
* `start` so that the middle of the words, where they are anchored, sits at
* `start`.
*/
export function bookTextCurvePath(curve: BookTextCurve, w: number, h: number, fontMm: number): BookTextCurvePath {
if (curve.type === 'circle') {
const r = Math.max(1, Math.min(w, h) / 2 - fontMm * 0.75);
const from = curve.start - 180;
const d = `M ${onCircle(w / 2, h / 2, r, from)} A ${r2(r)} ${r2(r)} 0 1 1 ${onCircle(w / 2, h / 2, r, from + 180)} A ${r2(r)} ${r2(r)} 0 1 1 ${onCircle(w / 2, h / 2, r, from + 360)}`;
return { d, length: 2 * Math.PI * r };
}
const inset = Math.min(fontMm * 0.5, w * 0.1);
const chord = Math.max(1, w - inset * 2);
const x0 = r2(inset);
const x1 = r2(inset + chord);
const sag = (Math.max(-100, Math.min(100, curve.bend)) / 100) * (chord / 2);
// The baseline through the middle of the frame, moved down by the bow so the
// whole curve and the letters on it sit centred.
const mid = h / 2 + fontMm * 0.35;
if (Math.abs(sag) < 0.01) {
const y = r2(mid);
return { d: `M ${x0} ${y} L ${x1} ${y}`, length: chord };
}
const ends = r2(mid + sag / 2);
const radius = (chord * chord) / 4 / (2 * Math.abs(sag)) + Math.abs(sag) / 2;
// An arch runs clockwise over the top, a smile anticlockwise under it.
const sweep = sag > 0 ? 1 : 0;
const length = 2 * radius * Math.asin(Math.min(1, chord / (2 * radius)));
return { d: `M ${x0} ${ends} A ${r2(radius)} ${r2(radius)} 0 0 ${sweep} ${x1} ${ends}`, length };
}
+35
View File
@@ -0,0 +1,35 @@
import type { BookTextEffects } from './book-text-effects.schema';
/**
* A text's effects in words, for `describe_book_page`: what a model that
* cannot see the page needs to know to keep or change them, in the terms the
* `style` operation sets them by. Empty for a text without any.
*/
const n = (v: number) => `${Math.round(v * 10) / 10}`;
const CASES: Record<string, string> = { upper: 'capitals', lower: 'lower case', smallcaps: 'small caps' };
function fillWords(fill: NonNullable<BookTextEffects['fillPaint']>): string {
if (fill.type === 'photo') {
return `letters filled with photo ${fill.photoId} (focal ${fill.focalX.toFixed(2)}/${fill.focalY.toFixed(2)}, zoom ${n(fill.zoom)})`;
}
return fill.alpha === 0 ? 'hollow letters (outline only)' : `fill ${fill.color} at alpha ${n(fill.alpha)}`;
}
export function bookTextEffectWords(el: BookTextEffects & { size: number }): string {
const parts: string[] = [];
const cased = el.transform ? CASES[el.transform] : undefined;
if (cased) parts.push(cased);
if (el.vAlign && el.vAlign !== 'top') parts.push(`set at the ${el.vAlign} of its frame`);
if (el.fillPaint) parts.push(fillWords(el.fillPaint));
if (el.outline) parts.push(`outline ${el.outline.color} ${n(el.outline.width)} mm`);
if (el.shadow) {
parts.push(`hard shadow ${el.shadow.color} offset ${n(el.shadow.dx)}/${n(el.shadow.dy)} mm`);
}
if (el.highlight) parts.push(`on a band of ${el.highlight.color}`);
if (el.curve?.type === 'arc') parts.push(`on an arc, bend ${n(el.curve.bend)}`);
if (el.curve?.type === 'circle') parts.push(`round a circle, centred at ${n(el.curve.start)} deg`);
if (el.fit === 'shrink') parts.push(`shrunk to fit (chosen ${n(el.fitMax ?? el.size)} pt)`);
return parts.join(', ');
}
@@ -0,0 +1,77 @@
import { bookTextIsDrawn } from './book-text-effects.schema';
import { bookTextElementSchema } from './book.schema';
import { describe, expect, it } from 'vitest';
/**
* The text effects as the document stores them: absent on every text written
* before they existed, each one a value or null, and the bounds the print
* renderer depends on.
*/
const frame = { x: 10, y: 10, w: 80, h: 30 };
const parse = (over: Record<string, unknown> = {}) =>
bookTextElementSchema.parse({ id: 't1', kind: 'text', frame, text: 'Lisbon', ...over });
describe('the effect fields of a text', () => {
it('BKFX-001: leave a text from before them exactly as it was, with no new key', () => {
const el = parse();
for (const key of [
'transform',
'vAlign',
'outline',
'shadow',
'highlight',
'curve',
'fillPaint',
'fit',
'fitMax',
]) {
expect(key in el, key).toBe(false);
}
});
it('BKFX-002: read every effect, fill their defaults in, and take null for an effect taken off', () => {
const el = parse({
transform: 'upper',
vAlign: 'middle',
outline: { color: '#ffffff', width: 0.4 },
shadow: { dx: 1, dy: 1, color: '#111111' },
highlight: { color: '#c2410c' },
curve: { type: 'arc' },
fillPaint: { type: 'photo', photoId: 12 },
fit: 'shrink',
fitMax: 120,
});
expect(el.shadow?.alpha).toBe(1);
expect(el.highlight).toEqual({ color: '#c2410c', alpha: 1, padX: 1.2, padY: 0.3, radius: 0 });
expect(el.curve).toEqual({ type: 'arc', bend: 40, start: 0 });
expect(el.fillPaint).toEqual({ type: 'photo', photoId: 12, focalX: 0.5, focalY: 0.5, zoom: 1 });
expect(parse({ outline: null, curve: null }).outline).toBeNull();
});
it('BKFX-003: set a word across a cover and capitals spaced to one and a half em, and no further', () => {
expect(parse({ size: 400, tracking: 1.5 }).size).toBe(400);
expect(bookTextElementSchema.safeParse({ id: 't', kind: 'text', frame, size: 401 }).success).toBe(false);
expect(bookTextElementSchema.safeParse({ id: 't', kind: 'text', frame, tracking: 1.6 }).success).toBe(false);
expect(
bookTextElementSchema.safeParse({ id: 't', kind: 'text', frame, shadow: { dx: 1, dy: 1, color: 'red' } }).success,
).toBe(false);
expect(
bookTextElementSchema.safeParse({
id: 't',
kind: 'text',
frame,
fillPaint: { type: 'pattern', color: '#111111' },
}).success,
).toBe(false);
});
it('BKFX-004: draws a curved or a photo-filled text as SVG, and every other one as type', () => {
expect(bookTextIsDrawn(parse())).toBe(false);
expect(bookTextIsDrawn(parse({ outline: { color: '#111111', width: 1 } }))).toBe(false);
expect(bookTextIsDrawn(parse({ fillPaint: { type: 'solid', color: '#111111', alpha: 0 } }))).toBe(false);
expect(bookTextIsDrawn(parse({ curve: { type: 'circle' } }))).toBe(true);
expect(bookTextIsDrawn(parse({ fillPaint: { type: 'photo', photoId: 3 } }))).toBe(true);
});
});
+142
View File
@@ -0,0 +1,142 @@
import { z } from 'zod';
/**
* What a text can be besides words in a face: outlined, given a hard shadow,
* set on a marker band, bent along an arc or round a circle, filled with a
* photograph, set in capitals or small caps, sat at the top, middle or foot of
* its frame, and shrunk to fit it.
*
* ── Why every field is optional ─────────────────────────────────────────────
*
* The fields are merged into the text element (book.schema.ts) and none of
* them has a default. A text written before they existed parses to exactly
* the object it was, so the stored book does not grow a key on its next save,
* and an absent field means what it always meant: no effect. Removing an
* effect is `null`, which reads the same as absent.
*
* ── Why each one is drawn the way it is ────────────────────────────────────
*
* All of them print as vectors (TextEffectsView.tsx in the client): the shadow
* is a second copy of the words, offset, never a blur; the outline is a
* stroked copy laid under the fill, so it grows outwards and never eats the
* letter; the band is a span background; a curve is SVG `textPath` on a path
* computed in millimetres; a photo fill is the words as an SVG clip over an
* `<image>`, which the print view waits for. Nothing here asks the renderer to
* measure, so the page stays synchronous: a fitted size is solved when the
* text is edited and stored (book-text-fit.ts).
*
* ── The fill and the paint system ──────────────────────────────────────────
*
* `fillPaint` takes a solid colour with its own alpha or a photograph today.
* Its solid variant has the shape the book's paint type gives a solid fill, so
* gradients and patterns join this union as further members, without a
* reader of today's fields changing.
*/
const hex = z.string().regex(/^#[0-9a-fA-F]{6}$/, 'expected #rrggbb');
const alpha = z.number().min(0).max(1);
/** How the letters are cased. `smallcaps` sets the lower case as small capitals. */
export const BOOK_TEXT_TRANSFORMS = ['none', 'upper', 'lower', 'smallcaps'] as const;
export type BookTextTransform = (typeof BOOK_TEXT_TRANSFORMS)[number];
/** Where the lines sit in the frame, top to bottom. */
export const BOOK_TEXT_VALIGNS = ['top', 'middle', 'bottom'] as const;
export type BookTextVAlign = (typeof BOOK_TEXT_VALIGNS)[number];
/** A line round each letter. `width` is millimetres outside the letter. */
export const bookTextOutlineSchema = z.object({
color: hex,
width: z.number().min(0.05).max(6),
});
export type BookTextOutline = z.infer<typeof bookTextOutlineSchema>;
/** A hard shadow: the words again, offset by `dx`/`dy` millimetres behind them. No blur, ever. */
export const bookTextShadowSchema = z.object({
dx: z.number().min(-30).max(30),
dy: z.number().min(-30).max(30),
color: hex,
alpha: alpha.default(1),
});
export type BookTextShadow = z.infer<typeof bookTextShadowSchema>;
/** A marker band behind each line of words, `padX`/`padY` millimetres round them. */
export const bookTextHighlightSchema = z.object({
color: hex,
alpha: alpha.default(1),
padX: z.number().min(0).max(20).default(1.2),
padY: z.number().min(0).max(20).default(0.3),
radius: z.number().min(0).max(20).default(0),
});
export type BookTextHighlight = z.infer<typeof bookTextHighlightSchema>;
/**
* Words on a curve. `arc` bends a line across the frame, up for a positive
* `bend` and down for a negative one, a half circle at 100; `circle` runs the
* words round the frame's inscribed circle with their middle at `start`
* degrees, 0 at the top and clockwise.
*/
export const BOOK_TEXT_CURVES = ['arc', 'circle'] as const;
export const bookTextCurveSchema = z.object({
type: z.enum(BOOK_TEXT_CURVES),
bend: z.number().min(-100).max(100).default(40),
start: z.number().min(-180).max(180).default(0),
});
export type BookTextCurve = z.infer<typeof bookTextCurveSchema>;
/** What fills the letters in place of `color`: a colour with its own alpha (0 leaves an outline only), or a photograph. */
export const bookTextFillSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('solid'), color: hex, alpha: alpha.default(1) }),
z.object({
type: z.literal('photo'),
/** `trek_photos.id`, as a photo element keeps it. */
photoId: z.number().int().positive(),
focalX: z.number().min(0).max(1).default(0.5),
focalY: z.number().min(0).max(1).default(0.5),
zoom: z.number().min(1).max(4).default(1),
}),
]);
export type BookTextFill = z.infer<typeof bookTextFillSchema>;
/** `shrink` sets the text at the largest size up to `fitMax` that holds the frame, solved on edit and stored in `size`. */
export const BOOK_TEXT_FITS = ['none', 'shrink'] as const;
/** The largest text size, in points: a word across a whole cover. */
export const MAX_BOOK_TEXT_SIZE = 400;
/** The effect fields of a text element, merged into its schema. */
export const BOOK_TEXT_EFFECT_FIELDS = {
transform: z.enum(BOOK_TEXT_TRANSFORMS).optional(),
vAlign: z.enum(BOOK_TEXT_VALIGNS).optional(),
outline: bookTextOutlineSchema.nullable().optional(),
shadow: bookTextShadowSchema.nullable().optional(),
highlight: bookTextHighlightSchema.nullable().optional(),
curve: bookTextCurveSchema.nullable().optional(),
fillPaint: bookTextFillSchema.nullable().optional(),
fit: z.enum(BOOK_TEXT_FITS).optional(),
/** The size a fitted text is set at when its frame holds it: the size the person chose. */
fitMax: z.number().min(4).max(MAX_BOOK_TEXT_SIZE).optional(),
};
/** The effect fields as one object, what a renderer or a check reads off a text. */
export interface BookTextEffects {
transform?: BookTextTransform;
vAlign?: BookTextVAlign;
outline?: BookTextOutline | null;
shadow?: BookTextShadow | null;
highlight?: BookTextHighlight | null;
curve?: BookTextCurve | null;
fillPaint?: BookTextFill | null;
fit?: (typeof BOOK_TEXT_FITS)[number];
fitMax?: number;
}
/**
* Whether a text is drawn as SVG rather than as a box of HTML type: on a
* curve, or filled with a photograph. Such a text is set line by line as
* written, never wrapped, which is what word art wants and what the checks
* measure it by.
*/
export function bookTextIsDrawn(el: BookTextEffects): boolean {
return !!el.curve || el.fillPaint?.type === 'photo';
}
+106
View File
@@ -0,0 +1,106 @@
import { spreadFindings } from './book-findings';
import { designFindings } from './book-findings-design';
import { bookTextHasOwnGround, textEffectFindings } from './book-text-findings';
import { bookPageSetupSchema, bookTextElementSchema, type BookSpread, type BookTextElement } from './book.schema';
import { describe, expect, it } from 'vitest';
/** What the checks say about text effects, and what they leave to them. */
const page = bookPageSetupSchema.parse({});
const text = (over: Record<string, unknown> = {}): BookTextElement =>
bookTextElementSchema.parse({
id: 't1',
kind: 'text',
frame: { x: 230, y: 40, w: 120, h: 40 },
text: 'Lisbon',
size: 30,
...over,
});
const spreadOf = (...elements: BookTextElement[]): BookSpread => ({
id: 'sp',
role: 'inner',
background: null,
elements,
parked: [],
entryId: null,
});
const codes = (list: { code: string }[]) => list.map((f) => f.code);
describe('the checks of a text effect', () => {
it('BKFXF-001: says when the words run past the end of their curve, and nothing when they fit', () => {
const long = text({
text: 'A postmark from the far end of the coast road',
curve: { type: 'arc', bend: 30, start: 0 },
});
expect(codes(textEffectFindings(spreadOf(long)))).toEqual(['curve_overflow']);
const fits = text({ curve: { type: 'arc', bend: 30, start: 0 } });
expect(textEffectFindings(spreadOf(fits))).toEqual([]);
});
it('BKFXF-002: measures photo-filled word art as written, and the general overflow check leaves it alone', () => {
const wide = text({ text: 'LISBON AND PORTO', size: 90, fillPaint: { type: 'photo', photoId: 2 } });
expect(codes(textEffectFindings(spreadOf(wide)))).toEqual(['text_overflow']);
const overflows = spreadFindings(spreadOf(wide), page).filter((f) => f.code === 'text_overflow');
expect(overflows).toHaveLength(1);
expect(overflows[0]?.message).toContain('without wrapping');
});
it('BKFXF-003: warns about an outline heavy enough to close the letters', () => {
const heavy = text({ outline: { color: '#111111', width: 2 } });
expect(codes(textEffectFindings(spreadOf(heavy)))).toEqual(['effect_heavy']);
expect(textEffectFindings(spreadOf(text({ outline: { color: '#111111', width: 0.4 } })))).toEqual([]);
});
it('BKFXF-004: checks the words against their own band rather than against the page', () => {
const poor = text({ color: '#777777', highlight: { color: '#666666' } });
expect(codes(textEffectFindings(spreadOf(poor)))).toEqual(['contrast_low']);
const good = text({ color: '#ffffff', highlight: { color: '#111111' } });
expect(textEffectFindings(spreadOf(good))).toEqual([]);
});
it('BKFXF-005: checks a photo fill as a photo frame is checked: in the gallery, shown, sharp enough', () => {
const filled = text({ fillPaint: { type: 'photo', photoId: 7 } });
expect(codes(textEffectFindings(spreadOf(filled), [{ photoId: 8 }]))).toEqual(['not_in_gallery']);
expect(codes(textEffectFindings(spreadOf(filled), [{ photoId: 7, hidden: true }]))).toEqual(['hidden_photo']);
expect(codes(textEffectFindings(spreadOf(filled), [{ photoId: 7, width: 400, height: 300 }]))).toEqual(['low_dpi']);
expect(textEffectFindings(spreadOf(filled), [{ photoId: 7, width: 4000, height: 3000 }])).toEqual([]);
expect(textEffectFindings(spreadOf(filled))).toEqual([]);
});
it('BKFXF-006: skips an empty text', () => {
expect(textEffectFindings(spreadOf(text({ text: ' ', outline: { color: '#111111', width: 5 } })))).toEqual([]);
});
});
describe('a text that brings its own ground', () => {
it('BKFXF-007: is a text on a band, filled with a photo, hollow, or with a real outline', () => {
expect(bookTextHasOwnGround(text())).toBe(false);
expect(bookTextHasOwnGround(text({ highlight: { color: '#111111' } }))).toBe(true);
expect(bookTextHasOwnGround(text({ fillPaint: { type: 'photo', photoId: 1 } }))).toBe(true);
expect(bookTextHasOwnGround(text({ fillPaint: { type: 'solid', color: '#111111', alpha: 0 } }))).toBe(true);
expect(bookTextHasOwnGround(text({ fillPaint: { type: 'solid', color: '#111111', alpha: 1 } }))).toBe(false);
expect(bookTextHasOwnGround(text({ outline: { color: '#111111', width: 0.5 } }))).toBe(true);
expect(bookTextHasOwnGround(text({ outline: { color: '#111111', width: 0.1 } }))).toBe(false);
});
it('BKFXF-008: is left out of the page contrast check, which reads it against the page otherwise', () => {
const pale = text({ color: '#f4f4f4' });
expect(codes(designFindings(spreadOf(pale), page))).toContain('contrast_low');
const outlined = text({ color: '#f4f4f4', outline: { color: '#111111', width: 0.6 } });
expect(codes(designFindings(spreadOf(outlined), page))).not.toContain('contrast_low');
});
it('BKFXF-009: a curved text is not compared for overlap by its frame', () => {
const ring = text({
id: 'ring',
frame: { x: 230, y: 20, w: 100, h: 100 },
curve: { type: 'circle', bend: 0, start: 0 },
});
const middle = text({ id: 'mid', frame: { x: 250, y: 50, w: 60, h: 40 }, size: 12 });
expect(codes(spreadFindings(spreadOf(ring, middle), page))).not.toContain('overlap');
});
});
+133
View File
@@ -0,0 +1,133 @@
import { contrastRatio, requiredContrast } from './book-colour';
import type { BookPhotoInfo } from './book-ops-core';
import type { BookFinding } from './book-ops.schema';
import { bookTextCurvePath } from './book-text-curve';
import { bookTextIsDrawn } from './book-text-effects.schema';
import { bookDrawnLines, bookTextRunMm } from './book-text-fit';
import type { BookSpread, BookTextElement } from './book.schema';
/**
* What can go wrong with a text effect, as a proof would show it: words that
* run past the end of their curve, word art wider than its frame, an outline
* so heavy it closes the letters, a band the words do not stand out on, and a
* photo fill that is missing, not shown or too small for its letters.
*
* Joined into the page's print findings (`spreadFindings`), so the Studio's
* assistant reads them beside every write and in `describe_book_page`.
*/
const n = (v: number) => `${Math.round(v * 10) / 10}`;
const ptToMm = (pt: number) => (pt * 25.4) / 72;
/** Below this many pixels per printed millimetre a photo fill looks soft: the 200 dpi of a photo. */
const MIN_FILL_PX_PER_MM = 200 / 25.4;
/**
* Whether a text brings its own ground, so the page under it does not decide
* whether it reads: a band behind it, a real outline, or letters filled with a
* picture or left hollow. The contrast and busy checks leave such a text to
* the checks here.
*/
export function bookTextHasOwnGround(el: BookTextElement): boolean {
if (el.highlight) return true;
if (el.fillPaint && (el.fillPaint.type === 'photo' || el.fillPaint.alpha < 0.5)) return true;
return !!el.outline && el.outline.width >= ptToMm(el.size) * 0.04;
}
function curveRoom(el: BookTextElement, out: BookFinding[]): void {
if (!el.curve) return;
const line = bookDrawnLines(el)[0] ?? '';
const need = bookTextRunMm(el, line);
const path = bookTextCurvePath(el.curve, el.frame.w, el.frame.h, ptToMm(el.size));
if (need <= path.length) return;
out.push({
code: 'curve_overflow',
severity: 'warn',
elementIds: [el.id],
message: `the curved text ${el.id} needs about ${n(need)} mm and its ${el.curve.type} is ${n(path.length)} mm long; the end of the words is cut off. Set it smaller, shorten it or enlarge the frame`,
});
}
function drawnRoom(el: BookTextElement, out: BookFinding[]): void {
if (el.curve || !bookTextIsDrawn(el)) return;
const lines = bookDrawnLines(el);
const widest = Math.max(0, ...lines.map((l) => bookTextRunMm(el, l)));
const tall = lines.length * ptToMm(el.size) * el.leading;
if (widest <= el.frame.w * 1.05 && tall <= el.frame.h * 1.1) return;
out.push({
code: 'text_overflow',
severity: 'severe',
elementIds: [el.id],
message: `the photo-filled text ${el.id} is set as written, without wrapping, and needs about ${n(widest)} x ${n(tall)} mm in a ${n(el.frame.w)} x ${n(el.frame.h)} mm frame; break the line, set it smaller or use fit shrink`,
});
}
function heavyOutline(el: BookTextElement, out: BookFinding[]): void {
if (!el.outline) return;
const share = el.outline.width / ptToMm(el.size);
if (share <= 0.12) return;
out.push({
code: 'effect_heavy',
severity: 'warn',
elementIds: [el.id],
message: `the outline of text ${el.id} is ${n(el.outline.width)} mm on ${n(el.size)} pt letters, heavy enough to close their counters; keep it under about a tenth of the letter height`,
});
}
function bandContrast(el: BookTextElement, out: BookFinding[]): void {
if (!el.highlight || el.highlight.alpha < 0.6 || el.fillPaint) return;
const ratio = contrastRatio(el.color, el.highlight.color);
const need = requiredContrast(el.size);
if (ratio >= need) return;
out.push({
code: 'contrast_low',
severity: ratio < 2 ? 'severe' : 'warn',
elementIds: [el.id],
message: `text ${el.id} in ${el.color} on its band of ${el.highlight.color} has a contrast of ${ratio.toFixed(1)}:1, under the ${need}:1 type of that size needs`,
});
}
function photoFill(el: BookTextElement, photos: readonly BookPhotoInfo[] | undefined, out: BookFinding[]): void {
if (el.fillPaint?.type !== 'photo') return;
const { photoId, zoom } = el.fillPaint;
const info = photos?.find((p) => p.photoId === photoId);
if (photos && !info) {
out.push({
code: 'not_in_gallery',
severity: 'warn',
elementIds: [el.id],
message: `photo ${photoId} filling text ${el.id} is not in this journey's gallery`,
});
}
if (info?.hidden) {
out.push({
code: 'hidden_photo',
severity: 'info',
elementIds: [el.id],
message: `photo ${photoId} filling text ${el.id} is by another contributor and is not shown in the page image`,
});
}
if (!info?.width || !info.height) return;
const pxPerMm = Math.min(info.width / (el.frame.w * zoom), info.height / (el.frame.h * zoom));
if (pxPerMm >= MIN_FILL_PX_PER_MM) return;
out.push({
code: 'low_dpi',
severity: 'warn',
elementIds: [el.id],
message: `photo ${photoId} filling text ${el.id} prints at about ${Math.round(pxPerMm * 25.4)} dpi; zoom it out or make the frame smaller`,
});
}
/** The findings of every text effect on a page. */
export function textEffectFindings(spread: BookSpread, photos?: readonly BookPhotoInfo[]): BookFinding[] {
const out: BookFinding[] = [];
for (const el of spread.elements) {
if (el.kind !== 'text' || !el.text.trim()) continue;
curveRoom(el, out);
drawnRoom(el, out);
heavyOutline(el, out);
bandContrast(el, out);
photoFill(el, photos, out);
}
return out.map((f) => ({ ...f, message: f.message.slice(0, 300) }));
}
+131
View File
@@ -0,0 +1,131 @@
import { textHeightNeeded } from './book-findings';
import { blankBook } from './book-pages';
import {
bookCasedText,
bookDrawnLines,
bookTextFits,
fitBookTexts,
fitSpreadTexts,
solveBookTextFit,
} from './book-text-fit';
import { bookTextElementSchema, type BookSpread, type BookTextElement } from './book.schema';
import { describe, expect, it } from 'vitest';
/** Text set to fit its frame: solved on edit, stored in `size`, the choice kept in `fitMax`. */
const text = (over: Record<string, unknown> = {}): BookTextElement =>
bookTextElementSchema.parse({
id: 't1',
kind: 'text',
frame: { x: 0, y: 0, w: 80, h: 20 },
text: 'Lisbon',
size: 40,
leading: 1,
...over,
});
const spreadOf = (...elements: BookTextElement[]): BookSpread => ({
id: 'sp',
role: 'inner',
background: null,
elements,
parked: [],
entryId: null,
});
describe('how a text is cased and lined up for drawing', () => {
it('BKFIT-001: cases the words as the page shows them, and joins a curved text into one line', () => {
expect(bookCasedText({ text: 'Rua Augusta', transform: 'upper' })).toBe('RUA AUGUSTA');
expect(bookCasedText({ text: 'Rua Augusta', transform: 'lower' })).toBe('rua augusta');
expect(bookCasedText({ text: 'Rua Augusta', transform: 'smallcaps' })).toBe('Rua Augusta');
expect(bookDrawnLines({ text: 'One\n\nTwo ' })).toEqual(['One', '', 'Two']);
expect(bookDrawnLines({ text: 'One\n\nTwo', curve: { type: 'arc', bend: 10, start: 0 } })).toEqual(['One Two']);
});
});
describe('the fit solver', () => {
it('BKFIT-002: keeps the chosen size when the words hold the frame at it', () => {
const el = text({ size: 20 });
expect(bookTextFits(el)).toBe(true);
expect(solveBookTextFit(el)).toBe(20);
});
it('BKFIT-003: finds the largest quarter point that holds a frame too small, and the overflow check agrees', () => {
const el = text({ text: 'Two weeks along the Portuguese coast', size: 60 });
expect(bookTextFits(el)).toBe(false);
const size = solveBookTextFit(el);
expect(size).toBeLessThan(60);
expect(size * 4).toBe(Math.round(size * 4));
expect(bookTextFits({ ...el, size })).toBe(true);
expect(bookTextFits({ ...el, size: size + 0.25 })).toBe(false);
expect(textHeightNeeded({ ...el, size })).toBeLessThanOrEqual(el.frame.h * 1.02);
});
it('BKFIT-004: never sets a word wider than its frame, even when the height would allow it', () => {
const el = text({ text: 'Mediterranean', frame: { x: 0, y: 0, w: 40, h: 200 }, size: 80 });
expect(solveBookTextFit(el)).toBeLessThan(20);
});
it('BKFIT-005: stops at the document floor of 4 pt', () => {
const el = text({
text: 'A very long sentence that will never fit in this small frame',
frame: { x: 0, y: 0, w: 5, h: 2 },
});
expect(solveBookTextFit(el)).toBe(4);
});
it('BKFIT-006: measures a curved text along its curve and a photo-filled one by its widest line', () => {
const curved = text({
text: 'Postmark from Lisbon',
curve: { type: 'circle', bend: 0, start: 0 },
frame: { x: 0, y: 0, w: 60, h: 60 },
});
const size = solveBookTextFit(curved);
expect(bookTextFits({ ...curved, size })).toBe(true);
const filled = text({ text: 'LISBON\nPORTO', fillPaint: { type: 'photo', photoId: 2 }, size: 200 });
expect(solveBookTextFit(filled)).toBeLessThan(200);
expect(bookTextFits({ ...filled, text: ' ' })).toBe(true);
});
});
describe('fitting a page', () => {
it('BKFIT-007: solves only the fitted texts and hands the same page back when nothing moved', () => {
const plain = text({ id: 'plain', text: 'Two weeks along the Portuguese coast', size: 60 });
const fit = text({ id: 'fit', text: 'Two weeks along the Portuguese coast', size: 60, fit: 'shrink' });
const sp = spreadOf(plain, fit);
const out = fitSpreadTexts(sp);
expect(out.elements[0]).toBe(plain);
const solved = out.elements[1] as BookTextElement;
expect(solved.size).toBeLessThan(60);
expect(solved.fitMax).toBe(60);
expect(fitSpreadTexts(out)).toBe(out);
});
it('BKFIT-008: gives the words their size back when the frame grows again', () => {
const fit = text({ text: 'Two weeks along the Portuguese coast', size: 60, fit: 'shrink' });
const small = fitSpreadTexts(spreadOf(fit));
const grown = small.elements.map((e) => ({ ...e, frame: { ...e.frame, w: 2000, h: 400 } })) as BookTextElement[];
const back = fitSpreadTexts(spreadOf(...grown), small).elements[0] as BookTextElement;
expect(back.size).toBe(60);
});
it('BKFIT-009: takes a size somebody set in the edit as the new choice', () => {
const fit = fitSpreadTexts(spreadOf(text({ size: 20, fit: 'shrink' })));
const chosen = fit.elements.map((e) => ({ ...e, size: 30 })) as BookTextElement[];
const out = fitSpreadTexts(spreadOf(...chosen), fit).elements[0] as BookTextElement;
expect(out.fitMax).toBe(30);
expect(out.size).toBe(30);
});
it('BKFIT-010: fits only the spreads an edit touched, and keeps the document when nothing changed', () => {
const doc = blankBook({ title: 'Lisbon', newId: (p) => `${p}-x` });
expect(fitBookTexts(doc, doc)).toBe(doc);
expect(fitBookTexts(doc, null)).toBe(doc);
const fit = text({ text: 'Two weeks along the Portuguese coast', size: 60, fit: 'shrink' });
const spreads = doc.spreads.map((sp, i) => (i === 0 ? { ...sp, elements: [fit] } : sp));
const next = fitBookTexts({ ...doc, spreads }, doc);
expect((next.spreads[0]?.elements[0] as BookTextElement).size).toBeLessThan(60);
expect(next.spreads[1]).toBe(doc.spreads[1]);
});
});
+120
View File
@@ -0,0 +1,120 @@
import { bookLetterMm, textHeightNeeded } from './book-findings';
import { bookTextCurvePath } from './book-text-curve';
import { bookTextIsDrawn } from './book-text-effects.schema';
import type { BookDocument, BookElement, BookSpread, BookTextElement } from './book.schema';
/**
* Text set to fit its frame, solved when it is edited and stored.
*
* A fitted text keeps two sizes: `fitMax`, the size somebody chose, and
* `size`, the largest size up to it at which the words hold the frame. The
* renderer reads `size` like any other text, so the page stays synchronous and
* a reader from before fitting existed draws the fitted size, which is the one
* that was designed. The solver uses the same letter measure as the overflow
* check, so a text it fitted is never reported as overflowing.
*
* Who runs it: the Studio after every change to the document, and the edit
* engine after a page's operations, both through `fitSpreadTexts`. A size that
* changed in that edit is a new choice and becomes the new `fitMax`; one that
* did not keeps the old ceiling, so a frame made smaller and then larger again
* gives the words their size back.
*/
/** The smallest size the solver goes to: the document's own floor. */
const MIN_SIZE = 4;
const ptToMm = (pt: number) => (pt * 25.4) / 72;
/** The words as they are cased on the page: what the measure counts and the SVG draws. */
export function bookCasedText(el: Pick<BookTextElement, 'text' | 'transform'>): string {
if (el.transform === 'upper') return el.text.toUpperCase();
if (el.transform === 'lower') return el.text.toLowerCase();
return el.text;
}
/** The lines of a text that is drawn as written: its paragraphs, a curved text's joined into one. */
export function bookDrawnLines(el: Pick<BookTextElement, 'text' | 'transform' | 'curve'>): string[] {
const lines = bookCasedText(el)
.split('\n')
.map((l) => l.trimEnd());
return el.curve ? [lines.filter(Boolean).join(' ')] : lines;
}
/** How wide a run of characters sets, roughly, in millimetres. */
export function bookTextRunMm(el: BookTextElement, run: string): number {
return [...run].length * bookLetterMm(el);
}
/** Whether a text at its current size holds its frame, as the checks measure it. */
export function bookTextFits(el: BookTextElement): boolean {
if (!el.text.trim()) return true;
if (bookTextIsDrawn(el)) {
const lines = bookDrawnLines(el);
const widest = Math.max(0, ...lines.map((l) => bookTextRunMm(el, l)));
if (el.curve) {
const path = bookTextCurvePath(el.curve, el.frame.w, el.frame.h, ptToMm(el.size));
return widest <= path.length * 0.98;
}
return widest <= el.frame.w && lines.length * ptToMm(el.size) * el.leading <= el.frame.h * 1.02;
}
const longest = Math.max(
0,
...bookCasedText(el)
.split(/\s+/)
.map((w) => bookTextRunMm(el, w)),
);
return longest <= el.frame.w && textHeightNeeded(el) <= el.frame.h * 1.02;
}
/** The size a fitted text is set at: its ceiling when that holds, else the largest quarter point that does. */
export function solveBookTextFit(el: BookTextElement, ceiling: number = el.fitMax ?? el.size): number {
const top = Math.max(MIN_SIZE, ceiling);
if (bookTextFits({ ...el, size: top })) return top;
let lo = MIN_SIZE * 4;
let hi = Math.floor(top * 4) - 1;
while (lo < hi) {
const mid = Math.ceil((lo + hi) / 2);
if (bookTextFits({ ...el, size: mid / 4 })) lo = mid;
else hi = mid - 1;
}
return lo / 4;
}
/** One text fitted, or the same object when it is not fitted or already right. */
function fitted(el: BookElement, before: BookElement | undefined): BookElement {
if (el.kind !== 'text' || el.fit !== 'shrink') return el;
const chose = before?.kind === 'text' && before.size !== el.size;
const ceiling = chose || el.fitMax === undefined ? el.size : el.fitMax;
const size = solveBookTextFit(el, ceiling);
return size === el.size && ceiling === el.fitMax ? el : { ...el, size, fitMax: ceiling };
}
/**
* Every fitted text of a spread set at its solved size. `before` is the spread
* as it was before the edit, when there was one, to tell a size somebody chose
* from one the solver set. The same spread comes back when nothing moved.
*/
export function fitSpreadTexts(spread: BookSpread, before?: BookSpread): BookSpread {
const prior = new Map((before?.elements ?? []).map((e) => [e.id, e]));
let changed = false;
const elements = spread.elements.map((el) => {
const next = fitted(el, prior.get(el.id));
if (next !== el) changed = true;
return next;
});
return changed ? { ...spread, elements } : spread;
}
/** `fitSpreadTexts` over the spreads an edit changed, against the document before it. */
export function fitBookTexts(next: BookDocument, before: BookDocument | null): BookDocument {
const prior = new Map((before?.spreads ?? []).map((s) => [s.id, s]));
let changed = false;
const spreads = next.spreads.map((sp) => {
const was = prior.get(sp.id);
if (was === sp) return sp;
const out = fitSpreadTexts(sp, was);
if (out !== sp) changed = true;
return out;
});
return changed ? { ...next, spreads } : next;
}
+63
View File
@@ -0,0 +1,63 @@
import { idSchema } from '../common/primitives.schema';
import { BOOK_LOCKUP_ROLES } from './book-lockups';
import { BOOK_LOCKUPS } from './book-lockups.data';
import { BOOK_TEXT_EFFECT_FIELDS } from './book-text-effects.schema';
import { z } from 'zod';
/**
* The assistant's side of the text effects and the lockups: the effect fields
* a `style` or an `add` of a text may set, and the `add_lockup` operation.
* The values are the document's own (book-text-effects.schema.ts); only a line
* on what each means is added, since the tool schema is all a model reads.
*/
const f = BOOK_TEXT_EFFECT_FIELDS;
const hex = z.string().regex(/^#[0-9a-fA-F]{6}$/, 'expected #rrggbb');
/** The effect fields of a text's style, each left as it is when not named; null takes an effect off. */
export const TEXT_EFFECT_PROPS = {
transform: f.transform,
vAlign: f.vAlign,
outline: f.outline.describe('Width in mm outside the letters.'),
shadow: f.shadow.describe('Hard, never blurred; dx, dy in mm.'),
highlight: f.highlight.describe('A marker band behind each line; pads in mm.'),
curve: f.curve.describe('One line on an arc (bend > 0 arches up) or round a circle (start: degrees, 0 top).'),
fillPaint: f.fillPaint.describe('Replaces color: solid (alpha 0 is hollow, with an outline) or a gallery photo.'),
fit: f.fit.describe('shrink: the largest size up to size that holds the frame.'),
};
const lockupIds = BOOK_LOCKUPS.map((l) => l.id) as [string, ...string[]];
/** Every lockup by id; the ids say what each sets. */
export const bookLockupIdSchema = z
.enum(lockupIds)
.describe('A set title, badge, postmark, quote, caption or chapter mark.');
/** The words of a lockup, by the role each plays. */
export const bookLockupWordsSchema = z
.strictObject(Object.fromEntries(BOOK_LOCKUP_ROLES.map((r) => [r, z.string().max(200).optional()])))
.describe('Words by role (label as "Day"); a part without words is left out.');
/**
* Set a lockup: a title, badge, postmark, quote, caption or chapter mark made
* of a few texts and shapes that belong together. Placed in `box`, or at its
* own size centred on the page; every text in it fits its frame.
*/
export const bookAddLockupOpSchema = z.strictObject({
op: z.literal('add_lockup'),
lockup: bookLockupIdSchema,
words: bookLockupWordsSchema,
box: z
.strictObject({
x: z.number().finite().min(-10000).max(10000),
y: z.number().finite().min(-10000).max(10000),
w: z.number().finite().min(1).max(10000),
h: z.number().finite().min(1).max(10000),
})
.optional(),
ink: hex.optional(),
accent: hex.describe('Best taken from the photos.').optional(),
photoId: idSchema.describe('Fills the letters of photo-word.').optional(),
});
export type BookAddLockupOp = z.infer<typeof bookAddLockupOpSchema>;
+249
View File
@@ -0,0 +1,249 @@
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 { bookAddLockupOpSchema } from './book-text-ops.schema';
import {
bookSpreadSchema,
bookTextElementSchema,
type BookDocument,
type BookElement,
type BookSpread,
type BookTextElement,
} from './book.schema';
import { describeSpread } from './describe-spread';
import { describe, expect, it } from 'vitest';
/**
* The assistant's side of the text effects and the lockups: `style` and `add`
* set every effect the inspector sets, `add_lockup` places what the shelf
* places, a fitted text is solved after the operations, and the page in words
* says what each text carries.
*/
let seq = 0;
const newId = (p: string) => `${p}-n${++seq}`;
const text = (id: string, over: Record<string, unknown> = {}) =>
bookTextElementSchema.parse({
id,
kind: 'text',
frame: { x: 230, y: 40, w: 120, h: 30 },
text: 'Lisbon',
size: 24,
...over,
}) as BookElement;
function book(elements: BookElement[]): BookDocument {
const doc = blankBook({ title: 'Lisbon', newId: (p) => `${p}-x` });
const spreads = doc.spreads.map((s, i) => ({ ...s, id: i === 2 ? 'sp-in' : `sp-${i}` }));
spreads[2] = { ...(spreads[2] as BookSpread), elements };
return { ...doc, spreads };
}
const gallery = [{ photoId: 1, width: 4000, height: 3000 }];
const ctx: BookOpsContext = { photos: gallery };
const run = (doc: BookDocument, ops: BookPageOpInput[]) =>
applyBookOps(doc, { spreadId: 'sp-in', ops }, { newId, ...ctx });
const inner = (doc: BookDocument) => doc.spreads[2] as BookSpread;
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 only = (doc: BookDocument, id = 't1') => inner(doc).elements.find((e) => e.id === id) as BookTextElement;
describe('style sets the effects of a text', () => {
it('BKTOP-001: sets each effect, and null takes one off again', () => {
const doc = ok(
run(book([text('t1')]), [
{
op: 'style',
elementId: 't1',
set: {
kind: 'text',
transform: 'upper',
vAlign: 'bottom',
outline: { color: '#ffffff', width: 0.4 },
shadow: { dx: 1, dy: 1.5, color: '#111111' },
highlight: { color: '#111111', padX: 2 },
curve: { type: 'arc', bend: 30 },
},
},
]),
);
expect(only(doc)).toMatchObject({
transform: 'upper',
vAlign: 'bottom',
outline: { color: '#ffffff', width: 0.4 },
shadow: { dx: 1, dy: 1.5, color: '#111111', alpha: 1 },
highlight: { color: '#111111', padX: 2, padY: 0.3 },
curve: { type: 'arc', bend: 30, start: 0 },
});
const off = ok(run(doc, [{ op: 'style', elementId: 't1', set: { kind: 'text', outline: null, curve: null } }]));
expect(only(off).outline).toBeNull();
expect(only(off).curve).toBeNull();
expect(only(off).shadow).toMatchObject({ dx: 1 });
});
it('BKTOP-002: fills the letters only with a photo of the gallery', () => {
const fill = { type: 'photo' as const, photoId: 1, zoom: 1.5 };
const doc = ok(run(book([text('t1')]), [{ op: 'style', elementId: 't1', set: { kind: 'text', fillPaint: fill } }]));
expect(only(doc).fillPaint).toMatchObject({ type: 'photo', photoId: 1, zoom: 1.5, focalX: 0.5 });
const stranger = { type: 'photo' as const, photoId: 99 };
expect(
refusal(run(book([text('t1')]), [{ op: 'style', elementId: 't1', set: { kind: 'text', fillPaint: stranger } }])),
).toBe('photo_not_in_gallery');
expect(refusal(run(book([]), [{ op: 'add', element: { kind: 'text', text: 'Porto', fillPaint: stranger } }]))).toBe(
'photo_not_in_gallery',
);
});
it('BKTOP-003: refuses an effect value the document cannot hold', () => {
const bad = run(book([text('t1')]), [
{ op: 'style', elementId: 't1', set: { kind: 'text', outline: { color: '#ffffff', width: 9 } } },
]);
expect(refusal(bad)).toBe('invalid_op');
});
it('BKTOP-004: adds a text with its effects in one operation', () => {
const doc = ok(
run(book([]), [
{
op: 'add',
element: {
kind: 'text',
preset: 'heading',
text: 'Sintra',
transform: 'smallcaps',
shadow: { dx: 1, dy: 1, color: '#c2410c' },
},
},
]),
);
const el = inner(doc).elements.at(-1) as BookTextElement;
expect(el).toMatchObject({ text: 'Sintra', size: 30, transform: 'smallcaps', shadow: { color: '#c2410c' } });
});
});
describe('a text set to fit its frame', () => {
const long = 'Two weeks along the Portuguese coast';
it('BKTOP-005: is solved after the operations, keeping the size asked for as its ceiling', () => {
const doc = ok(
run(book([text('t1', { text: long, size: 60 })]), [
{ op: 'style', elementId: 't1', set: { kind: 'text', fit: 'shrink' } },
]),
);
expect(only(doc).size).toBeLessThan(60);
expect(only(doc).fitMax).toBe(60);
expect(describeSpread(doc, 'sp-in')?.findings.some((f) => f.code === 'text_overflow')).toBe(false);
});
it('BKTOP-006: takes a new size as the new ceiling', () => {
const fitted = ok(
run(book([text('t1', { text: long, size: 60 })]), [
{ op: 'style', elementId: 't1', set: { kind: 'text', fit: 'shrink' } },
]),
);
const doc = ok(run(fitted, [{ op: 'style', elementId: 't1', set: { kind: 'text', size: 12 } }]));
expect(only(doc)).toMatchObject({ size: 12, fitMax: 12 });
});
});
describe('add_lockup', () => {
it('BKTOP-007: places a lockup on the right-hand page, its words by role and every text fitted', () => {
const doc = ok(
run(book([]), [
{ op: 'add_lockup', lockup: 'poster-stack', words: { title: 'Lisbon', subtitle: 'Summer', year: '2026' } },
]),
);
const els = inner(doc).elements;
expect(els.map((e) => (e.kind === 'text' ? e.text : e.kind))).toEqual(['Lisbon', 'Summer', '2026']);
for (const e of els) expect(e.frame.x).toBeGreaterThan(210);
expect(els.every((e) => e.kind === 'text' && e.fit === 'shrink')).toBe(true);
// One group, so the set moves as one.
expect(els[0]?.group).toBeTruthy();
expect(new Set(els.map((e) => e.group)).size).toBe(1);
});
it('BKTOP-008: sets the lockup into a box, in the colours given, a photo word filled from the gallery', () => {
const doc = ok(
run(book([]), [
{
op: 'add_lockup',
lockup: 'photo-word',
words: { title: 'Porto', kicker: 'Travel journal' },
box: { x: 10, y: 10, w: 150, h: 75 },
ink: '#202020',
accent: '#0f766e',
photoId: 1,
},
]),
);
const [kicker, title] = inner(doc).elements as BookTextElement[];
expect(kicker?.color).toBe('#202020');
expect(title?.fillPaint).toMatchObject({ type: 'photo', photoId: 1 });
expect(title?.frame.x).toBeGreaterThanOrEqual(10);
expect((title?.frame.x ?? 0) + (title?.frame.w ?? 0)).toBeLessThanOrEqual(160.01);
});
it('BKTOP-009: refuses a lockup without words, a photo outside the gallery and a page too full for it', () => {
expect(refusal(run(book([]), [{ op: 'add_lockup', lockup: 'postmark', words: {} }]))).toBe('text_required');
expect(
refusal(run(book([]), [{ op: 'add_lockup', lockup: 'photo-word', words: { title: 'Porto' }, photoId: 42 }])),
).toBe('photo_not_in_gallery');
const full = Array.from({ length: 89 }, (_, i) => text(`f${i}`));
expect(
refusal(
run(book(full), [{ op: 'add_lockup', lockup: 'poster-stack', words: { title: 'Lisbon', year: '2026' } }]),
),
).toBe('too_many_elements');
});
it('BKTOP-010: takes only the lockups and the roles it knows', () => {
expect(bookAddLockupOpSchema.safeParse({ op: 'add_lockup', lockup: 'banner', words: { title: 'A' } }).success).toBe(
false,
);
expect(bookAddLockupOpSchema.safeParse({ op: 'add_lockup', lockup: 'stamp', words: { motto: 'A' } }).success).toBe(
false,
);
expect(
bookAddLockupOpSchema.safeParse({ op: 'add_lockup', lockup: 'stamp', words: { place: 'Faro' } }).success,
).toBe(true);
});
});
describe('the page in words', () => {
it('BKTOP-011: says what effects each text carries, in the terms style sets them by', () => {
const doc = book([
text('t1', {
transform: 'upper',
vAlign: 'middle',
outline: { color: '#ffffff', width: 0.4 },
shadow: { dx: 1, dy: 1, color: '#111111' },
highlight: { color: '#c2410c' },
fit: 'shrink',
fitMax: 30,
}),
text('t2', { curve: { type: 'circle', start: 90 }, fillPaint: { type: 'solid', color: '#111111', alpha: 0 } }),
text('t3', { curve: { type: 'arc', bend: 20 }, fillPaint: { type: 'photo', photoId: 1 } }),
text('t4'),
]);
const words = describeSpread(doc, 'sp-in')?.text ?? '';
expect(words).toContain(
'capitals, set at the middle of its frame, outline #ffffff 0.4 mm, hard shadow #111111 offset 1/1 mm, on a band of #c2410c, shrunk to fit (chosen 30 pt)',
);
expect(words).toContain('hollow letters (outline only), round a circle, centred at 90 deg');
expect(words).toContain('letters filled with photo 1 (focal 0.50/0.50, zoom 1), on an arc, bend 20');
expect(words).toContain('sans 24 pt, left, #1a1a1a: "Lisbon"');
});
it('BKTOP-012: says a translucent fill by its alpha', () => {
const doc = book([text('t1', { fillPaint: { type: 'solid', color: '#111111', alpha: 0.5 } })]);
expect(describeSpread(doc, 'sp-in')?.text).toContain('fill #111111 at alpha 0.5');
});
});
+7 -4
View File
@@ -3,6 +3,7 @@ import { BOOK_LINE_FIELDS } from './book-line.schema';
import { bookPaintFieldSchema } from './book-paint.schema';
import { BOOK_PHOTO_LOOK_FIELDS } from './book-photo-look.schema';
import { BOOK_EDGE_FIELDS, BOOK_SHAPES_MORE } from './book-shapes-more';
import { BOOK_TEXT_EFFECT_FIELDS, MAX_BOOK_TEXT_SIZE } from './book-text-effects.schema';
import { MAX_STICKER_SLOTS } from './stickers/sticker-types';
import * as themed from './theme/book-theme.schema';
@@ -270,15 +271,15 @@ export const bookTextElementSchema = z.object({
kind: z.literal('text'),
text: z.string().max(MAX_TEXT_LENGTH).default(''),
font: bookCatalogueIdSchema(BOOK_FONTS_IDS).default('sans'),
/** Points. */
size: z.number().min(4).max(200).default(11),
/** Points, up to a word across a whole cover. */
size: z.number().min(4).max(MAX_BOOK_TEXT_SIZE).default(11),
weight: bookWeightSchema.default(400),
italic: z.boolean().default(false),
align: z.enum(['left', 'center', 'right', 'justify']).default('left'),
/** Multiple of the font size. */
leading: z.number().min(0.7).max(3).default(1.45),
/** Ems, may be negative. */
tracking: z.number().min(-0.2).max(1).default(0),
/** Ems, may be negative; wide enough for very spaced capitals. */
tracking: z.number().min(-0.2).max(1.5).default(0),
color: hex.default('#1a1a1a'),
...themed.THEMED_TEXT,
/** Where this text came from, when it came from the journey. */
@@ -327,6 +328,8 @@ export const bookTextElementSchema = z.object({
.default(null),
/** True once a human edited the text; stops it re-reading its source. */
overridden: z.boolean().default(false),
/** Outline, shadow, band, curve, fill, case, vertical place and fit (book-text-effects.schema.ts). */
...BOOK_TEXT_EFFECT_FIELDS,
});
export const bookShapeElementSchema = z.object({
+3 -1
View File
@@ -15,6 +15,7 @@ import type {
import { paintWords } from './book-paint';
import { photoLookWords } from './book-photo-look';
import { bookStickerWords } from './book-sticker';
import { bookTextEffectWords } from './book-text-describe';
import {
bookPageSetupSchema,
type BookDocument,
@@ -99,7 +100,8 @@ function elementWords(el: BookElement, photos: readonly BookPhotoInfo[] | undefi
const set = `${el.font} (${bookFontRole(el.font)}) ${n(el.size)} pt${weight === 400 ? '' : ` ${bookWeightWord(weight)}`}`;
const style = `${set}${el.italic ? ' italic' : ''}, ${el.align}, ${el.color}`;
const bound = el.binding ? `, bound to ${el.binding.source}${el.overridden ? ' (overridden)' : ''}` : '';
return `${style}: "${head(el.text, 80)}"${bound}`;
const effects = bookTextEffectWords(el);
return `${style}${effects ? `, ${effects}` : ''}: "${head(el.text, 80)}"${bound}`;
}
case 'shape':
return shapeWords(el);