@vectoriox/iox-ui 5.156.0 → 5.158.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectoriox/iox-ui",
3
- "version": "5.156.0",
3
+ "version": "5.158.0",
4
4
  "peerDependencies": {
5
5
  "@angular/common": ">=20.0.0",
6
6
  "@angular/core": ">=20.0.0",
@@ -0,0 +1,375 @@
1
+ import {
2
+ DesignTokenLike, elementStyleById, parseHexColor, ResolvedMode, resolveTokenValues, wcagContrastRatio,
3
+ } from '@vectoriox/iox-ui/design-core';
4
+ import {
5
+ FREE_ELEMENT_STYLES, FREE_HOLDERS, FREE_LEAD_ROLE, FREE_MOVES, FREE_PHONE_LAYERS, FREE_WORD_TYPES, FreeLayer, FreeNode,
6
+ FreeNodeType, FreePage, FreePictures, FreePurpose, FreeStyle, FreeTrigger, walkFree,
7
+ } from './free-wire';
8
+ import { factIssues, PlanWordContext, WrittenText } from './plan-words';
9
+ import { PageSectionPlan } from './site-plan.model';
10
+ import { PathIssue } from './shape-check';
11
+
12
+ /**
13
+ * THE FREE PAGE'S JUDGE (award plan §11.4 gates 1 + 2, FS3): every reason a free page may not be stamped, path first,
14
+ * in words the model can act on in its one repair. It judges SAFETY, LAW and TRUTH — never taste (R-H18): what is the
15
+ * look's stays a token (R-H1), a phone layer exists where a phone needs one (R-H4), no fact is invented (R-H6, the ONE
16
+ * `factIssues`), only what exists is named (R-H2), the words read on their ground (R-H12), and the answer says which of
17
+ * the owner's words it followed (R-H17). A place the fall back gave to a ready-made section (`readyMade`) is the plan's,
18
+ * not the model's: it is skipped, and the page rules that section would answer are relaxed. Pure.
19
+ */
20
+
21
+ export enum FreeIssueCode {
22
+ /** The page's structure: section count, ids, nesting, h1, lead, a closing action, a phone layout. */
23
+ Structure = 'structure',
24
+ /** A word node's words or element style. */
25
+ Words = 'words',
26
+ /** A style: a property outside the list, a value that is not one plain value, a side that is not start / end. */
27
+ Style = 'style',
28
+ /** A value the look owns written as something other than its token. */
29
+ Token = 'token',
30
+ /** A node a phone cannot hold as written, with no phone layer. */
31
+ Phone = 'phone',
32
+ /** A move: not the product's, two on a node, on the wrong node. */
33
+ Motion = 'motion',
34
+ /** A fact the owner never gave, a material id, a slot or a link that does not exist. */
35
+ Content = 'content',
36
+ /** Words that do not read on their ground (AA). */
37
+ Contrast = 'contrast',
38
+ /** The followed line is missing or quotes none of the owner's words. */
39
+ Prompt = 'prompt',
40
+ }
41
+
42
+ export type FreeIssue = PathIssue<FreeIssueCode>;
43
+
44
+ /** What a placed slot is, and the options it may carry (a list's mix words). */
45
+ export interface FreeSlotOffer {
46
+ kind: 'list' | 'form';
47
+ /** The list alias (`list:<alias>`) or the forms-core preset (`form:<preset>`). */
48
+ ref: string;
49
+ opts?: ReadonlyArray<string>;
50
+ }
51
+
52
+ export interface FreeJudgeContext {
53
+ /** The studio's token rows (with their types) — what a token reference may name and what it resolves to. */
54
+ tokens: ReadonlyArray<DesignTokenLike>;
55
+ /** The modes the site shows (the look's mode, or both under `auto`). */
56
+ modes?: ReadonlyArray<ResolvedMode>;
57
+ /** The material the page may place, by id. */
58
+ material: Readonly<Record<string, { kind: 'image' | 'video' }>>;
59
+ /** The slots this page was offered, by slot word (`list:projects`). */
60
+ slots?: Readonly<Record<string, FreeSlotOffer>>;
61
+ /** The site's page routes a Button may go to. */
62
+ pages: ReadonlyArray<string>;
63
+ /** Facts: the owner's own, and the owner's texts (the prompt, the material's words) — what a number may come from. */
64
+ facts: PlanWordContext['facts'];
65
+ known?: ReadonlyArray<string>;
66
+ avoidWords?: ReadonlyArray<string>;
67
+ /** The words the reading took from the owner's prompt — the followed line quotes one (R-H17). */
68
+ said?: ReadonlyArray<string>;
69
+ /** Home: a business with videos plays one there. */
70
+ home?: boolean;
71
+ }
72
+
73
+ /** A free page is this many sections. */
74
+ export const FREE_SECTIONS = { min: 4, max: 9 } as const;
75
+ /** Above this, a node needs its own phone layer. */
76
+ export const FREE_PHONE_LIMITS = { width: 340, fontSize: 44, turn: 8 } as const;
77
+ /** WCAG AA: words, and large words (display, h1, h2). */
78
+ export const FREE_CONTRAST = { text: 4.5, large: 3 } as const;
79
+ const LARGE_STYLES: ReadonlyArray<string> = ['display', 'h1', 'h2'];
80
+
81
+ /** The style properties whose value is the LOOK's: a token of this type, or one of the listed plain words. */
82
+ export const FREE_TOKEN_PROPS: Readonly<Record<string, string>> = {
83
+ color: 'color', backgroundColor: 'color', borderColor: 'color', outlineColor: 'color', textDecorationColor: 'color',
84
+ fontFamily: 'font', borderRadius: 'radius', boxShadow: 'shadow', transitionDuration: 'duration', transitionTimingFunction: 'easing',
85
+ };
86
+ const TOKEN_PLAIN: Readonly<Record<string, ReadonlyArray<string>>> = {
87
+ color: ['transparent', 'currentColor', 'inherit'], font: ['inherit'], radius: ['0', '0px', '50%'], shadow: ['none'], duration: [], easing: [],
88
+ };
89
+ /** A colour token may be either of these token types. */
90
+ const COLOUR_TYPES: ReadonlyArray<string> = ['color', 'paint'];
91
+ /** The free properties: geometry, arrangement, type scale and rhythm, clipping, blending. */
92
+ export const FREE_STYLE_PROPS: ReadonlyArray<string> = [
93
+ 'display', 'position', 'top', 'bottom', 'insetInlineStart', 'insetInlineEnd', 'zIndex', 'order',
94
+ 'width', 'minWidth', 'maxWidth', 'height', 'minHeight', 'maxHeight', 'aspectRatio', 'overflow',
95
+ 'margin', 'marginTop', 'marginBottom', 'marginInlineStart', 'marginInlineEnd', 'marginInline', 'marginBlock',
96
+ 'padding', 'paddingTop', 'paddingBottom', 'paddingInlineStart', 'paddingInlineEnd', 'paddingInline', 'paddingBlock',
97
+ 'gridTemplateColumns', 'gridTemplateRows', 'gridColumn', 'gridRow', 'gap', 'rowGap', 'columnGap',
98
+ 'flexDirection', 'flexWrap', 'flex', 'alignItems', 'alignContent', 'justifyContent', 'alignSelf', 'justifySelf', 'placeItems', 'placeSelf',
99
+ 'fontSize', 'fontWeight', 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'fontStyle', 'textWrap', 'whiteSpace',
100
+ 'translateX', 'translateY', 'rotate', 'scaleX', 'scaleY', 'transformOrigin',
101
+ 'clipPath', 'opacity', 'mixBlendMode', 'objectFit', 'objectPosition', 'borderWidth', 'borderStyle', 'filter', 'backdropFilter',
102
+ ];
103
+ /** A hover changes position, scale, turn, opacity or a colour token — never layout (Emil: transform / opacity only). */
104
+ export const FREE_HOVER_PROPS: ReadonlyArray<string> = ['translateX', 'translateY', 'scaleX', 'scaleY', 'rotate', 'opacity', 'color', 'backgroundColor', 'borderColor', 'boxShadow'];
105
+
106
+ const PHYSICAL = /^(left|right|marginLeft|marginRight|paddingLeft|paddingRight|borderLeft.*|borderRight.*|insetLeft|insetRight)$/;
107
+ const UNSAFE = /[;{}<>\\]|!important|url\s*\(|expression|@import|javascript:/i;
108
+ const LITERAL_COLOUR = /#[0-9a-f]{3,8}\b|\b(rgb|rgba|hsl|hsla|oklch|oklab|lab|lch|hwb)\s*\(/i;
109
+ const NAMED_COLOUR = /\b(white|black|red|blue|green|yellow|orange|purple|pink|gray|grey|gold|navy|teal|beige|ivory|cream)\b/i;
110
+ const TOKEN_REF = /var\(\s*--iox-([a-z0-9-]+)\s*(?:,[^)]*)?\)/g;
111
+ const ONE_TOKEN = /^var\(--iox-([a-z0-9-]+)\)$/;
112
+ const COLOUR_MIX = /^color-mix\(in (oklab|srgb), var\(--iox-[a-z0-9-]+\) \d{1,3}%, transparent\)$/;
113
+ const ANCHOR = /^#[a-z][\w-]*$/;
114
+ /** FS-T5: a size relative to the WINDOW's width (vw and its kin) — on the canvas, a transformed frame, the window is not
115
+ * the page. A size relative to the width is `cqi` (the page's / section's inline size), and only `cqi`. */
116
+ const WINDOW_WIDTH_UNIT = /(-?\d*\.?\d+)(?:[dsl]?vw|[dsl]?vi|[dsl]?vmin|[dsl]?vmax)(?![a-z])/i;
117
+ const OTHER_CQ_UNIT = /(-?\d*\.?\d+)(?:cqw|cqh|cqb|cqmin|cqmax)(?![a-z])/i;
118
+ const A_NUMBER = /^\D{0,3}\d[\d,.]*\D{0,3}$/;
119
+ /** The ground a page paints when no node does. */
120
+ const PAGE_GROUND = 'page-bg';
121
+
122
+ const tokensIn = (v: string) => [...v.matchAll(TOKEN_REF)].map(m => m[1]);
123
+ const oneToken = (v: unknown) => ONE_TOKEN.exec(String(v ?? '').trim())?.[1];
124
+ const px = (v: unknown) => { const m = /^(-?[\d.]+)px$/.exec(String(v ?? '').trim()); return m ? Number(m[1]) : null; };
125
+ const columnsOf = (v: unknown) => {
126
+ const s = String(v ?? '').trim();
127
+ const rep = /repeat\(\s*(\d+)/.exec(s);
128
+ return rep ? Number(rep[1]) : s.split(/\s+(?![^(]*\))/).filter(Boolean).length;
129
+ };
130
+ const hasPhoneLayer = (n: FreeNode) => FREE_PHONE_LAYERS.some(bp => Object.keys(n.responsive?.[bp as FreeLayer] ?? {}).length > 0);
131
+
132
+ /** One style map against the rules: a known property, one clean value, the look's token where the look owns it. */
133
+ export function freeStyleIssues(style: FreeStyle | undefined, path: string, ctx: Pick<FreeJudgeContext, 'tokens'>): FreeIssue[] {
134
+ const out: FreeIssue[] = [];
135
+ const types = new Map(ctx.tokens.map(t => [t.name, t.type]));
136
+ const say = (code: FreeIssueCode, prop: string, message: string) => out.push({ code, path: `${path}.${prop}`, message });
137
+ for (const [prop, raw] of Object.entries(style ?? {})) {
138
+ const v = String(raw).trim();
139
+ const kind = FREE_TOKEN_PROPS[prop];
140
+ if (PHYSICAL.test(prop)) { say(FreeIssueCode.Style, prop, 'write sides as start / end (insetInlineStart, marginInlineEnd …) — the site also runs right to left'); continue; }
141
+ if (!kind && !FREE_STYLE_PROPS.includes(prop)) { say(FreeIssueCode.Style, prop, 'not a style property this language has'); continue; }
142
+ if (!v || UNSAFE.test(v)) { say(FreeIssueCode.Style, prop, 'a value is one plain value — no url(), no ; { } !important'); continue; }
143
+ if (prop === 'textAlign' && /^(left|right)$/.test(v)) { say(FreeIssueCode.Style, prop, 'start | end | center'); continue; }
144
+ const win = WINDOW_WIDTH_UNIT.exec(v);
145
+ if (win) { say(FreeIssueCode.Style, prop, `"${win[0]}" follows the window, not the page — a size relative to the width is cqi: ${win[1]}cqi`); continue; }
146
+ const cq = OTHER_CQ_UNIT.exec(v);
147
+ if (cq) { say(FreeIssueCode.Style, prop, `"${cq[0]}" — a size relative to the width is cqi only: ${cq[1]}cqi`); continue; }
148
+ if (LITERAL_COLOUR.test(v) || (kind === 'color' && NAMED_COLOUR.test(v))) { say(FreeIssueCode.Token, prop, 'a literal colour — colours are the look\'s tokens: var(--iox-<colour token>)'); continue; }
149
+ if (!kind) continue;
150
+ const named = tokensIn(v);
151
+ const plain = TOKEN_PLAIN[kind].includes(v);
152
+ const mixed = kind === 'color' && COLOUR_MIX.test(v);
153
+ if (!plain && !mixed && !(named.length === 1 && v === `var(--iox-${named[0]})`)) {
154
+ const words = TOKEN_PLAIN[kind].length ? ` or ${TOKEN_PLAIN[kind].join(' / ')}` : '';
155
+ say(FreeIssueCode.Token, prop, `the look owns this — var(--iox-<${kind} token>)${words}${kind === 'color' ? ', or color-mix(in oklab, var(--iox-…) N%, transparent)' : ''}`);
156
+ continue;
157
+ }
158
+ for (const name of named) {
159
+ const type = types.get(name);
160
+ const fits = kind === 'color' ? COLOUR_TYPES.includes(type ?? '') : type === kind;
161
+ if (!fits) say(FreeIssueCode.Token, prop, `--iox-${name} is ${type ? `a ${type} token` : 'not a token of this look'} — a ${kind} token belongs here`);
162
+ }
163
+ }
164
+ return out;
165
+ }
166
+
167
+ /** Every reason a free page may not be stamped (gate 1), contrast included (gate 2's tree half). */
168
+ export function checkFree(page: FreePage, ctx: FreeJudgeContext): FreeIssue[] {
169
+ return judgeFree(page, ctx, false);
170
+ }
171
+
172
+ /**
173
+ * FS-D19 Basic: ONE free signature section on a page otherwise made of the plan's ready-made sections. The answer is a
174
+ * free page holding one Section; it is judged in its place (`at`) among the plan's sections — so the page rules hold
175
+ * for the page as the visitor sees it (a ready-made opening carries the h1 and the lead, a ready-made close the action;
176
+ * the section count is the plan's) — and every issue is said against the answer (`sections[0]…`), for its one repair.
177
+ */
178
+ export function checkFreeSection(answer: FreePage, ctx: FreeJudgeContext, place: { plan: ReadonlyArray<PageSectionPlan>; at: number }): FreeIssue[] {
179
+ const sections = Array.isArray(answer?.sections) ? answer.sections : [];
180
+ if (sections.length !== 1 || place.at < 0 || place.at >= place.plan.length) {
181
+ return [{ code: FreeIssueCode.Structure, path: 'sections', message: `a signature section is ONE Section (this answer has ${sections.length})` }];
182
+ }
183
+ const page = freeSignaturePage(answer, place.plan, place.at);
184
+ const here = `sections[${place.at}]`;
185
+ return judgeFree(page, ctx, true).map(i => ({ ...i, path: i.path === here || i.path.startsWith(`${here}.`) ? `sections[0]${i.path.slice(here.length)}` : i.path }));
186
+ }
187
+
188
+ /** The page a signature section stands in: the plan's ready-made sections, the free one at `at` in place of that one. */
189
+ export function freeSignaturePage(answer: FreePage, plan: ReadonlyArray<PageSectionPlan>, at: number): FreePage {
190
+ return {
191
+ ...answer,
192
+ sections: plan.map((p, i) => (i === at ? answer.sections[0] : { id: `ready-${i}`, type: FreeNodeType.Section, styleProps: {}, readyMade: { at: i, pattern: p.pattern } })),
193
+ };
194
+ }
195
+
196
+ function judgeFree(page: FreePage, ctx: FreeJudgeContext, signature: boolean): FreeIssue[] {
197
+ const issues: FreeIssue[] = [];
198
+ const say = (code: FreeIssueCode, path: string, message: string) => issues.push({ code, path, message });
199
+ const sections = Array.isArray(page?.sections) ? page.sections : [];
200
+ if (!signature && (sections.length < FREE_SECTIONS.min || sections.length > FREE_SECTIONS.max)) say(FreeIssueCode.Structure, 'sections', `a page is ${FREE_SECTIONS.min} to ${FREE_SECTIONS.max} sections (this one has ${sections.length})`);
201
+ const ready = (i: number) => !!sections[i]?.readyMade;
202
+ const walked = walkFree(sections).filter(w => !ready(w.section));
203
+ const ids = new Set(walkFree(sections).map(w => w.node.id));
204
+ const seen = new Set<string>();
205
+ const texts: WrittenText[] = [];
206
+ let h1 = 0;
207
+ for (const { node, path, up } of walked) {
208
+ if (!Object.values(FreeNodeType).includes(node.type)) { say(FreeIssueCode.Structure, path, `"${node.type}" is not a node type — ${Object.values(FreeNodeType).join(', ')}`); continue; }
209
+ if (!node.id || seen.has(node.id)) say(FreeIssueCode.Structure, path, node.id ? `the id "${node.id}" is used twice` : 'every node needs its own id');
210
+ seen.add(node.id);
211
+ if ((node.type === FreeNodeType.Section) !== (up.length === 0)) say(FreeIssueCode.Structure, path, up.length ? 'a Section sits at the top of the page only — use a Container inside' : 'the top of the page holds Sections only');
212
+ if (node.type === FreeNodeType.Section && !Object.values(FreePurpose).includes(node.purpose as FreePurpose)) say(FreeIssueCode.Structure, path, `a section says what it is for — purpose: ${Object.values(FreePurpose).join(' | ')}`);
213
+ if (node.children?.length && !FREE_HOLDERS.includes(node.type)) say(FreeIssueCode.Structure, path, `a ${node.type} holds no children`);
214
+ const styles = FREE_ELEMENT_STYLES[node.type] ?? [];
215
+ if (node.elementStyle && !styles.includes(node.elementStyle)) say(FreeIssueCode.Words, `${path}.elementStyle`, styles.length ? `"${node.elementStyle}" is not a style a ${node.type} wears — ${styles.join(', ')}` : `a ${node.type} wears no element style`);
216
+
217
+ if (FREE_WORD_TYPES.includes(node.type)) {
218
+ if (!String(node.text ?? '').trim()) say(FreeIssueCode.Words, `${path}.text`, 'its words are missing');
219
+ else texts.push({ path: `${path}.text`, text: String(node.text) });
220
+ if (!node.elementStyle) say(FreeIssueCode.Words, `${path}.elementStyle`, `a ${node.type} wears one of the look's element styles (${styles.join(', ')}) and changes what it needs on top`);
221
+ if (node.type === FreeNodeType.Heading) {
222
+ if (!Number.isInteger(node.level) || node.level! < 1 || node.level! > 4) say(FreeIssueCode.Words, `${path}.level`, 'a Heading is level 1 to 4');
223
+ if (node.level === 1) h1++;
224
+ }
225
+ if (node.type === FreeNodeType.Button && !ctx.pages.includes(node.href ?? '') && !(ANCHOR.test(node.href ?? '') && ids.has(node.href!.slice(1)))) {
226
+ say(FreeIssueCode.Content, `${path}.href`, `a button goes to a page of this site (${ctx.pages.join(', ')}) or to a section of this page (#id)`);
227
+ }
228
+ }
229
+ if (node.role && (node.role !== FREE_LEAD_ROLE || node.type !== FreeNodeType.Heading)) say(FreeIssueCode.Structure, `${path}.role`, 'role "lead" is for the heading a visitor reads first');
230
+ if (node.type === FreeNodeType.Image || node.type === FreeNodeType.Video) {
231
+ const m = ctx.material[node.src ?? ''];
232
+ if (!m) say(FreeIssueCode.Content, `${path}.src`, `"${node.src ?? ''}" is not in the material — use an id from the list`);
233
+ else if ((node.type === FreeNodeType.Video) !== (m.kind === 'video')) say(FreeIssueCode.Content, `${path}.src`, `"${node.src}" is a${m.kind === 'image' ? 'n image' : ' video'} — ${node.type === FreeNodeType.Video ? 'a Video plays a video' : 'an Image shows a picture'}`);
234
+ }
235
+ if (node.type === FreeNodeType.Slot) {
236
+ const offer = ctx.slots?.[node.slot ?? ''];
237
+ if (!offer) say(FreeIssueCode.Content, `${path}.slot`, `"${node.slot ?? ''}" is not a part this page may place — ${Object.keys(ctx.slots ?? {}).join(', ') || 'none'}`);
238
+ else for (const [k, o] of (node.opts ?? []).entries()) if (!(offer.opts ?? []).includes(o)) say(FreeIssueCode.Content, `${path}.opts[${k}]`, `"${o}" is not how this part may show — ${(offer.opts ?? []).join(', ') || 'no options'}`);
239
+ } else if (node.slot || node.opts?.length) say(FreeIssueCode.Structure, path, 'only a Slot places a part');
240
+
241
+ // styles, layer by layer
242
+ issues.push(...freeStyleIssues(node.styleProps, `${path}.styleProps`, ctx));
243
+ for (const [bp, style] of Object.entries(node.responsive ?? {})) {
244
+ if (!(Object.values(FreeLayer) as string[]).includes(bp)) { say(FreeIssueCode.Style, `${path}.responsive.${bp}`, `not a width — ${Object.values(FreeLayer).join(', ')}`); continue; }
245
+ issues.push(...freeStyleIssues(style, `${path}.responsive.${bp}`, ctx));
246
+ }
247
+ for (const prop of Object.keys(node.hover ?? {})) if (!FREE_HOVER_PROPS.includes(prop)) say(FreeIssueCode.Style, `${path}.hover.${prop}`, `a hover changes position, scale, turn, opacity or a colour token only (${FREE_HOVER_PROPS.join(', ')}) — never layout`);
248
+ issues.push(...freeStyleIssues(Object.fromEntries(Object.entries(node.hover ?? {}).filter(([p]) => FREE_HOVER_PROPS.includes(p))), `${path}.hover`, ctx));
249
+
250
+ // the one move
251
+ if (node.move) {
252
+ const spec = FREE_MOVES[node.move.trigger]?.[node.move.action];
253
+ if (!spec) say(FreeIssueCode.Motion, `${path}.move`, `under ${node.move.trigger} one of: ${Object.keys(FREE_MOVES[node.move.trigger] ?? {}).join(', ')}`);
254
+ else {
255
+ const value = spec.param ? node.move.params?.[spec.param] : undefined;
256
+ if (spec.param && value !== undefined && !spec.values?.includes(value)) say(FreeIssueCode.Motion, `${path}.move`, `${spec.param} is one of ${spec.values?.join(', ')}`);
257
+ if (node.move.action === 'revealText' && node.type !== FreeNodeType.Heading && node.type !== FreeNodeType.Text) say(FreeIssueCode.Motion, `${path}.move`, 'revealText lights words — on a Heading or a Text');
258
+ if (node.move.action === 'countUp' && !A_NUMBER.test(String(node.text ?? '').trim())) say(FreeIssueCode.Motion, `${path}.move`, 'countUp counts a number — on a Heading or Text whose words ARE a number the owner gave');
259
+ if (node.move.trigger === FreeTrigger.Scroll && up.length === 0) say(FreeIssueCode.Motion, `${path}.move`, 'a whole section never travels with the scroll — move a layer inside it');
260
+ }
261
+ }
262
+
263
+ // the phone: anything a 390px screen cannot hold as written needs its own layer
264
+ const base = node.styleProps ?? {};
265
+ const needs: string[] = [];
266
+ if (base['gridTemplateColumns'] && columnsOf(base['gridTemplateColumns']) >= 2) needs.push('its columns');
267
+ if (base['position'] === 'absolute') needs.push('its absolute place');
268
+ if ((px(base['width']) ?? 0) > FREE_PHONE_LIMITS.width || (px(base['minWidth']) ?? 0) > FREE_PHONE_LIMITS.width) needs.push('its fixed width');
269
+ if ((px(base['fontSize']) ?? 0) > FREE_PHONE_LIMITS.fontSize) needs.push('its type size (or write it as clamp(min, cqi, max))');
270
+ if (base['rotate'] && FREE_WORD_TYPES.includes(node.type) && Math.abs(parseFloat(base['rotate'])) > FREE_PHONE_LIMITS.turn) needs.push('its turn');
271
+ if (needs.length && !hasPhoneLayer(node)) say(FreeIssueCode.Phone, `${path}.responsive`, `needs a phone layer for ${needs.join(', ')}`);
272
+ }
273
+
274
+ // facts: the ONE judge, numbers included (R-H6)
275
+ for (const i of factIssues(texts, { avoidWords: ctx.avoidWords ?? [], facts: ctx.facts, known: ctx.known, numbers: true, quotes: true })) say(FreeIssueCode.Content, i.path, i.message);
276
+
277
+ // the page
278
+ const openingReady = ready(0);
279
+ if (openingReady ? h1 !== 0 : h1 !== 1) say(FreeIssueCode.Structure, 'sections', openingReady ? 'the opening carries the page\'s level-1 heading — use level 2 or lower' : `a page has exactly one Heading of level 1 (this one has ${h1})`);
280
+ if (sections[0] && !openingReady && !walkFree([sections[0]]).some(w => w.node.role === FREE_LEAD_ROLE)) say(FreeIssueCode.Structure, 'sections[0]', 'the first section names its lead — role "lead" on the heading a visitor reads first');
281
+ sections.forEach((s, i) => {
282
+ if (!ready(i) && !walkFree([s]).some(w => hasPhoneLayer(w.node))) say(FreeIssueCode.Phone, `sections[${i}]`, 'a phone layout is required — at least one node of every section carries a phone layer');
283
+ });
284
+ const last = sections.length - 1;
285
+ if (last >= 0 && !ready(last) && !walkFree([sections[last]]).some(w => w.node.type === FreeNodeType.Button)) say(FreeIssueCode.Structure, `sections[${last}]`, 'the page ends on something to do — a Button in the last section');
286
+ const hasVideos = Object.values(ctx.material).some(m => m.kind === 'video');
287
+ if (ctx.home && hasVideos && !sections.some(s => s.readyMade) && !walked.some(w => w.node.type === FreeNodeType.Video)) say(FreeIssueCode.Content, 'sections', 'this business has videos — the home page plays at least one (a Video node)');
288
+ if (!(Object.values(FreePictures) as string[]).includes(page?.pictures)) say(FreeIssueCode.Structure, 'pictures', `one word: ${Object.values(FreePictures).join(', ')}`);
289
+ issues.push(...followedIssues(page, ctx));
290
+ issues.push(...freeContrastIssues(page, ctx));
291
+ return issues;
292
+ }
293
+
294
+ /**
295
+ * THE OWNER'S PROMPT LEADS (§11.4a, R-H17): the followed line is there, and — when the reading took words from the prompt
296
+ * — it quotes at least one AS WRITTEN. Never a judgement of taste.
297
+ */
298
+ export function followedIssues(page: Pick<FreePage, 'read'>, ctx: Pick<FreeJudgeContext, 'said'>): FreeIssue[] {
299
+ const line = String(page?.read?.followed ?? '').trim();
300
+ if (!line) return [{ code: FreeIssueCode.Prompt, path: 'read.followed', message: 'say in one line the owner can read which of their words this page followed' }];
301
+ const said = (ctx.said ?? []).map(w => String(w).trim()).filter(Boolean);
302
+ const lower = line.toLowerCase();
303
+ if (said.length && !said.some(w => lower.includes(w.toLowerCase()))) {
304
+ return [{ code: FreeIssueCode.Prompt, path: 'read.followed', message: `the line names none of the owner's own words — quote at least one as they wrote it (${said.slice(0, 6).join(', ')})` }];
305
+ }
306
+ return [];
307
+ }
308
+
309
+ /** The token a node's words are painted in: its own colour, else its element style's; `inherit` reads up the tree. */
310
+ function inkOf(node: FreeNode, up: ReadonlyArray<FreeNode>): string | undefined {
311
+ for (const n of [node, ...[...up].reverse()]) {
312
+ const v = n.styleProps?.['color'] ?? elementStyleById(n.elementStyle)?.base['color'];
313
+ if (v === undefined || v === 'inherit' || v === 'currentColor') continue;
314
+ return oneToken(v);
315
+ }
316
+ return 'text';
317
+ }
318
+
319
+ /**
320
+ * The tokens a node's words may sit on, nearest first: its own ground, then each ancestor's, then the page's. `null` in
321
+ * the list is a ground that is no single token (a colour-mix): nothing past it can be judged from tokens.
322
+ */
323
+ function groundsOf(node: FreeNode, up: ReadonlyArray<FreeNode>): Array<string | null> {
324
+ const out: Array<string | null> = [];
325
+ for (const n of [node, ...[...up].reverse()]) {
326
+ const v = n.styleProps?.['backgroundColor'] ?? elementStyleById(n.elementStyle)?.base['backgroundColor'];
327
+ if (v === undefined || v === 'transparent') continue;
328
+ out.push(oneToken(v) ?? null);
329
+ }
330
+ return [...out, PAGE_GROUND];
331
+ }
332
+
333
+ /** A resolved ground that paints nothing (`transparent`, an alpha of 0) lets the one behind it show. */
334
+ const CLEAR = /^(transparent|rgba?\([^)]*,\s*0(\.0+)?\s*\)|#[0-9a-f]{6}00)$/i;
335
+
336
+ /** The hex the words sit on in one mode, or null when it cannot be told from tokens (left to the real pixels). */
337
+ function groundHex(grounds: ReadonlyArray<string | null>, values: Readonly<Record<string, string>>): { token: string; hex: string } | null {
338
+ for (const token of grounds) {
339
+ if (token === null) return null;
340
+ const value = String(values[token] ?? '').trim();
341
+ if (CLEAR.test(value)) continue;
342
+ return parseHexColor(value) ? { token, hex: value } : null;
343
+ }
344
+ return null;
345
+ }
346
+
347
+ /**
348
+ * THE TREE PAIR CHECK (R-H12, gate 2's tree half — `auditDesignContrast` judges the look, not a tree): each Heading's and
349
+ * Text's ink token against the ground token of the nearest painted node, resolved in every mode the site shows, AA
350
+ * (4.5, 3 for display / h1 / h2). A pair that is not two hex tokens (a colour-mix, a picture behind) is left to the
351
+ * real-pixel check. A Button paints its own pair through its element style, which the look's audit already covers.
352
+ */
353
+ export function freeContrastIssues(page: FreePage, ctx: Pick<FreeJudgeContext, 'tokens' | 'modes'>): FreeIssue[] {
354
+ const out: FreeIssue[] = [];
355
+ const resolved = (ctx.modes?.length ? ctx.modes : (['light'] as ResolvedMode[])).map(mode => ({ mode, values: resolveTokenValues(ctx.tokens, mode) }));
356
+ for (const { node, path, up, section } of walkFree(page?.sections ?? [])) {
357
+ if (page.sections[section]?.readyMade) continue;
358
+ if (node.type !== FreeNodeType.Heading && node.type !== FreeNodeType.Text) continue;
359
+ const ink = inkOf(node, up);
360
+ if (!ink) continue;
361
+ const grounds = groundsOf(node, up);
362
+ const need = LARGE_STYLES.includes(node.elementStyle ?? '') ? FREE_CONTRAST.large : FREE_CONTRAST.text;
363
+ for (const { mode, values } of resolved) {
364
+ const a = values[ink];
365
+ const ground = groundHex(grounds, values);
366
+ if (!a || !ground || !parseHexColor(a)) continue;
367
+ const ratio = wcagContrastRatio(a, ground.hex);
368
+ if (ratio < need) {
369
+ out.push({ code: FreeIssueCode.Contrast, path: `${path}.styleProps.color`, message: `--iox-${ink} on --iox-${ground.token} is ${ratio.toFixed(1)}:1 in ${mode} (needs ${need}) — another colour token for the words or the ground` });
370
+ break;
371
+ }
372
+ }
373
+ }
374
+ return out;
375
+ }
@@ -2,9 +2,9 @@ import { columnWordOf, DesignChoices, designTokenRows, parseCssColour, presetCho
2
2
  import { ParallaxDepth } from '@vectoriox/iox-ui/scene-core';
3
3
 
4
4
  import {
5
- LAYOUT_COLUMN_MENDED, LAYOUT_HIDDEN_OPACITY, LAYOUT_OPERATED, LAYOUT_TEXT_KINDS, LayoutBandMove, LayoutColour, LayoutDepth, LayoutDial, LayoutEnter, LayoutGalleryList, LayoutIssue, LayoutListShape, LayoutIssueCode, LayoutLayer, LayoutLayerKind, LayoutMend, LayoutMendKind,
5
+ LAYOUT_COLUMN_MENDED, LAYOUT_HIDDEN_OPACITY, LAYOUT_OPERATED, LAYOUT_TEXT_KINDS, LayoutBandMove, LayoutButtonVariant, LayoutColour, LayoutDepth, LayoutDial, LayoutEnter, LayoutGalleryList, LayoutIssue, LayoutListShape, LayoutIssueCode, LayoutLayer, LayoutLayerKind, LayoutMend, LayoutMendKind,
6
6
  LayoutGivenAway, LayoutListArrange, LayoutListArrive, LayoutListHover, LayoutListItem, LayoutListMix, LayoutListPhone, LayoutPage, LayoutPhotoSource,
7
- LayoutRole, LayoutScrubRefusal, LayoutSection, LayoutSectionKind, LayoutSourceChoice, LayoutTrackProp, parseLayoutPhotoId,
7
+ LayoutRole, LayoutScrubRefusal, LayoutSection, LayoutSectionKind, LayoutSize, LayoutSourceChoice, LayoutTrackProp, parseLayoutPhotoId,
8
8
  } from './layout-language';
9
9
  import { layoutScrubTakes } from './text-scroll';
10
10
  import { layoutColumnsOffered } from './layout-wire';
@@ -488,13 +488,16 @@ function examineLayout(page: LayoutPage, ctx: CheckLayoutContext, carried: Layou
488
488
  else if (l.variant !== undefined && !inList(V.buttonVariants, l.variant)) add(LayoutIssueCode.Value, `${lp}.variant`, V.buttonVariants.join(' | '));
489
489
  const text = String(l.text ?? (l.items ?? []).join(' '));
490
490
  const maxChars = l.size ? L.maxChars[l.size] : undefined;
491
- if (maxChars !== undefined && text.length > maxChars) add(LayoutIssueCode.Reading, `${lp}.text`, `${text.length} characters is too long for size ${l.size} (≤ ${maxChars})`);
491
+ // iox-ui#131: a near miss — one size step down holds them — is the composer's to settle.
492
+ const smaller = placed ? sizeStepDown(l, s, i, judgeColumnPx, daring) : null;
493
+ const sizeMend = smaller ? { kind: LayoutMendKind.Size as const, layer: lp, size: smaller } : undefined;
494
+ if (maxChars !== undefined && text.length > maxChars) add(LayoutIssueCode.Reading, `${lp}.text`, `${text.length} characters is too long for size ${l.size} (≤ ${maxChars})`, sizeMend);
492
495
  if ((l.size === 'm' || l.size === 's') && text.length > LIM.longTextChars && span(l.col) > LIM.longTextColumns) {
493
496
  add(LayoutIssueCode.Reading, `${lp}.col`, `long text is never wider than ${LIM.longTextColumns} columns`);
494
497
  }
495
498
  if (placed && isText(l) && l.size && l.size !== 'screen' && text && !layoutTextFits(l, s, l.size, judgeColumnPx)) {
496
499
  const lines = Math.floor(boxPx(l.col, l.row, s, judgeColumnPx).h / (L.sizePx[l.size] * LAYOUT_LINE_HEIGHT));
497
- add(LayoutIssueCode.Reading, `${lp}.row`, `${text.length} characters at ${l.size} do not fit a box of ${span(l.col)} columns × ${span(l.row)} rows (about ${Math.max(0, lines)} line${lines === 1 ? '' : 's'}) — give it more rows or columns, or fewer words`);
500
+ add(LayoutIssueCode.Reading, `${lp}.row`, `${text.length} characters at ${l.size} do not fit a box of ${span(l.col)} columns × ${span(l.row)} rows (about ${Math.max(0, lines)} line${lines === 1 ? '' : 's'}) — give it more rows or columns, or fewer words`, sizeMend);
498
501
  }
499
502
  if (l.size === 'screen' || l.size === 'xxl') huge++;
500
503
  if (l.size === 'screen') {
@@ -540,7 +543,8 @@ function examineLayout(page: LayoutPage, ctx: CheckLayoutContext, carried: Layou
540
543
  add(LayoutIssueCode.Motion, `${lp}.enter`, 'decoration only fades ("fade" or "none")', { kind: LayoutMendKind.Fade, layer: lp });
541
544
  }
542
545
  if ((l.motion ?? []).some(m => m.prop !== LayoutTrackProp.Opacity)) add(LayoutIssueCode.Motion, `${lp}.motion`, 'decoration only fades — opacity tracks only');
543
- if (l.depth === 'front') add(LayoutIssueCode.Motion, `${lp}.depth`, 'decoration never runs ahead — back or mid');
546
+ // iox-ui#131: settled alone — a decoration sent back glides as the floor asks (the salon's and store's pages fell on it).
547
+ if (l.depth === 'front') add(LayoutIssueCode.Motion, `${lp}.depth`, 'decoration never runs ahead — back or mid', { kind: LayoutMendKind.Depth, layers: [lp] });
544
548
  }
545
549
  if (l.kind === LayoutLayerKind.Shape && !layoutShapeHasPurpose(s, j)) {
546
550
  add(LayoutIssueCode.Look, lp, 'a shape that is there for nothing — not a rule (one row high), a band, a frame for a picture or a ground for words, and it does not move: an empty box on the page',
@@ -647,11 +651,15 @@ function examineLayout(page: LayoutPage, ctx: CheckLayoutContext, carried: Layou
647
651
  if (preset === 'lead' && !ctx.takesLeads) add(LayoutIssueCode.Content, `${lp}.form.preset`, 'this business takes no leads — use contact or booking');
648
652
  }
649
653
  if (f?.channel?.href) add(LayoutIssueCode.Content, `${lp}.form.channel.href`, 'no link — the second channel is filled from the owner\'s facts');
650
- if (span(l.col) < LIM.formColumns) add(LayoutIssueCode.Structure, `${lp}.col`, `a form needs at least ${LIM.formColumns} columns`);
654
+ if (span(l.col) < LIM.formColumns) {
655
+ const col = formWidening(s, j, LIM.formColumns, lastCol);
656
+ add(LayoutIssueCode.Structure, `${lp}.col`, `a form needs at least ${LIM.formColumns} columns`, col ? { kind: LayoutMendKind.Widen, layer: lp, col } : undefined);
657
+ }
651
658
  if (groundPhoto || layers.some(o => o !== l && isPictured(o) && overlaps(o, l))) add(LayoutIssueCode.Reading, lp, 'a form never sits on a photo');
652
659
  }
653
660
  if (l.kind === LayoutLayerKind.Button) {
654
- accentUses++;
661
+ // A secondary button wears the ink and a line, never the accent (iox-ui#131): it does not count.
662
+ if (l.variant !== LayoutButtonVariant.Secondary) accentUses++;
655
663
  if (!l.to) add(LayoutIssueCode.Content, `${lp}.to`, 'a button leads somewhere: a section id or a page route');
656
664
  else if (!ids.has(l.to) && !routes.includes(l.to)) {
657
665
  add(LayoutIssueCode.Content, `${lp}.to`, `"${l.to}" is not a section id${routes.length ? ` or one of the routes ${routes.join(' | ')}` : ''}`);
@@ -792,9 +800,11 @@ function examineLayout(page: LayoutPage, ctx: CheckLayoutContext, carried: Layou
792
800
  if (marquees > LIM.marquees) add(LayoutIssueCode.Structure, 'sections', `${marquees} marquees — at most ${LIM.marquees}`);
793
801
  const minDepth = Math.max(0, (look && inList(LIM.calmLooks, look.id) ? LIM.depthLayersCalm : LIM.depthLayers) - carried.layered);
794
802
  if (layered < minDepth) {
803
+ // iox-ui#131: the floor follows what the page can hold — every layer that may glide without its words meeting
804
+ // another's takes a depth; a page with none left to give is not refused for it (the salon's Home fell back whole on
805
+ // "4 layers glide — at least 6" with nothing more that could glide).
795
806
  const glide = glideChoice(sections, minDepth - layered);
796
- add(LayoutIssueCode.Motion, 'sections', `${layered} layers glide by depth or drift — at least ${minDepth}`,
797
- glide.length === minDepth - layered ? { kind: LayoutMendKind.Depth, layers: glide } : undefined);
807
+ if (glide.length) add(LayoutIssueCode.Motion, 'sections', `${layered} layers glide by depth or drift — at least ${minDepth}`, { kind: LayoutMendKind.Depth, layers: glide });
798
808
  }
799
809
  if (daring) {
800
810
  const d = LIM.daring;
@@ -813,8 +823,9 @@ function examineLayout(page: LayoutPage, ctx: CheckLayoutContext, carried: Layou
813
823
  if (look) {
814
824
  if (accentUses > look.accentMax) {
815
825
  const bands = paint ? accentBandMoves(sections, ground => paint.colours[ground], (name, text) => colourHex(name, text)) : [];
826
+ const buttons = accentButtonSteps(sections);
816
827
  add(LayoutIssueCode.Look, 'sections', `the accent is on ${accentUses} layers (a button counts, an accent ground twice) — the ${look.id} look allows ${look.accentMax}`,
817
- { kind: LayoutMendKind.Accent, over: accentUses - look.accentMax, ...(bands.length ? { bands } : {}) });
828
+ { kind: LayoutMendKind.Accent, over: accentUses - look.accentMax, ...(bands.length ? { bands } : {}), ...(buttons.length ? { buttons } : {}) });
818
829
  }
819
830
  if (limits.hugeMax !== undefined && huge > limits.hugeMax) add(LayoutIssueCode.Look, 'sections', `${huge} xxl/screen layers — the ${look.id} look allows ${limits.hugeMax}`);
820
831
  if (limits.centerMax !== undefined && textLayers && centered / textLayers > limits.centerMax) {
@@ -950,6 +961,52 @@ export function auditLayoutMotion(nodes: ReadonlyArray<SerializedNode>): LayoutI
950
961
  return issues;
951
962
  }
952
963
 
964
+ /** The sizes a near miss may step down from, and the step (iox-ui#131): one step, never below a heading's reading size. */
965
+ const SIZE_STEP_DOWN: Readonly<Partial<Record<`${LayoutSize}`, `${LayoutSize}`>>> = { [LayoutSize.Xxl]: LayoutSize.Xl, [LayoutSize.Xl]: LayoutSize.L, [LayoutSize.L]: LayoutSize.M };
966
+
967
+ /**
968
+ * iox-ui#131: the size one step down at which a text layer's words fit its box and the size still holds them — the near
969
+ * miss the composer settles. Never the opening's display (a daring page's one large thing — its own rule), never a word set
970
+ * to the screen. Null: the model's.
971
+ */
972
+ function sizeStepDown(l: LayoutLayer, s: LayoutSection, si: number, columnPx: number, daring: boolean): `${LayoutSize}` | null {
973
+ if (!isText(l) || !l.size) return null;
974
+ const to = SIZE_STEP_DOWN[l.size as `${LayoutSize}`];
975
+ // A daring page's opening keeps its display (the daring rule asks one); any other opening's heading may step too.
976
+ if (!to || (daring && si === 0 && l.size === LayoutSize.Xxl) || l.kind === LayoutLayerKind.Word) return null;
977
+ const max = L.maxChars[to as keyof typeof L.maxChars];
978
+ if (max !== undefined && String(l.text ?? (l.items ?? []).join(" ")).length > max) return null;
979
+ return layoutTextFits(l, s, to, columnPx) ? to : null;
980
+ }
981
+
982
+ /**
983
+ * iox-ui#131: the columns a form narrower than `need` takes by widening into empty cells of its own rows (toward the end,
984
+ * then the start; never over another layer, never past the grid). Null: no room — the model's.
985
+ */
986
+ function formWidening(s: LayoutSection, li: number, need: number, lastCol: number): [number, number] | null {
987
+ const l = s.layers[li];
988
+ let [c0, c1] = l.col;
989
+ const free = (col: [number, number]) => s.layers.every((o, j) => j === li || !overlaps({ ...l, col }, o));
990
+ while (c1 - c0 < need && c1 + 1 <= lastCol && free([c0, c1 + 1])) c1++;
991
+ while (c1 - c0 < need && c0 - 1 >= 1 && free([c0 - 1, c1])) c0--;
992
+ return c1 - c0 >= need ? [c0, c1] : null;
993
+ }
994
+
995
+ /**
996
+ * The primary buttons the accent mend may step to secondary (iox-ui#131), least important first: later sections first,
997
+ * never the main call to action (the first button that reaches the business — a form's section or a contact word — else
998
+ * the first button). A secondary one already paints no accent.
999
+ */
1000
+ function accentButtonSteps(sections: ReadonlyArray<LayoutSection>): string[] {
1001
+ const buttons = sections.flatMap((s, si) => (s.layers ?? []).map((l, li) => ({ l, si, li })).filter(({ l }) => l.kind === LayoutLayerKind.Button));
1002
+ const formIds = new Set(sections.filter(s => s.layers?.some(l => l.kind === LayoutLayerKind.Form)).map(s => s.id));
1003
+ const main = buttons.find(({ l }) => formIds.has(String(l.to)) || CONTACT_WORDS.test(`${l.to ?? ''} ${l.text ?? ''}`)) ?? buttons[0];
1004
+ return buttons
1005
+ .filter(b => b !== main && b.l.variant !== LayoutButtonVariant.Secondary)
1006
+ .sort((a, b) => b.si - a.si || b.li - a.li)
1007
+ .map(({ si, li }) => `sections[${si}].layers[${li}]`);
1008
+ }
1009
+
953
1010
  /** Most important first: which layers take a depth when too few glide (iox-ui#63). */
954
1011
  const GLIDE_ROLE_ORDER: ReadonlyArray<`${LayoutRole}` | undefined> = [LayoutRole.Lead, LayoutRole.Support, undefined, LayoutRole.Decoration];
955
1012
 
@@ -1139,11 +1196,30 @@ export function mendLayout(page: LayoutPage, issues: ReadonlyArray<LayoutIssue>)
1139
1196
  const accented = (next.sections ?? []).flatMap((s, si) => (s.layers ?? []).map(l => ({ l, si })))
1140
1197
  .filter(({ l }) => isText(l) && l.color === LayoutColour.Accent)
1141
1198
  .sort((a, b) => MEND_ROLE_ORDER.indexOf(a.l.role) - MEND_ROLE_ORDER.indexOf(b.l.role) || b.si - a.si);
1142
- // words first; a band (an accent ground counts twice) only for what the words cannot give back
1143
- const bands = accented.length >= mend.over ? 0 : Math.ceil((mend.over - accented.length) / ACCENT_GROUND_USES);
1144
- if (bands > (mend.bands?.length ?? 0)) continue;
1199
+ // words first; a band (an accent ground counts twice) only for what the words cannot give back; then a primary
1200
+ // button that is not the main call to action steps to secondary (iox-ui#131)
1201
+ const available = mend.bands?.length ?? 0;
1202
+ let bands = accented.length >= mend.over ? 0 : Math.ceil((mend.over - accented.length) / ACCENT_GROUND_USES);
1203
+ let steps: LayoutLayer[] = [];
1204
+ if (bands > available) {
1205
+ bands = available;
1206
+ const need = mend.over - accented.length - available * ACCENT_GROUND_USES;
1207
+ steps = (mend.buttons ?? []).map(layerAt).filter((b): b is LayoutLayer => !!b).slice(0, need);
1208
+ if (steps.length < need) continue;
1209
+ }
1145
1210
  for (const band of (mend.bands ?? []).slice(0, bands)) next.sections[band.section].ground = band.ground;
1146
- for (const { l } of accented.slice(0, Math.max(0, mend.over - bands * ACCENT_GROUND_USES))) delete l.color;
1211
+ for (const { l } of accented.slice(0, Math.max(0, mend.over - bands * ACCENT_GROUND_USES - steps.length))) delete l.color;
1212
+ for (const b of steps) b.variant = LayoutButtonVariant.Secondary;
1213
+ mended.push(issue);
1214
+ } else if (mend?.kind === LayoutMendKind.Size) {
1215
+ const layer = layerAt(mend.layer);
1216
+ if (!layer) continue;
1217
+ layer.size = mend.size;
1218
+ mended.push(issue);
1219
+ } else if (mend?.kind === LayoutMendKind.Widen) {
1220
+ const layer = layerAt(mend.layer);
1221
+ if (!layer) continue;
1222
+ layer.col = [...mend.col] as [number, number];
1147
1223
  mended.push(issue);
1148
1224
  } else if (mend?.kind === LayoutMendKind.Depth) {
1149
1225
  const layers = mend.layers.map(layerAt);
@@ -1220,3 +1296,36 @@ export function mendLayout(page: LayoutPage, issues: ReadonlyArray<LayoutIssue>)
1220
1296
  }
1221
1297
  return { page: mended.length ? next : page, mended };
1222
1298
  }
1299
+
1300
+ /** How many times the composer settles a page: a mend can make the next one possible (an accent band moved, then a
1301
+ * depth that no longer meets it), never more. */
1302
+ export const LAYOUT_SETTLE_PASSES = 3;
1303
+
1304
+ /**
1305
+ * iox-ui#131: settle a page as far as the composer can — the mends of what the gate finds, then the gate again on the
1306
+ * mended page, until nothing more is settled (at most `LAYOUT_SETTLE_PASSES`). `issuesOf` is the whole gate the page is
1307
+ * judged by (static + sameness). What is left after it is the model's, or the section fallback's. Pure.
1308
+ */
1309
+ export function settleLayoutPage(page: LayoutPage, issuesOf: (page: LayoutPage) => ReadonlyArray<LayoutIssue>): { page: LayoutPage; mended: LayoutIssue[] } {
1310
+ let current = page;
1311
+ const mended: LayoutIssue[] = [];
1312
+ for (let pass = 0; pass < LAYOUT_SETTLE_PASSES; pass++) {
1313
+ const settled = mendLayout(current, issuesOf(current));
1314
+ if (!settled.mended.length) break;
1315
+ current = settled.page;
1316
+ mended.push(...settled.mended);
1317
+ }
1318
+ return { page: current, mended };
1319
+ }
1320
+
1321
+ /** iox-ui#131: at most this many things left after the one repair is a near miss — asked once more, not given away. */
1322
+ export const LAYOUT_NEAR_MISS = 2;
1323
+
1324
+ /**
1325
+ * iox-ui#131: a repaired page that came close — at most `LAYOUT_NEAR_MISS` things left, and fewer than the check found
1326
+ * before the repair (the model is converging, not wandering) — gets a second repair before its sections are given away.
1327
+ * Pure: the service and a replay ask the same question.
1328
+ */
1329
+ export function layoutNearMiss(before: ReadonlyArray<LayoutIssue>, after: ReadonlyArray<LayoutIssue>): boolean {
1330
+ return after.length > 0 && after.length <= LAYOUT_NEAR_MISS && after.length < before.length;
1331
+ }