@vectoriox/iox-ui 5.89.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 (45) hide show
  1. package/design-core/index.d.ts +523 -2
  2. package/fesm2022/vectoriox-iox-ui-design-core.mjs +581 -1
  3. package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
  4. package/fesm2022/vectoriox-iox-ui-generation-core.mjs +8403 -4898
  5. package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
  6. package/fesm2022/vectoriox-iox-ui-harness-core.mjs +12 -1
  7. package/fesm2022/vectoriox-iox-ui-harness-core.mjs.map +1 -1
  8. package/fesm2022/vectoriox-iox-ui-scene-core.mjs +33 -6
  9. package/fesm2022/vectoriox-iox-ui-scene-core.mjs.map +1 -1
  10. package/fesm2022/vectoriox-iox-ui.mjs +3 -2
  11. package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
  12. package/generation-core/index.d.ts +1735 -507
  13. package/harness-core/index.d.ts +52 -3
  14. package/package.json +1 -1
  15. package/scene-core/index.d.ts +19 -2
  16. package/src/design-core/flavor-spec.generated.ts +500 -0
  17. package/src/design-core/font-metrics.ts +105 -0
  18. package/src/design-core/public-api.ts +1 -0
  19. package/src/generation-core/ai-run.ts +11 -0
  20. package/src/generation-core/audit-site.ts +5 -0
  21. package/src/generation-core/check-layout.ts +940 -0
  22. package/src/generation-core/compose-layout.ts +120 -34
  23. package/src/generation-core/compose-site.ts +122 -3
  24. package/src/generation-core/layout-drift.ts +78 -0
  25. package/src/generation-core/layout-edits.ts +122 -0
  26. package/src/generation-core/layout-fingerprint.ts +203 -0
  27. package/src/generation-core/layout-language.ts +195 -12
  28. package/src/generation-core/layout-look.ts +57 -0
  29. package/src/generation-core/layout-photos.ts +19 -0
  30. package/src/generation-core/layout-render-check.ts +275 -0
  31. package/src/generation-core/layout-section-fallback.ts +156 -0
  32. package/src/generation-core/layout-type.ts +48 -0
  33. package/src/generation-core/layout-wire.ts +282 -0
  34. package/src/generation-core/nav-shape.ts +23 -1
  35. package/src/generation-core/photo-inventory.ts +250 -0
  36. package/src/generation-core/plan-edits.ts +25 -2
  37. package/src/generation-core/plan-wire.ts +19 -2
  38. package/src/generation-core/public-api.ts +11 -0
  39. package/src/generation-core/site-plan.model.ts +16 -0
  40. package/src/generation-core/site-spec.generated.ts +759 -2
  41. package/src/generation-core/validate-site-plan.ts +55 -1
  42. package/src/harness-core/generation-view.ts +52 -1
  43. package/src/scene-core/scroll-driver.ts +14 -2
  44. package/src/scene-core/scroll-range.ts +23 -3
  45. package/styles/iox-forms.css +4 -0
@@ -0,0 +1,282 @@
1
+ import { JsonSchema, jsonClosedObject, jsonInteger, jsonListOf, jsonOneOf, jsonText } from './json-schema';
2
+ import {
3
+ LAYOUT_BEAT_DELAY, LayoutDial, LayoutForm, LayoutGallery, LayoutIssue, LayoutIssueCode, LayoutLayer, LayoutPage, LayoutSection, LayoutTrack,
4
+ } from './layout-language';
5
+ import { isPlainObject, PlainObject } from './shape-check';
6
+ import { SPEC_SITE_LAYOUT } from './site-spec.generated';
7
+
8
+ /**
9
+ * The LAYOUT WIRE (premium M8 gate 2, M8-G2-D2): the strict format a model writes ONE composed page in. Every key is
10
+ * required — "none" is `''`, `0`, `[]` or `'none'` — so the request stays at 37 properties, no optional key and no
11
+ * union (`strictSchemaComplexity`, held by iox-cms strict-schemas.spec). `expandLayoutWire` turns it into the layout
12
+ * language (`LayoutSection[]`, what `checkLayout` judges and `composeLayout` stamps); `layoutToWire` writes a layout back
13
+ * (the three proof sites, a repair's starting point). What the wire leaves out is derived, never asked: a layer's beat
14
+ * (the order it is written), the look, the pace and ease, the nav, the site's name and language.
15
+ */
16
+
17
+ const V = SPEC_SITE_LAYOUT.vocab;
18
+ const GALLERY_EFFECTS: ReadonlyArray<string> = V.galleryEffects;
19
+ const FORM_PRESETS: ReadonlyArray<string> = V.formPresets;
20
+ const BUTTON_VARIANTS: ReadonlyArray<string> = V.buttonVariants;
21
+ const NONE = 'none';
22
+ const CLIP = 'clipReveal';
23
+ const CLIP_SIDE = `${CLIP}-`;
24
+ /** A gallery the wire marks `autoplay` turns every 5 s — what the proof sites' autoplaying galleries do. */
25
+ export const LAYOUT_WIRE_AUTOPLAY_MS = 5000;
26
+ const CHIP_SLOTS: ReadonlyArray<string> = Array.from(new Set(Object.values(V.formChips as Record<string, ReadonlyArray<string>>).flat()));
27
+ const SLOT_NAMES: ReadonlyArray<string> = [...V.formSlots, ...CHIP_SLOTS];
28
+ const ENTER_ON_WIRE: ReadonlyArray<string> = V.enters.flatMap((e: string) => (e === CLIP ? V.sides.map((s: string) => `${CLIP_SIDE}${s}`) : [e]));
29
+ const VARIANT_ON_WIRE: ReadonlyArray<string> = [NONE, ...V.buttonVariants, ...V.galleryEffects, ...V.formPresets];
30
+
31
+ export interface LayoutWireSlot { slot: string; text: string }
32
+ export interface LayoutWireTrack { prop: string; ease: string; values: number[] }
33
+ export interface LayoutWireLayer {
34
+ kind: string; role: string; text: string; items: string[]; photos: string[]; source: string; box: number[];
35
+ size: string; color: string; align: string; z: number; bleed: string; rotate: number; to: string; variant: string;
36
+ enter: string; depth: string; inner: number; flags: string[]; perView: number; slots: LayoutWireSlot[]; motion: LayoutWireTrack[];
37
+ }
38
+ export interface LayoutWireSection {
39
+ id: string; kind: string; screens: number; hold: number; ground: string; rows: number; transition: string; phone: number[];
40
+ layers: LayoutWireLayer[];
41
+ }
42
+ export interface LayoutWire { sections: LayoutWireSection[] }
43
+
44
+ const text = (d: string) => ({ ...jsonText(), description: d });
45
+ const integer = (d: string) => ({ ...jsonInteger(), description: d });
46
+ const oneOf = (values: ReadonlyArray<string>, d: string) => ({ ...jsonOneOf(values), description: d });
47
+ const listOf = (items: JsonSchema, d: string) => ({ ...jsonListOf(items), description: d });
48
+ const closed = (properties: Record<string, JsonSchema>, d?: string) => jsonClosedObject(properties, Object.keys(properties), d);
49
+
50
+ /** The strict format for one composed page. */
51
+ export function layoutWireJsonSchema(): JsonSchema {
52
+ const layer = closed({
53
+ kind: oneOf(V.kinds, 'what the layer is'),
54
+ role: oneOf(V.roles, 'lead: the ONE thing the eye finds first in its section · support: follows it · decoration: only fades · static: never moves'),
55
+ text: text("the words (word, heading, text, label, number, button); '' for none; a fact you were not given is {fact:<key>}"),
56
+ items: listOf(jsonText(), 'list items · marquee phrases · one caption per gallery photo; [] for none'),
57
+ photos: listOf(jsonText(), 'photo: one photo id · gallery: its slides, in order; ids from the photos you are given; [] for none'),
58
+ source: text("gallery: the alias of a list data source whose items it shows instead of photos; '' for none"),
59
+ box: listOf(jsonInteger(), '[colStart, colEnd, rowStart, rowEnd]: grid lines 1..13 (1..12×hold+1 sideways) and 1..rows+1'),
60
+ size: oneOf([NONE, ...V.sizes], "type size; 'screen' = as wide as its columns, a word, never a sentence"),
61
+ color: oneOf(V.colours, "the look's colour by name"),
62
+ align: oneOf(V.aligns, 'text alignment'),
63
+ z: integer('0..9 stacking'),
64
+ bleed: oneOf(V.bleeds, 'runs off the screen at that edge'),
65
+ rotate: integer("degrees, within the look's limit"),
66
+ to: text("button: a section id of this page or a page route ('/contact'); '' for none"),
67
+ variant: oneOf(VARIANT_ON_WIRE, 'button: primary | secondary | ghost · gallery: its effect · form: its preset · none'),
68
+ enter: oneOf(ENTER_ON_WIRE, 'plays once as it arrives (time); clipReveal opens from that side'),
69
+ depth: oneOf([NONE, ...V.depths], 'the parallax trio (not in held sections)'),
70
+ inner: integer('0..3: how far a photo drifts inside its frame'),
71
+ flags: listOf(jsonOneOf(V.flags), 'switches: scrim (a shadow under words on a photo) · kinetic (lit word by word, held only) · contain · gallery: centered, freeMode, loop, drift, scroll (held only: the scroll turns it), autoplay; [] for none'),
72
+ perView: { type: 'number', description: 'gallery slides per view; 0 for none' },
73
+ slots: listOf(closed({ slot: oneOf(SLOT_NAMES, 'which words'), text: text('the words, in the business\'s language') }), "form: its title, intro, submit, successTitle, successText, channel, and one entry per chip (needs · budget · guests); [] for none"),
74
+ motion: listOf(closed({
75
+ prop: oneOf(V.trackProps, 'what moves'),
76
+ ease: oneOf(V.eases, 'how'),
77
+ values: listOf({ type: 'number' }, '[from, to, at0, at1]: values and the part of the hold it plays over (0..1)'),
78
+ }), 'held sections only: tracks the scroll plays; [] for none'),
79
+ });
80
+ const section = closed({
81
+ id: text('a short slug, unique on the page'),
82
+ kind: oneOf(V.sectionKinds, 'content · inhale (a breath: ≤ 2 small layers, no photo) · signature (exactly ONE)'),
83
+ screens: integer('1..5 screen heights'),
84
+ hold: integer('0 flows · 1 held (the page stops while its layers move) · 2..4 held and carried sideways that many screens'),
85
+ ground: text("a colour name, or photo:<id>"),
86
+ rows: integer('4..16 grid rows'),
87
+ transition: oneOf(V.transitions, 'how it arrives over the section before'),
88
+ phone: listOf(jsonInteger(), "every layer's index exactly once, in a phone's reading order"),
89
+ layers: listOf(layer, 'the layers'),
90
+ });
91
+ return closed({ sections: listOf(section, '4..8 sections') }, 'one composed page in the layout language');
92
+ }
93
+
94
+ const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v.trim() !== '';
95
+ const num = (v: unknown, fallback = 0): number => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
96
+ const strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []);
97
+
98
+ function expandForm(l: PlainObject, preset: string): LayoutForm {
99
+ const form: LayoutForm = { preset: preset as LayoutForm['preset'] };
100
+ const options: Record<string, string[]> = {};
101
+ for (const s of Array.isArray(l['slots']) ? l['slots'] : []) {
102
+ if (!isPlainObject(s) || !nonEmpty(s['text'])) continue;
103
+ const slot = String(s['slot']);
104
+ const words = String(s['text']).trim();
105
+ if (CHIP_SLOTS.includes(slot)) (options[slot] ??= []).push(words);
106
+ else if (slot === 'channel') form.channel = { label: words };
107
+ else if (slot === 'title' || slot === 'intro' || slot === 'submit' || slot === 'successTitle' || slot === 'successText') form[slot] = words;
108
+ }
109
+ if (Object.keys(options).length) form.options = options as LayoutForm['options'];
110
+ return form;
111
+ }
112
+
113
+ function expandGallery(l: PlainObject, flags: ReadonlySet<string>, variant: string): LayoutGallery {
114
+ const captions = strings(l['items']);
115
+ const gallery: LayoutGallery = {
116
+ slides: strings(l['photos']).map((id, i) => ({ photo: { id }, ...(nonEmpty(captions[i]) ? { caption: captions[i] } : {}) })),
117
+ };
118
+ if (GALLERY_EFFECTS.includes(variant)) gallery.effect = variant as LayoutGallery['effect'];
119
+ const perView = num(l['perView']);
120
+ if (perView > 0) gallery.perView = perView;
121
+ for (const f of ['centered', 'freeMode', 'loop', 'drift', 'scroll'] as const) if (flags.has(f)) gallery[f] = true;
122
+ if (flags.has('autoplay')) gallery.autoplay = LAYOUT_WIRE_AUTOPLAY_MS;
123
+ if (nonEmpty(l['source'])) gallery.source = String(l['source']).trim();
124
+ return gallery;
125
+ }
126
+
127
+ function expandTrack(t: PlainObject): LayoutTrack {
128
+ const v = Array.isArray(t['values']) ? (t['values'] as unknown[]).map(x => num(x)) : [];
129
+ return { prop: String(t['prop']) as LayoutTrack['prop'], from: v[0] ?? 0, to: v[1] ?? 0, at: [v[2] ?? 0, v[3] ?? 1], ease: String(t['ease']) as LayoutTrack['ease'] };
130
+ }
131
+
132
+ function expandLayer(l: PlainObject, beat: number): LayoutLayer {
133
+ const kind = String(l['kind']);
134
+ const box = Array.isArray(l['box']) ? (l['box'] as unknown[]).map(x => num(x)) : [];
135
+ const flags = new Set(strings(l['flags']));
136
+ const variant = String(l['variant'] ?? NONE);
137
+ const out: LayoutLayer = {
138
+ kind: kind as LayoutLayer['kind'],
139
+ role: String(l['role']) as LayoutLayer['role'],
140
+ col: [box[0] ?? 1, box[1] ?? 2],
141
+ row: [box[2] ?? 1, box[3] ?? 2],
142
+ };
143
+ if (nonEmpty(l['text'])) out.text = String(l['text']);
144
+ const items = strings(l['items']);
145
+ if (items.length && kind !== 'gallery') out.items = items;
146
+ if (kind === 'photo' && strings(l['photos'])[0]) out.photo = { id: strings(l['photos'])[0] };
147
+ if (kind === 'gallery') out.gallery = expandGallery(l, flags, variant);
148
+ if (kind === 'form') out.form = expandForm(l, FORM_PRESETS.includes(variant) ? variant : 'contact');
149
+ if (kind === 'button' && BUTTON_VARIANTS.includes(variant)) out.variant = variant as LayoutLayer['variant'];
150
+ if (nonEmpty(l['size']) && l['size'] !== NONE) out.size = String(l['size']) as LayoutLayer['size'];
151
+ if (nonEmpty(l['color'])) out.color = String(l['color']) as LayoutLayer['color'];
152
+ if (nonEmpty(l['align'])) out.align = String(l['align']) as LayoutLayer['align'];
153
+ if (num(l['z'])) out.z = num(l['z']);
154
+ if (nonEmpty(l['bleed']) && l['bleed'] !== NONE) out.bleed = String(l['bleed']) as LayoutLayer['bleed'];
155
+ if (num(l['rotate'])) out.rotate = num(l['rotate']);
156
+ if (nonEmpty(l['to'])) out.to = String(l['to']).trim();
157
+ if (flags.has('scrim')) out.scrim = true;
158
+ if (flags.has('kinetic')) out.kinetic = true;
159
+ if (flags.has('contain')) out.fit = 'contain';
160
+ const enter = String(l['enter'] ?? NONE);
161
+ if (enter.startsWith(CLIP_SIDE)) {
162
+ out.enter = CLIP;
163
+ out.from = enter.slice(CLIP_SIDE.length) as LayoutLayer['from'];
164
+ } else if (enter !== NONE) out.enter = enter as LayoutLayer['enter'];
165
+ if (out.enter) out.beat = beat;
166
+ if (nonEmpty(l['depth']) && l['depth'] !== NONE) out.depth = String(l['depth']) as LayoutLayer['depth'];
167
+ if (num(l['inner'])) out.inner = num(l['inner']);
168
+ const motion = (Array.isArray(l['motion']) ? l['motion'] : []).filter(isPlainObject).map(expandTrack);
169
+ if (motion.length) out.motion = motion;
170
+ return out;
171
+ }
172
+
173
+ /**
174
+ * A section's beats, never asked: the lead enters first; every other entering layer takes the next beat in the order it
175
+ * was written, held at the stagger's last (Emil's shrinking stagger reads the beat and stops shrinking at the sixth; the
176
+ * prototype wrote it on fewer than half the layers). ONE rule
177
+ * for the wire's expansion and for a page a repair edited (`applyLayoutEdits`).
178
+ */
179
+ export function derivedBeats(layers: ReadonlyArray<{ role?: unknown; enter?: unknown }>): number[] {
180
+ const last = LAYOUT_BEAT_DELAY.length - 1;
181
+ let beat = 0;
182
+ return layers.map(l => (l.role === 'lead' ? 0 : String(l.enter ?? NONE) !== NONE ? Math.min(++beat, last) : 0));
183
+ }
184
+
185
+ function expandSection(s: PlainObject): LayoutSection {
186
+ const kind = String(s['kind']);
187
+ const hold = Math.max(0, Math.round(num(s['hold'])));
188
+ const wired = (Array.isArray(s['layers']) ? s['layers'] : []).filter(isPlainObject);
189
+ const beats = derivedBeats(wired);
190
+ const layers = wired.map((l, i) => expandLayer(l, beats[i]));
191
+ const out: LayoutSection = {
192
+ id: String(s['id'] ?? ''),
193
+ screens: num(s['screens'], 1),
194
+ rows: num(s['rows'], 8),
195
+ ground: String(s['ground'] ?? 'ground'),
196
+ transition: String(s['transition'] ?? 'cut') as LayoutSection['transition'],
197
+ layers,
198
+ phone: Array.isArray(s['phone']) ? (s['phone'] as unknown[]).map(x => num(x, -1)) : [],
199
+ };
200
+ if (kind === 'inhale') out.kind = 'inhale';
201
+ if (kind === 'signature') out.signature = true;
202
+ if (hold >= 1) out.pin = true;
203
+ if (hold >= 2) out.track = hold;
204
+ return out;
205
+ }
206
+
207
+ /**
208
+ * The wire → a layout page. Refuses (issues with a path) only what it cannot read at all — a missing `sections`, a
209
+ * section or layer that is not an object; everything a model can get wrong in a well-formed answer is `checkLayout`'s.
210
+ */
211
+ export function expandLayoutWire(wire: unknown, dial: `${LayoutDial}`): { page: LayoutPage | null; issues: LayoutIssue[] } {
212
+ const issues: LayoutIssue[] = [];
213
+ const add = (path: string, message: string) => issues.push({ code: LayoutIssueCode.Shape, path, message });
214
+ if (!isPlainObject(wire) || !Array.isArray(wire['sections'])) {
215
+ add('sections', 'the answer has no sections');
216
+ return { page: null, issues };
217
+ }
218
+ (wire['sections'] as unknown[]).forEach((s, i) => {
219
+ if (!isPlainObject(s)) add(`sections[${i}]`, 'not an object');
220
+ else if (!Array.isArray(s['layers'])) add(`sections[${i}].layers`, 'no layers');
221
+ else (s['layers'] as unknown[]).forEach((l, j) => { if (!isPlainObject(l)) add(`sections[${i}].layers[${j}]`, 'not an object'); });
222
+ });
223
+ if (issues.length) return { page: null, issues };
224
+ return { page: { dial, sections: (wire['sections'] as PlainObject[]).map(expandSection) }, issues: [] };
225
+ }
226
+
227
+ function layerToWire(l: LayoutLayer): LayoutWireLayer {
228
+ const g = l.gallery;
229
+ const f = l.form;
230
+ const flags = [
231
+ l.scrim && 'scrim', l.kinetic && 'kinetic', l.fit === 'contain' && 'contain',
232
+ g?.centered && 'centered', g?.freeMode && 'freeMode', g?.loop && 'loop', g?.drift && 'drift', g?.scroll && 'scroll', g?.autoplay ? 'autoplay' : null,
233
+ ].filter((x): x is string => !!x);
234
+ const slots: LayoutWireSlot[] = f
235
+ ? [
236
+ ...(['title', 'intro', 'submit', 'successTitle', 'successText'] as const).filter(k => nonEmpty(f[k])).map(k => ({ slot: k, text: String(f[k]) })),
237
+ ...(f.channel?.label ? [{ slot: 'channel', text: f.channel.label }] : []),
238
+ ...Object.entries(f.options ?? {}).flatMap(([slot, words]) => (words ?? []).map(t => ({ slot, text: t }))),
239
+ ]
240
+ : [];
241
+ return {
242
+ kind: l.kind,
243
+ role: l.role ?? 'support',
244
+ text: l.text ?? '',
245
+ items: g ? g.slides.map(s => s.caption ?? '') : l.items ?? [],
246
+ photos: g ? g.slides.map(s => s.photo?.id ?? '') : l.photo ? [l.photo.id] : [],
247
+ source: g?.source ?? '',
248
+ box: [...(l.col ?? [1, 2]), ...(l.row ?? [1, 2])],
249
+ size: l.size ?? NONE,
250
+ color: l.color ?? 'ink',
251
+ align: l.align ?? 'start',
252
+ z: l.z ?? 0,
253
+ bleed: l.bleed ?? NONE,
254
+ rotate: l.rotate ?? 0,
255
+ to: l.to ?? '',
256
+ variant: l.variant ?? g?.effect ?? f?.preset ?? NONE,
257
+ enter: l.enter === CLIP ? `${CLIP_SIDE}${l.from ?? 'bottom'}` : l.enter ?? NONE,
258
+ depth: l.depth ?? NONE,
259
+ inner: l.inner ?? 0,
260
+ flags,
261
+ perView: typeof g?.perView === 'number' ? g.perView : 0,
262
+ slots,
263
+ motion: (l.motion ?? []).map(t => ({ prop: t.prop, ease: t.ease ?? 'out', values: [t.from, t.to, ...(t.at ?? [0, 1])] })),
264
+ };
265
+ }
266
+
267
+ /** A layout page (or a saved CL2.1 site's sections) → the wire. */
268
+ export function layoutToWire(page: Pick<LayoutPage, 'sections'>): LayoutWire {
269
+ return {
270
+ sections: page.sections.map(s => ({
271
+ id: s.id,
272
+ kind: s.signature ? 'signature' : s.kind ?? 'content',
273
+ screens: s.screens,
274
+ hold: s.pin ? s.track ?? 1 : 0,
275
+ ground: s.ground ?? 'ground',
276
+ rows: s.rows,
277
+ transition: s.transition ?? 'cut',
278
+ phone: s.phone ?? [],
279
+ layers: s.layers.map(layerToWire),
280
+ })),
281
+ };
282
+ }
@@ -322,7 +322,9 @@ function labelText(kit: Kit, suffix: string, words: string): SerializedNode {
322
322
  /** The menu button and the drawer's Close are ONE size — and the shared CSS pads the drawer like the header
323
323
  * (`.iox-role-nav-drawer` re-declares dialog-pad as nav-pad) — so the Close lands where the menu button is and
324
324
  * reads as the same button turned into an X. */
325
- const MENU_BUTTON_LAY = { width: '48px', height: '48px', alignItems: 'center', justifyContent: 'center' };
325
+ // The menu button and the drawer's Close keep their row's TOP line and their 48px: a business name that wraps to two
326
+ // lines makes the row taller, and two centred buttons in rows of different heights part (iox-ui#60).
327
+ const MENU_BUTTON_LAY = { width: '48px', height: '48px', alignItems: 'center', justifyContent: 'center', alignSelf: 'flex-start', flexShrink: '0' };
326
328
 
327
329
  function menuButton(kit: Kit, drawerId: string, at: string): SerializedNode {
328
330
  const btn = part(kit, 'menu', BUTTON, { tag: 'button', ariaLabel: NAV_SHAPE_COPY.menu }, 'button-ghost', NavRole.MenuButton, { ...MENU_BUTTON_LAY });
@@ -456,6 +458,25 @@ function centerBrandAt(root: SerializedNode, at: string, on: boolean): void {
456
458
  if (on) root.responsive = { ...(root.responsive ?? {}), [at]: { ...(root.responsive?.[at] ?? {}), styleProps: { ...(root.responsive?.[at]?.styleProps ?? {}), [JUSTIFY]: CENTER } } };
457
459
  }
458
460
 
461
+ const WRAP = 'flexWrap';
462
+ const MIN_WIDTH = 'minWidth';
463
+
464
+ /** iox-ui#60: at the phone width the header is ONE row — the brand and the menu button. The pattern's bar wraps (its
465
+ * links fall under the brand on a narrow laptop), which on a phone put the menu button UNDER a long name; there the
466
+ * row holds and the name wraps inside the brand instead. Owned in the phone layer only, like `centerBrandAt`. */
467
+ function phoneRowAt(root: SerializedNode, at: string, on: boolean): void {
468
+ const brand = find([root], NavRole.Brand);
469
+ for (const [node, key, value] of [[root, WRAP, 'nowrap'], [brand, MIN_WIDTH, '0px']] as const) {
470
+ if (!node) continue;
471
+ for (const [bp, layer] of Object.entries(node.responsive ?? {})) {
472
+ if (layer?.styleProps?.[key] !== value) continue;
473
+ const { [key]: _drop, ...rest } = layer.styleProps;
474
+ node.responsive![bp] = { ...layer, styleProps: rest };
475
+ }
476
+ if (on) node.responsive = { ...(node.responsive ?? {}), [at]: { ...(node.responsive?.[at] ?? {}), styleProps: { ...(node.responsive?.[at]?.styleProps ?? {}), [key]: value } } };
477
+ }
478
+ }
479
+
459
480
  function clampBarCount(n: number | undefined, shape: NavShape): number {
460
481
  const v = Number.isFinite(n) ? Math.round(n as number) : defaultBarCount(shape);
461
482
  return Math.min(BAR_ITEMS_MAX, Math.max(BAR_ITEMS_MIN, v));
@@ -496,6 +517,7 @@ export function planNavShape(globals: ReadonlyArray<SerializedNode>, shape: NavS
496
517
 
497
518
  for (const p of phoneHiddenParts(root)) { moveDisplayOverride(p, at); hideAt(p, at); }
498
519
  centerBrandAt(root, at, wantBar);
520
+ phoneRowAt(root, at, wantMenuButton);
499
521
 
500
522
  const kids = root.children ?? (root.children = []);
501
523
  if (menu) { moveDisplayOverride(menu, at); kids.push(menu); }
@@ -0,0 +1,250 @@
1
+ import { relativeLuminance, toHexColor } from '@vectoriox/iox-ui/design-core';
2
+
3
+ import { LayoutPhotoShape } from './layout-language';
4
+
5
+ /**
6
+ * THE PHOTO INVENTORY (premium components M8 gate 2, §5; the prototype's `code/inventory.cjs`, made pure): what a layout
7
+ * may know about a photo without seeing it — its shape, five main colours, and a 12×12 grid of how light and how busy each
8
+ * part is. iox-cms decodes the pixels (sharp → RGBA) and calls `photoInventory`; `checkLayout` reads the grid through
9
+ * `calmUnder` to judge words set over the part of the photo a frame SHOWS; the model reads `describeInventoryForPrompt`.
10
+ * No DOM, no decoder: RGBA bytes in, numbers out, deterministic.
11
+ */
12
+
13
+ export enum PhotoTone {
14
+ Light = 'light',
15
+ Dark = 'dark',
16
+ }
17
+
18
+ export interface PhotoInventory {
19
+ shape: `${LayoutPhotoShape}`;
20
+ width: number;
21
+ height: number;
22
+ grid: {
23
+ cols: number;
24
+ rows: number;
25
+ /** Each cell's mean WCAG relative luminance (linear light), row by row. */
26
+ luminance: number[];
27
+ /** Each cell's mean |Laplacian| of its gamma-encoded luma (edges and texture), row by row; 0 is a flat field. */
28
+ detail: number[];
29
+ };
30
+ /** Up to five main colours (`#rrggbb`), the most of the picture first; fewer when the picture holds fewer. */
31
+ colours: string[];
32
+ tone: `${PhotoTone}`;
33
+ }
34
+
35
+ /** A region of a frame, as fractions of its width (x) and height (y). */
36
+ export interface FrameRegion {
37
+ x0: number;
38
+ y0: number;
39
+ x1: number;
40
+ y1: number;
41
+ }
42
+
43
+ export interface CalmReading {
44
+ calm: boolean;
45
+ tone: `${PhotoTone}`;
46
+ /** The region's mean relative luminance (what a colour over it is measured against). */
47
+ luminance: number;
48
+ /** The region's mean detail. */
49
+ detail: number;
50
+ }
51
+
52
+ export const PHOTO_GRID = 12;
53
+ /** Pixels are averaged down to this width before they are measured: the prototype measured at 96 wide, and the calm
54
+ * threshold below was read off its 35 proof photos at that scale (a Laplacian grows with resolution). */
55
+ export const PHOTO_ANALYSIS_WIDTH = 96;
56
+ /** At least this many analysed rows, so a very wide photo still has a few pixels per grid row. */
57
+ const MIN_ANALYSIS_HEIGHT = 48;
58
+ /** Calm: the mean detail under the words is at most this. The prototype's absolute bar (0.045 at 96 px wide: the busiest
59
+ * cell it called calm across the proof photos); its relative bar (≤ 0.55 × the photo's busiest cell) is not ported —
60
+ * it called nothing calm on a photo that is flat everywhere. */
61
+ export const PHOTO_CALM_DETAIL = 0.045;
62
+ /** Light: above the luminance where black and white words have the same contrast (√(1.05 × 0.05) − 0.05). */
63
+ export const PHOTO_LIGHT_LUMINANCE = 0.179;
64
+ const COLOURS = 5;
65
+ const KMEANS_ROUNDS = 12;
66
+ /** Shape by width ÷ height (the prototype's `shapeOf`). */
67
+ const SHAPE_FROM_RATIO: ReadonlyArray<[number, LayoutPhotoShape]> = [
68
+ [1.68, LayoutPhotoShape.Wide],
69
+ [1.2, LayoutPhotoShape.Landscape],
70
+ [0.85, LayoutPhotoShape.Square],
71
+ [0.62, LayoutPhotoShape.Portrait],
72
+ ];
73
+ const RGBA = 4;
74
+ const BYTE = 255;
75
+ /** The 3×3 parts a prompt names, in reading order (the prototype's cells). */
76
+ const PARTS = ['top-start', 'top', 'top-end', 'start', 'middle', 'end', 'bottom-start', 'bottom', 'bottom-end'] as const;
77
+
78
+ /** A photo's shape from its size. */
79
+ export function photoShapeOf(width: number, height: number): LayoutPhotoShape {
80
+ const r = width / Math.max(1, height);
81
+ return SHAPE_FROM_RATIO.find(([min]) => r >= min)?.[1] ?? LayoutPhotoShape.Tall;
82
+ }
83
+
84
+ export const toneOf = (luminance: number): PhotoTone => (luminance > PHOTO_LIGHT_LUMINANCE ? PhotoTone.Light : PhotoTone.Dark);
85
+
86
+ /** The picture averaged down to the analysis size: sRGB 0..1 per channel. */
87
+ function downsample(rgba: ArrayLike<number>, width: number, height: number): { w: number; h: number; px: Float64Array } {
88
+ const w = Math.min(width, PHOTO_ANALYSIS_WIDTH);
89
+ const h = Math.min(height, Math.max(MIN_ANALYSIS_HEIGHT, Math.round((w * height) / width)));
90
+ const sum = new Float64Array(w * h * 3);
91
+ const count = new Float64Array(w * h);
92
+ for (let y = 0; y < height; y++) {
93
+ const ty = Math.min(h - 1, Math.floor((y * h) / height));
94
+ for (let x = 0; x < width; x++) {
95
+ const tx = Math.min(w - 1, Math.floor((x * w) / width));
96
+ const i = (y * width + x) * RGBA;
97
+ const t = ty * w + tx;
98
+ sum[t * 3] += rgba[i];
99
+ sum[t * 3 + 1] += rgba[i + 1];
100
+ sum[t * 3 + 2] += rgba[i + 2];
101
+ count[t]++;
102
+ }
103
+ }
104
+ const px = new Float64Array(w * h * 3);
105
+ for (let t = 0; t < w * h; t++) for (let c = 0; c < 3; c++) px[t * 3 + c] = sum[t * 3 + c] / Math.max(1, count[t]) / BYTE;
106
+ return { w, h, px };
107
+ }
108
+
109
+ /** Up to five colours by k-means over the analysed pixels, seeded from evenly spread pixels (the prototype's), most
110
+ * first; centres that land on one colour are one colour. */
111
+ function mainColours(px: Float64Array, n: number): string[] {
112
+ const k = Math.min(COLOURS, n);
113
+ let centres = Array.from({ length: k }, (_, i) => {
114
+ const p = Math.floor(((i + 0.5) * n) / k);
115
+ return [px[p * 3], px[p * 3 + 1], px[p * 3 + 2]];
116
+ });
117
+ let counts = new Array<number>(k).fill(0);
118
+ for (let round = 0; round < KMEANS_ROUNDS; round++) {
119
+ const sums = centres.map(() => [0, 0, 0]);
120
+ counts = new Array<number>(k).fill(0);
121
+ for (let p = 0; p < n; p++) {
122
+ let best = 0;
123
+ let bestD = Infinity;
124
+ for (let c = 0; c < k; c++) {
125
+ const d = (px[p * 3] - centres[c][0]) ** 2 + (px[p * 3 + 1] - centres[c][1]) ** 2 + (px[p * 3 + 2] - centres[c][2]) ** 2;
126
+ if (d < bestD) {
127
+ bestD = d;
128
+ best = c;
129
+ }
130
+ }
131
+ for (let ch = 0; ch < 3; ch++) sums[best][ch] += px[p * 3 + ch];
132
+ counts[best]++;
133
+ }
134
+ centres = centres.map((c, i) => (counts[i] ? sums[i].map(v => v / counts[i]) : c));
135
+ }
136
+ const shares = new Map<string, number>();
137
+ centres.forEach((c, i) => {
138
+ const hex = toHexColor({ r: c[0], g: c[1], b: c[2] });
139
+ shares.set(hex, (shares.get(hex) ?? 0) + counts[i]);
140
+ });
141
+ return [...shares].sort((a, b) => b[1] - a[1]).map(([hex]) => hex);
142
+ }
143
+
144
+ /** What a photo is, measured from its pixels (RGBA bytes, row by row). */
145
+ export function photoInventory(rgba: Uint8ClampedArray | Uint8Array, width: number, height: number): PhotoInventory {
146
+ const { w, h, px } = downsample(rgba, width, height);
147
+ const luma = new Float64Array(w * h);
148
+ const lum = new Float64Array(w * h);
149
+ for (let t = 0; t < w * h; t++) {
150
+ const [r, g, b] = [px[t * 3], px[t * 3 + 1], px[t * 3 + 2]];
151
+ luma[t] = 0.2126 * r + 0.7152 * g + 0.0722 * b;
152
+ lum[t] = relativeLuminance({ r, g, b });
153
+ }
154
+ const at = (x: number, y: number) => luma[Math.min(h - 1, Math.max(0, y)) * w + Math.min(w - 1, Math.max(0, x))];
155
+ const cells = PHOTO_GRID * PHOTO_GRID;
156
+ const detail = new Array<number>(cells).fill(0);
157
+ const luminance = new Array<number>(cells).fill(0);
158
+ const count = new Array<number>(cells).fill(0);
159
+ for (let y = 0; y < h; y++) {
160
+ const cy = Math.min(PHOTO_GRID - 1, Math.floor((y * PHOTO_GRID) / h));
161
+ for (let x = 0; x < w; x++) {
162
+ const cx = Math.min(PHOTO_GRID - 1, Math.floor((x * PHOTO_GRID) / w));
163
+ const c = cy * PHOTO_GRID + cx;
164
+ detail[c] += Math.abs(4 * at(x, y) - at(x - 1, y) - at(x + 1, y) - at(x, y - 1) - at(x, y + 1));
165
+ luminance[c] += lum[y * w + x];
166
+ count[c]++;
167
+ }
168
+ }
169
+ const round = (v: number) => Math.round(v * 10000) / 10000;
170
+ const mean = (v: number, c: number) => (count[c] ? v / count[c] : 0);
171
+ const luminanceGrid = luminance.map((v, c) => round(mean(v, c)));
172
+ return {
173
+ shape: photoShapeOf(width, height),
174
+ width,
175
+ height,
176
+ grid: { cols: PHOTO_GRID, rows: PHOTO_GRID, luminance: luminanceGrid, detail: detail.map((v, c) => round(Math.min(1, mean(v, c)))) },
177
+ colours: mainColours(px, w * h),
178
+ tone: toneOf(lum.reduce((a, b) => a + b, 0) / Math.max(1, w * h)),
179
+ };
180
+ }
181
+
182
+ /** The part of the photo a frame region shows under `object-fit: cover` (centred): the frame crops the photo's longer side. */
183
+ export function coverCrop(inv: Pick<PhotoInventory, 'width' | 'height'>, frame: { w: number; h: number }, region: FrameRegion): FrameRegion {
184
+ const photo = inv.width / Math.max(1, inv.height);
185
+ const box = frame.w / Math.max(1, frame.h);
186
+ const clamp = (v: number) => Math.min(1, Math.max(0, v));
187
+ if (photo > box) {
188
+ const shown = box / photo;
189
+ const off = (1 - shown) / 2;
190
+ return { x0: off + clamp(region.x0) * shown, x1: off + clamp(region.x1) * shown, y0: clamp(region.y0), y1: clamp(region.y1) };
191
+ }
192
+ const shown = photo / box;
193
+ const off = (1 - shown) / 2;
194
+ return { x0: clamp(region.x0), x1: clamp(region.x1), y0: off + clamp(region.y0) * shown, y1: off + clamp(region.y1) * shown };
195
+ }
196
+
197
+ /** The grid's cells under a region of the photo, each with the share of it the region covers. */
198
+ function cellsUnder(inv: PhotoInventory, r: FrameRegion): Array<{ cell: number; weight: number }> {
199
+ const { cols, rows } = inv.grid;
200
+ const out: Array<{ cell: number; weight: number }> = [];
201
+ for (let cy = 0; cy < rows; cy++) {
202
+ const h = Math.min(r.y1, (cy + 1) / rows) - Math.max(r.y0, cy / rows);
203
+ if (h <= 0) continue;
204
+ for (let cx = 0; cx < cols; cx++) {
205
+ const w = Math.min(r.x1, (cx + 1) / cols) - Math.max(r.x0, cx / cols);
206
+ if (w > 0) out.push({ cell: cy * cols + cx, weight: w * h });
207
+ }
208
+ }
209
+ return out;
210
+ }
211
+
212
+ /** How a region of the photo reads (fractions of the PHOTO). */
213
+ function readRegion(inv: PhotoInventory, r: FrameRegion): CalmReading {
214
+ const cells = cellsUnder(inv, r);
215
+ const total = cells.reduce((a, c) => a + c.weight, 0);
216
+ if (!total) return { calm: true, tone: inv.tone, luminance: 0, detail: 0 };
217
+ const detail = cells.reduce((a, c) => a + inv.grid.detail[c.cell] * c.weight, 0) / total;
218
+ const luminance = cells.reduce((a, c) => a + inv.grid.luminance[c.cell] * c.weight, 0) / total;
219
+ return { calm: detail <= PHOTO_CALM_DETAIL, tone: toneOf(luminance), luminance, detail };
220
+ }
221
+
222
+ /**
223
+ * Whether words over `region` of a frame (fractions of the FRAME, which shows the photo as `object-fit: cover`, centred)
224
+ * sit on a calm part of the photo, and how light it is there. A calm band the crop cuts away is not under the words.
225
+ */
226
+ export function calmUnder(inv: PhotoInventory, frame: { w: number; h: number }, region: FrameRegion): CalmReading {
227
+ return readRegion(inv, coverCrop(inv, frame, region));
228
+ }
229
+
230
+ /** The photo's 3×3 named parts that are calm, each light or dark (`top-start (dark)`). */
231
+ export function calmParts(inv: PhotoInventory): string[] {
232
+ return PARTS.flatMap((name, i) => {
233
+ const x = i % 3;
234
+ const y = Math.floor(i / 3);
235
+ const read = readRegion(inv, { x0: x / 3, x1: (x + 1) / 3, y0: y / 3, y1: (y + 1) / 3 });
236
+ return read.calm ? [`${name} (${read.tone})`] : [];
237
+ });
238
+ }
239
+
240
+ /** One line a model reads instead of the photo: its id, what it shows, shape, colours and where words may sit. */
241
+ export function describeInventoryForPrompt(id: string, inv: PhotoInventory, label?: string): string {
242
+ const calm = calmParts(inv);
243
+ return [
244
+ id,
245
+ ...(label?.trim() ? [label.trim()] : []),
246
+ `${inv.shape}, ${inv.tone}`,
247
+ `colours ${inv.colours.join(' ')}`,
248
+ `calm: ${calm.length ? calm.join(', ') : 'nowhere (busy)'}`,
249
+ ].join(' · ');
250
+ }
@@ -36,6 +36,8 @@ export enum PlanEditOp {
36
36
  AddContentType = 'addContentType',
37
37
  AddField = 'addField',
38
38
  SetSectionData = 'setSectionData',
39
+ /** A composed page's layout asked again with the owner's sentence (M8-G2-D13): its layout is dropped, the layout step re-asks it. */
40
+ RecomposePage = 'recomposePage',
39
41
  }
40
42
 
41
43
  export type PlanEdit =
@@ -51,7 +53,8 @@ export type PlanEdit =
51
53
  | { op: `${PlanEditOp.SetSlot}`; page: string; index: number; slot: string; text: string }
52
54
  | { op: `${PlanEditOp.AddContentType}`; contentType: ContentTypePlan; dataSources?: DataSourcePlan[] }
53
55
  | { op: `${PlanEditOp.AddField}`; contentType: string; field: ContentFieldPlan; sample?: string | string[] }
54
- | { op: `${PlanEditOp.SetSectionData}`; page: string; index: number; binding: string };
56
+ | { op: `${PlanEditOp.SetSectionData}`; page: string; index: number; binding: string }
57
+ | { op: `${PlanEditOp.RecomposePage}`; page: string; ask: string };
55
58
 
56
59
  /**
57
60
  * Every op's keys, explained — what the format is built from and what `validatePlanEdits` reads (`key?` optional).
@@ -71,6 +74,7 @@ export const PLAN_EDIT_SHAPE: Readonly<Record<`${PlanEditOp}`, ShapeEntry>> = {
71
74
  [PlanEditOp.AddContentType]: { op: "'addContentType'", contentType: 'contentType — a unique name', 'dataSources?': 'dataSource[] — the list / single sources its pages read' },
72
75
  [PlanEditOp.AddField]: { op: "'addField'", contentType: 'string — a content type of the plan', field: 'field', 'sample?': "string | string[] — the samples' value for it; absent: what the type's seed already holds for it, else ''" },
73
76
  [PlanEditOp.SetSectionData]: { op: "'setSectionData'", page: 'string — a page key', index: 'integer — the section', binding: 'string — the list source the section repeats' },
77
+ [PlanEditOp.RecomposePage]: { op: "'recomposePage'", page: 'string — a composed page key (compose: true)', ask: "string — what the owner asked of that page's layout, in their words" },
74
78
  };
75
79
 
76
80
  /**
@@ -89,6 +93,7 @@ export const PLAN_EDIT_OP_PART: Readonly<Record<`${PlanEditOp}`, PlanPart>> = {
89
93
  [PlanEditOp.SwapPattern]: PlanPart.Pages,
90
94
  [PlanEditOp.SetSlot]: PlanPart.Pages,
91
95
  [PlanEditOp.SetSectionData]: PlanPart.Pages,
96
+ [PlanEditOp.RecomposePage]: PlanPart.Pages,
92
97
  [PlanEditOp.AddContentType]: PlanPart.Structure,
93
98
  [PlanEditOp.AddField]: PlanPart.Structure,
94
99
  };
@@ -137,6 +142,8 @@ export enum PlanEditIssueCode {
137
142
  HomePage = 'home-page',
138
143
  /** A template page (one item per route) and a plain page cannot be merged. */
139
144
  MergeTemplate = 'merge-template',
145
+ /** Only a composed page's layout is asked again; a page of patterns is edited by its sections. */
146
+ NotComposed = 'not-composed',
140
147
  }
141
148
 
142
149
  export type PlanEditIssue = PathIssue<PlanEditIssueCode>;
@@ -364,8 +371,23 @@ const APPLY: Readonly<Record<`${PlanEditOp}`, Apply>> = {
364
371
  setSections(d, at, d.pages[at].sections.map((s, i) => (i === e.index ? { ...s, binding: e.binding } : s)));
365
372
  changed.push({ kind: PlanChangeKind.Section, action: PlanChangeAction.Changed, page: d.pages[at].key, index: e.index });
366
373
  },
374
+ [PlanEditOp.RecomposePage]: (d, e, c, path, changed) => {
375
+ const at = findPage(d, e.page, c, `${path}.page`);
376
+ if (at < 0) return;
377
+ if (!d.pages[at].compose) return c.add(PlanEditIssueCode.NotComposed, `${path}.page`, `page "${d.pages[at].key}" is built from sections — edit them instead`);
378
+ const { layout: _asked, ...page } = d.pages[at];
379
+ d.pages[at] = page;
380
+ changed.push({ kind: PlanChangeKind.Page, action: PlanChangeAction.Changed, page: page.key, name: page.name });
381
+ },
367
382
  };
368
383
 
384
+ /** The sentence each page's layout is asked again with (the set's last ask for a page wins) — what the layout step reads. */
385
+ export function recomposeAsks(edits: ReadonlyArray<PlanEdit>): Record<string, string> {
386
+ const out: Record<string, string> = {};
387
+ for (const e of edits) if (e.op === PlanEditOp.RecomposePage) out[e.page] = e.ask;
388
+ return out;
389
+ }
390
+
369
391
  /**
370
392
  * Apply a set of edits to a plan — all of them, or none (any issue refuses the set and returns the plan unchanged). The
371
393
  * sources only removed pages and sections read are dropped with them; sources nothing read before are kept; the sources
@@ -474,7 +496,7 @@ const EDIT_WIRE: Readonly<Record<string, EditWireKey>> = {
474
496
  to: indexKey('movePage / moveSection: the new 0-based place'),
475
497
  pattern: { text: 'string — swapPattern: the section pattern it becomes', none: '', schema: () => jsonOneOf(['', ...sectionPatternIds()]) },
476
498
  slot: textKey("setSlot: one of the pattern's slots"),
477
- text: textKey("setSlot: the words, in the owner's language and voice"),
499
+ text: textKey("setSlot: the words, in the owner's language and voice · recomposePage: what the owner asked of the page's layout"),
478
500
  binding: textKey('setSectionData: the list source the section repeats'),
479
501
  contentType: textKey('addField: a content type of the plan'),
480
502
  newPage: {
@@ -511,6 +533,7 @@ export const PLAN_EDIT_WIRE_KEYS: Readonly<Record<`${PlanEditOp}`, Readonly<Reco
511
533
  [PlanEditOp.AddContentType]: { contentType: 'newContentType', dataSources: 'dataSources' },
512
534
  [PlanEditOp.AddField]: { contentType: 'contentType', field: 'newField', sample: 'sample' },
513
535
  [PlanEditOp.SetSectionData]: { page: 'page', index: 'index', binding: 'binding' },
536
+ [PlanEditOp.RecomposePage]: { page: 'page', ask: 'text' },
514
537
  };
515
538
 
516
539
  /** The wire keys a part's edit carries: every key its ops read, in `EDIT_WIRE` order. */