@vectoriox/iox-ui 5.119.0 → 5.121.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.119.0",
3
+ "version": "5.121.0",
4
4
  "peerDependencies": {
5
5
  "@angular/common": ">=20.0.0",
6
6
  "@angular/core": ">=20.0.0",
@@ -4,6 +4,7 @@ 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';
9
10
  import { ContentRecord, clipText } from './summarize-item';
@@ -65,12 +66,13 @@ export interface AssistTurnRequest {
65
66
  }
66
67
 
67
68
  /** 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;
69
+ export type AssistEdit = FieldEdit | WordEdit | StyleEdit | SchemeEdit | SizeEdit | SectionEdit;
69
70
 
70
71
  /** What a turn changed, as the card says it. */
71
- export type AssistChange = FieldChange | WordChange | StyleChange;
72
+ export type AssistChange = FieldChange | WordChange | StyleChange | SectionChange;
72
73
 
73
- const isLookChange = (c: AssistChange): c is StyleChange => 'op' in c && (c.op === PageChangeOp.Style || c.op === PageChangeOp.Scheme || c.op === PageChangeOp.Size);
74
+ const isLookChange = (c: AssistChange): c is StyleChange | SectionChange => 'op' in c
75
+ && (c.op === PageChangeOp.Style || c.op === PageChangeOp.Scheme || c.op === PageChangeOp.Size || c.op === PageChangeOp.Section);
74
76
 
75
77
  /** POST's 202 answer. */
76
78
  export interface AssistTurnAccepted {
@@ -2,21 +2,26 @@ import { SerializedNode } from '@vectoriox/iox-ui/generation-core';
2
2
 
3
3
  import { AssistIssue } from './brief';
4
4
  import { applyWordEdits, SummarizedPage, WordChange, WordEdit, WordEditContext } from './page-words';
5
+ import { applySectionEdits, isSectionEdit, SectionChange, SectionEdit, SectionEditContext } from './page-sections';
5
6
  import { applyStyleEdits, BaselineStyles, isSchemeEdit, isSizeEdit, isStyleEdit, LookEdit, SchemeEdit, SizeEdit, StyleChange, StyleEdit } from './page-style';
6
7
 
7
8
  /**
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.
9
+ * Surface S1's answer as ONE thing (AI2b–AI2d): the edits of every family a page turn routed to — words (`{ handle, value }`),
10
+ * styles (`{ handle, style }`), schemes (`{ handle, scheme }`), size steps (`{ handle, axis, step }`), sections
11
+ * (`{ add | remove | move | swap }`) — applied in that order on a copy, all or none. Sections go last: every handle the
12
+ * other families name is read on the page as it stood. The server checks each family as it is asked; the builder's trial
13
+ * applies the turn's edits through this, so both read one rule.
12
14
  */
13
- export type PageEdit = WordEdit | StyleEdit | SchemeEdit | SizeEdit;
14
- export type PageChange = WordChange | StyleChange;
15
+ export type PageEdit = WordEdit | StyleEdit | SchemeEdit | SizeEdit | SectionEdit;
16
+ export type PageChange = WordChange | StyleChange | SectionChange;
15
17
 
16
18
  export interface PageEditContext extends Omit<WordEditContext, 'handles' | 'never'> {
17
- readonly summary: Pick<SummarizedPage, 'handles' | 'looks'> & { readonly brief: { readonly rules: { readonly never: WordEditContext['never'] } } };
19
+ readonly summary: Pick<SummarizedPage, 'handles' | 'looks'> & Partial<Pick<SummarizedPage, 'sections'>> & { readonly brief: { readonly rules: { readonly never: WordEditContext['never'] } } };
18
20
  /** The builder's registry baseline; default the saved shape's (`serializedBaselineStyles`). */
19
21
  readonly baseline?: BaselineStyles;
22
+ /** Family `sections`: the studio's name and pages (what the palette composes with) and the builder's fresh ids. */
23
+ readonly sectionInput?: SectionEditContext['input'];
24
+ readonly newId?: SectionEditContext['newId'];
20
25
  }
21
26
 
22
27
  export interface PageEditsOutcome {
@@ -27,14 +32,18 @@ export interface PageEditsOutcome {
27
32
  }
28
33
 
29
34
  const isWordEdit = (e: PageEdit): e is WordEdit => 'value' in e;
35
+ const isLookEdit = (e: PageEdit): e is LookEdit => !isWordEdit(e) && !isSectionEdit(e) && (isStyleEdit(e) || isSchemeEdit(e) || isSizeEdit(e));
30
36
 
31
37
  export function applyPageEdits(layout: ReadonlyArray<SerializedNode>, edits: ReadonlyArray<PageEdit>, ctx: PageEditContext): PageEditsOutcome {
32
38
  const words = applyWordEdits(layout, edits.filter(isWordEdit), {
33
39
  handles: ctx.summary.handles, never: ctx.summary.brief.rules.never, sentence: ctx.sentence, words: ctx.words,
34
40
  });
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];
41
+ const style = applyStyleEdits(words.result, edits.filter(isLookEdit), { looks: ctx.summary.looks, baseline: ctx.baseline });
42
+ const sectionEdits = edits.filter(isSectionEdit);
43
+ const sections = sectionEdits.length
44
+ ? applySectionEdits(style.result, sectionEdits, { sections: ctx.summary.sections ?? {}, input: ctx.sectionInput, newId: ctx.newId })
45
+ : { result: style.result, changes: [], issues: [] };
46
+ const issues = [...words.issues, ...style.issues, ...sections.issues];
38
47
  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: [] };
48
+ return { ok: true, result: sections.result, changes: [...words.changes, ...style.changes, ...sections.changes], issues: [] };
40
49
  }
@@ -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
+ }
@@ -312,6 +312,7 @@ export enum PageChangeOp {
312
312
  Style = 'style',
313
313
  Scheme = 'scheme',
314
314
  Size = 'size',
315
+ Section = 'section',
315
316
  }
316
317
 
317
318
  export interface StyleChange {
@@ -5,6 +5,7 @@ import { namedLocale } from './assist-locale';
5
5
  import { assertAssistBudget, MAX_ASSIST_PROPERTIES } from './budget';
6
6
  import { AssistIssue, AssistIssueCode, Brief, BriefRules, HandleMap, NeverWrite, resolveHandle } from './brief';
7
7
  import { LookMap, lookNames, PageChangeOp, PageLook, pageLooks, sectionLabel } from './page-style';
8
+ import { askSectionPatternNames, SectionMap, sectionPatternOf } from './page-sections';
8
9
  import { containsHtml, escapeText, paragraphsToRichText, richTextParagraphs } from './rich-text';
9
10
  import { clipText } from './summarize-item';
10
11
  import { AssistScope, AssistSurface, EditFamily, SURFACES } from './surfaces';
@@ -94,6 +95,8 @@ export interface PageSectionSummary {
94
95
  readonly parts: ReadonlyArray<PagePart>;
95
96
  /** Family `style`: the elements of the section that may take another element style, colour scheme or size step. */
96
97
  readonly looks?: ReadonlyArray<PageLook>;
98
+ /** Family `sections`: the library pattern the section was stamped from, when it is one Ask offers. */
99
+ readonly pattern?: string;
97
100
  }
98
101
 
99
102
  export interface PageFocus {
@@ -107,6 +110,8 @@ export interface PageFocus {
107
110
  /** How the owner reads the style and scheme ids the looks name. */
108
111
  readonly styleNames?: Readonly<Record<string, string>>;
109
112
  readonly schemeNames?: Readonly<Record<string, string>>;
113
+ /** Family `sections`: the library sections Ask may add or swap to, by id → name. */
114
+ readonly sectionPatterns?: Readonly<Record<string, string>>;
110
115
  }
111
116
 
112
117
  export interface PageAround {
@@ -140,6 +145,8 @@ export interface SummarizedPage {
140
145
  readonly nodes: Readonly<Record<string, string>>;
141
146
  /** Family `style`: the focus's targets — what a style request carries and the check may write. */
142
147
  readonly looks: LookMap;
148
+ /** Family `sections`: every section of the page by handle; the focus's may be removed, moved or swapped. */
149
+ readonly sections: SectionMap;
143
150
  }
144
151
 
145
152
  const sectionHandle = (index: number): string => `s${index}`;
@@ -237,6 +244,10 @@ export function summarizePage(layout: ReadonlyArray<SerializedNode>, ctx: PageBr
237
244
  handle: sectionHandle(index),
238
245
  label: sectionLabel(root, index),
239
246
  parts: walked.filter(w => w.section === index).map(w => ({ ...w.part, words: clipText(w.part.words, FOCUS_TEXT_CHARS) })),
247
+ ...(() => {
248
+ const pattern = sectionPatternOf(root);
249
+ return pattern ? { pattern } : {};
250
+ })(),
240
251
  ...(() => {
241
252
  const looks = walkedLooks.filter(l => l.section === index).map(l => l.look);
242
253
  return looks.length ? { looks } : {};
@@ -289,7 +300,11 @@ export function summarizePage(layout: ReadonlyArray<SerializedNode>, ctx: PageBr
289
300
  : selectedNode ? { selectedLabel: `${sections[0]?.label ?? ''} ▸ ${selectedNode.part.label}` } : {}),
290
301
  ...(Object.keys(names.styles).length ? { styleNames: names.styles } : {}),
291
302
  ...(Object.keys(names.schemes).length ? { schemeNames: names.schemes } : {}),
303
+ sectionPatterns: askSectionPatternNames(),
292
304
  };
305
+ const sectionMap: SectionMap = Object.fromEntries(layout.map((root, index) => [sectionHandle(index), {
306
+ id: root.id, label: sectionLabel(root, index), focus: scope === AssistScope.Page || index === selectedSection,
307
+ }]));
293
308
  return {
294
309
  brief: {
295
310
  surface: AssistSurface.BuilderPage,
@@ -303,6 +318,7 @@ export function summarizePage(layout: ReadonlyArray<SerializedNode>, ctx: PageBr
303
318
  focusHandles: focusWalked.filter(w => !w.part.bound).map(w => w.part.handle),
304
319
  nodes,
305
320
  looks,
321
+ sections: sectionMap,
306
322
  };
307
323
  }
308
324
 
@@ -24,6 +24,7 @@ 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';
27
28
  export * from './page-edits';
28
29
  export * from './assist-turn';
29
30
  export * from './assist-locale';
@@ -117,10 +117,10 @@ const spec = (s: Omit<SurfaceSpec, 'perContentType' | 'readsPhotos'> & Partial<P
117
117
 
118
118
  export const SURFACES: Readonly<Record<AssistSurface, SurfaceSpec>> = {
119
119
  // S1 offers only the families the server answers (the route can never pick one it cannot): Words first (AI2a);
120
- // Style, Sections and Look & motion join as each slice ships (ai-assist-plan §6, AI2).
120
+ // Look & motion joins when its slice ships (ai-assist-plan §6, AI2e).
121
121
  [AssistSurface.BuilderPage]: spec({
122
122
  surface: AssistSurface.BuilderPage,
123
- families: [EditFamily.Words, EditFamily.Style],
123
+ families: [EditFamily.Words, EditFamily.Style, EditFamily.Sections],
124
124
  commit: CommitKind.BuilderStep,
125
125
  steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
126
126
  permissions: [AssistPermission.PageUpdate],