@vectoriox/iox-ui 5.203.0 → 5.204.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 (50) hide show
  1. package/actions-core/index.d.ts +8 -1
  2. package/design-core/index.d.ts +62 -2
  3. package/fesm2022/vectoriox-iox-ui-actions-core.mjs +8 -1
  4. package/fesm2022/vectoriox-iox-ui-actions-core.mjs.map +1 -1
  5. package/fesm2022/vectoriox-iox-ui-design-core.mjs +121 -11
  6. package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
  7. package/fesm2022/vectoriox-iox-ui-generation-core.mjs +5165 -267
  8. package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
  9. package/fesm2022/vectoriox-iox-ui.mjs +381 -32
  10. package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
  11. package/generation-core/index.d.ts +2263 -5
  12. package/index.d.ts +117 -12
  13. package/package.json +1 -1
  14. package/src/actions-core/element-actions.ts +9 -0
  15. package/src/design-core/contrast-audit.ts +93 -11
  16. package/src/design-core/flavor-spec.generated.ts +19 -0
  17. package/src/design-core/image-alt.ts +27 -0
  18. package/src/design-core/public-api.ts +1 -0
  19. package/src/generation-core/audit-site.ts +17 -3
  20. package/src/generation-core/baseline-roles.ts +10 -6
  21. package/src/generation-core/check-free.ts +12 -2
  22. package/src/generation-core/check-layout.ts +3 -2
  23. package/src/generation-core/critic-calibration.ts +175 -0
  24. package/src/generation-core/critic-prompt.ts +153 -0
  25. package/src/generation-core/critic-rubric.generated.ts +24 -0
  26. package/src/generation-core/critic-sheet.ts +203 -0
  27. package/src/generation-core/critic.ts +175 -0
  28. package/src/generation-core/design-doc-index.ts +58 -0
  29. package/src/generation-core/design-motion.ts +247 -0
  30. package/src/generation-core/design-ops-check.ts +370 -0
  31. package/src/generation-core/design-ops-of.ts +200 -0
  32. package/src/generation-core/design-ops.model.ts +239 -0
  33. package/src/generation-core/design-ops.schema.ts +122 -0
  34. package/src/generation-core/design-ops.ts +361 -0
  35. package/src/generation-core/design-recipes.ts +58 -0
  36. package/src/generation-core/designer-brief.ts +81 -0
  37. package/src/generation-core/designer-direction.ts +248 -0
  38. package/src/generation-core/designer-estimate.ts +171 -0
  39. package/src/generation-core/designer-lessons.generated.ts +653 -0
  40. package/src/generation-core/designer-lessons.ts +153 -0
  41. package/src/generation-core/designer-stop.ts +94 -0
  42. package/src/generation-core/footer-mix.ts +3 -1
  43. package/src/generation-core/node-baselines.generated.ts +953 -10
  44. package/src/generation-core/public-api.ts +20 -0
  45. package/src/generation-core/site-spec.generated.ts +73 -11
  46. package/src/generation-core/social-links.ts +195 -2
  47. package/src/generation-core/structure-fingerprint.ts +565 -0
  48. package/src/generation-core/templates.ts +39 -3
  49. package/styles/iox-design.css +26 -1
  50. package/styles/iox-forms.css +22 -0
@@ -0,0 +1,175 @@
1
+ import { CRITIC_RUBRIC_DIMENSIONS, CRITIC_RUBRIC_POLISH } from './critic-rubric.generated';
2
+ import { jsonBoolean, jsonClosedObject, jsonListOf, JsonSchema, jsonText } from './json-schema';
3
+ import { isPlainObject, PathIssue } from './shape-check';
4
+
5
+ /**
6
+ * THE AI DESIGNER'S CRITIC — its answer (ai-designer-plan §2d, AD3, AD-D18). Each round the critic reads the sheet (the
7
+ * reference beside ours, view by view, and zoomed crops) and answers ONE strict object: a score 0–10 and one line of
8
+ * evidence for each of the reference score's eight dimensions (`team/reference-score.md` §2, ported — never retyped —
9
+ * into `critic-rubric.generated.ts`), the polish bugs it saw (a bug a visitor would call broken caps the page), and the
10
+ * 1–3 changes that move the lowest score most, written as a brief for the revise step. The arithmetic — the design mean,
11
+ * the cap, the headline — is this file's, never the model's. Pure.
12
+ */
13
+
14
+ /** The eight dimensions, by the key the critic answers under — the rubric's order (a spec holds it to the port). */
15
+ export enum CriticDimension {
16
+ Colour = 'colour',
17
+ Type = 'type',
18
+ Composition = 'composition',
19
+ Imagery = 'imagery',
20
+ Header = 'header',
21
+ Footer = 'footer',
22
+ Motion = 'motion',
23
+ Polish = 'polish',
24
+ }
25
+ export const CRITIC_DIMENSIONS: ReadonlyArray<CriticDimension> = Object.values(CriticDimension);
26
+ /** Dimensions 1–7: the headline is their mean. */
27
+ export const CRITIC_DESIGN_DIMENSIONS: ReadonlyArray<CriticDimension> = CRITIC_DIMENSIONS.filter(d => d !== CriticDimension.Polish);
28
+ /** A score is 0–10 in half points, as the tester scores. */
29
+ export const CRITIC_SCORE = { min: 0, max: 10, step: 0.5 } as const;
30
+ /** How many changes a critique gives the revise step. */
31
+ export const CRITIC_CHANGES = { min: 1, max: 3 } as const;
32
+ /** The answer's format name (the request's output). */
33
+ export const CRITIC_OUTPUT_NAME = 'critique';
34
+
35
+ export interface CriticScore {
36
+ score: number;
37
+ /** One line, read off the sheet as a position, a size or a colour: "<reference> does X; ours does Y". */
38
+ evidence: string;
39
+ }
40
+ export interface CriticBug {
41
+ what: string;
42
+ /** A visitor would call it broken (a 404, text over text, a dead button): the page is capped. */
43
+ broken: boolean;
44
+ }
45
+ export interface CriticChange {
46
+ dimension: CriticDimension;
47
+ /** What the revise step should do, in our own terms — never "make it look like the reference". */
48
+ brief: string;
49
+ }
50
+ export interface CriticAnswer {
51
+ scores: Record<CriticDimension, CriticScore>;
52
+ bugs: CriticBug[];
53
+ changes: CriticChange[];
54
+ }
55
+
56
+ /** The critic's strict output format: every property required, every object closed (`strictSchemaComplexity`). */
57
+ export function criticAnswerSchema(): JsonSchema {
58
+ const score = jsonClosedObject(
59
+ { score: { type: 'number', description: `0–10 in half points.` }, evidence: { ...jsonText(), description: 'One line read off the sheet: a position, a size or a colour, the reference\'s and ours.' } },
60
+ ['score', 'evidence'],
61
+ );
62
+ const byName = Object.fromEntries(CRITIC_RUBRIC_DIMENSIONS.map(d => [d.key, { ...score, description: `${d.name}: ${d.compares}` }]));
63
+ return jsonClosedObject({
64
+ scores: jsonClosedObject(byName, CRITIC_RUBRIC_DIMENSIONS.map(d => d.key), 'One score per dimension of the rubric.'),
65
+ bugs: jsonListOf(jsonClosedObject({ what: jsonText(), broken: jsonBoolean() }, ['what', 'broken'], 'A polish bug; broken = a visitor would call it broken.')),
66
+ changes: jsonListOf(jsonClosedObject(
67
+ { dimension: { type: 'string', enum: [...CRITIC_DIMENSIONS] }, brief: jsonText() }, ['dimension', 'brief'],
68
+ `${CRITIC_CHANGES.min}–${CRITIC_CHANGES.max} changes that move the lowest score most, as a brief for the next round.`,
69
+ )),
70
+ }, ['scores', 'bugs', 'changes'], 'The critique of one page.');
71
+ }
72
+
73
+ export enum CriticIssueCode {
74
+ /** Not the answer's shape. */
75
+ Shape = 'shape',
76
+ /** A score outside 0–10 or not in half points. */
77
+ Range = 'range',
78
+ /** Evidence that is not one line read off the sheet (no position, size or colour in it). */
79
+ Evidence = 'evidence',
80
+ /** Not 1–3 changes, or none aimed at the lowest score. */
81
+ Changes = 'changes',
82
+ /** A polish score above what its bugs leave. */
83
+ Polish = 'polish',
84
+ /** A brief that asks for resemblance (AD-D18): the reference's name, "copy", "look like". */
85
+ Likeness = 'likeness',
86
+ }
87
+ export type CriticIssue = PathIssue<CriticIssueCode>;
88
+
89
+ export interface CriticContext {
90
+ /** The reference the page is scored against (its name, as the cards are named: `graya-institute`). */
91
+ reference: string;
92
+ }
93
+
94
+ /** A measurement: a number (a size, a position, a share) or a hex colour. */
95
+ const MEASURED = /\d/;
96
+ const LIKENESS_WORDS = /\b(copy|copies|copying|mimic|replicate|imitate|clone|look(?:s|ing)? like|same as|just like)\b/i;
97
+ const MIN_NAME_PART = 4;
98
+
99
+ /** The words of a reference's name a brief may not say (`graya-institute` → graya, institute). */
100
+ const nameParts = (reference: string) => reference.toLowerCase().split(/[^a-z0-9]+/).filter(p => p.length >= MIN_NAME_PART);
101
+
102
+ /** Why an answer is not a usable critique, each reason with its path. The one gate between the model and the loop. */
103
+ export function criticAnswerIssues(answer: unknown, ctx: CriticContext): CriticIssue[] {
104
+ const out: CriticIssue[] = [];
105
+ const say = (code: CriticIssueCode, path: string, message: string) => out.push({ code, path, message });
106
+ if (!isPlainObject(answer) || !isPlainObject(answer['scores']) || !Array.isArray(answer['bugs']) || !Array.isArray(answer['changes'])) {
107
+ say(CriticIssueCode.Shape, '', 'a critique is { scores, bugs, changes }');
108
+ return out;
109
+ }
110
+ const scores = answer['scores'];
111
+ for (const d of CRITIC_DIMENSIONS) {
112
+ const s = scores[d];
113
+ const path = `scores.${d}`;
114
+ if (!isPlainObject(s) || typeof s['score'] !== 'number' || typeof s['evidence'] !== 'string') { say(CriticIssueCode.Shape, path, 'a score and its evidence'); continue; }
115
+ const v = s['score'];
116
+ if (v < CRITIC_SCORE.min || v > CRITIC_SCORE.max || !Number.isInteger(v / CRITIC_SCORE.step)) say(CriticIssueCode.Range, `${path}.score`, `0–10 in half points, not ${v}`);
117
+ const evidence = s['evidence'].trim();
118
+ if (!evidence || /\n/.test(evidence) || !MEASURED.test(evidence)) {
119
+ say(CriticIssueCode.Evidence, `${path}.evidence`, 'one line read off the sheet — a position, a size or a colour, the reference\'s and ours');
120
+ }
121
+ }
122
+ const bugs = answer['bugs'] as unknown[];
123
+ bugs.forEach((b, i) => {
124
+ if (!isPlainObject(b) || typeof b['what'] !== 'string' || typeof b['broken'] !== 'boolean') say(CriticIssueCode.Shape, `bugs[${i}]`, 'a bug is { what, broken }');
125
+ });
126
+ const polish = (scores[CriticDimension.Polish] as { score?: unknown } | undefined)?.score;
127
+ const allowed = CRITIC_SCORE.max - CRITIC_RUBRIC_POLISH.bugPenalty * bugs.length;
128
+ if (typeof polish === 'number' && polish > allowed) say(CriticIssueCode.Polish, `scores.${CriticDimension.Polish}.score`, `${bugs.length} bug(s) leave at most ${allowed}`);
129
+ const changes = answer['changes'] as unknown[];
130
+ if (changes.length < CRITIC_CHANGES.min || changes.length > CRITIC_CHANGES.max) say(CriticIssueCode.Changes, 'changes', `${CRITIC_CHANGES.min}–${CRITIC_CHANGES.max} changes, not ${changes.length}`);
131
+ const names = nameParts(ctx.reference);
132
+ changes.forEach((c, i) => {
133
+ const path = `changes[${i}]`;
134
+ if (!isPlainObject(c) || !CRITIC_DIMENSIONS.includes(c['dimension'] as CriticDimension) || typeof c['brief'] !== 'string' || !c['brief'].trim()) {
135
+ say(CriticIssueCode.Shape, path, 'a change is { dimension, brief }');
136
+ return;
137
+ }
138
+ const brief = c['brief'].toLowerCase();
139
+ const named = names.find(n => new RegExp(`\\b${n}\\b`).test(brief));
140
+ if (named || LIKENESS_WORDS.test(brief)) {
141
+ say(CriticIssueCode.Likeness, `${path}.brief`, 'a brief asks for the level, in our own terms — never the reference by name, never to copy or look like it (AD-D18)');
142
+ }
143
+ });
144
+ if (out.length) return out;
145
+ const lowest = lowestDimensions(answer as unknown as CriticAnswer);
146
+ if (!(changes as CriticChange[]).some(c => lowest.includes(c.dimension))) {
147
+ say(CriticIssueCode.Changes, 'changes', `no change is aimed at the lowest score (${lowest.join(', ')})`);
148
+ }
149
+ return out;
150
+ }
151
+
152
+ /** The dimensions holding the lowest score (ties together). */
153
+ export function lowestDimensions(answer: CriticAnswer): CriticDimension[] {
154
+ const low = Math.min(...CRITIC_DIMENSIONS.map(d => answer.scores[d].score));
155
+ return CRITIC_DIMENSIONS.filter(d => answer.scores[d].score === low);
156
+ }
157
+
158
+ export interface CriticVerdict {
159
+ /** The mean of dimensions 1–7. */
160
+ designMean: number;
161
+ polish: number;
162
+ /** How many bugs a visitor would call broken. */
163
+ broken: number;
164
+ /** The rubric's headline: the design mean, capped when a bug is broken. */
165
+ headline: number;
166
+ capped: boolean;
167
+ }
168
+
169
+ /** What a critique comes to, by the rubric's rule (`CRITIC_RUBRIC_HEADLINE`): the mean of 1–7, capped by a broken bug. */
170
+ export function criticVerdict(answer: CriticAnswer): CriticVerdict {
171
+ const designMean = CRITIC_DESIGN_DIMENSIONS.reduce((sum, d) => sum + answer.scores[d].score, 0) / CRITIC_DESIGN_DIMENSIONS.length;
172
+ const broken = answer.bugs.filter(b => b.broken).length;
173
+ const capped = broken > 0 && designMean > CRITIC_RUBRIC_POLISH.brokenCap;
174
+ return { designMean, polish: answer.scores[CriticDimension.Polish].score, broken, headline: capped ? CRITIC_RUBRIC_POLISH.brokenCap : designMean, capped };
175
+ }
@@ -0,0 +1,58 @@
1
+ import type { DesignDoc } from './design-ops.model';
2
+ import type { SerializedNode } from './serialized-node';
3
+
4
+ /**
5
+ * Where each node of a design document sits (AD1): the node, the list that holds it (the page's layout, the site's
6
+ * globals, or a parent's children) and that parent. `applyDesignOps` keeps it as it works; the static check reads it.
7
+ */
8
+ export interface DesignNodePlace {
9
+ node: SerializedNode;
10
+ list: SerializedNode[];
11
+ parent: SerializedNode | null;
12
+ }
13
+
14
+ export class DesignDocIndex {
15
+ private readonly places = new Map<string, DesignNodePlace>();
16
+
17
+ constructor(readonly doc: DesignDoc) {
18
+ this.rebuild();
19
+ }
20
+
21
+ /** Index every node again (after a move, a removal or a wrap). */
22
+ rebuild(): void {
23
+ this.places.clear();
24
+ this.addList(this.doc.layout, null);
25
+ this.addList(this.doc.globals, null);
26
+ }
27
+
28
+ /** Index a node and its subtree, just inserted into `list` under `parent`. */
29
+ add(node: SerializedNode, list: SerializedNode[], parent: SerializedNode | null): void {
30
+ this.places.set(node.id, { node, list, parent });
31
+ if (node.children?.length) this.addList(node.children, node);
32
+ }
33
+
34
+ find(id: string): DesignNodePlace | undefined {
35
+ return this.places.get(id);
36
+ }
37
+
38
+ has(id: string): boolean {
39
+ return this.places.has(id);
40
+ }
41
+
42
+ /** Every node, in no promised order. */
43
+ nodes(): SerializedNode[] {
44
+ return [...this.places.values()].map(p => p.node);
45
+ }
46
+
47
+ /** Whether `id` is `ancestor` or sits inside it. */
48
+ within(id: string, ancestor: string): boolean {
49
+ for (let at = this.places.get(id); at; at = at.parent ? this.places.get(at.parent.id) : undefined) {
50
+ if (at.node.id === ancestor) return true;
51
+ }
52
+ return false;
53
+ }
54
+
55
+ private addList(list: SerializedNode[], parent: SerializedNode | null): void {
56
+ for (const node of list) this.add(node, list, parent);
57
+ }
58
+ }
@@ -0,0 +1,247 @@
1
+ import { actionOfferedUnder, ELEMENT_ACTION_DESCRIPTORS, ENTRANCE_ACTION_TYPES, EXIT_ACTION_TYPES } from '@vectoriox/iox-ui/actions-core';
2
+ import { DesignTokenLike, LEAVE_SHARE } from '@vectoriox/iox-ui/design-core';
3
+
4
+ import { FREE_HOVER_PROPS, freeStyleIssues } from './check-free';
5
+ import { auditLayoutMotion, LAYOUT_ENTRANCE_TRIGGERS } from './check-layout';
6
+ import { DESIGN_POINTER_STATES } from './design-ops-check';
7
+ import { DesignDoc, DesignIssue, DesignIssueCode } from './design-ops.model';
8
+ import { SerializedNode, walkSerialized } from './serialized-node';
9
+
10
+ /**
11
+ * EMIL'S RULES, READ OFF A PAGE (ai-designer-plan §2f "Emil", R-H20): the static half of the motion review, over a saved
12
+ * page's own nodes — whoever wrote them (the designer's ops, a hand build, a composed page). What it holds:
13
+ * 1. PROPERTY — motion moves transform, opacity and clip-path (a filter only where the catalog's `blurIn` does): a
14
+ * transition never names a layout property (width, height, a side, margin, padding) nor `all`; a pointer state
15
+ * (hover, press) moves, scales, turns, fades or changes a colour token only (`FREE_HOVER_PROPS`). The catalog's own
16
+ * actions are held to the same by the spec (every motion action's frames, `buildInteractionKeyframes`).
17
+ * 2. ONE ENTRANCE — an element enters once (one entrance action under the self-playing triggers, whatever row it is in),
18
+ * and a CONTAINER that enters holds nothing that enters too: either the column rises or its words stagger in.
19
+ * 3. EXIT — an element's exit is faster than its entrance (about `LEAVE_SHARE` of it).
20
+ * 4. TIME — easings are tokens (a cubic-bezier, linear, a var()) and never ease-in; a CSS duration is the look's token
21
+ * (so reduced motion can collapse it); what a pointer drives on a control plays under `UI_MOTION_MAX_MS`, a
22
+ * picture's hover zoom in at most `PICTURE_HOVER_MAX_MS`; an entrance in at most `LAYOUT_ENTRANCE_MAX_MS` — but a
23
+ * count and a picture's ambient settle (AD-D23, `entranceCapExempt`); nothing grows from a tiny scale.
24
+ * 5. REDUCED MOTION, gentler not zero — the platform covers every catalog entrance with its floor's fade (`show` is the
25
+ * instant reveal a click opens, so it is refused as a self-playing entrance) and every scroll play with its own
26
+ * reduced play (scene-core `scroll-range`); a literal CSS duration is the one thing reduced motion cannot reach (4).
27
+ * 6. HOVER GATED — by the platform: every hover state is emitted inside `(hover: hover) and (pointer: fine)` and a hover
28
+ * trigger answers a mouse or a pen only (iox-ui `gateHoverRule`, `isHoverPointer`; held by the spec). A design has no
29
+ * other way to hover, so nothing here can break it.
30
+ * It reuses the composer's audit (`auditLayoutMotion`: ease-in, easing tokens, `transition: all`, scale floor, entrance
31
+ * length), the free tier's style rules (`freeStyleIssues`) and the catalog (actions-core) — never a second copy. Paths are
32
+ * node ids (`layout:<id>.interactions[0].actions[1].easing`). Pure.
33
+ */
34
+
35
+ /** What a pointer drives on the element itself plays this fast at most (Emil: UI under 300 ms; `emil-audit.cjs`). */
36
+ export const UI_MOTION_MAX_MS = 300;
37
+ /** The triggers that play by themselves: the composer's entrance triggers and a page arriving. */
38
+ export const MOTION_ENTRANCE_TRIGGERS: ReadonlySet<string> = new Set([...LAYOUT_ENTRANCE_TRIGGERS, 'pageEnter']);
39
+ /** The triggers a pointer drives. */
40
+ export const MOTION_POINTER_TRIGGERS: ReadonlySet<string> = new Set(['click', 'hover']);
41
+ /** A transition that names any of these animates layout (the prototype's Emil audit, `emil-audit.cjs`, ported). */
42
+ const LAYOUT_PROPERTY = /(^|[\s,])(width|height|top|left|right|bottom|inset|margin|padding)(-[a-z-]+)?(?![-\w])/i;
43
+ const EASE_IN = /(^|[\s,(])ease-in(?!-out)/;
44
+ /** The controls a visitor operates: what a pointer drives on them is UI (the prototype audit's `UI` selector, as types). */
45
+ export const MOTION_UI_TYPES: ReadonlySet<string> = new Set(['Button', 'ButtonBlock', 'Link', 'Field', 'SubmitButton']);
46
+ /** The parts that ARE a picture (AD-D23). */
47
+ export const MOTION_PICTURE_TYPES: ReadonlySet<string> = new Set(['Image', 'Video']);
48
+ /** AD-D23 (the lessons' "hover zoom under 0.9 s"): a picture's hover transform plays in this much at most. */
49
+ export const PICTURE_HOVER_MAX_MS = 900;
50
+ /** AD-D23: a picture's ambient settle (`zoomOut`) may play this long — the one entrance over the cap besides a count. */
51
+ export const PICTURE_SETTLE_MAX_MS = 7000;
52
+ /** AD-D23: the entrance cap's two named exemptions — a count (its duration is how long the digits count, nothing moves)
53
+ * and a picture's settle (`zoomOut` on a picture: 1.15 → 1, never under 0.9). */
54
+ export const COUNT_ACTION = 'countUp';
55
+ export const SETTLE_ACTION = 'zoomOut';
56
+ /** What a pointer state may move that is a transform (a picture's hover zoom). */
57
+ const TRANSFORM_PROPS: ReadonlyArray<string> = ['translateX', 'translateY', 'scaleX', 'scaleY', 'rotate'];
58
+ const CUBIC = /^cubic-bezier\(\s*([\d.]+)\s*,\s*(-?[\d.]+)\s*,/;
59
+ /** A look token made for a pointer state (`--iox-button-press-radius`, `--iox-button-hover-x`): the flavor's own state
60
+ * design, reviewed with it (premium-components), so a pointer state may name it whatever the property. */
61
+ const STATE_TOKEN = /^var\(\s*--iox-[a-z0-9-]*(hover|press)[a-z0-9-]*\s*\)$/;
62
+ /** The reveal a click opens: instant by design, so it has no reduced-motion fade (iox-ui `reducedEntranceFades`). */
63
+ const INSTANT_REVEAL = 'show';
64
+ const SELF = 'self';
65
+
66
+ export enum MotionRule {
67
+ Property = 'property',
68
+ OneEntrance = 'one-entrance',
69
+ Container = 'container',
70
+ Exit = 'exit',
71
+ Easing = 'easing',
72
+ Duration = 'duration',
73
+ Scale = 'scale',
74
+ Catalog = 'catalog',
75
+ Reduced = 'reduced',
76
+ }
77
+ export type MotionIssue = DesignIssue & { rule: MotionRule };
78
+
79
+ interface Action { type?: string; target?: string; duration?: number; easing?: string; params?: Record<string, unknown> }
80
+ interface Row { id?: string; trigger?: string; actions?: Action[] }
81
+ type Style = Record<string, unknown> | undefined;
82
+
83
+ /** A move as the page plays it: the element it moves, where it is written, its row's trigger. */
84
+ interface Move { element: string; path: string; trigger: string; action: Action }
85
+
86
+ const rowsOf = (node: SerializedNode) => (Array.isArray(node.interactions) ? node.interactions : []) as Row[];
87
+ const elementOf = (node: SerializedNode, a: Action) => (a.target && a.target !== SELF ? a.target : node.id);
88
+ const isEntrance = (m: Move) => MOTION_ENTRANCE_TRIGGERS.has(m.trigger) && ENTRANCE_ACTION_TYPES.has(String(m.action.type));
89
+ const isExit = (m: Move) => EXIT_ACTION_TYPES.has(String(m.action.type));
90
+ const ms = (m: Move) => Number(m.action.duration ?? 0);
91
+ const isMotion = (m: Move) => ELEMENT_ACTION_DESCRIPTORS.find(d => d.type === m.action.type)?.group === MOTION_GROUP;
92
+ const MOTION_GROUP = 'motion';
93
+ /** The token type of the look's curves (`ease-standard`, `ease-enter`…). */
94
+ const EASING_TOKEN_TYPE = 'easing';
95
+
96
+ /** A CSS time in ms: a literal (`240ms`, `.3s`) or a token the look holds (`var(--iox-dur-base)`); null when unknown. */
97
+ export function cssMs(value: unknown, tokens: ReadonlyArray<DesignTokenLike> = []): number | null {
98
+ const raw = String(value ?? '').trim();
99
+ const token = /^var\(\s*--iox-([a-z0-9-]+)/.exec(raw);
100
+ const v = token ? tokens.find(t => t.name === token[1])?.value ?? '' : raw;
101
+ const m = /^([\d.]+)(ms|s)$/.exec(v.trim());
102
+ return m ? Number(m[1]) * (m[2] === 's' ? 1000 : 1) : null;
103
+ }
104
+
105
+ /** The composer's audit, as this check's issues (its node paths turned into the page's). */
106
+ function composerAudit(nodes: ReadonlyArray<SerializedNode>, named: ReadonlySet<string>): MotionIssue[] {
107
+ const ruleOf = (path: string): MotionRule =>
108
+ (/\.easing$/.test(path) ? MotionRule.Easing : /\.duration$/.test(path) ? MotionRule.Duration : /transition/.test(path) ? MotionRule.Property : MotionRule.Scale);
109
+ // An easing that NAMES the look's curve (`ease-enter`: both runtimes resolve it, iox-ui `interaction-easing`) is the
110
+ // token itself — the composer's audit, which stamps cubic-beziers, does not know the names.
111
+ return auditLayoutMotion(nodes).map(i => {
112
+ const path = i.path.replace(/^node\(([^)]*)\)/, 'layout:$1');
113
+ return { code: DesignIssueCode.Motion, rule: ruleOf(path), path, message: i.message };
114
+ }).filter(i => !named.has(i.path));
115
+ }
116
+
117
+ /** Every style map a node holds, with its path. */
118
+ function stylesOf(node: SerializedNode, at: string): Array<[string, Style, string | null]> {
119
+ return [
120
+ [`${at}.styleProps`, node.styleProps, null],
121
+ ...Object.entries(node.stateStyles ?? {}).map(([s, v]) => [`${at}.stateStyles.${s}`, v as Style, s] as [string, Style, string]),
122
+ ...Object.entries(node.responsive ?? {}).map(([w, r]) => [`${at}.responsive.${w}.styleProps`, (r as { styleProps?: Style })?.styleProps, null] as [string, Style, null]),
123
+ ];
124
+ }
125
+
126
+ /** Rules 1 and 4 on a node's own styles. */
127
+ function styleIssues(node: SerializedNode, at: string, tokens: ReadonlyArray<DesignTokenLike> | undefined, say: (rule: MotionRule, path: string, message: string) => void): void {
128
+ const pointer = MOTION_UI_TYPES.has(node.type) && DESIGN_POINTER_STATES.some(s => Object.keys(node.stateStyles?.[s] ?? {}).length > 0);
129
+ // An unset duration is CSS's initial 0s; a state or a width without one plays the base's.
130
+ const zooms = MOTION_PICTURE_TYPES.has(node.type) && Object.keys(node.stateStyles?.['hover'] ?? {}).some(k => TRANSFORM_PROPS.includes(k));
131
+ const baseTime = node.styleProps?.['transitionDuration'] === undefined ? 0 : cssMs(node.styleProps['transitionDuration'], tokens);
132
+ for (const [path, style, state] of stylesOf(node, at)) {
133
+ if (!style) continue;
134
+ for (const key of ['transition', 'transitionProperty']) {
135
+ const v = String(style[key] ?? '');
136
+ const prop = LAYOUT_PROPERTY.exec(v);
137
+ if (prop) say(MotionRule.Property, `${path}.${key}`, `a transition on "${prop[2]}" animates layout — move transform and opacity (a clip-path to reveal) instead`);
138
+ }
139
+ for (const key of ['transition', 'transitionTimingFunction']) {
140
+ if (EASE_IN.test(String(style[key] ?? ''))) say(MotionRule.Easing, `${path}.${key}`, 'never ease-in: it starts slow where the eye is watching');
141
+ }
142
+ if (state && DESIGN_POINTER_STATES.includes(state)) {
143
+ for (const [k, v] of Object.entries(style)) {
144
+ if (v !== '' && !FREE_HOVER_PROPS.includes(k) && !STATE_TOKEN.test(String(v))) say(MotionRule.Property, `${path}.${k}`, `a ${state} moves, scales, turns, fades or changes a colour token only (${FREE_HOVER_PROPS.join(', ')}) — never "${k}"`);
145
+ }
146
+ }
147
+ // A transition that lasts nothing plays nothing: the palette's stamp (`0ms`, `ease`) is not a choice to judge.
148
+ const time = cssMs(style['transitionDuration'], tokens) ?? (style['transitionDuration'] === undefined ? baseTime : null);
149
+ if (tokens && time !== 0) {
150
+ const timing = Object.fromEntries(['transitionDuration', 'transitionTimingFunction'].filter(k => style[k] !== undefined && style[k] !== '').map(k => [k, style[k] as string]));
151
+ for (const i of freeStyleIssues(timing, path, { tokens })) {
152
+ say(/Duration/.test(i.path) ? MotionRule.Duration : MotionRule.Easing, i.path, `${i.message} — a token, so reduced motion can collapse it`);
153
+ }
154
+ }
155
+ if (pointer && state === null && path.endsWith('.styleProps') && time !== null && time > UI_MOTION_MAX_MS) {
156
+ say(MotionRule.Duration, `${path}.transitionDuration`, `${time}ms — what a pointer drives plays under ${UI_MOTION_MAX_MS}ms`);
157
+ }
158
+ if (zooms && state === null && path.endsWith('.styleProps') && time !== null && time > PICTURE_HOVER_MAX_MS) {
159
+ say(MotionRule.Duration, `${path}.transitionDuration`, `${time}ms — a picture's hover zoom plays in ${PICTURE_HOVER_MAX_MS}ms at most`);
160
+ }
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Emil's rules over a page (its layout and the site's global parts), each refusal with its path. `tokens` (the look's
166
+ * rows) lets a CSS time be read through its token and asks that it BE one; without them only literal times are read.
167
+ */
168
+ export function designMotionIssues(doc: Pick<DesignDoc, 'layout' | 'globals'>, options: { tokens?: ReadonlyArray<DesignTokenLike> } = {}): MotionIssue[] {
169
+ const nodes = [...doc.layout, ...doc.globals];
170
+ const curves = new Set((options.tokens ?? []).filter(t => t.type === EASING_TOKEN_TYPE).map(t => t.name));
171
+ const named = new Set<string>();
172
+ const types = new Map<string, string>();
173
+ walkSerialized(nodes, node => types.set(node.id, node.type));
174
+ walkSerialized(nodes, node => rowsOf(node).forEach((row, i) => (row?.actions ?? []).forEach((a, j) => {
175
+ const at = `layout:${node.id}.interactions[${i}].actions[${j}]`;
176
+ if (curves.has(String(a.easing ?? ''))) named.add(`${at}.easing`);
177
+ if (entranceCapExempt(a, types.get(elementOf(node, a)), curves)) named.add(`${at}.duration`);
178
+ })));
179
+ const out: MotionIssue[] = composerAudit(nodes, named);
180
+ const say = (rule: MotionRule, path: string, message: string) => out.push({ code: DesignIssueCode.Motion, rule, path, message });
181
+ const parents = new Map<string, string[]>();
182
+ const moves: Move[] = [];
183
+ walkSerialized(nodes, (node, ancestors) => {
184
+ const at = `layout:${node.id}`;
185
+ parents.set(node.id, ancestors.map(a => a.id));
186
+ styleIssues(node, at, options.tokens, say);
187
+ rowsOf(node).forEach((row, i) => (row?.actions ?? []).forEach((a, j) => {
188
+ const path = `${at}.interactions[${i}].actions[${j}]`;
189
+ const trigger = String(row.trigger ?? '');
190
+ const d = ELEMENT_ACTION_DESCRIPTORS.find(x => x.type === a.type);
191
+ if (!d) { say(MotionRule.Catalog, `${path}.type`, `"${a.type}" is not an action of the catalog`); return; }
192
+ if (!actionOfferedUnder(d, trigger)) { say(MotionRule.Catalog, `${path}.type`, `${a.type} is not offered under "${trigger}" — ${(d.triggers ?? []).join(', ')}`); return; }
193
+ moves.push({ element: elementOf(node, a), path, trigger, action: a });
194
+ }));
195
+ });
196
+ const entering = new Map<string, Move>();
197
+ for (const m of moves) {
198
+ if (MOTION_POINTER_TRIGGERS.has(m.trigger) && isMotion(m) && m.element === pathNode(m.path) && !isEntrance(m) && !isExit(m) && ms(m) > UI_MOTION_MAX_MS) {
199
+ say(MotionRule.Duration, `${m.path}.duration`, `${ms(m)}ms — what a pointer drives on the element itself plays under ${UI_MOTION_MAX_MS}ms`);
200
+ }
201
+ if (!isEntrance(m)) continue;
202
+ if (m.action.type === INSTANT_REVEAL) say(MotionRule.Reduced, `${m.path}.type`, `"show" is the instant reveal a click opens — an entrance that plays by itself fades, rises or reveals (reduced motion keeps a fade; it has none)`);
203
+ const first = entering.get(m.element);
204
+ if (first) say(MotionRule.OneEntrance, `${m.path}.type`, `"${m.element}" already enters (${first.path}) — one entrance per element; put a second move on a wrapper`);
205
+ else entering.set(m.element, m);
206
+ }
207
+ for (const [element, m] of entering) {
208
+ const above = (parents.get(element) ?? []).find(id => entering.has(id));
209
+ if (above) say(MotionRule.Container, `${m.path}.type`, `"${element}" enters inside "${above}", which enters too — one entrance per container: either the container rises or what it holds staggers in`);
210
+ }
211
+ for (const m of moves.filter(isExit)) {
212
+ const enter = entering.get(m.element);
213
+ if (enter && ms(enter) > 0 && ms(m) >= ms(enter)) {
214
+ say(MotionRule.Exit, `${m.path}.duration`, `${ms(m)}ms leaving against ${ms(enter)}ms entering — an exit is faster, about ${Math.round(ms(enter) * LEAVE_SHARE)}ms`);
215
+ }
216
+ }
217
+ return out;
218
+ }
219
+
220
+ /**
221
+ * AD-D23: an entrance the 1,200 ms cap lets pass — a count (its duration is the digits' clock), or a picture's ambient
222
+ * settle: `zoomOut` on an Image or a Video, at most `PICTURE_SETTLE_MAX_MS`, on an ease-out curve (the look's curve by
223
+ * name or var(), or a cubic-bezier that starts fast).
224
+ */
225
+ function entranceCapExempt(a: Action, elementType: string | undefined, curves: ReadonlySet<string>): boolean {
226
+ if (a.type === COUNT_ACTION) return true;
227
+ if (a.type !== SETTLE_ACTION || !elementType || !MOTION_PICTURE_TYPES.has(elementType) || Number(a.duration ?? 0) > PICTURE_SETTLE_MAX_MS) return false;
228
+ const easing = String(a.easing ?? '').trim();
229
+ if (curves.has(easing) || /^var\(\s*--iox-ease-/.test(easing)) return true;
230
+ const m = CUBIC.exec(easing);
231
+ return !!m && Number(m[2]) > Number(m[1]);
232
+ }
233
+
234
+ /** The node id a move's path is written on. */
235
+ function pathNode(path: string): string {
236
+ return /^layout:([^.]*)/.exec(path)?.[1] ?? '';
237
+ }
238
+
239
+ /** One key per issue — what is new after an op is what that op did. */
240
+ export const motionIssueKey = (i: MotionIssue) => `${i.rule}|${i.path}|${i.message}`;
241
+
242
+ /** The rules' order, for a report: how many of each. */
243
+ export function motionIssueCounts(issues: ReadonlyArray<MotionIssue>): Partial<Record<MotionRule, number>> {
244
+ const out: Partial<Record<MotionRule, number>> = {};
245
+ for (const i of issues) out[i.rule] = (out[i.rule] ?? 0) + 1;
246
+ return out;
247
+ }