@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
@@ -24,6 +24,9 @@ import { SitePlanSourceKind, ContentFieldControl, ContentFieldPlan,
24
24
  } from './site-plan.model';
25
25
  import { assertValidSitePlan, nextSourceOf, routeParams } from './validate-site-plan';
26
26
  import { NavShape, planNavShape } from './nav-shape';
27
+ import { composeLayout, LayoutColourMode } from './compose-layout';
28
+ import { LayoutGalleryList, LayoutPage, LayoutPhotoShape, LayoutPhotoSource, LayoutSite, parseLayoutPhotoId } from './layout-language';
29
+ import { layoutMotionOf, layoutPresetOf } from './layout-look';
27
30
 
28
31
  /**
29
32
  * THE composer — a Site Plan in, ordinary IOX data out (design-system plan §6b, W1). Deterministic and
@@ -108,6 +111,31 @@ export interface ComposeIssue {
108
111
  export interface ComposeContext {
109
112
  /** The calendar year the copyright line reads (`{year}`), from the caller's clock. */
110
113
  year: number;
114
+ /** M8 gate 2: where a composed page's photo lives (`own:<assetId>`, `stock:<key>`; a `box:<shape>` has none). A
115
+ * photo with no address is the empty image box (DS3), publish-blocking like a pattern's. */
116
+ photoSrc?: (photoId: string) => string;
117
+ /** A photo's description ('' = decorative). */
118
+ photoAlt?: (photoId: string) => string;
119
+ /** A photo's shape (the inventory's); a `box:<shape>` id names its own. */
120
+ photoShape?: (photoId: string) => `${LayoutPhotoShape}` | undefined;
121
+ }
122
+
123
+ /** Where a composed layout's photos are, as the server keeps them and the screens read them (M8 gate 2): id → address. */
124
+ export interface LayoutPhotoAddress {
125
+ url: string;
126
+ alt: string;
127
+ shape?: string;
128
+ }
129
+
130
+ /** The composer's context for a site whose layouts name photos: the year, and each photo's address, words and shape. */
131
+ export function composeContextOf(year: number, photos?: Readonly<Record<string, LayoutPhotoAddress>>): ComposeContext {
132
+ if (!photos) return { year };
133
+ return {
134
+ year,
135
+ photoSrc: id => photos[id]?.url ?? '',
136
+ photoAlt: id => photos[id]?.alt ?? '',
137
+ photoShape: id => photos[id]?.shape as `${LayoutPhotoShape}` | undefined,
138
+ };
111
139
  }
112
140
 
113
141
  export interface ComposedPage {
@@ -118,8 +146,9 @@ export interface ComposedPage {
118
146
  status: 'draft';
119
147
  /** The site's language (L0-2): the page's locale — the fonts it loads, the side its entrances slide from. */
120
148
  locale: `${SiteLocale}`;
121
- /** DS3: every page the wizard creates follows the look (page-bg / text / font-body). */
122
- pageSettings: { designSystem: true };
149
+ /** DS3: every page the wizard creates follows the look (page-bg / text / font-body). M8 gate 2: a composed page names
150
+ * the plan page its layout is (`layoutSource`; the build adds its run) — what Design ▸ Re-fit recomposes it from. */
151
+ pageSettings: { designSystem: true; layoutSource?: { pageKey: string; runId?: string } };
123
152
  /** M1-6c: the page's search-result words — written (a static page) or bound to the route item (a template page),
124
153
  * in the seo-core document shape the shared `resolveSeo` reads. */
125
154
  seo: SeoRawDoc;
@@ -394,13 +423,31 @@ function stampedPageValue(path: string, ctx: Ctx, nodeId: string): string {
394
423
  const isPageScope = (path: string | undefined) => !!path && path.split('.')[0] === BindScope.Page;
395
424
 
396
425
  /** The content type behind a data source alias (a relative source reads its `within` list's type). */
397
- function contentTypeOfSource(alias: string, plan: SitePlan): ContentTypePlan | undefined {
426
+ export function contentTypeOfSource(alias: string, plan: SitePlan): ContentTypePlan | undefined {
398
427
  const ds = plan.dataSources.find(d => d.alias === alias);
399
428
  if (!ds) return undefined;
400
429
  if (ds.type === PlanDataSourceType.Relative) return contentTypeOfSource(ds.within, plan);
401
430
  return plan.contentTypes.find(t => t.name === ds.contentType);
402
431
  }
403
432
 
433
+ /** Every list a composed gallery could name (the plan's query sources), in plan order: what it is called and whether its
434
+ * items carry a picture (an `image` role). */
435
+ export function layoutGalleryLists(plan: SitePlan): LayoutGalleryList[] {
436
+ return plan.dataSources
437
+ .filter(d => d.type === PlanDataSourceType.Cms && d.mode === PlanDataSourceMode.Query)
438
+ .map(d => {
439
+ const type = contentTypeOfSource(d.alias, plan);
440
+ return { alias: d.alias, words: [d.alias, type?.name, type?.label].filter((w): w is string => !!w), pictures: !!roleField(type, 'image') };
441
+ });
442
+ }
443
+
444
+ /** The list sources a composed gallery may show (`gallery.source`): the plan's query sources whose items have a picture.
445
+ * A list with none (a FAQ) would repeat no slide and draw an empty band (iox-ui#59), so it is never offered and the check
446
+ * refuses it. */
447
+ export function layoutGallerySources(plan: SitePlan): string[] {
448
+ return layoutGalleryLists(plan).filter(l => l.pictures).map(l => l.alias);
449
+ }
450
+
404
451
  function addBinding(node: SerializedNode, binding: SerializedBinding): void {
405
452
  const declared = NODE_BASELINES[node.type]?.traits ?? [];
406
453
  if (!declared.includes(binding.prop) && !binding.prop.startsWith('routeParam:')) {
@@ -526,14 +573,26 @@ function composeForm(node: SerializedNode, pn: PatternNode, id: string, ctx: Ctx
526
573
  }
527
574
  // A section may give the pattern's form another preset (`form`: Practice's contact page asks to book).
528
575
  const presetId = ctx.section?.form ?? pn.preset;
576
+ if (pn.c?.length) throw new ComposeError(`${id}: a preset Form takes its fields from the preset, not the pattern`);
577
+ stampPresetForm(node, presetId, id, ctx.owner);
578
+ }
579
+
580
+ /** A preset's name, stable form id and children on a Form node — the ONE stamping `composeSite` and `composeLayout` share. */
581
+ function stampPresetForm(node: SerializedNode, presetId: string, id: string, owner: string): void {
529
582
  const preset = formPresetById(presetId);
530
583
  if (!preset) throw new ComposeError(`${id}: no form preset "${presetId}" in forms-core`);
531
- if (pn.c?.length) throw new ComposeError(`${id}: a preset Form takes its fields from the preset, not the pattern`);
532
584
  setProp(node, 'name', preset.formName);
533
- setProp(node, 'formId', `${preset.id}-${stableHash(`${ctx.owner}/${id}`)}`);
585
+ setProp(node, 'formId', `${preset.id}-${stableHash(`${owner}/${id}`)}`);
534
586
  node.children = presetChildren(preset, id);
535
587
  }
536
588
 
589
+ /** A NEW Form stamped from a forms-core preset, exactly as a pattern's preset form is (premium M8: a layout's form layer). */
590
+ export function composePresetForm(id: string, presetId: string, owner: string): SerializedNode {
591
+ const node = create(id, FORM);
592
+ stampPresetForm(node, presetId, id, owner);
593
+ return node;
594
+ }
595
+
537
596
  /** A pattern node's children; an `each` child is stamped once per navigation page, its id carrying the
538
597
  * page key so it survives a page being left out or reordered. */
539
598
  function composeChildren(pn: PatternNode, id: string, repeater: RepeaterScope | null, ctx: Ctx): SerializedNode[] {
@@ -1161,6 +1220,69 @@ function composeItems(type: ContentTypePlan, fillEmpty: boolean): ComposedItem[]
1161
1220
  return items;
1162
1221
  }
1163
1222
 
1223
+ const FACT_TOKEN = /\{fact:([a-zA-Z]+)\}/g;
1224
+ const LAYOUT_TEXT_PROPS: ReadonlyArray<string> = ['content', 'caption', 'alt', 'label', 'ariaLabel'];
1225
+
1226
+ /**
1227
+ * M8 gate 2: a composed page — its layout stamped by `composeLayout` in the plan's look (the preset's composition
1228
+ * notes give the pace and ease), with the site's facts written in: a `{fact:<key>}` the owner gave becomes their words,
1229
+ * one they did not becomes the fact's label and a publish-blocking placeholder (never invented). A photo with no
1230
+ * address is the empty image box, a placeholder like a pattern's. The site's header and footer are the plan's globals.
1231
+ */
1232
+ function composeLayoutPage(
1233
+ page: PagePlan, layout: LayoutPage, plan: SitePlan, context: ComposeContext, design: DesignChoices, placeholders: ComposedPlaceholder[],
1234
+ readyMade: (section: PageSectionPlan, id: string) => SerializedNode,
1235
+ ): SerializedNode[] {
1236
+ const preset = layoutPresetOf(plan.design);
1237
+ const site: LayoutSite = {
1238
+ name: plan.business.name,
1239
+ locale: plan.locale ?? DEFAULT_SITE_LOCALE,
1240
+ dial: layout.dial,
1241
+ look: { preset: preset.id },
1242
+ motion: layoutMotionOf(preset.id),
1243
+ sections: layout.sections,
1244
+ };
1245
+ const boxShape = (id: string) => {
1246
+ const read = parseLayoutPhotoId(id);
1247
+ return read?.source === LayoutPhotoSource.Box ? (read.key as `${LayoutPhotoShape}`) : undefined;
1248
+ };
1249
+ const { layout: nodes } = composeLayout(site, {
1250
+ id: page.key,
1251
+ mode: design.mode === LayoutColourMode.Dark ? LayoutColourMode.Dark : LayoutColourMode.Light,
1252
+ design,
1253
+ readyMade: (s, id) => {
1254
+ const section = page.sections[s.readyMade!.at];
1255
+ if (!section) throw new ComposeError(`${page.key}: a ready-made place names plan section ${s.readyMade!.at}, which the page does not have`);
1256
+ return readyMade(section, id);
1257
+ },
1258
+ photoSrc: id => (boxShape(id) ? '' : context.photoSrc?.(id) ?? ''),
1259
+ photoAlt: id => (boxShape(id) ? '' : context.photoAlt?.(id) ?? ''),
1260
+ photoShape: id => boxShape(id) ?? context.photoShape?.(id),
1261
+ sourceFields: alias => {
1262
+ const type = contentTypeOfSource(alias, plan);
1263
+ const image = roleField(type, 'image');
1264
+ return image ? { image, ...(roleField(type, 'title') ? { title: roleField(type, 'title')! } : {}) } : null;
1265
+ },
1266
+ });
1267
+ const facts = plan.business.facts ?? {};
1268
+ walkSerialized(nodes, node => {
1269
+ for (const prop of LAYOUT_TEXT_PROPS) {
1270
+ const value = node.props[prop];
1271
+ if (typeof value !== 'string' || !value.includes('{fact:')) continue;
1272
+ const missing: FactKey[] = [];
1273
+ node.props[prop] = value.replace(FACT_TOKEN, (_, key: string) => {
1274
+ const given = (facts as Record<string, string | undefined>)[key];
1275
+ if (nonEmpty(given)) return given.trim();
1276
+ missing.push(key as FactKey);
1277
+ return SITE_FACT_LABELS[key as FactKey] ?? key;
1278
+ });
1279
+ for (const fact of missing) placeholders.push({ nodeId: node.id, owner: page.key, kind: PlaceholderKind.Fact, fact, text: String(node.props[prop]) });
1280
+ }
1281
+ if (node.type === IMAGE && !node.props['src'] && !node.bindings.length) placeholders.push({ nodeId: node.id, owner: page.key, kind: PlaceholderKind.Image, text: '' });
1282
+ });
1283
+ return nodes;
1284
+ }
1285
+
1164
1286
  /**
1165
1287
  * Compose a Site Plan. Throws `SitePlanError` (every issue) when the plan does not validate — the
1166
1288
  * composer never repairs a plan. `context` carries what the composer may not read for itself (the year).
@@ -1180,6 +1302,15 @@ export function composeSite(plan: SitePlan, context: ComposeContext): ComposedSi
1180
1302
  const rtl = isRtlLocale(locale);
1181
1303
  const pages: ComposedPage[] = plan.pages.map(page => {
1182
1304
  const nextAlias = page.routeSource ? nextSourceOf(relatives, page.routeSource) : null;
1305
+ if (page.layout) {
1306
+ return {
1307
+ key: page.key, name: page.name, route: { path: page.route }, isHome: page.isHome === true, status: STATUS_DRAFT, locale,
1308
+ pageSettings: { designSystem: true, layoutSource: { pageKey: page.key } }, seo: composePageSeo(page, plan),
1309
+ layout: composeLayoutPage(page, page.layout, plan, context, design, placeholders, (section, id) =>
1310
+ composePattern(patternById(section.pattern) as SitePattern, id, { ...base, owner: page.key, page, section, nextAlias },
1311
+ { level: section.enter ?? design.animate ?? null, rtl })),
1312
+ };
1313
+ }
1183
1314
  const layout = page.sections.map((section, i) => {
1184
1315
  const pattern = patternById(section.pattern) as SitePattern;
1185
1316
  const motion: SectionMotion = { level: section.enter ?? design.animate ?? null, rtl };
@@ -0,0 +1,78 @@
1
+ import {
2
+ normalizeParallaxPhone, parallaxOffset, parallaxRest, parallaxShift, ParallaxDepth, rangeDistance, rangeProgress, ScrollRange,
3
+ } from '@vectoriox/iox-ui/scene-core';
4
+
5
+ import { LAYOUT_DEPTH_ON_PHONE, LAYOUT_OPERATED, LayoutDepth, LayoutLayer, LayoutSection } from './layout-language';
6
+
7
+ /**
8
+ * Motion ON, judged without playing it (iox-ui#65). A layer at a depth glides against the page while it passes, so two
9
+ * layers at different depths move toward or away from each other as the page scrolls. The render check measures the page
10
+ * at rest; this replays the scroll over those boxes with the runtime's own maths (scene-core `parallaxShift` ·
11
+ * `parallaxRest` · `parallaxOffset`, the `cover` range the composer gives every depth) and says where two of them meet on
12
+ * screen. The same maths guards the depth mend (`checkLayout`), so a depth the composer adds can never cause one.
13
+ */
14
+
15
+ /** A box in the page's px, the page's top at 0. */
16
+ export interface DriftBox { l: number; t: number; r: number; b: number }
17
+
18
+ /** One layer as the scroll sees it: where it stands at rest and the depth it glides at, if any. */
19
+ export interface DriftLayer {
20
+ box: DriftBox;
21
+ depth: `${ParallaxDepth}` | null;
22
+ }
23
+
24
+ /** Where two layers meet as the page scrolls: the scroll (px from the top) where they overlap most, and by how much. */
25
+ export interface DriftMeeting {
26
+ scroll: number;
27
+ overlap: DriftBox;
28
+ area: number;
29
+ }
30
+
31
+ /** The scroll is replayed in steps this long (px). */
32
+ const STEP_PX = 4;
33
+
34
+ /** The depth a layer glides at in a section, as the composer stamps it — or null (mid, a held section, what a visitor
35
+ * operates). ONE rule: `composeLayout` stamps by it, the render check and the depth mend replay by it. */
36
+ export function layoutGlideDepth(section: Pick<LayoutSection, 'pin'>, layer: Pick<LayoutLayer, 'depth' | 'kind'>): `${ParallaxDepth}` | null {
37
+ if (section.pin || !layer.depth || layer.depth === LayoutDepth.Mid || LAYOUT_OPERATED.has(layer.kind)) return null;
38
+ return layer.depth === LayoutDepth.Front ? ParallaxDepth.Front : ParallaxDepth.Back;
39
+ }
40
+
41
+ /** How far a layer at `depth` stands off its place with the page scrolled `scroll` px, on a screen `viewHeight` tall. */
42
+ export function driftAt(layer: DriftLayer, scroll: number, viewHeight: number, phone = false): number {
43
+ if (!layer.depth) return 0;
44
+ const view = { top: 0, height: viewHeight };
45
+ const height = layer.box.b - layer.box.t;
46
+ const shift = parallaxShift(rangeDistance(ScrollRange.Cover, { top: layer.box.t, height }, view), viewHeight, { phone, onPhone: normalizeParallaxPhone(LAYOUT_DEPTH_ON_PHONE) });
47
+ if (!shift) return 0;
48
+ const rest = parallaxRest(rangeProgress(ScrollRange.Cover, { top: layer.box.t, height }, view));
49
+ const progress = rangeProgress(ScrollRange.Cover, { top: layer.box.t - scroll, height }, view);
50
+ return parallaxOffset(layer.depth as ParallaxDepth, shift, progress, rest);
51
+ }
52
+
53
+ const meet = (a: DriftBox, b: DriftBox): DriftBox => ({ l: Math.max(a.l, b.l), t: Math.max(a.t, b.t), r: Math.min(a.r, b.r), b: Math.min(a.b, b.b) });
54
+ const areaOf = (r: DriftBox) => Math.max(0, r.r - r.l) * Math.max(0, r.b - r.t);
55
+ const moved = (r: DriftBox, dy: number): DriftBox => ({ l: r.l, r: r.r, t: r.t + dy, b: r.b + dy });
56
+
57
+ /**
58
+ * Where two layers overlap most on screen while the page scrolls past them, at least one gliding — inside `clip` (their
59
+ * section, which clips a glide) — or null when they never meet more than they already do at rest. `pageHeight` bounds the
60
+ * scroll. Pure: the same answer in the browser and the server.
61
+ */
62
+ export function driftOverlap(a: DriftLayer, b: DriftLayer, view: { width: number; height: number; pageHeight: number; phone?: boolean }, clip?: DriftBox): DriftMeeting | null {
63
+ if (!a.depth && !b.depth) return null;
64
+ const rest = areaOf(clip ? meet(meet(a.box, b.box), clip) : meet(a.box, b.box));
65
+ const from = Math.max(0, Math.min(a.box.t, b.box.t) - view.height);
66
+ const to = Math.min(Math.max(0, view.pageHeight - view.height), Math.max(a.box.b, b.box.b));
67
+ let best: DriftMeeting | null = null;
68
+ for (let scroll = from; scroll <= to; scroll += STEP_PX) {
69
+ const screen: DriftBox = { l: 0, r: view.width, t: scroll, b: scroll + view.height };
70
+ const ra = moved(a.box, driftAt(a, scroll, view.height, view.phone));
71
+ const rb = moved(b.box, driftAt(b, scroll, view.height, view.phone));
72
+ let overlap = meet(meet(ra, rb), screen);
73
+ if (clip) overlap = meet(overlap, clip);
74
+ const area = areaOf(overlap);
75
+ if (area > rest && (!best || area > best.area)) best = { scroll, overlap: moved(overlap, -scroll), area };
76
+ }
77
+ return best;
78
+ }
@@ -0,0 +1,122 @@
1
+ import { jsonClosedObject, jsonListOf, jsonOneOf, JsonSchema, jsonText } from './json-schema';
2
+ import { LayoutIssue, LayoutIssueCode, LayoutPage } from './layout-language';
3
+ import { derivedBeats } from './layout-wire';
4
+
5
+ /**
6
+ * THE LAYOUT REPAIR (premium components M8 gate 2, §4.1; the prototype's `applyEdits`, `code/cl2.mjs`): a refused page
7
+ * comes back as a few path edits instead of the whole page — the paths `checkLayout` names (`sections[2].layers[1].col`).
8
+ * The strict format carries every value as JSON text (one string type, no unions); a value that is not JSON is a plain
9
+ * string. Pure: the page given is never changed.
10
+ */
11
+
12
+ export enum LayoutEditOp {
13
+ Set = 'set',
14
+ Remove = 'remove',
15
+ Insert = 'insert',
16
+ }
17
+
18
+ export interface LayoutEdit {
19
+ op: `${LayoutEditOp}`;
20
+ /** Relative to the page: `sections[2].layers[1].col`. */
21
+ path: string;
22
+ /** The new value as JSON text (`[3, 7]`, `"xl"`, `{"kind": "label", …}`); '' for a remove. */
23
+ value: string;
24
+ }
25
+
26
+ /**
27
+ * A layer's keys the strict layout format always carries and writes `"none"` when absent (`layout-wire.ts`): the model
28
+ * that wrote the page in that format repairs it in the same words, so setting one to "none", "" or null removes it — on
29
+ * the page as expanded, "none" is no value (the live run's Opus repairs set `depth: "none"` in a held section and failed).
30
+ */
31
+ const ABSENT_AS_NONE: ReadonlySet<string> = new Set(['size', 'bleed', 'depth', 'variant', 'color']);
32
+ const meansAbsent = (value: unknown): boolean => value === null || value === '' || value === 'none';
33
+
34
+ /** Keys no path may walk through. */
35
+ const UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'prototype', 'constructor']);
36
+
37
+ /** A path's steps: object keys and array indexes (`sections[2].phone` → ['sections', 2, 'phone']). */
38
+ export function layoutPathSteps(path: string): Array<string | number> {
39
+ const out: Array<string | number> = [];
40
+ for (const part of String(path ?? '').split('.')) {
41
+ for (const m of part.matchAll(/([^[\]]+)|\[(\d+)\]/g)) out.push(m[1] !== undefined ? m[1] : Number(m[2]));
42
+ }
43
+ return out;
44
+ }
45
+
46
+ function parseValue(text: string): unknown {
47
+ try {
48
+ return JSON.parse(text);
49
+ } catch {
50
+ return text;
51
+ }
52
+ }
53
+
54
+ type Container = Record<string | number, unknown> | unknown[];
55
+ const isContainer = (v: unknown): v is Container => !!v && typeof v === 'object';
56
+
57
+ /** Applies the edits in order. An edit that cannot apply is skipped and named (`edits[3]`); the rest still apply. */
58
+ export function applyLayoutEdits(page: LayoutPage, edits: ReadonlyArray<LayoutEdit>): { page: LayoutPage; issues: LayoutIssue[] } {
59
+ const out = structuredClone(page) as unknown as Record<string, unknown>;
60
+ const issues: LayoutIssue[] = [];
61
+ const refuse = (n: number, message: string): void => {
62
+ issues.push({ code: LayoutIssueCode.Shape, path: `edits[${n}]`, message });
63
+ };
64
+ (edits ?? []).forEach((e, n) => {
65
+ const steps = layoutPathSteps(e?.path);
66
+ if (!steps.length) return refuse(n, 'no path');
67
+ if (steps.some(s => typeof s === 'string' && UNSAFE_KEYS.has(s))) return refuse(n, `${e.path}: not a path of the page`);
68
+ let parent: unknown = out;
69
+ for (const [k, step] of steps.slice(0, -1).entries()) {
70
+ if (!isContainer(parent)) return refuse(n, `${e.path}: nothing at ${steps.slice(0, k).join('.')}`);
71
+ const next = (parent as Record<string | number, unknown>)[step];
72
+ if (next === undefined && typeof step === 'string' && !Array.isArray(parent)) (parent as Record<string, unknown>)[step] = {};
73
+ else if (!isContainer(next)) return refuse(n, `${e.path}: nothing at ${String(step)}`);
74
+ parent = (parent as Record<string | number, unknown>)[step];
75
+ }
76
+ const last = steps[steps.length - 1];
77
+ if (!isContainer(parent)) return refuse(n, `${e.path}: nothing to edit`);
78
+ switch (e.op) {
79
+ case LayoutEditOp.Remove:
80
+ if (Array.isArray(parent) && typeof last === 'number' && last < parent.length) parent.splice(last, 1);
81
+ else if (!Array.isArray(parent) && typeof last === 'string' && last in parent) delete (parent as Record<string, unknown>)[last];
82
+ else refuse(n, `nothing at ${e.path}`);
83
+ return;
84
+ case LayoutEditOp.Insert:
85
+ if (Array.isArray(parent) && typeof last === 'number') parent.splice(Math.min(last, parent.length), 0, parseValue(e.value));
86
+ else refuse(n, 'insert needs an array index');
87
+ return;
88
+ case LayoutEditOp.Set:
89
+ if (Array.isArray(parent) && (typeof last !== 'number' || last > parent.length)) return refuse(n, `${e.path}: an index of the list (0..${parent.length})`);
90
+ if (!Array.isArray(parent) && typeof last === 'string' && ABSENT_AS_NONE.has(last) && meansAbsent(parseValue(e.value))) {
91
+ delete (parent as Record<string, unknown>)[last];
92
+ return;
93
+ }
94
+ (parent as Record<string | number, unknown>)[last] = parseValue(e.value);
95
+ return;
96
+ default:
97
+ refuse(n, `op is ${Object.values(LayoutEditOp).join(' | ')}`);
98
+ }
99
+ });
100
+ // A layer's beat is derived, never written (the strict format has none): a repair that adds, moves, re-roles or stops an
101
+ // entrance gets its beats again (the live run's Opus repair made layer 2 the lead and kept its old beat).
102
+ for (const section of (out['sections'] as LayoutPage['sections'] | undefined) ?? []) {
103
+ if (!Array.isArray(section?.layers)) continue;
104
+ const beats = derivedBeats(section.layers);
105
+ section.layers.forEach((l, i) => {
106
+ if (!l || typeof l !== 'object') return;
107
+ if (l.enter && l.enter !== 'none') l.beat = beats[i];
108
+ else delete l.beat;
109
+ });
110
+ }
111
+ return { page: out as unknown as LayoutPage, issues };
112
+ }
113
+
114
+ /** The strict format a repair is asked in: `{ edits: [{ op, path, value }] }`, every key required. */
115
+ export function layoutRepairJsonSchema(): JsonSchema {
116
+ const edit = jsonClosedObject({
117
+ op: { ...jsonOneOf(Object.values(LayoutEditOp)), description: 'set a value, remove it, or insert into a list at the index' },
118
+ path: { ...jsonText(), description: 'the path the check named, relative to the page: sections[2].layers[1].col' },
119
+ value: { ...jsonText(), description: 'the new value as JSON text ([3, 7], "xl", {"kind": "label", …}); "" for a remove' },
120
+ }, ['op', 'path', 'value']);
121
+ return jsonClosedObject({ edits: { ...jsonListOf(edit), description: 'the fewest edits that answer every issue' } }, ['edits']);
122
+ }
@@ -0,0 +1,203 @@
1
+ import { parseCssColour, relativeLuminance } from '@vectoriox/iox-ui/design-core';
2
+
3
+ import { layoutPresetColours, splitSide } from './check-layout';
4
+ import { LayoutColour, LayoutIssue, LayoutIssueCode, LayoutLayerKind, LayoutPage, LayoutRole, LayoutSection, LayoutSectionKind, LayoutSize, LayoutTrackProp } from './layout-language';
5
+ import { PHOTO_LIGHT_LUMINANCE, PhotoTone } from './photo-inventory';
6
+ import { SPEC_SITE_LAYOUT } from './site-spec.generated';
7
+
8
+ /**
9
+ * THE CROSS-SITE FINGERPRINT (premium components M8 gate 2, M8-G2-D7; the prototype's `fingerprint` + `sameness`,
10
+ * `code/cl2.mjs`): what makes two composed pages read as the same — how the page opens, the sequence of its sections, the
11
+ * mechanism of its signature, whether it opens light or dark, and the preset it wears. Structure only: no words, no
12
+ * business data. Round three found that pages composed alone converge on one skeleton, and that telling the model what
13
+ * already exists is what broke it. Pure.
14
+ */
15
+
16
+ /** How a section reads in the page's sequence (the contract's `sequenceTokens`). */
17
+ export enum LayoutSequenceToken {
18
+ Inhale = 'inhale',
19
+ Sideways = 'sideways',
20
+ HeldWords = 'held-words',
21
+ HeldReel = 'held-reel',
22
+ Held = 'held',
23
+ PhotoGround = 'photo-ground',
24
+ Gallery = 'gallery',
25
+ Split = 'split',
26
+ Composition = 'composition',
27
+ }
28
+
29
+ /** The signature mechanisms (the contract's `signatures`); `held-screen` is the fallback, never the aim. */
30
+ export enum LayoutSignatureId {
31
+ WordsLit = 'words-lit',
32
+ PhotoUnveiled = 'photo-unveiled',
33
+ ZoomThrough = 'zoom-through',
34
+ ScrollReel = 'scroll-reel',
35
+ PicturesStacking = 'pictures-stacking',
36
+ HalvesApart = 'halves-apart',
37
+ SidewaysWalk = 'sideways-walk',
38
+ ObjectTurning = 'object-turning',
39
+ HeldScreen = 'held-screen',
40
+ }
41
+
42
+ export interface LayoutFingerprint {
43
+ /** What the lead of the first section is: `screen-word`, `photo`, `gallery`, or `<size>-<kind>` (`xl-heading`). */
44
+ opening: string;
45
+ sequence: string[];
46
+ signature: string;
47
+ ground: `${PhotoTone}`;
48
+ preset: string;
49
+ }
50
+
51
+ export interface FingerprintedPage {
52
+ name: string;
53
+ fingerprint: LayoutFingerprint;
54
+ businessType?: string;
55
+ /** A demo (the proof sites): its opening and signature are not to be repeated, its order of sections may be. */
56
+ demo?: boolean;
57
+ }
58
+
59
+ const OPENING_SCREEN_WORD = 'screen-word';
60
+
61
+ /** A section's token in the page's sequence. */
62
+ export function sequenceTokenOf(s: LayoutSection): LayoutSequenceToken {
63
+ if (s.kind === LayoutSectionKind.Inhale) return LayoutSequenceToken.Inhale;
64
+ if ((s.track ?? 1) > 1) return LayoutSequenceToken.Sideways;
65
+ const layers = s.layers ?? [];
66
+ if (s.pin) {
67
+ if (layers.some(l => l.kinetic)) return LayoutSequenceToken.HeldWords;
68
+ return layers.some(l => l.gallery?.scroll) ? LayoutSequenceToken.HeldReel : LayoutSequenceToken.Held;
69
+ }
70
+ if (String(s.ground ?? '').startsWith('photo:')) return LayoutSequenceToken.PhotoGround;
71
+ if (layers.some(l => l.kind === LayoutLayerKind.Gallery)) return LayoutSequenceToken.Gallery;
72
+ return splitSide(s) ? LayoutSequenceToken.Split : LayoutSequenceToken.Composition;
73
+ }
74
+
75
+ /** The mechanism of the signature section, by what moves in it (first match wins, as the prototype's). */
76
+ const SIGNATURE_BY_TRACK: ReadonlyArray<[LayoutTrackProp, LayoutSignatureId]> = [
77
+ [LayoutTrackProp.Clip, LayoutSignatureId.PhotoUnveiled],
78
+ [LayoutTrackProp.Rotate, LayoutSignatureId.ObjectTurning],
79
+ [LayoutTrackProp.X, LayoutSignatureId.HalvesApart],
80
+ [LayoutTrackProp.Y, LayoutSignatureId.PicturesStacking],
81
+ [LayoutTrackProp.Scale, LayoutSignatureId.ZoomThrough],
82
+ ];
83
+
84
+ export function signatureOf(s: LayoutSection | undefined): LayoutSignatureId {
85
+ if (!s) return LayoutSignatureId.HeldScreen;
86
+ const layers = s.layers ?? [];
87
+ if (layers.some(l => l.kinetic)) return LayoutSignatureId.WordsLit;
88
+ if (layers.some(l => l.gallery?.scroll)) return LayoutSignatureId.ScrollReel;
89
+ if ((s.track ?? 1) > 1) return LayoutSignatureId.SidewaysWalk;
90
+ const props = new Set(layers.flatMap(l => (l.motion ?? []).map(m => m.prop)));
91
+ return SIGNATURE_BY_TRACK.find(([prop]) => props.has(prop))?.[1] ?? LayoutSignatureId.HeldScreen;
92
+ }
93
+
94
+ /** A place given to the plan's ready-made section (silent section fallback): its token in the sequence and the opening. */
95
+ export const LAYOUT_READY_MADE_TOKEN = 'ready-made';
96
+ const READY_MADE_OPENING = `${LAYOUT_READY_MADE_TOKEN}:`;
97
+
98
+ function openingOf(s: LayoutSection | undefined): string {
99
+ if (s?.readyMade) return `${READY_MADE_OPENING}${s.readyMade.pattern}`;
100
+ const layers = s?.layers ?? [];
101
+ const lead = layers.find(l => l.role === LayoutRole.Lead) ?? layers[0];
102
+ if (!lead) return 'none';
103
+ if (lead.size === LayoutSize.Screen) return OPENING_SCREEN_WORD;
104
+ if (lead.kind === LayoutLayerKind.Photo || lead.kind === LayoutLayerKind.Gallery) return lead.kind;
105
+ return lead.size ? `${lead.size}-${lead.kind}` : lead.kind;
106
+ }
107
+
108
+ /** A page's fingerprint, worn in `preset` and `mode`. A photo ground opens on the page's own ground colour. */
109
+ export function fingerprintOf(page: LayoutPage, preset: string, mode: 'light' | 'dark'): LayoutFingerprint {
110
+ const sections = page.sections ?? [];
111
+ const first = sections[0];
112
+ const ground = String(first?.ground ?? LayoutColour.Ground);
113
+ const name = (Object.values(LayoutColour) as string[]).includes(ground) ? (ground as LayoutColour) : LayoutColour.Ground;
114
+ const colour = parseCssColour(layoutPresetColours(preset, mode)?.[name]);
115
+ const light = colour ? relativeLuminance(colour) > PHOTO_LIGHT_LUMINANCE : mode === 'light';
116
+ return {
117
+ opening: openingOf(first),
118
+ sequence: sections.map(s => (s.readyMade ? LAYOUT_READY_MADE_TOKEN : sequenceTokenOf(s))),
119
+ signature: signatureOf(sections.find(s => s.signature)),
120
+ ground: light ? PhotoTone.Light : PhotoTone.Dark,
121
+ preset,
122
+ };
123
+ }
124
+
125
+ /** The longest common subsequence of two sequences. */
126
+ function lcs(a: ReadonlyArray<string>, b: ReadonlyArray<string>): number {
127
+ const d = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
128
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) d[i][j] = a[i - 1] === b[j - 1] ? d[i - 1][j - 1] + 1 : Math.max(d[i - 1][j], d[i][j - 1]);
129
+ return d[a.length][b.length];
130
+ }
131
+
132
+ /** The share of the longer sequence two pages have in common. */
133
+ export function sequenceShare(a: ReadonlyArray<string>, b: ReadonlyArray<string>): number {
134
+ return lcs(a, b) / Math.max(1, a.length, b.length);
135
+ }
136
+
137
+ const openingWords = (opening: string) =>
138
+ opening.startsWith(READY_MADE_OPENING) ? `the ready-made ${opening.slice(READY_MADE_OPENING.length)}` : opening === OPENING_SCREEN_WORD ? 'a screen-size word' : opening === 'photo' || opening === 'gallery' ? `a ${opening}` : `a ${opening.replace('-', ' ')}`;
139
+ const signatureWords = (id: string) => SPEC_SITE_LAYOUT.signatures.find(s => s.id === id)?.label ?? id;
140
+
141
+ /**
142
+ * Refuses a page that repeats one already made (M8-G2-D7): most of the same sequence (`SPEC_SITE_LAYOUT.sameness.sequence`,
143
+ * 6 of 7), or the same opening AND signature; against a page of the same business type, the same opening or the same
144
+ * signature alone. The sequence is compared with real pages only — this studio's, other studios', this site's — never a
145
+ * demo's (Doron, 2026-11-09: the proof sites' order is the product's grammar, not someone's site). The look is the
146
+ * owner's pick and is never a reason.
147
+ */
148
+ export function samenessIssues(me: LayoutFingerprint, others: ReadonlyArray<FingerprintedPage>, businessType?: string): LayoutIssue[] {
149
+ const issues: LayoutIssue[] = [];
150
+ const add = (path: string, message: string): void => {
151
+ issues.push({ code: LayoutIssueCode.Sameness, path, message });
152
+ };
153
+ for (const o of others) {
154
+ const them = o.fingerprint;
155
+ const sameType = !!businessType && o.businessType === businessType;
156
+ const opening = me.opening === them.opening;
157
+ const signature = me.signature === them.signature;
158
+ if (opening && (signature || sameType)) add('sections[0]', `"${o.name}" already opens on ${openingWords(them.opening)}${sameType ? ', and it is the same kind of business' : ` with ${signatureWords(them.signature)}`} — open another way`);
159
+ if (signature && (opening || sameType)) add('sections', `"${o.name}"'s signature is already ${signatureWords(them.signature)} — find another mechanism`);
160
+ if (!o.demo && sequenceShare(me.sequence, them.sequence) >= SPEC_SITE_LAYOUT.sameness.sequence) {
161
+ add('sections', `your sequence (${me.sequence.join(' → ')}) repeats "${o.name}"'s (${them.sequence.join(' → ')}) — change the order and the kinds of sections`);
162
+ }
163
+ }
164
+ return issues;
165
+ }
166
+
167
+ /** The three proof sites' fingerprints (premium M8): every new page's opening and signature are compared with them, never
168
+ * its order of sections (`demo`). layout-fingerprint.spec holds them equal to `fingerprintOf` of the proof layouts. */
169
+ export const PROOF_FINGERPRINTS: ReadonlyArray<FingerprintedPage> = [
170
+ {
171
+ name: 'bar-daring',
172
+ demo: true,
173
+ fingerprint: {
174
+ opening: OPENING_SCREEN_WORD,
175
+ sequence: [LayoutSequenceToken.Composition, LayoutSequenceToken.Gallery, LayoutSequenceToken.Inhale, LayoutSequenceToken.HeldWords, LayoutSequenceToken.Sideways, LayoutSequenceToken.Gallery, LayoutSequenceToken.Composition],
176
+ signature: LayoutSignatureId.WordsLit,
177
+ ground: PhotoTone.Dark,
178
+ preset: 'after-dark',
179
+ },
180
+ },
181
+ {
182
+ name: 'makers-daring',
183
+ demo: true,
184
+ fingerprint: {
185
+ opening: OPENING_SCREEN_WORD,
186
+ sequence: [LayoutSequenceToken.Composition, LayoutSequenceToken.Sideways, LayoutSequenceToken.Gallery, LayoutSequenceToken.Gallery, LayoutSequenceToken.Inhale, LayoutSequenceToken.HeldWords, LayoutSequenceToken.PhotoGround],
187
+ signature: LayoutSignatureId.WordsLit,
188
+ ground: PhotoTone.Light,
189
+ preset: 'warm-editorial',
190
+ },
191
+ },
192
+ {
193
+ name: 'cafe-he-daring',
194
+ demo: true,
195
+ fingerprint: {
196
+ opening: 'xxl-heading',
197
+ sequence: [LayoutSequenceToken.Composition, LayoutSequenceToken.Composition, LayoutSequenceToken.Inhale, LayoutSequenceToken.Held, LayoutSequenceToken.HeldReel, LayoutSequenceToken.Gallery, LayoutSequenceToken.Composition],
198
+ signature: LayoutSignatureId.PhotoUnveiled,
199
+ ground: PhotoTone.Light,
200
+ preset: 'warm-editorial',
201
+ },
202
+ },
203
+ ];