@vectoriox/iox-ui 5.120.0 → 5.122.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.120.0",
3
+ "version": "5.122.0",
4
4
  "peerDependencies": {
5
5
  "@angular/common": ">=20.0.0",
6
6
  "@angular/core": ">=20.0.0",
@@ -4,8 +4,10 @@ import type { SerializedNode } from '@vectoriox/iox-ui/generation-core';
4
4
 
5
5
  import { FieldChange } from './field-edits';
6
6
  import { FieldEdit } from './fields-schema';
7
+ import { SectionChange, SectionEdit } from './page-sections';
7
8
  import { PageChangeOp, SchemeEdit, SizeEdit, StyleChange, StyleEdit } from './page-style';
8
9
  import { WordChange, WordEdit } from './page-words';
10
+ import { SiteLookChange, SiteLookEdit } from './site-look';
9
11
  import { ContentRecord, clipText } from './summarize-item';
10
12
  import { AssistScope, AssistSurface, CommitKind, EditFamily, SURFACES, SurfaceStatus } from './surfaces';
11
13
 
@@ -65,12 +67,13 @@ export interface AssistTurnRequest {
65
67
  }
66
68
 
67
69
  /** What a turn proposes, per family: a field's value (`fields`), a part's words (`words`), an element's style or a section's scheme (`style`). */
68
- export type AssistEdit = FieldEdit | WordEdit | StyleEdit | SchemeEdit | SizeEdit;
70
+ export type AssistEdit = FieldEdit | WordEdit | StyleEdit | SchemeEdit | SizeEdit | SectionEdit | SiteLookEdit;
69
71
 
70
72
  /** What a turn changed, as the card says it. */
71
- export type AssistChange = FieldChange | WordChange | StyleChange;
73
+ export type AssistChange = FieldChange | WordChange | StyleChange | SectionChange | SiteLookChange;
72
74
 
73
- const isLookChange = (c: AssistChange): c is StyleChange => 'op' in c && (c.op === PageChangeOp.Style || c.op === PageChangeOp.Scheme || c.op === PageChangeOp.Size);
75
+ const isLookChange = (c: AssistChange): c is StyleChange | SectionChange | SiteLookChange => 'op' in c
76
+ && (c.op === PageChangeOp.Style || c.op === PageChangeOp.Scheme || c.op === PageChangeOp.Size || c.op === PageChangeOp.Section || c.op === PageChangeOp.Look);
74
77
 
75
78
  /** POST's 202 answer. */
76
79
  export interface AssistTurnAccepted {
@@ -65,6 +65,8 @@ export enum AssistIssueCode {
65
65
  InventedFact = 'inventedFact',
66
66
  /** A word this site must not use. */
67
67
  AvoidWord = 'avoidWord',
68
+ /** A look whose colours fail the contrast audit in a mode the site is worn in (family `look`, R4). */
69
+ Contrast = 'contrast',
68
70
  }
69
71
 
70
72
  export interface AssistIssue {
@@ -1,22 +1,32 @@
1
+ import type { DesignChoices } from '@vectoriox/iox-ui/design-core';
1
2
  import { SerializedNode } from '@vectoriox/iox-ui/generation-core';
2
3
 
3
4
  import { AssistIssue } from './brief';
4
5
  import { applyWordEdits, SummarizedPage, WordChange, WordEdit, WordEditContext } from './page-words';
5
- import { applyStyleEdits, BaselineStyles, isSchemeEdit, isSizeEdit, isStyleEdit, LookEdit, SchemeEdit, SizeEdit, StyleChange, StyleEdit } from './page-style';
6
+ import { applySectionEdits, isSectionEdit, SectionChange, SectionEdit, SectionEditContext } from './page-sections';
7
+ import { applyStyleEdits, BaselineStyles, isSchemeEdit, isSizeEdit, isStyleEdit, NodeStyleEdit, SchemeEdit, SizeEdit, StyleChange, StyleEdit } from './page-style';
8
+ import { applyLookEdits, isSiteLookEdit, SiteLookChange, SiteLookEdit } from './site-look';
6
9
 
7
10
  /**
8
- * Surface S1's answer as ONE thing (AI2b, AI2c): the edits of every family a page turn routed to — words (`{ handle, value }`),
9
- * styles (`{ handle, style }`), schemes (`{ handle, scheme }`), size steps (`{ handle, axis, step }`) — applied in that
10
- * order on a copy, all or none. The server
11
- * checks each family as it is asked; the builder's trial applies the turn's edits through this, so both read one rule.
11
+ * Surface S1's answer as ONE thing (AI2b–AI2d): the edits of every family a page turn routed to — words (`{ handle, value }`),
12
+ * styles (`{ handle, style }`), schemes (`{ handle, scheme }`), size steps (`{ handle, axis, step }`), sections
13
+ * (`{ add | remove | move | swap }`) — applied in that order on a copy, all or none. Sections go last: every handle the
14
+ * other families name is read on the page as it stood. The site's look (`{ look }`, AI2e) changes no node: it is applied
15
+ * on `ctx.look` (the look the site wears) and comes back as `look`, the choices the trial wears. The server checks each family as it is asked; the builder's trial
16
+ * applies the turn's edits through this, so both read one rule.
12
17
  */
13
- export type PageEdit = WordEdit | StyleEdit | SchemeEdit | SizeEdit;
14
- export type PageChange = WordChange | StyleChange;
18
+ export type PageEdit = WordEdit | StyleEdit | SchemeEdit | SizeEdit | SectionEdit | SiteLookEdit;
19
+ export type PageChange = WordChange | StyleChange | SectionChange | SiteLookChange;
15
20
 
16
21
  export interface PageEditContext extends Omit<WordEditContext, 'handles' | 'never'> {
17
- readonly summary: Pick<SummarizedPage, 'handles' | 'looks'> & { readonly brief: { readonly rules: { readonly never: WordEditContext['never'] } } };
22
+ readonly summary: Pick<SummarizedPage, 'handles' | 'looks'> & Partial<Pick<SummarizedPage, 'sections'>> & { readonly brief: { readonly rules: { readonly never: WordEditContext['never'] } } };
18
23
  /** The builder's registry baseline; default the saved shape's (`serializedBaselineStyles`). */
19
24
  readonly baseline?: BaselineStyles;
25
+ /** Family `sections`: the studio's name and pages (what the palette composes with) and the builder's fresh ids. */
26
+ readonly sectionInput?: SectionEditContext['input'];
27
+ readonly newId?: SectionEditContext['newId'];
28
+ /** Family `look`: the look the site wears (its stored choices); absent = the default look. */
29
+ readonly look?: DesignChoices | null;
20
30
  }
21
31
 
22
32
  export interface PageEditsOutcome {
@@ -24,17 +34,28 @@ export interface PageEditsOutcome {
24
34
  readonly result: SerializedNode[];
25
35
  readonly changes: ReadonlyArray<PageChange>;
26
36
  readonly issues: ReadonlyArray<AssistIssue>;
37
+ /** Family `look`: the choices the turn's look wears — present only when the turn changed the look. */
38
+ readonly look?: DesignChoices;
27
39
  }
28
40
 
29
41
  const isWordEdit = (e: PageEdit): e is WordEdit => 'value' in e;
42
+ const isNodeStyleEdit = (e: PageEdit): e is NodeStyleEdit => !isWordEdit(e) && !isSectionEdit(e) && !isSiteLookEdit(e) && (isStyleEdit(e) || isSchemeEdit(e) || isSizeEdit(e));
30
43
 
31
44
  export function applyPageEdits(layout: ReadonlyArray<SerializedNode>, edits: ReadonlyArray<PageEdit>, ctx: PageEditContext): PageEditsOutcome {
32
45
  const words = applyWordEdits(layout, edits.filter(isWordEdit), {
33
46
  handles: ctx.summary.handles, never: ctx.summary.brief.rules.never, sentence: ctx.sentence, words: ctx.words,
34
47
  });
35
- const looks = edits.filter((e): e is LookEdit => !isWordEdit(e) && (isStyleEdit(e) || isSchemeEdit(e) || isSizeEdit(e)));
36
- const style = applyStyleEdits(words.result, looks, { looks: ctx.summary.looks, baseline: ctx.baseline });
37
- const issues = [...words.issues, ...style.issues];
48
+ const style = applyStyleEdits(words.result, edits.filter(isNodeStyleEdit), { looks: ctx.summary.looks, baseline: ctx.baseline });
49
+ const sectionEdits = edits.filter(isSectionEdit);
50
+ const sections = sectionEdits.length
51
+ ? applySectionEdits(style.result, sectionEdits, { sections: ctx.summary.sections ?? {}, input: ctx.sectionInput, newId: ctx.newId })
52
+ : { result: style.result, changes: [], issues: [] };
53
+ const lookEdits = edits.filter(isSiteLookEdit);
54
+ const look = lookEdits.length ? applyLookEdits(ctx.look, lookEdits) : null;
55
+ const issues = [...words.issues, ...style.issues, ...sections.issues, ...(look?.issues ?? [])];
38
56
  if (issues.length) return { ok: false, result: JSON.parse(JSON.stringify(layout)) as SerializedNode[], changes: [], issues };
39
- return { ok: true, result: style.result, changes: [...words.changes, ...style.changes], issues: [] };
57
+ return {
58
+ ok: true, result: sections.result, changes: [...words.changes, ...style.changes, ...sections.changes, ...(look?.changes ?? [])], issues: [],
59
+ ...(look?.changes.length ? { look: look.choices } : {}),
60
+ };
40
61
  }
@@ -0,0 +1,371 @@
1
+ import {
2
+ composeSection, jsonClosedObject, jsonListOf, jsonOneOf, JsonSchema, jsonText, patternById, SectionInput, SerializedNode, walkSerialized,
3
+ } from '@vectoriox/iox-ui/generation-core';
4
+
5
+ import { assertAssistBudget } from './budget';
6
+ import { AssistIssue, AssistIssueCode } from './brief';
7
+ import { PageChangeOp } from './page-style';
8
+
9
+ /**
10
+ * Surface S1 (the builder, this page), family `sections` (ai-assist-plan AI2d; ai-session-panel-plan `addSection` /
11
+ * `removeSection` / `moveSection` / `swapPattern`): a section is added, removed, moved or swapped for another — and every
12
+ * section Ask adds is a library pattern stamped by generation-core's `composeSection`, the SAME recipe the builder palette's
13
+ * ready-made sections and the composer use (R-H9). The model names a pattern from a closed list and a place by handle;
14
+ * it never writes a node. The same pure functions run on the server (the check on a copy) and in the builder (the trial).
15
+ */
16
+
17
+ /**
18
+ * The library patterns Ask may add or swap to — those `composeSection` stamps on their own with no Site Plan behind
19
+ * them. Not offered: headers and footers (globals), lists and products (they need a content source — a Pages & data
20
+ * change), Scenes and the owner's film (the look's motion decides them, and a page holds one).
21
+ */
22
+ export const ASK_SECTION_PATTERNS: ReadonlyArray<string> = [
23
+ 'hero.split', 'hero.centered', 'hero.full-bleed-media', 'hero.stacked-editorial',
24
+ 'proof.logo-strip', 'proof.stat-row', 'proof.testimonial-single',
25
+ 'feature.triad', 'feature.alternating-rows', 'feature.icon-list', 'feature.tabbed',
26
+ 'story.long-form', 'story.timeline', 'story.quote-break',
27
+ 'cta.banner', 'cta.split-form', 'contact.simple', 'faq.accordion', 'pricing.tiers',
28
+ ];
29
+
30
+ /** Where an added or moved section goes when it is first on the page. */
31
+ export const SECTION_START = 'start';
32
+
33
+ /** The library pattern a section root was stamped from, by its label (the composer names a root by its pattern). */
34
+ export function sectionPatternOf(root: Pick<SerializedNode, 'label'>): string | undefined {
35
+ const label = (root.label ?? '').split(' · ')[0].trim();
36
+ if (!label) return undefined;
37
+ return ASK_SECTION_PATTERNS.find(id => patternById(id)?.label === label);
38
+ }
39
+
40
+ /** The patterns Ask offers, as the model and the owner read them: id → its name ("Hero — words centred"). */
41
+ export function askSectionPatternNames(): Record<string, string> {
42
+ return Object.fromEntries(ASK_SECTION_PATTERNS.map(id => [id, patternById(id)?.label ?? id]));
43
+ }
44
+
45
+ /** A section of the page the family may name: its root, its name, and whether it is in the focus (may be removed, moved, swapped). */
46
+ export interface SectionTarget {
47
+ readonly id: string;
48
+ readonly label: string;
49
+ readonly focus: boolean;
50
+ }
51
+
52
+ /** Every section of the page by handle (`s0`…) — `after` may name any of them; only focus ones may be changed. */
53
+ export type SectionMap = Readonly<Record<string, SectionTarget>>;
54
+
55
+ export enum SectionsAnswerKey {
56
+ Add = 'add',
57
+ Remove = 'remove',
58
+ Move = 'move',
59
+ Swap = 'swap',
60
+ Note = 'note',
61
+ }
62
+
63
+ /**
64
+ * The strict format of family `sections` — ONE request: `add [{pattern, after}]`, `remove [{handle}]`,
65
+ * `move [{handle, after}]`, `swap [{handle, pattern}]`, `note`. Handles are enums of the page's sections (the focus's for
66
+ * what may change), patterns an enum of {@link ASK_SECTION_PATTERNS}. Whether an op makes sense is the check's.
67
+ */
68
+ export function sectionsJsonSchema(sections: SectionMap): { parts: JsonSchema[]; handles: string[][] } {
69
+ const all = Object.keys(sections);
70
+ const focus = all.filter(h => sections[h].focus);
71
+ const places = [SECTION_START, ...all];
72
+ const patterns = jsonOneOf([...ASK_SECTION_PATTERNS]);
73
+ const properties: Record<string, JsonSchema> = {
74
+ [SectionsAnswerKey.Add]: {
75
+ ...jsonListOf(jsonClosedObject({ pattern: patterns, after: jsonOneOf(places) }, ['pattern', 'after'])),
76
+ description: 'A new section from the library, placed after a section (or at the start); [] adds none.',
77
+ },
78
+ };
79
+ if (focus.length) {
80
+ properties[SectionsAnswerKey.Remove] = {
81
+ ...jsonListOf(jsonClosedObject({ handle: jsonOneOf(focus) }, ['handle'])),
82
+ description: 'A section taken off the page; [] removes none.',
83
+ };
84
+ properties[SectionsAnswerKey.Move] = {
85
+ ...jsonListOf(jsonClosedObject({ handle: jsonOneOf(focus), after: jsonOneOf(places) }, ['handle', 'after'])),
86
+ description: 'A section moved to after another (or to the start); [] moves none.',
87
+ };
88
+ properties[SectionsAnswerKey.Swap] = {
89
+ ...jsonListOf(jsonClosedObject({ handle: jsonOneOf(focus), pattern: patterns }, ['handle', 'pattern'])),
90
+ description: 'A section redrawn as another library section, its words and pictures carried over; [] swaps none.',
91
+ };
92
+ }
93
+ properties[SectionsAnswerKey.Note] = { ...jsonText(), description: 'One short line for the owner on what changed, or what needs them.' };
94
+ const part = jsonClosedObject(properties, Object.keys(properties));
95
+ assertAssistBudget('sections', [part]);
96
+ return { parts: [part], handles: [focus] };
97
+ }
98
+
99
+ export interface SectionAdd { readonly add: string; readonly after: string }
100
+ export interface SectionRemove { readonly remove: string }
101
+ export interface SectionMove { readonly move: string; readonly after: string }
102
+ export interface SectionSwap { readonly swap: string; readonly pattern: string }
103
+
104
+ /** Any edit of family `sections`. */
105
+ export type SectionEdit = SectionAdd | SectionRemove | SectionMove | SectionSwap;
106
+
107
+ export const isSectionEdit = (e: object): e is SectionEdit => 'add' in e || 'remove' in e || 'move' in e || 'swap' in e;
108
+
109
+ const listOf = (answer: unknown, key: SectionsAnswerKey): Array<Record<string, unknown>> => {
110
+ const list = answer && typeof answer === 'object' ? (answer as Record<string, unknown>)[key] : undefined;
111
+ return Array.isArray(list) ? list.filter((x): x is Record<string, unknown> => !!x && typeof x === 'object') : [];
112
+ };
113
+ const str = (v: unknown) => String(v ?? '');
114
+
115
+ /** The answer → the edits it makes. */
116
+ export function decodeSectionsAnswers(answers: ReadonlyArray<unknown>): SectionEdit[] {
117
+ return answers.flatMap(answer => [
118
+ ...listOf(answer, SectionsAnswerKey.Swap).map(x => ({ swap: str(x['handle']), pattern: str(x['pattern']) })),
119
+ ...listOf(answer, SectionsAnswerKey.Remove).map(x => ({ remove: str(x['handle']) })),
120
+ ...listOf(answer, SectionsAnswerKey.Move).map(x => ({ move: str(x['handle']), after: str(x['after']) })),
121
+ ...listOf(answer, SectionsAnswerKey.Add).map(x => ({ add: str(x['pattern']), after: str(x['after']) })),
122
+ ]);
123
+ }
124
+
125
+ export enum SectionChangeKind {
126
+ Add = 'add',
127
+ Remove = 'remove',
128
+ Move = 'move',
129
+ Swap = 'swap',
130
+ }
131
+
132
+ export interface SectionChange {
133
+ readonly op: PageChangeOp.Section;
134
+ readonly kind: SectionChangeKind;
135
+ /** The section's handle (`s2`), or `new` for one added. */
136
+ readonly handle: string;
137
+ /** The node the card outlines — the new root of an added or swapped section, the moved one; a removed one's id (gone). */
138
+ readonly nodeId: string;
139
+ readonly label: string;
140
+ /** The pattern added or swapped to. */
141
+ readonly pattern?: string;
142
+ /** Where it stood / stands, or what it was / is, as the owner reads it. */
143
+ readonly before: string;
144
+ readonly after: string;
145
+ /** A swap: the owner's words and pictures the new section had no place for (still in the old one — Discard keeps it). */
146
+ readonly notPlaced?: number;
147
+ }
148
+
149
+ export interface SectionEditContext {
150
+ readonly sections: SectionMap;
151
+ /** The studio's name and pages, as the palette composes with (`composeSection`). */
152
+ readonly input?: SectionInput;
153
+ /** A fresh node id (the builder's); default a stable `ask-s<n>` no node of the page holds. */
154
+ readonly newId?: () => string;
155
+ }
156
+
157
+ export interface SectionEditsOutcome {
158
+ readonly ok: boolean;
159
+ readonly result: SerializedNode[];
160
+ readonly changes: ReadonlyArray<SectionChange>;
161
+ readonly issues: ReadonlyArray<AssistIssue>;
162
+ }
163
+
164
+ /** Why a section cannot be redrawn as another: it holds what a swap would lose (a form, words from content, a Scene). */
165
+ function swapBlocker(root: SerializedNode): string | null {
166
+ let blocker: string | null = null;
167
+ walkSerialized([root], n => {
168
+ if (blocker) return;
169
+ if (n.role === 'scene') blocker = 'it plays as a Scene';
170
+ else if (n.type === 'Form') blocker = 'it holds a form';
171
+ else if (n.type === 'Repeater' || (n.bindings ?? []).length) blocker = 'its words come from your content';
172
+ });
173
+ return blocker;
174
+ }
175
+
176
+ /** A section's parts a swap carries over, in reading order, by kind. */
177
+ enum CarryKind { Eyebrow = 'eyebrow', Heading = 'heading', Text = 'text', Button = 'button', Image = 'image' }
178
+
179
+ /** A button the owner's words and link travel in — never a tab, a price switch or a cart button (their recipe's own). */
180
+ const CARRIED_BUTTON_STYLES: ReadonlySet<string> = new Set(['button-primary', 'button-secondary', 'button-ghost']);
181
+ /** Words that belong to their recipe, not the owner's copy: a figure ("40+", a price), a badge — left where they are. */
182
+ const KEPT_TEXT_STYLES: ReadonlySet<string> = new Set(['price', 'badge-label']);
183
+
184
+ function carryKind(n: SerializedNode): CarryKind | null {
185
+ if (n.elementStyle === 'eyebrow' && (n.type === 'Heading' || n.type === 'Text')) return CarryKind.Eyebrow;
186
+ if (n.type === 'Heading') return CarryKind.Heading;
187
+ if (n.type === 'Text') return KEPT_TEXT_STYLES.has(n.elementStyle ?? '') ? null : CarryKind.Text;
188
+ if (n.type === 'Image') return CarryKind.Image;
189
+ return null;
190
+ }
191
+
192
+ function carryParts(root: SerializedNode): Record<CarryKind, SerializedNode[]> {
193
+ const out: Record<CarryKind, SerializedNode[]> = { eyebrow: [], heading: [], text: [], button: [], image: [] };
194
+ const visit = (n: SerializedNode) => {
195
+ if (n.type === 'ButtonBlock') {
196
+ if (CARRIED_BUTTON_STYLES.has(n.elementStyle ?? '')) out.button.push(n);
197
+ return;
198
+ }
199
+ const kind = carryKind(n);
200
+ if (kind) out[kind].push(n);
201
+ for (const c of n.children ?? []) visit(c);
202
+ };
203
+ for (const c of root.children ?? []) visit(c);
204
+ return out;
205
+ }
206
+
207
+ const BUTTON_LINK_PROPS = ['tag', 'linkType', 'href', 'pageRoute', 'url', 'target'];
208
+ const labelOf = (button: SerializedNode) => (button.children ?? []).find(c => c.type === 'Text');
209
+
210
+ /** The owner's words and pictures, placed into the new section part for part (kind by kind, in order); how many found no place. */
211
+ function carryOver(from: SerializedNode, to: SerializedNode): number {
212
+ const old = carryParts(from);
213
+ const fresh = carryParts(to);
214
+ let notPlaced = 0;
215
+ for (const kind of Object.values(CarryKind)) {
216
+ old[kind].forEach((source, i) => {
217
+ const target = fresh[kind][i];
218
+ if (!target) {
219
+ const hasContent = kind === CarryKind.Image ? !!source.props['src'] : true;
220
+ if (hasContent) notPlaced++;
221
+ return;
222
+ }
223
+ if (kind === CarryKind.Image) {
224
+ if (!source.props['src']) return;
225
+ target.props = { ...target.props, src: source.props['src'], alt: source.props['alt'] ?? target.props['alt'] };
226
+ } else if (kind === CarryKind.Button) {
227
+ const words = labelOf(source);
228
+ const into = labelOf(target);
229
+ if (words && into) into.props = { ...into.props, content: words.props['content'] };
230
+ const link = Object.fromEntries(BUTTON_LINK_PROPS.filter(k => k in source.props).map(k => [k, source.props[k]]));
231
+ target.props = { ...target.props, ...link };
232
+ } else {
233
+ target.props = { ...target.props, content: source.props['content'] };
234
+ }
235
+ });
236
+ }
237
+ return notPlaced;
238
+ }
239
+
240
+ /** A stable id no node of the page holds (nor any of its parts' derived ids, `<id>-0-1`). */
241
+ function stableIds(layout: ReadonlyArray<SerializedNode>): () => string {
242
+ const taken: string[] = [];
243
+ walkSerialized([...layout], n => taken.push(n.id));
244
+ let n = 0;
245
+ return () => {
246
+ let id: string;
247
+ do id = `ask-s${++n}`; while (taken.some(t => t === id || t.startsWith(`${id}-`)));
248
+ taken.push(id);
249
+ return id;
250
+ };
251
+ }
252
+
253
+ const patternName = (id: string) => patternById(id)?.label ?? id;
254
+
255
+ /**
256
+ * Family `sections`, applied — the SAME check on the server and in the builder. All or none; never mutates its input.
257
+ * Swaps redraw in place, then removals, moves and additions, each placed by the ORIGINAL handles. Refused (re-asked once
258
+ * by the server, never repaired): a handle not on the page or not in the focus, a pattern not offered, a section given two
259
+ * changes, a place that is the section itself or one removed in the same answer, a swap of a section holding a form,
260
+ * content-bound words or a Scene.
261
+ */
262
+ export function applySectionEdits(
263
+ layout: ReadonlyArray<SerializedNode>, edits: ReadonlyArray<SectionEdit>, ctx: SectionEditContext,
264
+ ): SectionEditsOutcome {
265
+ const result = JSON.parse(JSON.stringify(layout)) as SerializedNode[];
266
+ const issues: AssistIssue[] = [];
267
+ const changes: SectionChange[] = [];
268
+ const newId = ctx.newId ?? stableIds(layout);
269
+ const has = (h: string) => Object.prototype.hasOwnProperty.call(ctx.sections, h);
270
+ const refuse = (handle: string, code: AssistIssueCode, message: string) => issues.push({ code, handle, message });
271
+ /** The sections as they stood — what "before" reads, and what a moved, swapped section is placed by. */
272
+ const original = ctx.sections;
273
+ /** The kinds of change each section was given: a swap may come with a move; a removal comes alone; no kind twice. */
274
+ const touched = new Map<string, Set<SectionChangeKind>>();
275
+ const removed = new Set<string>(edits.filter((e): e is SectionRemove => 'remove' in e).map(e => e.remove));
276
+
277
+ const changeable = (handle: string, kind: SectionChangeKind): SectionTarget | null => {
278
+ if (!has(handle)) { refuse(handle, AssistIssueCode.UnknownHandle, `"${handle}" is not a section of this page`); return null; }
279
+ const target = ctx.sections[handle];
280
+ if (!target.focus) { refuse(handle, AssistIssueCode.UnknownHandle, `${target.label} is not in the focus — widen the chip to change it`); return null; }
281
+ const kinds = touched.get(handle) ?? new Set<SectionChangeKind>();
282
+ if (kinds.has(kind) || (kinds.size && (kind === SectionChangeKind.Remove || kinds.has(SectionChangeKind.Remove)))) {
283
+ refuse(handle, AssistIssueCode.Duplicate, `${target.label} is given two changes that cannot go together`);
284
+ return null;
285
+ }
286
+ touched.set(handle, kinds.add(kind));
287
+ return target;
288
+ };
289
+ const place = (handle: string, after: string): boolean => {
290
+ if (after === SECTION_START) return true;
291
+ if (!has(after)) { refuse(handle, AssistIssueCode.UnknownHandle, `"${after}" is not a section of this page`); return false; }
292
+ if (after === handle) { refuse(handle, AssistIssueCode.NotAnOption, 'a section cannot go after itself'); return false; }
293
+ if (removed.has(after)) { refuse(handle, AssistIssueCode.NotAnOption, `${ctx.sections[after].label} is removed in the same answer — place it after another section`); return false; }
294
+ return true;
295
+ };
296
+ const offered = (handle: string, pattern: string): boolean => {
297
+ if (ASK_SECTION_PATTERNS.includes(pattern)) return true;
298
+ refuse(handle, AssistIssueCode.NotAnOption, `"${pattern}" is not a section Ask can add`);
299
+ return false;
300
+ };
301
+ const indexOf = (id: string) => result.findIndex(n => n.id === id);
302
+ const whereLabel = (after: string) => after === SECTION_START ? 'At the start' : `After ${ctx.sections[after].label}`;
303
+ /** The handle of the section a section stood after, or the start. */
304
+ const stoodAfter = (handle: string): string => {
305
+ const at = layout.findIndex(n => n.id === original[handle].id);
306
+ const prev = at > 0 ? Object.entries(original).find(([, t]) => t.id === layout[at - 1].id) : undefined;
307
+ return prev ? prev[0] : SECTION_START;
308
+ };
309
+ const standsAfter = (handle: string): string => {
310
+ const prev = stoodAfter(handle);
311
+ return prev === SECTION_START ? 'At the start' : `After ${original[prev].label}`;
312
+ };
313
+ const insertAfter = (node: SerializedNode, after: string) => {
314
+ if (after === SECTION_START) { result.unshift(node); return; }
315
+ const at = indexOf(ctx.sections[after].id);
316
+ result.splice(at + 1, 0, node);
317
+ };
318
+
319
+ // Swaps first, in place — so an addition or a move placed after a swapped section lands after its new drawing.
320
+ for (const edit of edits) {
321
+ if (!('swap' in edit)) continue;
322
+ const target = changeable(edit.swap, SectionChangeKind.Swap);
323
+ if (!target || !offered(edit.swap, edit.pattern)) continue;
324
+ const at = indexOf(target.id);
325
+ const blocker = swapBlocker(result[at]);
326
+ if (blocker) { refuse(edit.swap, AssistIssueCode.NotAnOption, `${target.label} cannot be redrawn — ${blocker}; add a new section and remove this one instead`); continue; }
327
+ const section = composeSection(edit.pattern, ctx.input ?? {}, { id: newId() }).section;
328
+ const notPlaced = carryOver(result[at], section);
329
+ result[at] = section;
330
+ // Later places name the section by its ORIGINAL id — it stands where the swapped one stood.
331
+ ctx = { ...ctx, sections: { ...ctx.sections, [edit.swap]: { ...target, id: section.id } } };
332
+ changes.push({
333
+ op: PageChangeOp.Section, kind: SectionChangeKind.Swap, handle: edit.swap, nodeId: section.id, label: target.label,
334
+ pattern: edit.pattern, before: target.label, after: patternName(edit.pattern), ...(notPlaced ? { notPlaced } : {}),
335
+ });
336
+ }
337
+ for (const edit of edits) {
338
+ if (!('remove' in edit)) continue;
339
+ const target = changeable(edit.remove, SectionChangeKind.Remove);
340
+ if (!target) continue;
341
+ result.splice(indexOf(target.id), 1);
342
+ changes.push({ op: PageChangeOp.Section, kind: SectionChangeKind.Remove, handle: edit.remove, nodeId: target.id, label: target.label, before: standsAfter(edit.remove), after: 'Removed' });
343
+ }
344
+ for (const edit of edits) {
345
+ if (!('move' in edit)) continue;
346
+ const target = changeable(edit.move, SectionChangeKind.Move);
347
+ if (!target || !place(edit.move, edit.after)) continue;
348
+ const [node] = result.splice(indexOf(target.id), 1);
349
+ insertAfter(node, edit.after);
350
+ if (stoodAfter(edit.move) === edit.after) continue;
351
+ changes.push({
352
+ op: PageChangeOp.Section, kind: SectionChangeKind.Move, handle: edit.move, nodeId: target.id, label: target.label,
353
+ before: standsAfter(edit.move), after: whereLabel(edit.after),
354
+ });
355
+ }
356
+ // Additions in answer order: two after the same section stand in that order.
357
+ const lastAdded = new Map<string, string>();
358
+ for (const edit of edits) {
359
+ if (!('add' in edit)) continue;
360
+ if (!offered('new', edit.add) || !place('new', edit.after)) continue;
361
+ const section = composeSection(edit.add, ctx.input ?? {}, { id: newId() }).section;
362
+ const anchor = lastAdded.get(edit.after);
363
+ if (anchor) result.splice(indexOf(anchor) + 1, 0, section);
364
+ else insertAfter(section, edit.after);
365
+ lastAdded.set(edit.after, section.id);
366
+ changes.push({ op: PageChangeOp.Section, kind: SectionChangeKind.Add, handle: 'new', nodeId: section.id, label: patternName(edit.add), pattern: edit.add, before: '', after: whereLabel(edit.after) });
367
+ }
368
+
369
+ if (issues.length) return { ok: false, result: JSON.parse(JSON.stringify(layout)) as SerializedNode[], changes: [], issues };
370
+ return { ok: true, result, changes, issues: [] };
371
+ }
@@ -286,7 +286,7 @@ export interface SizeEdit {
286
286
  }
287
287
 
288
288
  /** Any edit of family `style`. */
289
- export type LookEdit = StyleEdit | SchemeEdit | SizeEdit;
289
+ export type NodeStyleEdit = StyleEdit | SchemeEdit | SizeEdit;
290
290
 
291
291
  const listOf = (answer: unknown, key: StyleAnswerKey): Array<Record<string, unknown>> => {
292
292
  const list = answer && typeof answer === 'object' ? (answer as Record<string, unknown>)[key] : undefined;
@@ -294,7 +294,7 @@ const listOf = (answer: unknown, key: StyleAnswerKey): Array<Record<string, unkn
294
294
  };
295
295
 
296
296
  /** The answer → the edits it makes. */
297
- export function decodeStyleAnswers(answers: ReadonlyArray<unknown>): LookEdit[] {
297
+ export function decodeStyleAnswers(answers: ReadonlyArray<unknown>): NodeStyleEdit[] {
298
298
  return answers.flatMap(answer => [
299
299
  ...listOf(answer, StyleAnswerKey.Styles).map(x => ({ handle: String(x['handle'] ?? ''), style: String(x['style'] ?? '') })),
300
300
  ...listOf(answer, StyleAnswerKey.Schemes).map(x => ({ handle: String(x['handle'] ?? ''), scheme: String(x['scheme'] ?? '') })),
@@ -312,6 +312,9 @@ export enum PageChangeOp {
312
312
  Style = 'style',
313
313
  Scheme = 'scheme',
314
314
  Size = 'size',
315
+ Section = 'section',
316
+ /** The site's look (family `look`, AI2e) — every page follows. */
317
+ Look = 'look',
315
318
  }
316
319
 
317
320
  export interface StyleChange {
@@ -362,7 +365,7 @@ const styleLabel = (id: string) => elementStyleById(id)?.label ?? id;
362
365
  * once by the server, never repaired here); an edit that changes nothing is dropped.
363
366
  */
364
367
  export function applyStyleEdits(
365
- layout: ReadonlyArray<SerializedNode>, edits: ReadonlyArray<LookEdit>, ctx: StyleEditContext,
368
+ layout: ReadonlyArray<SerializedNode>, edits: ReadonlyArray<NodeStyleEdit>, ctx: StyleEditContext,
366
369
  ): StyleEditsOutcome {
367
370
  const result = JSON.parse(JSON.stringify(layout)) as SerializedNode[];
368
371
  const byId = new Map<string, SerializedNode>();
@@ -1,10 +1,13 @@
1
1
  import { jsonClosedObject, jsonListOf, JsonSchema, jsonText, SerializedNode, walkSerialized } from '@vectoriox/iox-ui/generation-core';
2
+ import type { DesignChoices } from '@vectoriox/iox-ui/design-core';
2
3
 
3
4
  import { assistFactIssues, AssistWordContext } from './assist-facts';
4
5
  import { namedLocale } from './assist-locale';
5
6
  import { assertAssistBudget, MAX_ASSIST_PROPERTIES } from './budget';
6
7
  import { AssistIssue, AssistIssueCode, Brief, BriefRules, HandleMap, NeverWrite, resolveHandle } from './brief';
7
8
  import { LookMap, lookNames, PageChangeOp, PageLook, pageLooks, sectionLabel } from './page-style';
9
+ import { askSectionPatternNames, SectionMap, sectionPatternOf } from './page-sections';
10
+ import { LookSummary, summarizeLook } from './site-look';
8
11
  import { containsHtml, escapeText, paragraphsToRichText, richTextParagraphs } from './rich-text';
9
12
  import { clipText } from './summarize-item';
10
13
  import { AssistScope, AssistSurface, EditFamily, SURFACES } from './surfaces';
@@ -94,6 +97,8 @@ export interface PageSectionSummary {
94
97
  readonly parts: ReadonlyArray<PagePart>;
95
98
  /** Family `style`: the elements of the section that may take another element style, colour scheme or size step. */
96
99
  readonly looks?: ReadonlyArray<PageLook>;
100
+ /** Family `sections`: the library pattern the section was stamped from, when it is one Ask offers. */
101
+ readonly pattern?: string;
97
102
  }
98
103
 
99
104
  export interface PageFocus {
@@ -107,6 +112,8 @@ export interface PageFocus {
107
112
  /** How the owner reads the style and scheme ids the looks name. */
108
113
  readonly styleNames?: Readonly<Record<string, string>>;
109
114
  readonly schemeNames?: Readonly<Record<string, string>>;
115
+ /** Family `sections`: the library sections Ask may add or swap to, by id → name. */
116
+ readonly sectionPatterns?: Readonly<Record<string, string>>;
110
117
  }
111
118
 
112
119
  export interface PageAround {
@@ -114,6 +121,8 @@ export interface PageAround {
114
121
  readonly sections: ReadonlyArray<{ readonly handle: string; readonly label: string; readonly headline: string }>;
115
122
  /** The site's other pages, by name. */
116
123
  readonly pages: ReadonlyArray<string>;
124
+ /** Family `look`: the look the whole site wears, one readable value per axis (AI2e). */
125
+ readonly look?: LookSummary;
117
126
  }
118
127
 
119
128
  export type PageBrief = Brief<PageFocus, PageAround>;
@@ -128,6 +137,8 @@ export interface PageBriefContext {
128
137
  readonly pages?: ReadonlyArray<string>;
129
138
  readonly owner?: string | null;
130
139
  readonly memory?: ReadonlyArray<string>;
140
+ /** The look the site wears (its stored choices) — said in the brief so "rounder", "darker", "calmer" read from it. */
141
+ readonly look?: DesignChoices | null;
131
142
  }
132
143
 
133
144
  export interface SummarizedPage {
@@ -140,6 +151,8 @@ export interface SummarizedPage {
140
151
  readonly nodes: Readonly<Record<string, string>>;
141
152
  /** Family `style`: the focus's targets — what a style request carries and the check may write. */
142
153
  readonly looks: LookMap;
154
+ /** Family `sections`: every section of the page by handle; the focus's may be removed, moved or swapped. */
155
+ readonly sections: SectionMap;
143
156
  }
144
157
 
145
158
  const sectionHandle = (index: number): string => `s${index}`;
@@ -237,6 +250,10 @@ export function summarizePage(layout: ReadonlyArray<SerializedNode>, ctx: PageBr
237
250
  handle: sectionHandle(index),
238
251
  label: sectionLabel(root, index),
239
252
  parts: walked.filter(w => w.section === index).map(w => ({ ...w.part, words: clipText(w.part.words, FOCUS_TEXT_CHARS) })),
253
+ ...(() => {
254
+ const pattern = sectionPatternOf(root);
255
+ return pattern ? { pattern } : {};
256
+ })(),
240
257
  ...(() => {
241
258
  const looks = walkedLooks.filter(l => l.section === index).map(l => l.look);
242
259
  return looks.length ? { looks } : {};
@@ -289,12 +306,16 @@ export function summarizePage(layout: ReadonlyArray<SerializedNode>, ctx: PageBr
289
306
  : selectedNode ? { selectedLabel: `${sections[0]?.label ?? ''} ▸ ${selectedNode.part.label}` } : {}),
290
307
  ...(Object.keys(names.styles).length ? { styleNames: names.styles } : {}),
291
308
  ...(Object.keys(names.schemes).length ? { schemeNames: names.schemes } : {}),
309
+ sectionPatterns: askSectionPatternNames(),
292
310
  };
311
+ const sectionMap: SectionMap = Object.fromEntries(layout.map((root, index) => [sectionHandle(index), {
312
+ id: root.id, label: sectionLabel(root, index), focus: scope === AssistScope.Page || index === selectedSection,
313
+ }]));
293
314
  return {
294
315
  brief: {
295
316
  surface: AssistSurface.BuilderPage,
296
317
  focus,
297
- around: { sections: around, pages: [...(ctx.pages ?? [])] },
318
+ around: { sections: around, pages: [...(ctx.pages ?? [])], ...(ctx.look ? { look: summarizeLook(ctx.look) } : {}) },
298
319
  owner: ctx.owner ?? null,
299
320
  rules,
300
321
  memory: [...(ctx.memory ?? [])],
@@ -303,6 +324,7 @@ export function summarizePage(layout: ReadonlyArray<SerializedNode>, ctx: PageBr
303
324
  focusHandles: focusWalked.filter(w => !w.part.bound).map(w => w.part.handle),
304
325
  nodes,
305
326
  looks,
327
+ sections: sectionMap,
306
328
  };
307
329
  }
308
330
 
@@ -24,6 +24,8 @@ export * from './assist-facts';
24
24
  export * from './field-edits';
25
25
  export * from './page-words';
26
26
  export * from './page-style';
27
+ export * from './page-sections';
28
+ export * from './site-look';
27
29
  export * from './page-edits';
28
30
  export * from './assist-turn';
29
31
  export * from './assist-locale';