@vectoriox/iox-ui 5.88.0 → 5.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/design-core/index.d.ts +523 -2
  2. package/fesm2022/vectoriox-iox-ui-composite-core.mjs +3 -2
  3. package/fesm2022/vectoriox-iox-ui-composite-core.mjs.map +1 -1
  4. package/fesm2022/vectoriox-iox-ui-design-core.mjs +581 -1
  5. package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
  6. package/fesm2022/vectoriox-iox-ui-generation-core.mjs +4692 -160
  7. package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
  8. package/fesm2022/vectoriox-iox-ui-harness-core.mjs +12 -1
  9. package/fesm2022/vectoriox-iox-ui-harness-core.mjs.map +1 -1
  10. package/fesm2022/vectoriox-iox-ui-scene-core.mjs +46 -6
  11. package/fesm2022/vectoriox-iox-ui-scene-core.mjs.map +1 -1
  12. package/fesm2022/vectoriox-iox-ui.mjs +6 -4
  13. package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
  14. package/generation-core/index.d.ts +1611 -10
  15. package/harness-core/index.d.ts +52 -3
  16. package/package.json +1 -1
  17. package/scene-core/index.d.ts +28 -2
  18. package/src/composite-core/slider.ts +3 -2
  19. package/src/design-core/flavor-spec.generated.ts +500 -0
  20. package/src/design-core/font-metrics.ts +105 -0
  21. package/src/design-core/public-api.ts +1 -0
  22. package/src/generation-core/ai-run.ts +11 -0
  23. package/src/generation-core/audit-site.ts +5 -0
  24. package/src/generation-core/check-layout.ts +940 -0
  25. package/src/generation-core/compose-layout.ts +907 -0
  26. package/src/generation-core/compose-site.ts +136 -5
  27. package/src/generation-core/layout-drift.ts +78 -0
  28. package/src/generation-core/layout-edits.ts +122 -0
  29. package/src/generation-core/layout-fingerprint.ts +203 -0
  30. package/src/generation-core/layout-language.ts +537 -0
  31. package/src/generation-core/layout-look.ts +57 -0
  32. package/src/generation-core/layout-photos.ts +19 -0
  33. package/src/generation-core/layout-render-check.ts +275 -0
  34. package/src/generation-core/layout-section-fallback.ts +156 -0
  35. package/src/generation-core/layout-type.ts +48 -0
  36. package/src/generation-core/layout-wire.ts +282 -0
  37. package/src/generation-core/nav-shape.ts +23 -1
  38. package/src/generation-core/photo-inventory.ts +250 -0
  39. package/src/generation-core/plan-edits.ts +25 -2
  40. package/src/generation-core/plan-wire.ts +19 -2
  41. package/src/generation-core/public-api.ts +13 -0
  42. package/src/generation-core/site-plan.model.ts +16 -0
  43. package/src/generation-core/site-spec.generated.ts +759 -2
  44. package/src/generation-core/validate-site-plan.ts +55 -1
  45. package/src/harness-core/generation-view.ts +52 -1
  46. package/src/scene-core/scroll-driver.ts +14 -2
  47. package/src/scene-core/scroll-range.ts +37 -4
  48. package/styles/iox-design.css +17 -0
  49. package/styles/iox-forms.css +4 -0
@@ -0,0 +1,940 @@
1
+ import { DesignChoices, designTokenRows, parseCssColour, presetChoices, relativeLuminance, resolveTokenValues, toHexColor } from '@vectoriox/iox-ui/design-core';
2
+ import { ParallaxDepth } from '@vectoriox/iox-ui/scene-core';
3
+
4
+ import {
5
+ LAYOUT_HIDDEN_OPACITY, LAYOUT_OPERATED, LAYOUT_TEXT_KINDS, LayoutBandMove, LayoutColour, LayoutDepth, LayoutDial, LayoutEnter, LayoutGalleryList, LayoutIssue, LayoutIssueCode, LayoutLayer, LayoutLayerKind, LayoutMend, LayoutMendKind,
6
+ LayoutPage, LayoutPhotoSource,
7
+ LayoutRole, LayoutSection, LayoutSectionKind, LayoutSourceChoice, LayoutTrackProp, parseLayoutPhotoId,
8
+ } from './layout-language';
9
+ import { DriftBox, driftOverlap, layoutGlideDepth } from './layout-drift';
10
+ import { layoutLookOf } from './layout-look';
11
+ import { patternById } from './patterns';
12
+ import { layoutDesignOf, screenWordMisfit } from './layout-type';
13
+ import { calmParts, calmUnder, FrameRegion, PhotoInventory, PHOTO_LIGHT_LUMINANCE } from './photo-inventory';
14
+ import { SerializedNode, walkSerialized } from './serialized-node';
15
+ import { SPEC_SITE_FACTS, SPEC_SITE_LAYOUT } from './site-spec.generated';
16
+
17
+ /**
18
+ * THE STATIC LAYOUT GATE (premium components M8 gate 2, M8-G2-D6; the prototype's `check` + `check21`, `code/cl2.mjs` and
19
+ * `cl21.mjs`): one composed page against every rule the language keeps — structure, the look's composition notes, Emil's
20
+ * motion rules, reading (words over the calm part of what a frame shows, contrast, an estimate of fit), content (photos,
21
+ * sources, facts and forms that are the business's) and what the dial asks. Every number is the contract's
22
+ * (`SPEC_SITE_LAYOUT`). Refuses with a path the repair can edit (`applyLayoutEdits`); never repairs. Pure.
23
+ *
24
+ * What the product owns is not judged here: fonts, colour values, radius, the navigation, the motion's ease and pace. The
25
+ * look is the preset's (`presetLook`), its colours the preset's in the page's mode.
26
+ */
27
+
28
+ const L = SPEC_SITE_LAYOUT;
29
+ /** The pattern families whose ready-made section lets people reach the business. */
30
+ const READY_MADE_REACH: ReadonlySet<string> = new Set(['cta', 'contact']);
31
+ const V = L.vocab;
32
+ const LIM = L.limits;
33
+
34
+ export interface CheckLayoutContext {
35
+ presetId: string;
36
+ mode: 'light' | 'dark';
37
+ locale: 'en' | 'he';
38
+ /** Every photo the page may use: its inventory, or null when it was not measured (words never sit on it). */
39
+ photos: Record<string, PhotoInventory | null>;
40
+ /** The list data sources a gallery may show (`gallery.source`). */
41
+ sources?: string[];
42
+ /** Every list the plan has (`layoutGalleryLists`): a gallery naming one without pictures is mended to one with them. */
43
+ lists?: ReadonlyArray<LayoutGalleryList>;
44
+ /** The site's page routes a button may lead to (`/contact`). */
45
+ routes?: string[];
46
+ /** Every word the owner gave and what was read from it: a number not in here was invented. */
47
+ facts?: string;
48
+ /** The fact keys a `{fact:<key>}` token may name (default: the contract's `site.facts`). */
49
+ factKeys?: string[];
50
+ /** The business takes leads (the lead form is offered). */
51
+ takesLeads?: boolean;
52
+ /** This is the home page: it must offer a way to reach the business. */
53
+ first?: boolean;
54
+ /** The design the page will wear: its fonts decide whether a `screen` word fits (iox-ui#46). Default: the preset's. */
55
+ design?: DesignChoices;
56
+ }
57
+
58
+ /** The look's composition notes, read as one shape (the contract's looks differ in which limits they set). */
59
+ interface LookNotes {
60
+ id: string;
61
+ empty: number;
62
+ contrast: readonly [number, number];
63
+ enters: ReadonlyArray<string>;
64
+ rotateMax: number;
65
+ accentMax: number;
66
+ limits: {
67
+ hugeMax?: number;
68
+ noScrim?: boolean;
69
+ centerMax?: number;
70
+ firstButtonsMax?: number;
71
+ lightGroundsMax?: number;
72
+ rotatedPerSectionMax?: number;
73
+ noTextOnPhoto?: boolean;
74
+ };
75
+ }
76
+
77
+ export type LayoutColours = Readonly<Record<LayoutColour, string>>;
78
+
79
+ const COLOUR_TOKEN: Readonly<Record<LayoutColour, string>> = {
80
+ [LayoutColour.Ground]: 'bg',
81
+ [LayoutColour.Ink]: 'text',
82
+ [LayoutColour.Accent]: 'accent',
83
+ [LayoutColour.Soft]: 'surface-2',
84
+ [LayoutColour.Muted]: 'text-muted',
85
+ };
86
+ /** Words in the accent colour paint with its text shade (`LAYOUT_ACCENT_TEXT`). */
87
+ const ACCENT_TEXT_TOKEN = 'accent-text';
88
+
89
+ function presetPaint(presetId: string, mode: 'light' | 'dark'): { colours: LayoutColours; accentText: string } | null {
90
+ const choices = presetChoices(presetId, mode);
91
+ if (!choices) return null;
92
+ const values = resolveTokenValues(designTokenRows(choices), mode);
93
+ const hex = (token: string) => {
94
+ const c = parseCssColour(values[token]);
95
+ return c ? toHexColor(c) : null;
96
+ };
97
+ const entries = Object.entries(COLOUR_TOKEN).map(([name, token]) => [name, hex(token)] as const);
98
+ if (entries.some(([, v]) => !v)) return null;
99
+ const colours = Object.fromEntries(entries) as Record<LayoutColour, string>;
100
+ return { colours, accentText: hex(ACCENT_TEXT_TOKEN) ?? colours[LayoutColour.Accent] };
101
+ }
102
+
103
+ /** A preset's five colours in a mode as `#rrggbb` (the prototype's `presetColours`), or null when it does not wear that mode. */
104
+ export function layoutPresetColours(presetId: string, mode: 'light' | 'dark'): LayoutColours | null {
105
+ return presetPaint(presetId, mode)?.colours ?? null;
106
+ }
107
+
108
+ // ── Geometry ────────────────────────────────────────────────────────────────────────────────────────────
109
+
110
+ /**
111
+ * The laptop the estimates are made on (the render check's 1440 × 900). A grid column is taken as 1440 / 12 px and a row
112
+ * as its section's screens × 900 / rows (a held section's grid is its one-screen stage): the gutter and the column gaps
113
+ * are left out, so a box reads about a fifth wider than it renders — the render check measures the real one.
114
+ */
115
+ export const LAYOUT_CHECK_VIEWPORT = { width: 1440, height: 900 } as const;
116
+ const GRID = 12;
117
+ const COLUMN_PX = LAYOUT_CHECK_VIEWPORT.width / GRID;
118
+ /** A line of words stands its size × this tall. */
119
+ const LINE_HEIGHT = 1.2;
120
+ /** WCAG's large text (≥ 24 px): 3:1 is enough. */
121
+ const LARGE_TEXT_PX = 24;
122
+ const CONTRAST_LARGE = 3;
123
+ const CONTRAST_BODY = 4.5;
124
+ /** The prototype's numbers the contract does not carry yet. */
125
+ const TRACK_SCALE_MAX = 1.3;
126
+ const INNER_MAX = 3;
127
+ const BEAT_MAX = 5;
128
+ const POP_WORDS = 3;
129
+ const SPLITS_IN_A_ROW = 3;
130
+ const EYEBROW_SHARE = 0.5;
131
+ const START_EDGE = 0.05;
132
+ const START_OPACITY_MIN = 0.6;
133
+ const START_CLIP_MIN = 40;
134
+ const HIDDEN_CLIP = 30;
135
+ /** A button or section that reads as a way to reach the business (the prototype's words, English and Hebrew). */
136
+ const CONTACT_WORDS = /contact|book|reserve|visit|table|sign.?up|enquir|צור|הזמ|קשר|שולחן|ביקור|הרשמ/i;
137
+ const HEBREW = /[֐-׿]/;
138
+ const LATIN_SENTENCE = /[A-Za-z]{3,}(\s+[A-Za-z]{3,}){2,}/;
139
+ const NUMBER_GIVEN = /\d[\d:.,]{2,}|[$₪€£]\s?\d+/g;
140
+ const CHIP_NUMBER = /\d{2,}|[$₪€£]/;
141
+ const BRACKET = /\[([^\]\n]{1,40})\]/g;
142
+ const FACT_TOKEN = /\{fact:([^}]*)\}/g;
143
+ const PHOTO_GROUND = 'photo:';
144
+ /** An accent ground counts as this many accent uses (a band of colour weighs more than a word). */
145
+ const ACCENT_GROUND_USES = 2;
146
+
147
+ const inList = (list: ReadonlyArray<string>, v: unknown): boolean => typeof v === 'string' && list.includes(v);
148
+ const wordsOf = (t: string | undefined) => String(t ?? '').trim().split(/\s+/).filter(Boolean).length;
149
+ const span = (r: readonly number[] | undefined) => (r ? r[1] - r[0] : 0);
150
+ const overlaps = (a: LayoutLayer, b: LayoutLayer) => {
151
+ const ov = (p: readonly number[], q: readonly number[]) => p[0] < q[1] && q[0] < p[1];
152
+ return ov(a.col ?? [0, 0], b.col ?? [0, 0]) && ov(a.row ?? [0, 0], b.row ?? [0, 0]);
153
+ };
154
+ const trackOf = (s: LayoutSection) => s.track ?? 1;
155
+ const groundPhotoOf = (s: LayoutSection) => (String(s.ground ?? '').startsWith(PHOTO_GROUND) ? String(s.ground).slice(PHOTO_GROUND.length) : null);
156
+ const isText = (l: LayoutLayer) => LAYOUT_TEXT_KINDS.has(l.kind);
157
+ const isPictured = (l: LayoutLayer) => l.kind === LayoutLayerKind.Photo || l.kind === LayoutLayerKind.Gallery;
158
+ const contrastOf = (a: number, b: number) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
159
+
160
+ /** A grid box's size in px on the laptop. */
161
+ function boxPx(col: readonly number[], row: readonly number[], s: LayoutSection): { w: number; h: number } {
162
+ const height = (s.pin ? 1 : s.screens) * LAYOUT_CHECK_VIEWPORT.height;
163
+ return { w: span(col) * COLUMN_PX, h: (span(row) * height) / Math.max(1, s.rows) };
164
+ }
165
+
166
+ /** A section of one photo on one side and words on the other: 'start' | 'end' | null (the prototype's `splitSide`). */
167
+ export function splitSide(s: LayoutSection): 'start' | 'end' | null {
168
+ const photos = (s.layers ?? []).filter(isPictured);
169
+ if (photos.length !== 1 || trackOf(s) > 1) return null;
170
+ const [c0, c1] = photos[0].col ?? [0, 0];
171
+ if (c1 - c0 < 4 || c1 - c0 > 8) return null;
172
+ const side = c0 <= 2 ? 'start' : c1 >= GRID ? 'end' : null;
173
+ if (!side) return null;
174
+ const words = (s.layers ?? []).filter(isText);
175
+ const across = words.every(w => (side === 'start' ? (w.col?.[0] ?? 0) >= c1 - 1 : (w.col?.[1] ?? 99) <= c0 + 1));
176
+ return words.length && across ? side : null;
177
+ }
178
+
179
+ /** The share of a section's grid no layer covers; a photo or gallery that bleeds off the screen is ground, not clutter. */
180
+ function emptyShare(s: LayoutSection): number {
181
+ const cols = GRID * trackOf(s);
182
+ const used = new Set<string>();
183
+ for (const l of s.layers ?? []) {
184
+ if (isPictured(l) && l.bleed && l.bleed !== 'none') continue;
185
+ const [c0, c1] = l.col ?? [1, 1];
186
+ const [r0, r1] = l.row ?? [1, 1];
187
+ for (let c = Math.max(1, c0); c < Math.min(cols + 1, c1); c++) for (let r = Math.max(1, r0); r < Math.min(s.rows + 1, r1); r++) used.add(`${c}:${r}`);
188
+ }
189
+ return 1 - used.size / Math.max(1, cols * s.rows);
190
+ }
191
+
192
+ /** Every photo id a page names: photo layers, gallery slides, photo grounds. */
193
+ export function layoutPhotoIds(page: LayoutPage): string[] {
194
+ const ids: string[] = [];
195
+ for (const s of page.sections ?? []) {
196
+ const ground = groundPhotoOf(s);
197
+ if (ground) ids.push(ground);
198
+ for (const l of s.layers ?? []) {
199
+ if (l.kind === LayoutLayerKind.Photo && l.photo?.id) ids.push(l.photo.id);
200
+ for (const slide of l.gallery?.slides ?? []) if (slide.photo?.id) ids.push(slide.photo.id);
201
+ }
202
+ }
203
+ return ids;
204
+ }
205
+
206
+ /** Where a photo under words is, as the frame that shows it and the words' region in it. */
207
+ interface PhotoUnder {
208
+ id: string;
209
+ frame: { w: number; h: number };
210
+ region: FrameRegion;
211
+ }
212
+
213
+ /** The words' region inside a photo layer's box (fractions of the box), both placed on the same grid. */
214
+ function regionInLayer(photo: LayoutLayer, l: LayoutLayer): FrameRegion {
215
+ const f = (v: number, [a, b]: readonly number[]) => Math.min(1, Math.max(0, (v - a) / Math.max(1, b - a)));
216
+ return { x0: f(l.col[0], photo.col), x1: f(l.col[1], photo.col), y0: f(l.row[0], photo.row), y1: f(l.row[1], photo.row) };
217
+ }
218
+
219
+ /**
220
+ * The words' region over a photo ground. The ground covers the whole section (screens tall, one screen wide); a held
221
+ * section's grid is its stage, which sticks while the section passes, so its words sweep every screen of the ground —
222
+ * judged on the union. A sideways section's words walk the whole width.
223
+ */
224
+ function regionOnGround(s: LayoutSection, l: LayoutLayer): FrameRegion {
225
+ const screens = Math.max(1, s.screens);
226
+ const r0 = (l.row[0] - 1) / s.rows;
227
+ const r1 = (l.row[1] - 1) / s.rows;
228
+ const y = s.pin ? { y0: r0 / screens, y1: (r1 + screens - 1) / screens } : { y0: r0, y1: r1 };
229
+ const x = trackOf(s) > 1 ? { x0: 0, x1: 1 } : { x0: (l.col[0] - 1) / GRID, x1: (l.col[1] - 1) / GRID };
230
+ return { ...x, ...y };
231
+ }
232
+
233
+ /** Text whose facts, numbers and placeholders are judged: a layer's words, its items, its captions and its form's words. */
234
+ function wordsOfLayer(l: LayoutLayer): string[] {
235
+ const f = l.form;
236
+ return [
237
+ l.text ?? '',
238
+ ...(l.items ?? []),
239
+ ...(l.gallery?.slides ?? []).map(s => s.caption ?? ''),
240
+ ...(f ? [f.title, f.intro, f.submit, f.successTitle, f.successText, f.channel?.label].map(t => t ?? '') : []),
241
+ ].filter(Boolean);
242
+ }
243
+
244
+ /** Every rule a composed page keeps, each refused with a path. Empty means it passes. */
245
+ export function checkLayout(page: LayoutPage, ctx: CheckLayoutContext): LayoutIssue[] {
246
+ const issues: LayoutIssue[] = [];
247
+ const add = (code: LayoutIssueCode, path: string, message: string, mend?: LayoutMend): void => {
248
+ issues.push({ code, path, message, ...(mend ? { mend } : {}) });
249
+ };
250
+ if (!page || !Array.isArray(page.sections)) {
251
+ add(LayoutIssueCode.Shape, 'sections', 'the page has no sections');
252
+ return issues;
253
+ }
254
+ const look: LookNotes | null = L.presetLook[ctx.presetId as keyof typeof L.presetLook] ? layoutLookOf(ctx.presetId) : null;
255
+ const paint = presetPaint(ctx.presetId, ctx.mode);
256
+ const design = ctx.design ?? layoutDesignOf(ctx.presetId, ctx.mode);
257
+ if (!look) add(LayoutIssueCode.Value, 'look', `"${ctx.presetId}" is not a style preset`);
258
+ if (!paint) add(LayoutIssueCode.Value, 'look', `the "${ctx.presetId}" preset is not worn ${ctx.mode}`);
259
+ const limits = look?.limits ?? {};
260
+ const daring = page.dial === LayoutDial.Daring;
261
+ if (!inList(V.dials, page.dial)) add(LayoutIssueCode.Value, 'dial', V.dials.join(' | '));
262
+ const facts = String(ctx.facts ?? '');
263
+ const factKeys = ctx.factKeys ?? Object.keys(SPEC_SITE_FACTS);
264
+ const routes = ctx.routes ?? [];
265
+ const sources = ctx.sources ?? [];
266
+ const lumOf = (hex: string) => {
267
+ const c = parseCssColour(hex);
268
+ return c ? relativeLuminance(c) : 0;
269
+ };
270
+ const colourHex = (name: string | undefined, text: boolean) => {
271
+ if (!paint) return null;
272
+ const colour = (inList(V.colours, name) ? name : LayoutColour.Ink) as LayoutColour;
273
+ return text && colour === LayoutColour.Accent ? paint.accentText : paint.colours[colour];
274
+ };
275
+
276
+ // ── the sections ──
277
+ const sections = page.sections;
278
+ const [minSections, maxSections] = LIM.sections;
279
+ if (sections.length < minSections || sections.length > maxSections) add(LayoutIssueCode.Structure, 'sections', `${sections.length} sections — ${minSections} to ${maxSections}`);
280
+ const ids = new Set(sections.map(s => s.id));
281
+ if (ids.size !== sections.length) add(LayoutIssueCode.Structure, 'sections', 'every section id is different');
282
+ const signatures = sections.map((s, i) => (s.signature ? i : -1)).filter(i => i >= 0);
283
+ if (signatures.length !== 1) add(LayoutIssueCode.Structure, 'sections', `${signatures.length} signature sections — exactly one`);
284
+ if (daring && signatures.length === 1 && sections[signatures[0] - 1]?.kind !== LayoutSectionKind.Inhale) {
285
+ add(LayoutIssueCode.Daring, `sections[${signatures[0]}]`, 'on daring the section right before the signature is an inhale');
286
+ }
287
+ const formSections = new Set(sections.filter(s => s.layers?.some(l => l.kind === LayoutLayerKind.Form)).map(s => s.id));
288
+
289
+ let reachable = false;
290
+ let galleries = 0;
291
+ let swappable = 0;
292
+ let layered = 0;
293
+ let accentUses = 0;
294
+ let huge = 0;
295
+ let centered = 0;
296
+ let textLayers = 0;
297
+ let sectionsWithEnters = 0;
298
+ let eyebrows = 0;
299
+ let splitRun = 0;
300
+ let lightGrounds = 0;
301
+ let bleeds = 0;
302
+ let screenWords = 0;
303
+ let wordsOnPhoto = 0;
304
+ let holds = 0;
305
+ let pinned = 0;
306
+ let marquees = 0;
307
+ let boxes = 0;
308
+ const photos = new Set<string>();
309
+
310
+ // A place given to the plan's ready-made section (silent section fallback) is the pattern's own, already proven: none
311
+ // of a composed section's rules reach into it, and the page's counts are the composed sections'. It still lets people
312
+ // reach the business when its pattern is a call to act or a contact.
313
+ const composedCount = sections.filter(s => !s.readyMade).length;
314
+ if (sections.some(s => s.readyMade && READY_MADE_REACH.has(patternById(s.readyMade.pattern)?.family ?? ''))) reachable = true;
315
+ sections.forEach((s, i) => {
316
+ if (s.readyMade) return;
317
+ const at = `sections[${i}]`;
318
+ const track = trackOf(s);
319
+ const kind = s.kind ?? LayoutSectionKind.Content;
320
+ const content = kind === LayoutSectionKind.Content;
321
+ if (!String(s.id ?? '').trim()) add(LayoutIssueCode.Structure, `${at}.id`, 'a short slug');
322
+ if (!inList([LayoutSectionKind.Content, LayoutSectionKind.Inhale], kind)) add(LayoutIssueCode.Value, `${at}.kind`, 'content | inhale (a signature is a content section)');
323
+ if (!(s.screens >= LIM.screens[0] && s.screens <= LIM.screens[1])) add(LayoutIssueCode.Value, `${at}.screens`, `${LIM.screens[0]}..${LIM.screens[1]}`);
324
+ if (!(Number.isInteger(s.rows) && s.rows >= LIM.rows[0] && s.rows <= LIM.rows[1])) add(LayoutIssueCode.Value, `${at}.rows`, `a whole number ${LIM.rows[0]}..${LIM.rows[1]}`);
325
+ if (!(Number.isInteger(track) && track >= 1 && track <= LIM.hold[1])) add(LayoutIssueCode.Value, `${at}.track`, `1..${LIM.hold[1]}`);
326
+ if (track > 1 && !s.pin) add(LayoutIssueCode.Structure, `${at}.track`, 'a sideways section is held');
327
+ if (s.transition && !inList(V.transitions, s.transition)) add(LayoutIssueCode.Value, `${at}.transition`, V.transitions.join(' | '));
328
+ const ground = String(s.ground ?? LayoutColour.Ground);
329
+ const groundPhoto = groundPhotoOf(s);
330
+ if (!inList(V.colours, ground) && !groundPhoto) add(LayoutIssueCode.Value, `${at}.ground`, 'a colour name or photo:<id>');
331
+ if (groundPhoto) {
332
+ photos.add(groundPhoto);
333
+ if (parseLayoutPhotoId(groundPhoto)?.source === LayoutPhotoSource.Box) add(LayoutIssueCode.Content, `${at}.ground`, 'a box is never a ground — choose a photo, or a colour');
334
+ else if (!(groundPhoto in ctx.photos)) add(LayoutIssueCode.Content, `${at}.ground`, `"${groundPhoto}" is not one of the photos — use only the ids you were given`);
335
+ }
336
+ if (inList(V.colours, ground) && paint && lumOf(paint.colours[ground as LayoutColour]) > PHOTO_LIGHT_LUMINANCE) lightGrounds++;
337
+ if (ground === LayoutColour.Accent) accentUses += ACCENT_GROUND_USES;
338
+ const layers = Array.isArray(s.layers) ? s.layers : [];
339
+ if (!layers.length) add(LayoutIssueCode.Structure, `${at}.layers`, 'at least one layer');
340
+ if (s.pin) pinned++;
341
+ if (s.pin && (s.screens >= 2 || track > 1)) holds++;
342
+ if (i === 0 && daring && splitSide(s)) add(LayoutIssueCode.Daring, at, 'a daring page never opens on a split (photo one side, words the other) — break it');
343
+ const phone = Array.isArray(s.phone) ? s.phone : [];
344
+ if (phone.length !== layers.length || new Set(phone).size !== layers.length || phone.some(n => !(Number.isInteger(n) && n >= 0 && n < layers.length))) {
345
+ add(LayoutIssueCode.Structure, `${at}.phone`, 'every layer index exactly once, in a phone\'s reading order');
346
+ }
347
+ if (kind === LayoutSectionKind.Inhale) {
348
+ if (layers.length > LIM.inhaleLayers) add(LayoutIssueCode.Structure, `${at}.layers`, `an inhale holds at most ${LIM.inhaleLayers} small layers`);
349
+ if (layers.some(isPictured) || groundPhoto) add(LayoutIssueCode.Structure, at, 'an inhale has no photo and no gallery');
350
+ if (s.screens > LIM.inhaleScreens) add(LayoutIssueCode.Structure, `${at}.screens`, `an inhale is 1–${LIM.inhaleScreens} screens`);
351
+ }
352
+ const leads = layers.filter(l => l.role === LayoutRole.Lead).length;
353
+ if (content && leads !== 1) add(LayoutIssueCode.Structure, `${at}.layers`, `${leads} leads — exactly one layer is the lead`);
354
+ if (!content && leads > 1) add(LayoutIssueCode.Structure, `${at}.layers`, 'an inhale has at most one lead');
355
+ if (look && content && !groundPhoto) {
356
+ const empty = emptyShare(s);
357
+ if (empty < look.empty - 0.001) {
358
+ add(LayoutIssueCode.Look, at, `${Math.round(empty * 100)}% of its grid is empty — the ${look.id} look needs ${Math.round(look.empty * 100)}%: make layers smaller or remove one`);
359
+ }
360
+ }
361
+ splitRun = splitSide(s) ? splitRun + 1 : 0;
362
+ if (splitRun === SPLITS_IN_A_ROW) add(LayoutIssueCode.Look, at, `the ${SPLITS_IN_A_ROW}rd "split" section in a row (one photo on one side, words on the other) — change the composition`);
363
+ const display = layers.filter(l => (l.kind === 'word' || l.kind === 'heading' || l.kind === 'number') && l.size).map(l => L.sizePx[l.size!] ?? 0);
364
+ const body = layers.filter(l => l.kind === 'text' || l.kind === 'list');
365
+ if (look && display.length && body.length && content) {
366
+ const bodyPx = Math.max(...body.map(l => L.sizePx[l.size ?? 'm']));
367
+ const ratio = Math.max(...display) / bodyPx;
368
+ const need = i === 0 ? look.contrast[0] : look.contrast[1];
369
+ if (ratio < need) add(LayoutIssueCode.Look, at, `its biggest display is ${ratio.toFixed(1)}× its body text — the ${look.id} look needs ${need}× here`);
370
+ }
371
+ const entering = layers.filter(l => l.enter && l.enter !== LayoutEnter.None && l.enter !== LayoutEnter.Fade);
372
+ if (entering.length) sectionsWithEnters++;
373
+ const recipes = new Set(entering.filter(l => l.role !== LayoutRole.Lead).map(l => l.enter));
374
+ if (recipes.size > 1) add(LayoutIssueCode.Motion, `${at}.layers`, `the supporting layers enter in ${recipes.size} ways — one entrance per section besides the lead's`);
375
+ if (entering.length > LIM.enteringPerSection) add(LayoutIssueCode.Motion, `${at}.layers`, `${entering.length} layers enter — at most ${LIM.enteringPerSection}; let the rest simply be there`);
376
+
377
+ let rotated = 0;
378
+ layers.forEach((l, j) => {
379
+ const lp = `${at}.layers[${j}]`;
380
+ if (!inList(V.kinds, l.kind)) {
381
+ add(LayoutIssueCode.Value, `${lp}.kind`, V.kinds.join(' | '));
382
+ return;
383
+ }
384
+ if (!inList(V.roles, l.role)) add(LayoutIssueCode.Value, `${lp}.role`, V.roles.join(' | '));
385
+ const lastCol = GRID * track + 1;
386
+ const [c0, c1] = l.col ?? [];
387
+ const [r0, r1] = l.row ?? [];
388
+ const placed = c0 >= 1 && c1 <= lastCol && c0 < c1 && r0 >= 1 && r1 <= s.rows + 1 && r0 < r1;
389
+ if (!(c0 >= 1 && c1 <= lastCol && c0 < c1)) add(LayoutIssueCode.Value, `${lp}.col`, `[start, end] within 1..${lastCol}, start < end`);
390
+ if (!(r0 >= 1 && r1 <= s.rows + 1 && r0 < r1)) add(LayoutIssueCode.Value, `${lp}.row`, `[start, end] within 1..${s.rows + 1}, start < end`);
391
+ if (l.size && !inList(V.sizes, l.size)) add(LayoutIssueCode.Value, `${lp}.size`, V.sizes.join(' | '));
392
+ if (l.color && !inList(V.colours, l.color)) add(LayoutIssueCode.Value, `${lp}.color`, V.colours.join(' | '));
393
+ if (l.align && !inList(V.aligns, l.align)) add(LayoutIssueCode.Value, `${lp}.align`, V.aligns.join(' | '));
394
+ if (l.bleed && !inList(V.bleeds, l.bleed)) add(LayoutIssueCode.Value, `${lp}.bleed`, V.bleeds.join(' | '));
395
+ if (l.variant !== undefined && l.kind !== LayoutLayerKind.Button) add(LayoutIssueCode.Value, `${lp}.variant`, `a ${l.kind} has no button variant`);
396
+ else if (l.variant !== undefined && !inList(V.buttonVariants, l.variant)) add(LayoutIssueCode.Value, `${lp}.variant`, V.buttonVariants.join(' | '));
397
+ const text = String(l.text ?? (l.items ?? []).join(' '));
398
+ const maxChars = l.size ? L.maxChars[l.size] : undefined;
399
+ if (maxChars !== undefined && text.length > maxChars) add(LayoutIssueCode.Reading, `${lp}.text`, `${text.length} characters is too long for size ${l.size} (≤ ${maxChars})`);
400
+ if ((l.size === 'm' || l.size === 's') && text.length > LIM.longTextChars && span(l.col) > LIM.longTextColumns) {
401
+ add(LayoutIssueCode.Reading, `${lp}.col`, `long text is never wider than ${LIM.longTextColumns} columns`);
402
+ }
403
+ if (placed && isText(l) && l.size && l.size !== 'screen' && text) {
404
+ const px = L.sizePx[l.size];
405
+ const box = boxPx(l.col, l.row, s);
406
+ const lines = Math.floor(box.h / (px * LINE_HEIGHT));
407
+ const advance = HEBREW.test(text) ? LIM.advance.hebrew : LIM.advance.latin;
408
+ const items = l.kind === LayoutLayerKind.List ? Math.max(1, l.items?.length ?? 1) : 1;
409
+ const fits = lines >= items && (text.length * px * advance) / Math.max(1, lines) <= box.w * LIM.textFitSlack;
410
+ if (!fits) add(LayoutIssueCode.Reading, `${lp}.row`, `${text.length} characters at ${l.size} do not fit a box of ${span(l.col)} columns × ${span(l.row)} rows (about ${Math.max(0, lines)} line${lines === 1 ? '' : 's'}) — give it more rows or columns, or fewer words`);
411
+ }
412
+ if (l.size === 'screen' || l.size === 'xxl') huge++;
413
+ if (l.size === 'screen') {
414
+ screenWords++;
415
+ const misfit = text ? screenWordMisfit(l, design) : null;
416
+ if (misfit) add(LayoutIssueCode.Reading, `${lp}.text`, `"${text}" is ${misfit.px}px too wide for ${misfit.phone ? `a ${misfit.width}px phone` : 'its columns'} even at the smallest screen size — fewer letters, ${misfit.phone ? '' : 'more columns, '}or size xxl`);
417
+ }
418
+ if (l.bleed && l.bleed !== 'none') bleeds++;
419
+ if (l.depth !== undefined && !inList(V.depths, l.depth)) add(LayoutIssueCode.Value, `${lp}.depth`, V.depths.join(' | '));
420
+ const deep = !!l.depth && l.depth !== 'mid';
421
+ if (deep && s.pin) add(LayoutIssueCode.Motion, `${lp}.depth`, 'no depth inside a held section — use motion');
422
+ if (l.inner !== undefined && !(l.inner >= 0 && l.inner <= INNER_MAX)) add(LayoutIssueCode.Value, `${lp}.inner`, `0..${INNER_MAX}`);
423
+ if ((deep && !s.pin) || l.inner) layered++;
424
+ if (LAYOUT_OPERATED.has(l.kind) && deep) add(LayoutIssueCode.Motion, `${lp}.depth`, 'what a visitor operates never moves for style — give it no depth (mid)');
425
+
426
+ // the entrance
427
+ if (l.enter !== undefined && !inList(V.enters, l.enter)) add(LayoutIssueCode.Value, `${lp}.enter`, V.enters.join(' | '));
428
+ else if (look && l.enter && l.enter !== LayoutEnter.None && l.enter !== LayoutEnter.Fade && !look.enters.includes(l.enter)) {
429
+ add(LayoutIssueCode.Look, `${lp}.enter`, `the ${look.id} look enters with ${['fade', ...look.enters].join(' | ')}`);
430
+ }
431
+ if (l.enter === LayoutEnter.ClipReveal && l.from && !inList(V.sides, l.from)) add(LayoutIssueCode.Value, `${lp}.from`, V.sides.join(' | '));
432
+ if (l.enter === LayoutEnter.Pop && isText(l) && wordsOf(l.text) > POP_WORDS) add(LayoutIssueCode.Look, `${lp}.enter`, `pop only on ${POP_WORDS} words or fewer`);
433
+ if (l.beat !== undefined && !(Number.isInteger(l.beat) && l.beat >= 0 && l.beat <= BEAT_MAX)) add(LayoutIssueCode.Value, `${lp}.beat`, `0..${BEAT_MAX}`);
434
+ if (l.role === LayoutRole.Lead && l.enter && l.enter !== LayoutEnter.None && (l.beat ?? 0) !== 0) add(LayoutIssueCode.Motion, `${lp}.beat`, 'the lead enters first (beat 0)');
435
+ if (l.role === LayoutRole.Decoration) {
436
+ if (l.enter && l.enter !== LayoutEnter.None && l.enter !== LayoutEnter.Fade) {
437
+ add(LayoutIssueCode.Motion, `${lp}.enter`, 'decoration only fades ("fade" or "none")', { kind: LayoutMendKind.Fade, layer: lp });
438
+ }
439
+ if ((l.motion ?? []).some(m => m.prop !== LayoutTrackProp.Opacity)) add(LayoutIssueCode.Motion, `${lp}.motion`, 'decoration only fades — opacity tracks only');
440
+ if (l.depth === 'front') add(LayoutIssueCode.Motion, `${lp}.depth`, 'decoration never runs ahead — back or mid');
441
+ }
442
+ if (l.role === LayoutRole.Static && ((l.enter && l.enter !== LayoutEnter.None) || l.motion?.length || deep)) add(LayoutIssueCode.Motion, `${lp}.role`, 'a static layer has no enter, motion or depth');
443
+
444
+ if (l.rotate) {
445
+ rotated++;
446
+ const max = Math.min(LIM.maxRotate, look?.rotateMax ?? LIM.maxRotate);
447
+ if (Math.abs(l.rotate) > max) add(LayoutIssueCode.Look, `${lp}.rotate`, `at most ±${max}° in the ${look?.id ?? ''} look`);
448
+ }
449
+
450
+ // motion tracks
451
+ if (l.motion?.length && !s.pin) add(LayoutIssueCode.Motion, `${lp}.motion`, 'tracks play only in a held section — hold the section, or give it an entrance');
452
+ if (LAYOUT_OPERATED.has(l.kind) && (l.motion ?? []).some(m => m.prop !== LayoutTrackProp.Opacity)) {
453
+ add(LayoutIssueCode.Motion, `${lp}.motion`, 'what a visitor operates never moves by tracks — it may only fade in (opacity)');
454
+ }
455
+ const shows: number[] = [];
456
+ const hides: number[] = [];
457
+ (l.motion ?? []).forEach((m, k) => {
458
+ const mp = `${lp}.motion[${k}]`;
459
+ if (!inList(V.trackProps, m.prop)) add(LayoutIssueCode.Value, `${mp}.prop`, V.trackProps.join(' | '));
460
+ const okAt = Array.isArray(m.at) && m.at[0] >= 0 && m.at[1] <= 1 && m.at[0] < m.at[1];
461
+ if (!okAt) add(LayoutIssueCode.Value, `${mp}.at`, '[from, to] within 0..1');
462
+ if (m.ease !== undefined && !inList(V.eases, m.ease)) add(LayoutIssueCode.Value, `${mp}.ease`, V.eases.join(' | '));
463
+ if (m.prop === LayoutTrackProp.Scale && (Math.min(m.from, m.to) < LIM.minScale || Math.max(m.from, m.to) > TRACK_SCALE_MAX)) {
464
+ add(LayoutIssueCode.Motion, mp, `scale stays within ${LIM.minScale}..${TRACK_SCALE_MAX} — nothing grows from nothing`);
465
+ }
466
+ if (m.prop === LayoutTrackProp.Blur && isText(l) && Math.max(m.from, m.to) > LIM.maxTextBlur) add(LayoutIssueCode.Motion, mp, `blur on words at most ${LIM.maxTextBlur}px`);
467
+ if (m.prop === LayoutTrackProp.Rotate && Math.max(Math.abs(m.from), Math.abs(m.to)) > LIM.maxRotate) add(LayoutIssueCode.Motion, mp, `rotation at most ±${LIM.maxRotate}°`);
468
+ const length = okAt ? m.at[1] - m.at[0] : 0;
469
+ const opacity = m.prop === LayoutTrackProp.Opacity;
470
+ const clip = m.prop === LayoutTrackProp.Clip;
471
+ if ((opacity && m.to < m.from && m.to <= LAYOUT_HIDDEN_OPACITY) || (clip && m.to < m.from && m.to <= HIDDEN_CLIP)) hides.push(length);
472
+ if ((opacity && m.to > m.from && m.from <= LAYOUT_HIDDEN_OPACITY) || (clip && m.to > m.from && m.from <= HIDDEN_CLIP)) shows.push(length);
473
+ });
474
+ if (shows.length && hides.length && Math.max(...hides) > Math.max(...shows)) add(LayoutIssueCode.Motion, `${lp}.motion`, 'it leaves more slowly than it arrived — an exit is shorter than the entrance');
475
+ if (l.kinetic) {
476
+ if (l.kind !== LayoutLayerKind.Word && l.kind !== LayoutLayerKind.Heading) add(LayoutIssueCode.Value, `${lp}.kinetic`, 'only a word or heading');
477
+ if (wordsOf(l.text) > LIM.kineticWords) add(LayoutIssueCode.Look, `${lp}.kinetic`, `${wordsOf(l.text)} words — kinetic words hold at most ${LIM.kineticWords}`);
478
+ if (!s.pin) add(LayoutIssueCode.Motion, `${lp}.kinetic`, 'kinetic words light by the scroll of a HELD section');
479
+ }
480
+
481
+ // photos: only the pool, or a box
482
+ const photoId = (id: string | undefined, path: string) => {
483
+ if (!id) {
484
+ add(LayoutIssueCode.Content, path, 'an id from the photos you were given, or box:<shape>');
485
+ return;
486
+ }
487
+ const parsed = parseLayoutPhotoId(id);
488
+ if (parsed?.source === LayoutPhotoSource.Box) boxes++;
489
+ else {
490
+ photos.add(id);
491
+ if (!(id in ctx.photos)) add(LayoutIssueCode.Content, path, `"${id}" is not one of the photos — use only the ids you were given, or box:<shape>`);
492
+ }
493
+ };
494
+ if (l.kind === LayoutLayerKind.Photo) photoId(l.photo?.id, `${lp}.photo`);
495
+ if (l.kind === LayoutLayerKind.Gallery) {
496
+ galleries++;
497
+ const g = l.gallery ?? { slides: [] };
498
+ const slides = Array.isArray(g.slides) ? g.slides : [];
499
+ const [minSlides, maxSlides] = LIM.gallerySlides;
500
+ if (g.source !== undefined && !sources.includes(g.source)) {
501
+ const named = ctx.lists?.find(x => x.alias === g.source);
502
+ // Words written for the refused list stay over whatever it would show instead: left to the repair (iox-ui#66).
503
+ const chosen = named && !named.pictures && !sectionNames(s, named) ? gallerySourceFor(s, (ctx.lists ?? []).filter(x => x.pictures && sources.includes(x.alias))) : null;
504
+ add(LayoutIssueCode.Content, `${lp}.gallery.source`, sources.length ? `one of ${sources.join(' | ')}` : 'the site has no list to show — give the gallery its photos',
505
+ chosen ? { kind: LayoutMendKind.Source, layer: lp, ...chosen } : undefined);
506
+ }
507
+ if (g.source === undefined && (slides.length < minSlides || slides.length > maxSlides)) add(LayoutIssueCode.Value, `${lp}.gallery.slides`, `${minSlides}..${maxSlides} slides`);
508
+ if (g.source !== undefined && slides.length > maxSlides) add(LayoutIssueCode.Value, `${lp}.gallery.slides`, `at most ${maxSlides} slides`);
509
+ if (g.effect !== undefined && !inList(V.galleryEffects, g.effect)) add(LayoutIssueCode.Value, `${lp}.gallery.effect`, V.galleryEffects.join(' | '));
510
+ if (g.scroll && !s.pin) add(LayoutIssueCode.Motion, `${lp}.gallery.scroll`, 'a scroll-turned gallery sits in a held section');
511
+ if (!g.scroll) swappable++;
512
+ slides.forEach((slide, k) => photoId(slide.photo?.id, `${lp}.gallery.slides[${k}]`));
513
+ }
514
+ if (l.kind === LayoutLayerKind.Marquee) {
515
+ marquees++;
516
+ const items = l.items ?? [];
517
+ const [minItems, maxItems] = LIM.marqueeItems;
518
+ if (items.length < minItems || items.length > maxItems || items.some(t => String(t).length > LIM.marqueeChars)) {
519
+ add(LayoutIssueCode.Content, `${lp}.items`, `${minItems}–${maxItems} phrases of at most ${LIM.marqueeChars} characters`);
520
+ }
521
+ }
522
+ if (l.kind === LayoutLayerKind.Form) {
523
+ reachable = true;
524
+ const f = l.form;
525
+ const preset = f?.preset;
526
+ if (!inList(V.formPresets, preset)) add(LayoutIssueCode.Value, `${lp}.form.preset`, V.formPresets.join(' | '));
527
+ else {
528
+ const chips: ReadonlyArray<string> = V.formChips[preset as keyof typeof V.formChips];
529
+ const [minChips, maxChips] = LIM.formChips;
530
+ for (const name of chips) {
531
+ const opts = f?.options?.[name as 'needs' | 'budget' | 'guests'];
532
+ if (!Array.isArray(opts) || opts.length < minChips || opts.length > maxChips) add(LayoutIssueCode.Content, `${lp}.form.options.${name}`, `${minChips}–${maxChips} short choices`);
533
+ for (const o of opts ?? []) if (CHIP_NUMBER.test(o) && !facts.includes(o)) add(LayoutIssueCode.Content, `${lp}.form.options.${name}`, `"${o}" is a number nobody gave — use words`);
534
+ }
535
+ for (const name of Object.keys(f?.options ?? {})) if (!chips.includes(name)) add(LayoutIssueCode.Value, `${lp}.form.options.${name}`, `a ${preset} form has no ${name} choices`);
536
+ if (preset === 'lead' && !ctx.takesLeads) add(LayoutIssueCode.Content, `${lp}.form.preset`, 'this business takes no leads — use contact or booking');
537
+ }
538
+ if (f?.channel?.href) add(LayoutIssueCode.Content, `${lp}.form.channel.href`, 'no link — the second channel is filled from the owner\'s facts');
539
+ if (span(l.col) < LIM.formColumns) add(LayoutIssueCode.Structure, `${lp}.col`, `a form needs at least ${LIM.formColumns} columns`);
540
+ if (groundPhoto || layers.some(o => o !== l && isPictured(o) && overlaps(o, l))) add(LayoutIssueCode.Reading, lp, 'a form never sits on a photo');
541
+ }
542
+ if (l.kind === LayoutLayerKind.Button) {
543
+ accentUses++;
544
+ if (!l.to) add(LayoutIssueCode.Content, `${lp}.to`, 'a button leads somewhere: a section id or a page route');
545
+ else if (!ids.has(l.to) && !routes.includes(l.to)) {
546
+ add(LayoutIssueCode.Content, `${lp}.to`, `"${l.to}" is not a section id${routes.length ? ` or one of the routes ${routes.join(' | ')}` : ''}`);
547
+ } else if (formSections.has(l.to) || CONTACT_WORDS.test(`${l.to} ${l.text ?? ''}`)) reachable = true;
548
+ } else if (l.color === LayoutColour.Accent) accentUses++;
549
+ if (isText(l)) {
550
+ textLayers++;
551
+ if (l.align === 'center') centered++;
552
+ }
553
+
554
+ // reading: words on a photo only over a calm part of what its frame shows (or a scrim the look allows); off a photo, by contrast
555
+ if (placed && (isText(l) || l.kind === LayoutLayerKind.Button)) {
556
+ const under: PhotoUnder[] = layers
557
+ .filter(o => o !== l && o.kind === LayoutLayerKind.Photo && (o.z ?? 0) < (l.z ?? 0) && overlaps(o, l) && o.photo?.id)
558
+ .map(o => ({ id: o.photo!.id, frame: boxPx(o.col, o.row, s), region: regionInLayer(o, l) }));
559
+ if (groundPhoto) under.push({ id: groundPhoto, frame: { w: LAYOUT_CHECK_VIEWPORT.width, h: s.screens * LAYOUT_CHECK_VIEWPORT.height }, region: regionOnGround(s, l) });
560
+ const fgHex = isText(l) ? colourHex(l.color, true) : null;
561
+ const fg = fgHex ? lumOf(fgHex) : null;
562
+ const large = (L.sizePx[l.size ?? 'm'] ?? 0) >= LARGE_TEXT_PX;
563
+ const need = large ? CONTRAST_LARGE : CONTRAST_BODY;
564
+ if (under.length && isText(l)) wordsOnPhoto++;
565
+ for (const p of under) {
566
+ if (limits.noTextOnPhoto && isText(l)) {
567
+ add(LayoutIssueCode.Look, lp, `the ${look?.id} look never puts words on a photo`);
568
+ break;
569
+ }
570
+ if (l.scrim) {
571
+ if (limits.noScrim) add(LayoutIssueCode.Look, `${lp}.scrim`, `the ${look?.id} look has no scrims — move the words to a calm part, or off the photo`);
572
+ continue;
573
+ }
574
+ const box = parseLayoutPhotoId(p.id)?.source === LayoutPhotoSource.Box;
575
+ if (!box && !(p.id in ctx.photos)) continue;
576
+ const inv = ctx.photos[p.id];
577
+ if (box || !inv) {
578
+ add(LayoutIssueCode.Reading, lp, `"${p.id}" has no picture to read yet — words never sit on it`);
579
+ continue;
580
+ }
581
+ const read = calmUnder(inv, p.frame, p.region);
582
+ if (!read.calm) {
583
+ const calm = calmParts(inv);
584
+ add(LayoutIssueCode.Reading, lp, `sits on a busy part of "${p.id}" as its frame shows it; its calm parts are ${calm.join(', ') || 'none'}${limits.noScrim ? '' : ' — move it there, or add a scrim'}`,
585
+ limits.noScrim ? undefined : { kind: LayoutMendKind.Scrim, layer: lp });
586
+ } else if (fg !== null && contrastOf(fg, read.luminance) < need) {
587
+ add(LayoutIssueCode.Reading, `${lp}.color`, `${contrastOf(fg, read.luminance).toFixed(2)}:1 over the ${read.tone} part of "${p.id}" — use a colour that contrasts (${need}:1)`,
588
+ limits.noScrim ? undefined : { kind: LayoutMendKind.Scrim, layer: lp });
589
+ }
590
+ }
591
+ if (!under.length && fg !== null) {
592
+ const shape = layers.filter(o => o !== l && o.kind === LayoutLayerKind.Shape && (o.z ?? 0) < (l.z ?? 0) && overlaps(o, l)).sort((a, b) => (b.z ?? 0) - (a.z ?? 0))[0];
593
+ const bgHex = shape ? colourHex(shape.color ?? LayoutColour.Accent, false) : colourHex(inList(V.colours, ground) ? ground : LayoutColour.Ground, false);
594
+ if (bgHex) {
595
+ const ratio = contrastOf(fg, lumOf(bgHex));
596
+ const ink = colourHex(LayoutColour.Ink, true);
597
+ const inkHolds = !!l.color && l.color !== LayoutColour.Ink && !!ink && contrastOf(lumOf(ink), lumOf(bgHex)) >= need;
598
+ if (ratio < need) add(LayoutIssueCode.Reading, `${lp}.color`, `${ratio.toFixed(2)}:1 on its ${shape ? 'shape' : 'ground'} — too faint to read (${need}:1)`,
599
+ inkHolds ? { kind: LayoutMendKind.Ink, layer: lp } : undefined);
600
+ }
601
+ }
602
+ }
603
+
604
+ // eyebrows: a small label right on top of a heading
605
+ if ((l.kind === LayoutLayerKind.Word || l.kind === LayoutLayerKind.Heading) && layers.some(o => o.kind === LayoutLayerKind.Label
606
+ && (o.row?.[1] ?? 0) >= (l.row?.[0] ?? 0) - 1 && (o.row?.[1] ?? 0) <= (l.row?.[0] ?? 0)
607
+ && (o.col?.[0] ?? 0) < (l.col?.[1] ?? 0) && (l.col?.[0] ?? 0) < (o.col?.[1] ?? 0))) eyebrows++;
608
+
609
+ // facts: tokens that name a fact, placeholders that should be one, numbers nobody gave
610
+ for (const words of wordsOfLayer(l)) {
611
+ for (const [, key] of words.matchAll(FACT_TOKEN)) if (!factKeys.includes(key)) add(LayoutIssueCode.Content, `${lp}.text`, `{fact:${key}} names no fact — one of ${factKeys.join(' | ')}`);
612
+ const plain = words.replace(FACT_TOKEN, '');
613
+ for (const [whole, inner] of plain.matchAll(BRACKET)) {
614
+ const key = factKeys.find(k => k === inner.trim().toLowerCase());
615
+ add(LayoutIssueCode.Content, `${lp}.text`, key ? `"${whole}" is written {fact:${key}}` : `"${whole}" is not a fact the owner can give — leave it out, or say it in words`);
616
+ }
617
+ for (const n of plain.match(NUMBER_GIVEN) ?? []) if (!facts.includes(n.replace(/[$₪€£\s]/g, ''))) add(LayoutIssueCode.Content, `${lp}.text`, `"${n}" was not given — name a fact ({fact:hours}) or leave it out`);
618
+ if (ctx.locale === 'he' && LATIN_SENTENCE.test(plain)) add(LayoutIssueCode.Content, `${lp}.text`, 'the site is Hebrew — write it in Hebrew');
619
+ }
620
+ });
621
+ if (limits.rotatedPerSectionMax !== undefined && rotated > limits.rotatedPerSectionMax) add(LayoutIssueCode.Look, at, `${rotated} rotated layers — at most ${limits.rotatedPerSectionMax}`);
622
+ if (i === 0 && limits.firstButtonsMax !== undefined && layers.filter(l => l.kind === LayoutLayerKind.Button).length > limits.firstButtonsMax) {
623
+ add(LayoutIssueCode.Look, at, `at most ${limits.firstButtonsMax} button in the first section`);
624
+ }
625
+ });
626
+
627
+ (sections[0]?.layers ?? []).forEach((l, j) => {
628
+ for (const m of l.motion ?? []) {
629
+ if ((m.at?.[0] ?? 0) > START_EDGE) continue;
630
+ const from = Number(m.from);
631
+ if ((m.prop === LayoutTrackProp.Opacity && from < START_OPACITY_MIN) || (m.prop === LayoutTrackProp.Clip && from < START_CLIP_MIN)) {
632
+ add(LayoutIssueCode.Motion, `sections[0].layers[${j}].motion`, `${m.prop} starts at ${from}: the first screen shows it before anyone scrolls`);
633
+ }
634
+ }
635
+ });
636
+ if (ctx.first && !reachable) add(LayoutIssueCode.Content, 'sections', 'nothing lets people reach the business — a form, or a button to one');
637
+ if (galleries < LIM.galleriesMin) add(LayoutIssueCode.Structure, 'sections', `${galleries} galleries — at least ${LIM.galleriesMin}`);
638
+ if (LIM.galleriesMin > 0 && galleries && !swappable) add(LayoutIssueCode.Structure, 'sections', 'no gallery can be dragged or swiped — at least one without "scroll"');
639
+ if (marquees > LIM.marquees) add(LayoutIssueCode.Structure, 'sections', `${marquees} marquees — at most ${LIM.marquees}`);
640
+ const minDepth = look && inList(LIM.calmLooks, look.id) ? LIM.depthLayersCalm : LIM.depthLayers;
641
+ if (layered < minDepth) {
642
+ const glide = glideChoice(sections, minDepth - layered);
643
+ add(LayoutIssueCode.Motion, 'sections', `${layered} layers glide by depth or drift — at least ${minDepth}`,
644
+ glide.length === minDepth - layered ? { kind: LayoutMendKind.Depth, layers: glide } : undefined);
645
+ }
646
+ if (daring) {
647
+ const d = LIM.daring;
648
+ if (bleeds < d.bleeds) add(LayoutIssueCode.Daring, 'sections', `${bleeds} layer(s) bleed off an edge — a daring page lets at least ${d.bleeds} run off the screen`);
649
+ if (screenWords < d.screenWords) add(LayoutIssueCode.Daring, 'sections', 'no word at "screen" size — a daring page lets one thing be enormous');
650
+ if (wordsOnPhoto < d.wordsOnPhoto && !limits.noTextOnPhoto) add(LayoutIssueCode.Daring, 'sections', 'words never sit over a photo — a daring page sets words over a calm part of a picture at least once');
651
+ if (holds < d.holds) add(LayoutIssueCode.Daring, 'sections', `${holds} section(s) hold the page — a daring page holds at least ${d.holds} (held 2+ screens, or sideways)`);
652
+ } else if (pinned > LIM.distinct.holdsMax) {
653
+ add(LayoutIssueCode.Structure, 'sections', `${pinned} held sections — a distinct page holds at most ${LIM.distinct.holdsMax}`);
654
+ }
655
+ if (photos.size + boxes > LIM.maxPhotos) add(LayoutIssueCode.Content, 'sections', `${photos.size + boxes} photos — at most ${LIM.maxPhotos}`);
656
+ const enteringMax = Math.floor(composedCount * LIM.enteringSections) + 1;
657
+ if (sectionsWithEnters > enteringMax) add(LayoutIssueCode.Motion, 'sections', `${sectionsWithEnters} sections have entrances — at most ${enteringMax}; let the others glide`);
658
+ if (eyebrows > composedCount * EYEBROW_SHARE) add(LayoutIssueCode.Look, 'sections', `${eyebrows} headings carry a small label right above them — the AI-site cliché; keep it to a few`);
659
+ if (look) {
660
+ if (accentUses > look.accentMax) {
661
+ const bands = paint ? accentBandMoves(sections, ground => paint.colours[ground], (name, text) => colourHex(name, text)) : [];
662
+ add(LayoutIssueCode.Look, 'sections', `the accent is on ${accentUses} layers (a button counts, an accent ground twice) — the ${look.id} look allows ${look.accentMax}`,
663
+ { kind: LayoutMendKind.Accent, over: accentUses - look.accentMax, ...(bands.length ? { bands } : {}) });
664
+ }
665
+ if (limits.hugeMax !== undefined && huge > limits.hugeMax) add(LayoutIssueCode.Look, 'sections', `${huge} xxl/screen layers — the ${look.id} look allows ${limits.hugeMax}`);
666
+ if (limits.centerMax !== undefined && textLayers && centered / textLayers > limits.centerMax) {
667
+ add(LayoutIssueCode.Look, 'sections', `${centered} of ${textLayers} text layers are centred — the ${look.id} look allows ${Math.round(limits.centerMax * 100)}%`);
668
+ }
669
+ if (limits.lightGroundsMax !== undefined && lightGrounds > limits.lightGroundsMax) add(LayoutIssueCode.Look, 'sections', `${lightGrounds} sections on a light ground — the ${look.id} look allows ${limits.lightGroundsMax}`);
670
+ }
671
+ return uniqueIssues(issues);
672
+ }
673
+
674
+ /**
675
+ * M8-G2-D12 — what a look switch costs a composed page: the issues the check finds in the new look (`ctx`) at a place
676
+ * where the look it was composed for (`from`) found none of that kind. Nothing to say → []; the page's own known misses
677
+ * (in both looks) are never blamed on the switch.
678
+ */
679
+ export function layoutLookChanges(page: LayoutPage, ctx: CheckLayoutContext, from: Pick<CheckLayoutContext, 'presetId' | 'mode'>): LayoutIssue[] {
680
+ const before = new Set(checkLayout(page, { ...ctx, ...from }).map(i => `${i.code}|${i.path}`));
681
+ return checkLayout(page, ctx).filter(i => !before.has(`${i.code}|${i.path}`));
682
+ }
683
+
684
+ function uniqueIssues(issues: LayoutIssue[]): LayoutIssue[] {
685
+ const seen = new Set<string>();
686
+ return issues.filter(i => {
687
+ const key = `${i.code}|${i.path}|${i.message}`;
688
+ return !seen.has(key) && !!seen.add(key);
689
+ });
690
+ }
691
+
692
+ // ── Emil's audit, the static half (M8-G2-D9): what can be read off the stamped nodes ────────────────────────
693
+
694
+ /** The longest a time entrance plays. */
695
+ export const LAYOUT_ENTRANCE_MAX_MS = 1200;
696
+ /** The scale an action starts from, where it is not 1 (iox-ui `buildInteractionKeyframes`; held equal by the spec). */
697
+ export const ACTION_START_SCALE: Readonly<Record<string, number>> = { scaleIn: 0.8 };
698
+ const ENTRANCE_TRIGGERS: ReadonlySet<string> = new Set(['viewportEnter', 'pageLoad']);
699
+ const EASE_IN = /(^|[\s,(])ease-in(?!-out)/;
700
+ const EASING_TOKEN = /^(cubic-bezier\(|linear(\(|$)|var\(--)/;
701
+ const TRANSITION_ALL = /(^|[\s,])all([\s,]|$)/;
702
+
703
+ interface StampedAction { type?: string; duration?: number; easing?: string; params?: Record<string, unknown> }
704
+ interface StampedInteraction { trigger?: string; actions?: StampedAction[] }
705
+ interface StampedTrack { prop?: string; keys?: Array<[number, number]> }
706
+
707
+ /** Emil's rules a composed page's nodes can be held to without running them: eases, `transition: all`, scale, entrance length. */
708
+ export function auditLayoutMotion(nodes: ReadonlyArray<SerializedNode>): LayoutIssue[] {
709
+ const issues: LayoutIssue[] = [];
710
+ const add = (path: string, message: string): void => {
711
+ issues.push({ code: LayoutIssueCode.Motion, path, message });
712
+ };
713
+ walkSerialized(nodes, node => {
714
+ const at = `node(${node.id})`;
715
+ (node.interactions as StampedInteraction[]).forEach((ix, i) => (ix?.actions ?? []).forEach((a, j) => {
716
+ const ap = `${at}.interactions[${i}].actions[${j}]`;
717
+ const moves = (a.duration ?? 0) > 0;
718
+ const easing = String(a.easing ?? '');
719
+ if (EASE_IN.test(easing)) add(`${ap}.easing`, 'never ease-in: it starts slow where the eye is watching');
720
+ else if (moves && !EASING_TOKEN.test(easing)) add(`${ap}.easing`, `"${easing}" is not an easing token — a cubic-bezier, linear or a var()`);
721
+ if (moves && ENTRANCE_TRIGGERS.has(String(ix.trigger)) && (a.duration ?? 0) > LAYOUT_ENTRANCE_MAX_MS) add(`${ap}.duration`, `${a.duration}ms — an entrance plays in at most ${LAYOUT_ENTRANCE_MAX_MS}ms`);
722
+ const start = ACTION_START_SCALE[String(a.type)];
723
+ if (start !== undefined && start < LIM.minScale) add(`${ap}.type`, `${a.type} starts at scale ${start} — nothing grows from under ${LIM.minScale}`);
724
+ }));
725
+ for (const [k, t] of ((node.sceneTracks ?? []) as StampedTrack[]).entries()) {
726
+ if (t?.prop === LayoutTrackProp.Scale && (t.keys ?? []).some(([, v]) => v < LIM.minScale)) add(`${at}.sceneTracks[${k}]`, `a scale track under ${LIM.minScale}`);
727
+ }
728
+ const styles = [node.styleProps, ...Object.values(node.stateStyles ?? {}), ...Object.values(node.responsive ?? {}).map(r => r?.styleProps ?? {})];
729
+ for (const style of styles) {
730
+ for (const key of ['transition', 'transitionProperty']) {
731
+ if (TRANSITION_ALL.test(String(style?.[key] ?? ''))) add(`${at}.styleProps.${key}`, 'never transition: all — name the properties that move');
732
+ }
733
+ }
734
+ });
735
+ return issues;
736
+ }
737
+
738
+ /** Most important first: which layers take a depth when too few glide (iox-ui#63). */
739
+ const GLIDE_ROLE_ORDER: ReadonlyArray<`${LayoutRole}` | undefined> = [LayoutRole.Lead, LayoutRole.Support, undefined, LayoutRole.Decoration];
740
+
741
+ /**
742
+ * The layers that may glide and do not, most important first (role, then pictures before words, then page order): never
743
+ * in a held section (a Scene moves by its tracks), never what a visitor operates, never a static layer, never words over
744
+ * a photo (they must stay where the photo is calm), never a layer that already glides or drifts.
745
+ */
746
+ function glideCandidates(sections: ReadonlyArray<LayoutSection>): string[] {
747
+ const found: Array<{ path: string; role: number; words: number; si: number; li: number }> = [];
748
+ sections.forEach((s, si) => {
749
+ if (s.pin) return;
750
+ const layers = Array.isArray(s.layers) ? s.layers : [];
751
+ const photoGround = !!groundPhotoOf(s);
752
+ layers.forEach((l, li) => {
753
+ if (!inList(V.kinds, l.kind) || LAYOUT_OPERATED.has(l.kind) || l.role === LayoutRole.Static) return;
754
+ if ((l.depth && l.depth !== LayoutDepth.Mid) || l.inner) return;
755
+ const words = isText(l);
756
+ if (words && (photoGround || layers.some(o => o !== l && isPictured(o) && overlaps(o, l)))) return;
757
+ const role = GLIDE_ROLE_ORDER.indexOf(l.role);
758
+ found.push({ path: `sections[${si}].layers[${li}]`, role: role < 0 ? GLIDE_ROLE_ORDER.length : role, words: words ? 1 : 0, si, li });
759
+ });
760
+ });
761
+ return found.sort((a, b) => a.role - b.role || a.words - b.words || a.si - b.si || a.li - b.li).map(f => f.path);
762
+ }
763
+
764
+ const isWordy = (l: LayoutLayer) => isText(l) || l.kind === LayoutLayerKind.Button;
765
+
766
+ /** Every section's box on the laptop, the page's top at 0 (a held section's runway is its screens tall). */
767
+ function sectionBoxes(sections: ReadonlyArray<LayoutSection>): DriftBox[] {
768
+ let top = 0;
769
+ return sections.map(s => {
770
+ const box = { l: 0, r: LAYOUT_CHECK_VIEWPORT.width * trackOf(s), t: top, b: top + Math.max(1, s.screens) * LAYOUT_CHECK_VIEWPORT.height };
771
+ top = box.b;
772
+ return box;
773
+ });
774
+ }
775
+
776
+ /** A layer's cell on the laptop, inside its section's box. */
777
+ function cellBox(s: LayoutSection, l: LayoutLayer, section: DriftBox): DriftBox {
778
+ const rowPx = ((s.pin ? 1 : s.screens) * LAYOUT_CHECK_VIEWPORT.height) / Math.max(1, s.rows);
779
+ const [c0, c1] = l.col ?? [1, 1];
780
+ const [r0, r1] = l.row ?? [1, 1];
781
+ return { l: (c0 - 1) * COLUMN_PX, r: (c1 - 1) * COLUMN_PX, t: section.t + (r0 - 1) * rowPx, b: section.t + (r1 - 1) * rowPx };
782
+ }
783
+
784
+ /**
785
+ * The layers the depth mend gives `back`, `count` of them or fewer (iox-ui#63, #65): the glide candidates in their order,
786
+ * each taken only when, gliding, its cell never moves into a cell that carries words or a button — nor words into a
787
+ * picture — more than at rest, with the layers already taken gliding too (scene-core's maths, `driftOverlap`). Cells are
788
+ * wider than the ink, so this refuses what the render check might pass: a depth the composer adds never makes words meet.
789
+ */
790
+ function glideChoice(sections: ReadonlyArray<LayoutSection>, count: number): string[] {
791
+ if (count <= 0) return [];
792
+ const boxes = sectionBoxes(sections);
793
+ const pageHeight = boxes.length ? boxes[boxes.length - 1].b : 0;
794
+ const view = { width: LAYOUT_CHECK_VIEWPORT.width, height: LAYOUT_CHECK_VIEWPORT.height, pageHeight };
795
+ const taken: string[] = [];
796
+ for (const path of glideCandidates(sections)) {
797
+ const [, si, li] = /^sections\[(\d+)\]\.layers\[(\d+)\]$/.exec(path)!.map(Number);
798
+ const s = sections[si];
799
+ const l = s.layers[li];
800
+ const depthOf = (o: LayoutLayer, j: number) => (j === li || taken.includes(`sections[${si}].layers[${j}]`) ? ParallaxDepth.Back : layoutGlideDepth(s, o));
801
+ const meets = s.layers.some((o, j) => {
802
+ if (j === li || !(isWordy(l) || isWordy(o)) || !(isWordy(o) || isPictured(o)) || !(isWordy(l) || isPictured(l))) return false;
803
+ return !!driftOverlap({ box: cellBox(s, l, boxes[si]), depth: ParallaxDepth.Back }, { box: cellBox(s, o, boxes[si]), depth: depthOf(o, j) }, view, boxes[si]);
804
+ });
805
+ if (meets) continue;
806
+ taken.push(path);
807
+ if (taken.length === count) break;
808
+ }
809
+ return taken;
810
+ }
811
+
812
+ /** The grounds an accent band may take, the one nearest the accent in light first. */
813
+ const BAND_GROUNDS: ReadonlyArray<LayoutColour> = [LayoutColour.Ink, LayoutColour.Muted, LayoutColour.Soft, LayoutColour.Ground];
814
+
815
+ /**
816
+ * The accent bands the accent mend may move, least important first (an inhale, then later sections), each with the
817
+ * ground nearest the accent in light on which every word of the band still reads. Never the first section, never the
818
+ * band holding the main call to action (the first button that reaches the business, else the first button) or a form.
819
+ */
820
+ function accentBandMoves(
821
+ sections: ReadonlyArray<LayoutSection>,
822
+ groundHex: (ground: LayoutColour) => string,
823
+ colourHex: (name: string | undefined, text: boolean) => string | null,
824
+ ): LayoutBandMove[] {
825
+ const lum = (hex: string | null) => {
826
+ const c = hex ? parseCssColour(hex) : null;
827
+ return c ? relativeLuminance(c) : 0;
828
+ };
829
+ const buttons = sections.flatMap((s, si) => (s.layers ?? []).filter(l => l.kind === LayoutLayerKind.Button).map(l => ({ l, si })));
830
+ const formIds = new Set(sections.filter(s => s.layers?.some(l => l.kind === LayoutLayerKind.Form)).map(s => s.id));
831
+ const main = buttons.find(({ l }) => formIds.has(String(l.to)) || CONTACT_WORDS.test(`${l.to ?? ''} ${l.text ?? ''}`)) ?? buttons[0];
832
+ const accent = lum(groundHex(LayoutColour.Accent));
833
+ const grounds = [...BAND_GROUNDS].sort((a, b) => Math.abs(lum(groundHex(a)) - accent) - Math.abs(lum(groundHex(b)) - accent));
834
+ return sections
835
+ .map((s, si) => ({ s, si }))
836
+ .filter(({ s, si }) => si > 0 && s.ground === LayoutColour.Accent && si !== main?.si && !formIds.has(s.id))
837
+ .sort((a, b) => Number(b.s.kind === LayoutSectionKind.Inhale) - Number(a.s.kind === LayoutSectionKind.Inhale) || b.si - a.si)
838
+ .flatMap(({ s, si }) => {
839
+ const words = (s.layers ?? []).filter(isText);
840
+ const ground = grounds.find(g => words.every(l => {
841
+ const need = (L.sizePx[l.size ?? 'm'] ?? 0) >= LARGE_TEXT_PX ? CONTRAST_LARGE : CONTRAST_BODY;
842
+ return contrastOf(lum(colourHex(l.color, true)), lum(groundHex(g))) >= need;
843
+ }));
844
+ return ground ? [{ section: si, ground }] : [];
845
+ });
846
+ }
847
+
848
+ /** A word as a list name is matched: lower case, a plural's ending off (treatments → treatment, galleries → gallery). */
849
+ function stemOf(word: string): string {
850
+ const w = word.toLowerCase();
851
+ if (w.length > 4 && w.endsWith('ies')) return `${w.slice(0, -3)}y`;
852
+ if (w.length > 4 && /(ches|shes|xes|sses)$/.test(w)) return w.slice(0, -2);
853
+ if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss')) return w.slice(0, -1);
854
+ return w;
855
+ }
856
+
857
+ const nameWordsOf = (text: string, min = 4): string[] =>
858
+ text.replace(/([a-z])([A-Z])/g, '$1 $2').split(/[^\p{L}\p{N}]+/u).filter(w => w.length >= min).map(stemOf);
859
+
860
+ /** A list's name words: a one-word name keeps a short one (`faq`), a longer label only its words of 4 letters or more. */
861
+ const listWordsOf = (name: string): string[] => {
862
+ const words = nameWordsOf(name, 1);
863
+ return words.length === 1 ? nameWordsOf(name, 3) : nameWordsOf(name);
864
+ };
865
+
866
+ /** True when the section's own words name the list (its alias, type name or label: "Questions patients ask" → questions). */
867
+ function sectionNames(section: LayoutSection, list: LayoutGalleryList): boolean {
868
+ const said = new Set((section.layers ?? []).filter(l => (isText(l) || l.kind === LayoutLayerKind.Button) && typeof l.text === 'string').flatMap(l => nameWordsOf(l.text!, 3)));
869
+ return list.words.some(w => listWordsOf(w).some(x => said.has(x)));
870
+ }
871
+
872
+ /**
873
+ * The list a gallery naming a list without pictures shows instead (iox-ui#64), and the rule that chose it: the only list
874
+ * with pictures; else the first (plan order) whose alias, type name or label the section's own words name; else the first.
875
+ * None: null (the model is asked).
876
+ */
877
+ function gallerySourceFor(section: LayoutSection, candidates: ReadonlyArray<LayoutGalleryList>): { source: string; by: `${LayoutSourceChoice}` } | null {
878
+ if (!candidates.length) return null;
879
+ if (candidates.length === 1) return { source: candidates[0].alias, by: LayoutSourceChoice.Only };
880
+ const named = candidates.find(c => sectionNames(section, c));
881
+ return named ? { source: named.alias, by: LayoutSourceChoice.Intent } : { source: candidates[0].alias, by: LayoutSourceChoice.Order };
882
+ }
883
+
884
+ /** Least important first: what gives the accent back. */
885
+ const MEND_ROLE_ORDER: ReadonlyArray<`${LayoutRole}` | undefined> = [LayoutRole.Decoration, LayoutRole.Static, undefined, LayoutRole.Support, LayoutRole.Lead];
886
+
887
+ /**
888
+ * What the composer settles by itself before the model is asked to repair (M8 gate 2, found by the live run: the real
889
+ * model's repair missed 4.43:1 against 4.5:1 and a third accent where two are allowed): words over a busy or too-light part
890
+ * of a photo get the scrim the look allows; words too faint on their ground go back to the ink where the ink holds there;
891
+ * decoration that enters with a move fades instead; the accent leaves the least important words (decoration, then
892
+ * support, later sections first) until the look's count holds, and where the words cannot give enough back, the least
893
+ * important accent bands take the ground nearest the accent their words read on (never the first band, the main call to
894
+ * action's or a form's); and where fewer layers glide than the look asks, the most important layers that may glide take a
895
+ * depth (back) — exactly as many as are missing, or none (iox-ui#63); a gallery naming a list with no pictures shows a list
896
+ * that has them — the only one, else the one the section's words name, else the first (iox-ui#64; none, or words that name
897
+ * the list it named: the model's — #66). No
898
+ * word, place or photo changes and a button is never touched; what cannot be settled this way is the model's. Pure: a new page and the issues it settled.
899
+ */
900
+ export function mendLayout(page: LayoutPage, issues: ReadonlyArray<LayoutIssue>): { page: LayoutPage; mended: LayoutIssue[] } {
901
+ const mended: LayoutIssue[] = [];
902
+ if (!issues.some(i => i.mend)) return { page, mended };
903
+ const next = structuredClone(page) as LayoutPage;
904
+ const layerAt = (path: string): LayoutLayer | undefined => {
905
+ const m = /^sections\[(\d+)\]\.layers\[(\d+)\]$/.exec(path);
906
+ return m ? next.sections?.[Number(m[1])]?.layers?.[Number(m[2])] : undefined;
907
+ };
908
+ for (const issue of issues) {
909
+ const mend = issue.mend;
910
+ if (mend?.kind === LayoutMendKind.Scrim || mend?.kind === LayoutMendKind.Ink || mend?.kind === LayoutMendKind.Fade) {
911
+ const layer = layerAt(mend.layer);
912
+ if (!layer) continue;
913
+ if (mend.kind === LayoutMendKind.Scrim) layer.scrim = true;
914
+ else if (mend.kind === LayoutMendKind.Ink) delete layer.color;
915
+ else layer.enter = LayoutEnter.Fade;
916
+ mended.push(issue);
917
+ } else if (mend?.kind === LayoutMendKind.Accent) {
918
+ const accented = (next.sections ?? []).flatMap((s, si) => (s.layers ?? []).map(l => ({ l, si })))
919
+ .filter(({ l }) => isText(l) && l.color === LayoutColour.Accent)
920
+ .sort((a, b) => MEND_ROLE_ORDER.indexOf(a.l.role) - MEND_ROLE_ORDER.indexOf(b.l.role) || b.si - a.si);
921
+ // words first; a band (an accent ground counts twice) only for what the words cannot give back
922
+ const bands = accented.length >= mend.over ? 0 : Math.ceil((mend.over - accented.length) / ACCENT_GROUND_USES);
923
+ if (bands > (mend.bands?.length ?? 0)) continue;
924
+ for (const band of (mend.bands ?? []).slice(0, bands)) next.sections[band.section].ground = band.ground;
925
+ for (const { l } of accented.slice(0, Math.max(0, mend.over - bands * ACCENT_GROUND_USES))) delete l.color;
926
+ mended.push(issue);
927
+ } else if (mend?.kind === LayoutMendKind.Depth) {
928
+ const layers = mend.layers.map(layerAt);
929
+ if (layers.some(l => !l)) continue;
930
+ for (const l of layers) l!.depth = LayoutDepth.Back;
931
+ mended.push(issue);
932
+ } else if (mend?.kind === LayoutMendKind.Source) {
933
+ const layer = layerAt(mend.layer);
934
+ if (!layer?.gallery) continue;
935
+ layer.gallery.source = mend.source;
936
+ mended.push(issue);
937
+ }
938
+ }
939
+ return { page: mended.length ? next : page, mended };
940
+ }