@vectoriox/iox-ui 5.34.0 → 5.36.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.
@@ -0,0 +1,650 @@
1
+ import { readOwnedTrait } from '@vectoriox/iox-ui/design-core';
2
+
3
+ import {
4
+ CompositeNode, CompositeNodeFactory, findByRole, readProp, removeFromComposite, walkComposite, writeProp, writeStyles,
5
+ } from './composite-node';
6
+
7
+ /**
8
+ * ACCORDION (CC2 — composite K1; complex-components boards 3, 4 and 9, APPROVED 2026-10-20). Not a
9
+ * component: a recipe of ordinary nodes, each part carrying a role, so every part is selectable on the
10
+ * canvas, in the layer tree and the breadcrumb, and wears its own element style (R2).
11
+ *
12
+ * Container `box` role accordion traits multiple · defaultOn (Manual)
13
+ * — or a Repeater bound to a list role accordion ONE template item (From content, R3)
14
+ * └─ Container `accordion-item` role accordion.item itemKey k1 … (Manual) · the row's id (From content)
15
+ * ├─ LinkedContainer `accordion-trigger` role accordion.trigger → <hN><button> (the question's level)
16
+ * │ ├─ Heading `h3` the question (rendered as phrasing inside the button)
17
+ * │ └─ Icon `icon` role accordion.icon Item open → rotate
18
+ * └─ Container `accordion-panel` role accordion.panel inside a hidden="until-found" region
19
+ * └─ Text `body` the answer
20
+ *
21
+ * The behaviour is BUILT IN (composite plan D1 = B): which items are open is one state machine
22
+ * (`nextAccordionState`), the ARIA and DOM state one planner (`accordionItemState` and the attribute
23
+ * functions), the keyboard one key map — read by the builder canvas, both engine paths and the composer.
24
+ */
25
+
26
+ export enum AccordionRole {
27
+ Accordion = 'accordion',
28
+ Item = 'accordion.item',
29
+ Trigger = 'accordion.trigger',
30
+ Icon = 'accordion.icon',
31
+ Panel = 'accordion.panel',
32
+ }
33
+
34
+ /** The behaviour options a composite root stores as ordinary TRAITS (composite plan §3). */
35
+ export enum CompositeBehaviourTrait {
36
+ /** Several items may be open at once ("Allow several open"). */
37
+ Multiple = 'multiple',
38
+ /** Which items open by default: first · none · all. */
39
+ DefaultOn = 'defaultOn',
40
+ }
41
+
42
+ export enum AccordionDefaultOn {
43
+ First = 'first',
44
+ None = 'none',
45
+ All = 'all',
46
+ }
47
+
48
+ export const ACCORDION_DEFAULT_ONS: ReadonlyArray<AccordionDefaultOn> = [AccordionDefaultOn.First, AccordionDefaultOn.None, AccordionDefaultOn.All];
49
+
50
+ /** Behaviour ▸ Icon — a preset over the items' icons, never a stored trait (detected from the icons). */
51
+ export enum AccordionIcon {
52
+ Chevron = 'chevron',
53
+ Plus = 'plus',
54
+ None = 'none',
55
+ }
56
+
57
+ export const ACCORDION_ICONS: ReadonlyArray<AccordionIcon> = [AccordionIcon.Chevron, AccordionIcon.Plus, AccordionIcon.None];
58
+
59
+ /** Each icon's glyph and how far it turns when its item opens (board 4: a chevron flips, a plus becomes ×). */
60
+ export const ACCORDION_ICON_GLYPH: Readonly<Record<Exclude<AccordionIcon, AccordionIcon.None>, { iconClass: string; turn: string }>> = {
61
+ [AccordionIcon.Chevron]: { iconClass: 'ph ph-caret-down', turn: '180deg' },
62
+ [AccordionIcon.Plus]: { iconClass: 'ph ph-plus', turn: '45deg' },
63
+ };
64
+
65
+ /** The item-open style state (a part INSIDE an item, styled by its item being open — board 9 "Item open"). */
66
+ export const ITEM_OPEN_STATE = 'trigger-on';
67
+ /** A part that IS on (an item, its header, its panel — board 9 "Open"). */
68
+ export const ON_STATE = 'on';
69
+
70
+ /** Items from content default to twenty rows (board 9 Q13). */
71
+ export const ACCORDION_CONTENT_LIMIT = 20;
72
+
73
+ export interface AccordionWords {
74
+ question: string;
75
+ answer: string;
76
+ }
77
+
78
+ /** The words a fresh accordion starts with — generic, the author's to replace (as Card v2's are). */
79
+ export const ACCORDION_WORDS: ReadonlyArray<AccordionWords> = [
80
+ { question: 'Write the first question people ask', answer: 'Answer it plainly, in two or three short sentences.' },
81
+ { question: 'Write the second question', answer: 'Answer it plainly, in two or three short sentences.' },
82
+ { question: 'Write the third question', answer: 'Answer it plainly, in two or three short sentences.' },
83
+ ];
84
+ export const ACCORDION_NEW_ITEM_WORDS: Readonly<AccordionWords> = { question: 'Write a new question', answer: 'Answer it plainly, in two or three short sentences.' };
85
+
86
+ enum Type {
87
+ Container = 'Container',
88
+ LinkedContainer = 'LinkedContainer',
89
+ Heading = 'Heading',
90
+ Text = 'Text',
91
+ Icon = 'Icon',
92
+ Repeater = 'Repeater',
93
+ }
94
+
95
+ enum Style {
96
+ Root = 'box',
97
+ Item = 'accordion-item',
98
+ Trigger = 'accordion-trigger',
99
+ Question = 'h3',
100
+ Icon = 'icon',
101
+ Panel = 'accordion-panel',
102
+ Answer = 'body',
103
+ }
104
+
105
+ const ZERO_BOX = '0px 0px 0px 0px';
106
+ const HEADING_LEVELS = ['h2', 'h3', 'h4', 'h5', 'h6'];
107
+ const DEFAULT_LEVEL = 'h3';
108
+ /** A linked trait the header must never carry: it is a button, not a link. */
109
+ const LINK_TYPE = 'linkType';
110
+
111
+ /** What each part holds in the recipe — layout only; its LOOK is its element style. */
112
+ const PART_BASE: Readonly<Record<string, Readonly<Record<string, string>>>> = {
113
+ // The items are a column a token apart (`accordion-gap`: 0 for a divider list, 12px for cards).
114
+ [AccordionRole.Accordion]: { display: 'flex', flexDirection: 'column', gap: 'var(--iox-accordion-gap)', width: '100%', minHeight: 'auto', height: 'auto' },
115
+ [AccordionRole.Item]: { display: 'block', width: '100%', minHeight: 'auto', height: 'auto' },
116
+ // The header is the whole row: the question takes the line, the icon sits at its end (board 4).
117
+ [AccordionRole.Trigger]: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px', width: '100%', minHeight: 'auto', height: 'auto', textAlign: 'start', cursor: 'pointer' },
118
+ [AccordionRole.Icon]: { flexShrink: '0', fontSize: '22px', transitionDuration: 'var(--iox-dur-base)', transitionTimingFunction: 'var(--iox-ease-standard)' },
119
+ [AccordionRole.Panel]: { display: 'block', width: '100%', minHeight: 'auto', height: 'auto' },
120
+ };
121
+ /** The question INHERITS the header's ink (board 4's wears table: the Question reads no colour token), so the
122
+ * header's hover ink reaches the words; and it sits in the row with no margin of its own. */
123
+ const QUESTION_BASE: Readonly<Record<string, string>> = { color: 'inherit', margin: ZERO_BOX, flexGrow: '1', minWidth: '0px' };
124
+ const ANSWER_BASE: Readonly<Record<string, string>> = { margin: ZERO_BOX, padding: ZERO_BOX, minHeight: 'auto' };
125
+
126
+ // ── recipe ──────────────────────────────────────────────────────────────────────────────────────
127
+
128
+ export interface AccordionOptions {
129
+ /** The items' words (three generic items by default). */
130
+ items?: ReadonlyArray<AccordionWords>;
131
+ multiple?: boolean;
132
+ defaultOn?: AccordionDefaultOn;
133
+ icon?: AccordionIcon;
134
+ }
135
+
136
+ function make(create: CompositeNodeFactory, key: string, type: string, role: AccordionRole | null, style: string,
137
+ props: Record<string, unknown> = {}, label?: string): CompositeNode {
138
+ const node = create({ key, type, props, elementStyle: style });
139
+ if (role) node.role = role;
140
+ if (label) node.label = label;
141
+ if (role && PART_BASE[role]) writeStyles(node, PART_BASE[role]);
142
+ return node;
143
+ }
144
+
145
+ /** The item's icon; its Item-open state (the turn) is driven by ITS item (`stateTriggers`). */
146
+ function buildIcon(create: CompositeNodeFactory, key: string, icon: Exclude<AccordionIcon, AccordionIcon.None>, itemId?: string): CompositeNode {
147
+ const glyph = ACCORDION_ICON_GLYPH[icon];
148
+ const node = make(create, key, Type.Icon, AccordionRole.Icon, Style.Icon, { iconClass: glyph.iconClass }, 'Icon');
149
+ node.stateStyles = { ...(node.stateStyles ?? {}), [ITEM_OPEN_STATE]: { rotate: glyph.turn } };
150
+ if (itemId) node.stateTriggers = { ...(node.stateTriggers ?? {}), [ITEM_OPEN_STATE]: itemId };
151
+ return node;
152
+ }
153
+
154
+ /** One item: header (question + icon) and panel (answer). `key` makes every part's recipe key unique. */
155
+ export function buildAccordionItem(create: CompositeNodeFactory, words: AccordionWords, itemKey: string, icon: AccordionIcon = AccordionIcon.Chevron): CompositeNode {
156
+ const item = make(create, `${itemKey}`, Type.Container, AccordionRole.Item, Style.Item, {}, 'Item');
157
+ item.itemKey = itemKey;
158
+ const trigger = make(create, `${itemKey}-trigger`, Type.LinkedContainer, AccordionRole.Trigger, Style.Trigger, {}, 'Header');
159
+ const question = make(create, `${itemKey}-question`, Type.Heading, null, Style.Question, { content: words.question, level: DEFAULT_LEVEL }, 'Heading');
160
+ writeStyles(question, QUESTION_BASE);
161
+ trigger.children = [question, ...(icon === AccordionIcon.None ? [] : [buildIcon(create, `${itemKey}-icon`, icon, item.id)])];
162
+ const panel = make(create, `${itemKey}-panel`, Type.Container, AccordionRole.Panel, Style.Panel, {}, 'Panel');
163
+ const answer = make(create, `${itemKey}-answer`, Type.Text, null, Style.Answer, { content: words.answer, tag: 'p' }, 'Text');
164
+ writeStyles(answer, ANSWER_BASE);
165
+ panel.children = [answer];
166
+ item.children = [trigger, panel];
167
+ return item;
168
+ }
169
+
170
+ /** A fresh Accordion: three items, one open at a time, the first open by default (board 4). */
171
+ export function buildAccordionRecipe(create: CompositeNodeFactory, options: AccordionOptions = {}): CompositeNode {
172
+ const root = make(create, 'accordion', Type.Container, AccordionRole.Accordion, Style.Root, {}, 'Accordion');
173
+ writeProp(root, CompositeBehaviourTrait.Multiple, options.multiple ?? false);
174
+ writeProp(root, CompositeBehaviourTrait.DefaultOn, options.defaultOn ?? AccordionDefaultOn.First);
175
+ const words = options.items ?? ACCORDION_WORDS;
176
+ root.children = words.map((w, i) => buildAccordionItem(create, w, `k${i + 1}`, options.icon ?? AccordionIcon.Chevron));
177
+ return root;
178
+ }
179
+
180
+ // ── reading a tree ──────────────────────────────────────────────────────────────────────────────
181
+
182
+ export function isAccordionRoot(node: { role?: string | null } | null | undefined): boolean {
183
+ return node?.role === AccordionRole.Accordion;
184
+ }
185
+
186
+ /** True for any part of an accordion (its root included). */
187
+ export function isAccordionPart(node: { role?: string | null } | null | undefined): boolean {
188
+ return !!node?.role && (node.role === AccordionRole.Accordion || node.role.startsWith(`${AccordionRole.Accordion}.`));
189
+ }
190
+
191
+ /** The accordion a node belongs to: the nearest ancestor (or the node itself) playing `accordion`.
192
+ * `path` = the node's ancestors, root first. */
193
+ export function accordionRootOf<T extends { role?: string | null }>(node: T, path: ReadonlyArray<T>): T | null {
194
+ if (isAccordionRoot(node)) return node;
195
+ for (let i = path.length - 1; i >= 0; i--) if (isAccordionRoot(path[i])) return path[i];
196
+ return null;
197
+ }
198
+
199
+ /** The item a node sits in (the node itself when it is one), or null. */
200
+ export function accordionItemOf<T extends { role?: string | null }>(node: T, path: ReadonlyArray<T>): T | null {
201
+ if (node.role === AccordionRole.Item) return node;
202
+ for (let i = path.length - 1; i >= 0; i--) {
203
+ if (path[i].role === AccordionRole.Item) return path[i];
204
+ if (isAccordionRoot(path[i])) return null;
205
+ }
206
+ return null;
207
+ }
208
+
209
+ /** True when the root takes its items from content (a Repeater bound to a list, R3). */
210
+ export function isAccordionFromContent(root: CompositeNode | null | undefined): boolean {
211
+ return !!root && root.type === Type.Repeater;
212
+ }
213
+
214
+ /** The root's items in order — every item (Manual), or the one template item (From content). */
215
+ export function accordionItems(root: CompositeNode): CompositeNode[] {
216
+ return (root.children ?? []).filter(c => c.role === AccordionRole.Item);
217
+ }
218
+
219
+ export interface AccordionBehaviour {
220
+ multiple: boolean;
221
+ defaultOn: AccordionDefaultOn;
222
+ }
223
+
224
+ const asBool = (v: unknown) => v === true || v === 'true';
225
+
226
+ /** The root's behaviour (an unset trait reads its default: one at a time, the first open). */
227
+ export function accordionBehaviour(root: CompositeNode | null | undefined): AccordionBehaviour {
228
+ const raw = root ? readProp(root, CompositeBehaviourTrait.DefaultOn) : undefined;
229
+ const defaultOn = ACCORDION_DEFAULT_ONS.includes(raw as AccordionDefaultOn) ? raw as AccordionDefaultOn : AccordionDefaultOn.First;
230
+ return { multiple: root ? asBool(readProp(root, CompositeBehaviourTrait.Multiple)) : false, defaultOn };
231
+ }
232
+
233
+ /** Behaviour ▸ Allow several open / Open by default. False when the node has no such trait. */
234
+ export function setAccordionBehaviour(root: CompositeNode, patch: Partial<AccordionBehaviour>): boolean {
235
+ let ok = true;
236
+ if (patch.multiple !== undefined) ok = writeProp(root, CompositeBehaviourTrait.Multiple, patch.multiple) && ok;
237
+ if (patch.defaultOn !== undefined) ok = writeProp(root, CompositeBehaviourTrait.DefaultOn, patch.defaultOn) && ok;
238
+ return ok;
239
+ }
240
+
241
+ /** The header of an item. */
242
+ export function accordionTriggerOf(item: CompositeNode): CompositeNode | undefined {
243
+ return findByRole(item, AccordionRole.Trigger);
244
+ }
245
+
246
+ /** The panel of an item. */
247
+ export function accordionPanelOf(item: CompositeNode): CompositeNode | undefined {
248
+ return findByRole(item, AccordionRole.Panel);
249
+ }
250
+
251
+ /** The question: the first Heading inside the header. */
252
+ export function accordionQuestionOf(item: CompositeNode): CompositeNode | undefined {
253
+ const trigger = accordionTriggerOf(item);
254
+ let hit: CompositeNode | undefined;
255
+ if (trigger) walkComposite(trigger, n => { if (!hit && n.type === Type.Heading) hit = n; });
256
+ return hit;
257
+ }
258
+
259
+ /** The answer: the first Text inside the panel. */
260
+ export function accordionAnswerOf(item: CompositeNode): CompositeNode | undefined {
261
+ const panel = accordionPanelOf(item);
262
+ let hit: CompositeNode | undefined;
263
+ if (panel) walkComposite(panel, n => { if (!hit && n.type === Type.Text) hit = n; });
264
+ return hit;
265
+ }
266
+
267
+ const stripTags = (v: unknown) => String(v ?? '').replace(/<[^>]*>/g, '').trim();
268
+
269
+ /** An item's name in the Items list and the layer tree: its question's words. */
270
+ export function accordionItemLabel(item: CompositeNode): string {
271
+ const q = accordionQuestionOf(item);
272
+ return q ? stripTags(readProp(q, 'content')) : '';
273
+ }
274
+
275
+ /** Items ▸ rename: the question's words. */
276
+ export function renameAccordionItem(item: CompositeNode, question: string): boolean {
277
+ const q = accordionQuestionOf(item);
278
+ return !!q && writeProp(q, 'content', question);
279
+ }
280
+
281
+ /** The heading level the header's wrapper renders (`<h3><button>`): its question's level. */
282
+ export function accordionHeadingLevel(trigger: { children?: ReadonlyArray<CompositeNode> | null } | null | undefined): string {
283
+ let level: unknown;
284
+ const visit = (n: CompositeNode) => {
285
+ if (level !== undefined) return;
286
+ if (n.type === Type.Heading) { level = readProp(n, 'level'); return; }
287
+ for (const c of n.children ?? []) visit(c);
288
+ };
289
+ for (const c of trigger?.children ?? []) visit(c);
290
+ return HEADING_LEVELS.includes(level as string) ? level as string : DEFAULT_LEVEL;
291
+ }
292
+
293
+ // ── editing (Items list, selection toolbar, Behaviour ▸ Icon) ──────────────────────────────────
294
+
295
+ /** A key no item of `root` holds yet (`k4`…). */
296
+ export function nextItemKey(root: CompositeNode): string {
297
+ const taken = new Set(accordionItems(root).map(i => i.itemKey).filter(Boolean));
298
+ let n = taken.size + 1;
299
+ while (taken.has(`k${n}`)) n++;
300
+ return `k${n}`;
301
+ }
302
+
303
+ /** Items ▸ Add item (and the toolbar's "Add item"): a fresh item after `after` (or at the end), wearing the
304
+ * accordion's current icon. Returns the new item. */
305
+ export function addAccordionItem(root: CompositeNode, create: CompositeNodeFactory, after?: CompositeNode | null, words: AccordionWords = ACCORDION_NEW_ITEM_WORDS): CompositeNode {
306
+ const key = nextItemKey(root);
307
+ const item = buildAccordionItem(create, words, key, detectAccordionIcon(root));
308
+ const children = [...(root.children ?? [])];
309
+ const at = after ? children.indexOf(after) : -1;
310
+ children.splice(at < 0 ? children.length : at + 1, 0, item);
311
+ root.children = children;
312
+ return item;
313
+ }
314
+
315
+ /** Items ▸ drag to reorder: move an item to `toIndex` among the items. False when it is not an item of `root`. */
316
+ export function moveAccordionItem(root: CompositeNode, item: CompositeNode, toIndex: number): boolean {
317
+ const children = [...(root.children ?? [])];
318
+ const from = children.indexOf(item);
319
+ if (from < 0 || item.role !== AccordionRole.Item) return false;
320
+ children.splice(from, 1);
321
+ const items = children.filter(c => c.role === AccordionRole.Item);
322
+ const anchor = items[Math.max(0, Math.min(toIndex, items.length))];
323
+ const at = anchor ? children.indexOf(anchor) : children.length;
324
+ children.splice(at, 0, item);
325
+ root.children = children;
326
+ return true;
327
+ }
328
+
329
+ export enum AccordionEditRefusal {
330
+ /** An accordion keeps at least one item (composite plan T11). */
331
+ LastItem = 'last-item',
332
+ }
333
+
334
+ /** Why removing `item` from `root` is refused, or null. */
335
+ export function accordionRemovalRefusal(root: CompositeNode | null | undefined, item: CompositeNode | null | undefined): AccordionEditRefusal | null {
336
+ if (!root || item?.role !== AccordionRole.Item) return null;
337
+ return accordionItems(root).length <= 1 ? AccordionEditRefusal.LastItem : null;
338
+ }
339
+
340
+ /** The icon the accordion's items wear now (the first item's; None when it has no icon). */
341
+ export function detectAccordionIcon(root: CompositeNode): AccordionIcon {
342
+ const first = accordionItems(root)[0];
343
+ const icon = first ? findByRole(first, AccordionRole.Icon) : undefined;
344
+ if (!icon) return first ? AccordionIcon.None : AccordionIcon.Chevron;
345
+ const cls = String(readProp(icon, 'iconClass') ?? '');
346
+ return cls.includes(ACCORDION_ICON_GLYPH[AccordionIcon.Plus].iconClass.split(' ')[1]) ? AccordionIcon.Plus : AccordionIcon.Chevron;
347
+ }
348
+
349
+ /**
350
+ * Behaviour ▸ Icon: every item's header shows the chevron, the plus, or no icon. A switch between glyphs
351
+ * keeps the icon NODE (its styles and interactions) and changes its glyph and turn; None removes it, and a
352
+ * glyph after None stamps it back from the recipe. Returns how many items changed.
353
+ */
354
+ export function setAccordionIcon(root: CompositeNode, icon: AccordionIcon, create?: CompositeNodeFactory): number {
355
+ let changed = 0;
356
+ for (const item of accordionItems(root)) {
357
+ const trigger = accordionTriggerOf(item);
358
+ if (!trigger) continue;
359
+ const existing = findByRole(trigger, AccordionRole.Icon);
360
+ if (icon === AccordionIcon.None) {
361
+ if (existing && removeFromComposite(trigger, existing)) changed++;
362
+ continue;
363
+ }
364
+ const glyph = ACCORDION_ICON_GLYPH[icon];
365
+ if (existing) {
366
+ writeProp(existing, 'iconClass', glyph.iconClass);
367
+ existing.stateStyles = { ...(existing.stateStyles ?? {}), [ITEM_OPEN_STATE]: { ...(existing.stateStyles?.[ITEM_OPEN_STATE] ?? {}), rotate: glyph.turn } };
368
+ changed++;
369
+ } else if (create) {
370
+ trigger.children = [...(trigger.children ?? []), buildIcon(create, `${item.itemKey ?? 'item'}-icon`, icon, item.id)];
371
+ changed++;
372
+ }
373
+ }
374
+ return changed;
375
+ }
376
+
377
+ /** The node id every `trigger-on` state inside an item points at: its ITEM (`stateTriggers['trigger-on']`). */
378
+ export function itemOpenTriggerIds(root: CompositeNode): void {
379
+ for (const item of accordionItems(root)) {
380
+ if (!item.id) continue;
381
+ walkComposite(item, n => {
382
+ if (n === item || !n.stateStyles?.[ITEM_OPEN_STATE]) return;
383
+ n.stateTriggers = { ...(n.stateTriggers ?? {}), [ITEM_OPEN_STATE]: item.id! };
384
+ });
385
+ }
386
+ }
387
+
388
+ // ── state machine ───────────────────────────────────────────────────────────────────────────────
389
+
390
+ /** The keys open on first render: the first item, none, or all (From content: resolved against the rows). */
391
+ export function initialAccordionOpen(keys: ReadonlyArray<string>, defaultOn: AccordionDefaultOn): Set<string> {
392
+ if (defaultOn === AccordionDefaultOn.None || !keys.length) return new Set();
393
+ if (defaultOn === AccordionDefaultOn.All) return new Set(keys);
394
+ return new Set([keys[0]]);
395
+ }
396
+
397
+ /** The open keys after toggling `key`: one at a time closes the others; several leaves them. */
398
+ export function nextAccordionState(open: ReadonlySet<string>, key: string, behaviour: Pick<AccordionBehaviour, 'multiple'>): Set<string> {
399
+ if (open.has(key)) {
400
+ const next = new Set(open);
401
+ next.delete(key);
402
+ return next;
403
+ }
404
+ return behaviour.multiple ? new Set([...open, key]) : new Set([key]);
405
+ }
406
+
407
+ /** The open keys after OPENING `key` (find-in-page, selecting into a closed panel). */
408
+ export function openAccordionItem(open: ReadonlySet<string>, key: string, behaviour: Pick<AccordionBehaviour, 'multiple'>): Set<string> {
409
+ return open.has(key) ? new Set(open) : nextAccordionState(open, key, behaviour);
410
+ }
411
+
412
+ export enum AccordionKeyAction {
413
+ Next = 'next',
414
+ Previous = 'previous',
415
+ First = 'first',
416
+ Last = 'last',
417
+ }
418
+
419
+ /** The APG accordion's keys on a header: ↓ ↑ move (and wrap), Home / End jump. Enter and Space are the
420
+ * button's own. */
421
+ const KEY_ACTIONS: Readonly<Record<string, AccordionKeyAction>> = {
422
+ ArrowDown: AccordionKeyAction.Next,
423
+ ArrowUp: AccordionKeyAction.Previous,
424
+ Home: AccordionKeyAction.First,
425
+ End: AccordionKeyAction.Last,
426
+ };
427
+
428
+ export function accordionKeyAction(key: string): AccordionKeyAction | null {
429
+ return KEY_ACTIONS[key] ?? null;
430
+ }
431
+
432
+ /** The header index `action` moves focus to, from `current` among `count` headers (↓ ↑ wrap). */
433
+ export function accordionFocusIndex(action: AccordionKeyAction, current: number, count: number): number {
434
+ if (count <= 0) return -1;
435
+ switch (action) {
436
+ case AccordionKeyAction.Next: return (current + 1) % count;
437
+ case AccordionKeyAction.Previous: return (current - 1 + count) % count;
438
+ case AccordionKeyAction.First: return 0;
439
+ case AccordionKeyAction.Last: return count - 1;
440
+ }
441
+ }
442
+
443
+ // ── identity, ids and attributes (both renderers, SSR included) ────────────────────────────────
444
+
445
+ /** A key safe in an element id. */
446
+ export function domSafeKey(raw: unknown): string {
447
+ return String(raw ?? '').replace(/[^A-Za-z0-9_-]/g, '-');
448
+ }
449
+
450
+ /** A content row's identity: its own id (never its index — a reorder in the CMS must never pair a header with
451
+ * another row's panel, R3); the index only for a row that has none. */
452
+ export function rowItemKey(row: unknown, index: number): string {
453
+ const r = row as { _id?: unknown; id?: unknown } | null;
454
+ const id = r && typeof r === 'object' ? (r._id ?? r.id) : undefined;
455
+ return id !== undefined && id !== null && id !== '' ? domSafeKey(id) : `row-${index}`;
456
+ }
457
+
458
+ export interface AccordionDomIds {
459
+ trigger: string;
460
+ panel: string;
461
+ }
462
+
463
+ /** The ARIA pairing ids of an item: unique per accordion (its root's node id) and per item (its key). */
464
+ export function accordionDomIds(rootId: string, itemKey: string): AccordionDomIds {
465
+ const base = `iox-acc-${domSafeKey(rootId)}-${domSafeKey(itemKey)}`;
466
+ return { trigger: `${base}-h`, panel: `${base}-p` };
467
+ }
468
+
469
+ /** One item's render state: its identity, whether it is open, and its ARIA ids. */
470
+ export interface AccordionItemState {
471
+ key: string;
472
+ index: number;
473
+ on: boolean;
474
+ ids: AccordionDomIds;
475
+ }
476
+
477
+ /** The render scope of one accordion: its root id, behaviour and every item key in order. */
478
+ export interface AccordionScope {
479
+ rootId: string;
480
+ behaviour: AccordionBehaviour;
481
+ keys: ReadonlyArray<string>;
482
+ open: ReadonlySet<string>;
483
+ }
484
+
485
+ export function accordionScope(rootId: string, behaviour: AccordionBehaviour, keys: ReadonlyArray<string>): AccordionScope {
486
+ return { rootId, behaviour, keys, open: initialAccordionOpen(keys, behaviour.defaultOn) };
487
+ }
488
+
489
+ export function accordionItemState(scope: AccordionScope, index: number): AccordionItemState {
490
+ const key = scope.keys[index] ?? `item-${index}`;
491
+ return { key, index, on: scope.open.has(key), ids: accordionDomIds(scope.rootId, key) };
492
+ }
493
+
494
+ /** Attribute values: a string, or '' for a present boolean attribute. Absent attributes are left out. */
495
+ export type DomAttributes = Record<string, string>;
496
+
497
+ /** `data-iox-on` — the ONE attribute every "on" style keys on (Open, Item open). */
498
+ export const ON_ATTRIBUTE = 'data-iox-on';
499
+ export const ITEM_KEY_ATTRIBUTE = 'data-iox-item-key';
500
+ export const COMPOSITE_ATTRIBUTE = 'data-iox-composite';
501
+ export const MULTIPLE_ATTRIBUTE = 'data-iox-multiple';
502
+ export const DEFAULT_ON_ATTRIBUTE = 'data-iox-default-on';
503
+ /** The value a closed panel's region carries: find-in-page can still reveal it (D9, board 4). */
504
+ export const UNTIL_FOUND = 'until-found';
505
+
506
+ /** The structural classes the renderers write around an accordion's parts (no node owns them). */
507
+ export enum AccordionClass {
508
+ Heading = 'iox-accordion-heading',
509
+ Button = 'iox-accordion-button',
510
+ Track = 'iox-accordion-track',
511
+ Region = 'iox-accordion-region',
512
+ }
513
+
514
+ export function accordionRootAttributes(behaviour: AccordionBehaviour): DomAttributes {
515
+ return {
516
+ [COMPOSITE_ATTRIBUTE]: AccordionRole.Accordion,
517
+ [DEFAULT_ON_ATTRIBUTE]: behaviour.defaultOn,
518
+ ...(behaviour.multiple ? { [MULTIPLE_ATTRIBUTE]: '' } : {}),
519
+ };
520
+ }
521
+
522
+ export function accordionItemAttributes(state: AccordionItemState): DomAttributes {
523
+ return { [ITEM_KEY_ATTRIBUTE]: state.key, ...(state.on ? { [ON_ATTRIBUTE]: '' } : {}) };
524
+ }
525
+
526
+ export function accordionTriggerAttributes(state: AccordionItemState): DomAttributes {
527
+ return {
528
+ type: 'button',
529
+ id: state.ids.trigger,
530
+ 'aria-expanded': state.on ? 'true' : 'false',
531
+ 'aria-controls': state.ids.panel,
532
+ ...(state.on ? { [ON_ATTRIBUTE]: '' } : {}),
533
+ };
534
+ }
535
+
536
+ /** The track wrapping a panel: its row collapses to 0 while closed (the ONE hiding rule, iox-design.css). */
537
+ export function accordionTrackAttributes(state: AccordionItemState): DomAttributes {
538
+ return state.on ? { [ON_ATTRIBUTE]: '' } : {};
539
+ }
540
+
541
+ /** The region the panel sits in: `hidden="until-found"` while closed, so its words stay in the page. */
542
+ export function accordionRegionAttributes(state: AccordionItemState): DomAttributes {
543
+ return {
544
+ role: 'region',
545
+ id: state.ids.panel,
546
+ 'aria-labelledby': state.ids.trigger,
547
+ ...(state.on ? {} : { hidden: UNTIL_FOUND }),
548
+ };
549
+ }
550
+
551
+ export function accordionPanelAttributes(state: AccordionItemState): DomAttributes {
552
+ return state.on ? { [ON_ATTRIBUTE]: '' } : {};
553
+ }
554
+
555
+ /** `attrs` as an HTML attribute string (` a="b" c`), values escaped by `esc`. */
556
+ export function serializeDomAttributes(attrs: DomAttributes, esc: (v: string) => string): string {
557
+ return Object.entries(attrs).map(([k, v]) => (v === '' ? ` ${k}` : ` ${k}="${esc(v)}"`)).join('');
558
+ }
559
+
560
+ // ── Items from content (R3) ─────────────────────────────────────────────────────────────────────
561
+
562
+ /** A field of a content type, as both the CMS schema and a site plan describe it. */
563
+ export interface ContentFieldLike {
564
+ name: string;
565
+ type?: string;
566
+ controller?: string;
567
+ }
568
+
569
+ const SHORT_TEXT = new Set(['text']);
570
+ const LONG_TEXT = new Set(['textarea', 'richText', 'editor']);
571
+
572
+ export interface AccordionAutoBinds {
573
+ /** The first short-text field: the question. */
574
+ question: string | null;
575
+ /** The first long-text field: the answer. */
576
+ answer: string | null;
577
+ }
578
+
579
+ /** R3 (board 9 Q19): switching to From content binds the question to the first short-text field and the
580
+ * answer to the first long-text field. ONE rule for the builder's switch and the composer. */
581
+ export function pickAccordionAutoBinds(fields: ReadonlyArray<ContentFieldLike>): AccordionAutoBinds {
582
+ const isString = (f: ContentFieldLike) => !f.type || f.type === 'string';
583
+ const question = fields.find(f => isString(f) && SHORT_TEXT.has(String(f.controller ?? 'text')))?.name ?? null;
584
+ const answer = fields.find(f => isString(f) && LONG_TEXT.has(String(f.controller ?? '')) && f.name !== question)?.name ?? null;
585
+ return { question, answer };
586
+ }
587
+
588
+ /** The bound props of the question and the answer (each a content trait). */
589
+ export const ACCORDION_BIND_PROP = 'content';
590
+
591
+ /**
592
+ * Manual → From content (board 9 "Items: Manual · From content"): the root becomes `repeater` (a Repeater node
593
+ * the caller created with the same id, role, label, element style and styles — a type change is the
594
+ * consumer's), the FIRST item becomes the one template (its parts, styles and interactions kept; its key
595
+ * dropped — a row's key is its id) and the others are removed. Returns the removed items.
596
+ */
597
+ export function accordionToContent(root: CompositeNode, repeater: CompositeNode): CompositeNode[] {
598
+ const items = accordionItems(root);
599
+ const [template, ...rest] = items;
600
+ if (template) delete template.itemKey;
601
+ repeater.role = AccordionRole.Accordion;
602
+ repeater.children = template ? [template] : [];
603
+ writeProp(repeater, CompositeBehaviourTrait.Multiple, accordionBehaviour(root).multiple);
604
+ writeProp(repeater, CompositeBehaviourTrait.DefaultOn, accordionBehaviour(root).defaultOn);
605
+ return rest;
606
+ }
607
+
608
+ /**
609
+ * From content → Manual: the rows come in as static items — each a copy of the template (`cloneItem`, which
610
+ * gives the copy fresh ids) whose bound words are written in as its own and whose bindings are dropped.
611
+ * `container` is the manual root the caller created. Returns the new items.
612
+ */
613
+ export function accordionToManual(root: CompositeNode, container: CompositeNode, rows: ReadonlyArray<unknown>,
614
+ cloneItem: (template: CompositeNode) => CompositeNode, resolve: (row: unknown, binding: CompositeBinding) => unknown): CompositeNode[] {
615
+ const template = accordionItems(root)[0];
616
+ container.role = AccordionRole.Accordion;
617
+ writeProp(container, CompositeBehaviourTrait.Multiple, accordionBehaviour(root).multiple);
618
+ writeProp(container, CompositeBehaviourTrait.DefaultOn, accordionBehaviour(root).defaultOn);
619
+ const items = template ? rows.map((row, i) => {
620
+ const item = cloneItem(template);
621
+ item.itemKey = `k${i + 1}`;
622
+ walkComposite(item, n => {
623
+ const bindings = (n as BoundNode).bindings ?? [];
624
+ for (const b of bindings) {
625
+ const value = resolve(row, b);
626
+ if (value !== undefined && value !== null) writeProp(n, b.prop, value);
627
+ }
628
+ if (bindings.length) (n as BoundNode).bindings = [];
629
+ });
630
+ return item;
631
+ }) : [];
632
+ container.children = items;
633
+ return items;
634
+ }
635
+
636
+ export interface CompositeBinding {
637
+ prop: string;
638
+ source: string;
639
+ path?: string;
640
+ pipes?: unknown[];
641
+ }
642
+
643
+ interface BoundNode extends CompositeNode {
644
+ bindings?: CompositeBinding[];
645
+ }
646
+
647
+ /** The style a part holds for `name` (both node shapes) — exported for the consumers' detectors. */
648
+ export function accordionPartStyle(node: CompositeNode, name: string): unknown {
649
+ return readOwnedTrait(node, { trait: name });
650
+ }
@@ -21,6 +21,11 @@ export interface CompositeNode extends ElementStyleTarget {
21
21
  /** The part this node plays in its composite (`card.title`). Additive; saved; read by the shared CSS
22
22
  * (`iox-role-<role>`), the structure guard and the composite's own editors. */
23
23
  role?: string;
24
+ /** An item's identity inside its composite (Accordion `k1`… — composite plan §3, `itemKey`). Additive; saved.
25
+ * From content, a row's key is the row's own id and the template carries none. */
26
+ itemKey?: string;
27
+ /** For a targeted state (`trigger-on`): the node whose state drives it. */
28
+ stateTriggers?: Partial<Record<string, string>>;
24
29
  label?: string;
25
30
  props?: Record<string, unknown>;
26
31
  traits?: CompositeTrait[];
@@ -2,10 +2,13 @@
2
2
  * @vectoriox/iox-ui/composite-core — composites built from the builder's own parts (composite-components
3
3
  * plan §3a). FRAMEWORK-FREE: the builder, the SSR engine and iox-cms (generation-core's composer, the site
4
4
  * build) read the same recipes, roles and structure rules. Card v2 + Badge / Chip (T23 / T25) are the
5
- * first; Accordion and Tabs join with their own phases.
5
+ * first; the Accordion (CC2) adds the first composite RUNTIME (accordion-runtime.ts — DOM only, no
6
+ * framework); Tabs join with their own phase.
6
7
  * ⚠️ Consumers wire the usual trio — ng-package raw-ts assets, jest moduleNameMapper, tsconfig paths.
7
8
  */
8
9
  export * from './composite-node';
10
+ export * from './accordion';
11
+ export * from './accordion-runtime';
9
12
  export * from './badge';
10
13
  export * from './card';
11
14
  export * from './structure';