@vectoriox/iox-ui 5.9.0 → 5.11.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,103 @@
1
+ import { deriveAccentTokens } from './brand';
2
+ import { cssString } from './fonts';
3
+ import { SPEC_AXES } from './flavor-spec.generated';
4
+ import {
5
+ DesignChoices, DesignTokenRow, FlavorPackV2, FlavorSpecToken, flavorSourceStamp, USER_TOKEN_SOURCE,
6
+ } from './design-token.model';
7
+
8
+ /**
9
+ * A flavor's COMPLETE token set for a studio's choices (design-system plan §3a/§3e). A flavor IS
10
+ * its token values, so switching flavor — or any choice — rewrites token rows and nothing else.
11
+ *
12
+ * Layering, each step over the last (the boards' `tokenMap`, with the product's colour math):
13
+ * pack tokens → chosen font pair → shape · density · motion axes → pill-button rule →
14
+ * the author's own font roles → a seed ≠ the pack's own re-derives the accent quartet.
15
+ *
16
+ * `mode` does not change rows — every row keeps its light value and its dark override; mode is
17
+ * how the stylesheet is compiled.
18
+ */
19
+
20
+ const LABEL = 'label';
21
+ const BUTTON_RADIUS = 'button-radius';
22
+ const PILL_RADIUS = 'var(--iox-radius-pill)';
23
+ const CONTROL_RADIUS = 'var(--iox-radius-sm)';
24
+ const USER_FONT_FALLBACK = 'system-ui, sans-serif';
25
+
26
+ type AxisTable = Readonly<Record<string, Readonly<Record<string, string>>>>;
27
+
28
+ const axisValues = (table: AxisTable, id: string): Array<[string, string]> =>
29
+ Object.entries(table[id] ?? {}).filter(([k]) => k !== LABEL);
30
+
31
+ /** The pack's own defaults as a full set of choices — what Apply means with nothing changed. */
32
+ export function defaultDesignChoices(pack: FlavorPackV2): DesignChoices {
33
+ return {
34
+ flavorId: pack.id,
35
+ seed: pack.seed,
36
+ pairId: pack.pairs[0]?.id ?? '',
37
+ ...pack.defaults,
38
+ };
39
+ }
40
+
41
+ /** `'<Family>', system-ui, sans-serif` — the value a font role holds once the author picks a face. */
42
+ export function userFontStack(family: string): string {
43
+ return `${cssString(family.trim())}, ${USER_FONT_FALLBACK}`;
44
+ }
45
+
46
+ const toRow = (t: FlavorSpecToken, source: string): DesignTokenRow => ({
47
+ name: t.name,
48
+ type: t.type,
49
+ value: t.value,
50
+ ...(t.dark !== undefined ? { values: { dark: t.dark } } : {}),
51
+ source,
52
+ group: t.group,
53
+ tier: t.tier,
54
+ });
55
+
56
+ export function buildFlavorTokens(pack: FlavorPackV2, choices: DesignChoices): DesignTokenRow[] {
57
+ const stamp = flavorSourceStamp(pack.id);
58
+ const rows = pack.tokens.map(t => toRow(t, stamp));
59
+ const byName = new Map(rows.map(r => [r.name, r]));
60
+
61
+ /** An override is ONE value in every mode — a pair or axis value has no dark twin. */
62
+ const set = (name: string, value: string, source = stamp) => {
63
+ const row = byName.get(name);
64
+ if (!row) return;
65
+ row.value = value;
66
+ delete row.values;
67
+ row.source = source;
68
+ };
69
+
70
+ const pair = pack.pairs.find(p => p.id === choices.pairId) ?? pack.pairs[0];
71
+ for (const [name, value] of Object.entries(pair?.tokens ?? {})) set(name, value);
72
+
73
+ const axes = SPEC_AXES;
74
+ for (const [name, value] of [
75
+ ...axisValues(axes.shapes, choices.shape),
76
+ ...axisValues(axes.densities, choices.density),
77
+ ...axisValues(axes.motions, choices.motion),
78
+ ]) set(name, value);
79
+
80
+ const buttonRadius = pack.tokens.find(t => t.name === BUTTON_RADIUS);
81
+ set(BUTTON_RADIUS, choices.pillButtons ? PILL_RADIUS : (buttonRadius?.overridden ? buttonRadius.value : CONTROL_RADIUS));
82
+
83
+ for (const [role, family] of Object.entries(choices.fonts ?? {})) {
84
+ if (typeof family === 'string' && family.trim() !== '') set(role, userFontStack(family), USER_TOKEN_SOURCE);
85
+ }
86
+
87
+ if (choices.seed && choices.seed.toLowerCase() !== pack.seed.toLowerCase()) {
88
+ const bg = byName.get('bg');
89
+ const inverseBg = byName.get('inverse-bg');
90
+ for (const accent of deriveAccentTokens(choices.seed, {
91
+ bg: bg?.value ?? '', bgDark: bg?.values?.dark,
92
+ inverseBg: inverseBg?.value, inverseBgDark: inverseBg?.values?.dark,
93
+ })) {
94
+ const row = byName.get(accent.name);
95
+ if (!row) continue;
96
+ row.value = accent.value;
97
+ if (accent.values?.dark) row.values = { dark: accent.values.dark };
98
+ else delete row.values;
99
+ }
100
+ }
101
+
102
+ return rows;
103
+ }
@@ -0,0 +1,137 @@
1
+ import { styleKeyToKebab } from './css-names';
2
+ import { DesignTokenGroup, DesignTokenTier, DesignTokenType } from './design-token.model';
3
+
4
+ /**
5
+ * Flavors (flavors-and-theming-plan.md, F1): the design language a studio launches with,
6
+ * expressed as data. THE invariant — a flavor never writes a literal into a node; it writes
7
+ * tokens, and element defaults that REFERENCE tokens. To that end a pack's `defaults` map
8
+ * holds TOKEN NAMES, not CSS values: the resolver builds `var(--iox-<name>, <packValue>)`,
9
+ * so smuggling a literal in is impossible by construction, and the validator only has to
10
+ * check that every referenced token exists.
11
+ *
12
+ * The fallback is the bootstrap: until F2 seeds the org's `designtokens` rows, no `--iox-*`
13
+ * var is defined anywhere, and `var(--iox-radius-control, 4px)` must still paint identically
14
+ * in the builder canvas and the SSR page. Once tokens ARE seeded (or re-themed), the var wins
15
+ * over the fallback everywhere — which is exactly the §3 propagation story.
16
+ */
17
+
18
+ export interface FlavorTokenDef {
19
+ name: string;
20
+ value: string;
21
+ /** Dark-scheme override, seeded into DesignToken.values.dark at F2. */
22
+ values?: { dark?: string };
23
+ type?: DesignTokenType;
24
+ group?: DesignTokenGroup;
25
+ tier?: DesignTokenTier;
26
+ }
27
+
28
+ export interface FlavorPack {
29
+ id: string;
30
+ /** Bumped when the pack's values change; seeding stamps `flavor:<id>@<version>` as DesignToken.source. */
31
+ version: number;
32
+ label: string;
33
+ blurb: string;
34
+ tokens: FlavorTokenDef[];
35
+ /** type → styleTrait → TOKEN NAME (never a CSS value — see the module header). */
36
+ defaults: Record<string, Record<string, string>>;
37
+ /** F2: the accent's hue rotation (degrees in OKLab) from the brand seed — a pack opinion. */
38
+ accentHueDeg?: number;
39
+ }
40
+
41
+ /** trait → `var(--iox-<token>, <packValue>)` for one node type. Unknown type → {}. */
42
+ export function resolveFlavorDefaults(
43
+ type: string,
44
+ pack: FlavorPack | null | undefined,
45
+ ): Record<string, string> {
46
+ const map = pack?.defaults?.[type];
47
+ if (!map) return {};
48
+ const byName = new Map((pack!.tokens ?? []).map(t => [t.name, t.value]));
49
+ const out: Record<string, string> = {};
50
+ for (const [trait, tokenName] of Object.entries(map)) {
51
+ const fallback = byName.get(tokenName);
52
+ if (fallback === undefined) continue; // validator fails the build; runtime stays safe
53
+ out[trait] = `var(--iox-${tokenName}, ${fallback})`;
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * The ENGINE's half of the cascade: kebab `prop: var(…)` declarations for every pack default
60
+ * the node's persisted styleProps does NOT set. Appended beside renderDefaultDeclarations —
61
+ * same guard-on-undefined discipline, so a node saved post-F1 (var already serialised via the
62
+ * builder's trait defaults) is untouched, and a legacy node picks the pack default up at
63
+ * render time. Node styleProps always wins.
64
+ */
65
+ export function flavorDefaultDeclarations(
66
+ type: string,
67
+ styleProps: Record<string, any> | null | undefined,
68
+ pack: FlavorPack | null | undefined,
69
+ ): string[] {
70
+ const sp = styleProps ?? {};
71
+ const out: string[] = [];
72
+ for (const [trait, value] of Object.entries(resolveFlavorDefaults(type, pack))) {
73
+ if (sp[trait] === undefined) out.push(`${styleKeyToKebab(trait)}: ${value}`);
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /**
79
+ * The CI gate (flavors plan §10 C4): a pack may only name types and traits that exist in the
80
+ * live component registry, and tokens it defines itself. Returns human-readable errors; a
81
+ * consumer spec feeds it the REAL registry and asserts [].
82
+ */
83
+ export function validateFlavorPack(
84
+ pack: FlavorPack,
85
+ knownTraitsByType: Record<string, ReadonlySet<string> | string[]>,
86
+ ): string[] {
87
+ const errors: string[] = [];
88
+ const tokenNames = new Set((pack.tokens ?? []).map(t => t.name));
89
+ for (const t of pack.tokens ?? []) {
90
+ if (!t.name) errors.push(`${pack.id}: token with empty name`);
91
+ if (!t.value) errors.push(`${pack.id}: token "${t.name}" has no value`);
92
+ }
93
+ for (const [type, traits] of Object.entries(pack.defaults ?? {})) {
94
+ const known = knownTraitsByType[type];
95
+ if (!known) { errors.push(`${pack.id}: unknown component type "${type}"`); continue; }
96
+ const knownSet = known instanceof Set ? known : new Set(known);
97
+ for (const [trait, tokenName] of Object.entries(traits)) {
98
+ if (!knownSet.has(trait)) errors.push(`${pack.id}: "${type}" has no style trait "${trait}"`);
99
+ if (!tokenNames.has(tokenName)) errors.push(`${pack.id}: "${type}.${trait}" references undefined token "${tokenName}"`);
100
+ if (/[:(]|^#|\d/.test(tokenName)) errors.push(`${pack.id}: "${type}.${trait}" must name a token, not a value ("${tokenName}")`);
101
+ }
102
+ }
103
+ return errors;
104
+ }
105
+
106
+ /**
107
+ * Swiss — the default pack (flavors plan §8: "the flavor that can never embarrass anyone").
108
+ * Deliberately SMALL at F1: radius + control padding on the clickables, surface radius on Card.
109
+ * Colour, type and motion arrive with the brand step (F2) — a colour default here would repaint
110
+ * legacy pages before anyone chose anything.
111
+ */
112
+ export const SWISS_FLAVOR: FlavorPack = {
113
+ id: 'swiss',
114
+ version: 1,
115
+ label: 'Swiss',
116
+ blurb: 'Grid discipline, hairline rules, near-zero motion.',
117
+ tokens: [
118
+ { name: 'radius-control', value: '4px', type: 'size', group: 'shape' },
119
+ { name: 'radius-surface', value: '4px', type: 'size', group: 'shape' },
120
+ { name: 'space-control', value: '10px 18px', type: 'spacing', group: 'space' },
121
+ { name: 'space-stack', value: '12px', type: 'spacing', group: 'space' },
122
+ ],
123
+ defaults: {
124
+ Button: { borderRadius: 'radius-control', padding: 'space-control' },
125
+ ButtonBlock: { borderRadius: 'radius-control', padding: 'space-control' },
126
+ Card: { borderRadius: 'radius-surface' },
127
+ },
128
+ // F2: Swiss turns the seed toward a cool counterpoint. NOTE deliberately: the brand tokens
129
+ // deriveBrandTokens() emits are SEEDED per org — they do not join `defaults` here, because a
130
+ // colour default repaints legacy nodes whose saved styleProps lack the key (the engine fills
131
+ // missing keys from config defaults). Coloured element defaults are a Swiss v2 upgrade
132
+ // decision (§10 C2), taken with the picker in front of the author — never a side effect.
133
+ accentHueDeg: 150,
134
+ };
135
+
136
+ /** What both renderers use until F2 lets an org choose. */
137
+ export const DEFAULT_FLAVOR: FlavorPack = SWISS_FLAVOR;
@@ -0,0 +1,98 @@
1
+ import { SPEC_FONTS } from './flavor-spec.generated';
2
+ import { DesignTokenLike } from './token-css';
3
+
4
+ /**
5
+ * Fonts (design-system plan §5b, D7): ONE Google catalog for both renderers, and ONE face builder
6
+ * for the families a studio uploads.
7
+ */
8
+
9
+ /** Family name → Google Fonts css2 `family=` id. Replaces the engine's private GOOGLE_FONTS map. */
10
+ export const FONT_CATALOG: Readonly<Record<string, string>> = SPEC_FONTS;
11
+
12
+ export type FontFormat = 'woff2' | 'woff' | 'truetype' | 'opentype';
13
+ export type FontStyle = 'normal' | 'italic';
14
+
15
+ /** One uploaded font FILE (spec `fontDescriptor`) — a family is all descriptors sharing `family`. */
16
+ export interface FontDescriptor {
17
+ family: string;
18
+ /** 100–900, from the file's OS/2 `usWeightClass`. */
19
+ weight: number;
20
+ style: FontStyle;
21
+ url: string;
22
+ format: FontFormat;
23
+ }
24
+
25
+ /** The token roles whose values name the families a page renders in. */
26
+ export const FONT_FAMILY_TOKENS = ['font-display', 'font-body', 'font-label', 'font-mono'] as const;
27
+
28
+ const DEFAULT_WEIGHT = 400;
29
+ const MIN_WEIGHT = 100;
30
+ const MAX_WEIGHT = 900;
31
+ const FONT_FORMATS: ReadonlyArray<FontFormat> = ['woff2', 'woff', 'truetype', 'opentype'];
32
+
33
+ /**
34
+ * A CSS string literal, single-quoted: `\` and `'` escaped, line breaks and NUL dropped, and `<` /
35
+ * `>` hex-escaped (`\3c `) — the face CSS is inlined into a `<style>` by the SSR engine, where an
36
+ * uploaded family named `</style><script>` would otherwise close the element.
37
+ */
38
+ export function cssString(value: string): string {
39
+ const body = String(value)
40
+ .replace(/[\r\n\f\0]/g, '')
41
+ .replace(/\\/g, '\\\\')
42
+ .replace(/'/g, "\\'")
43
+ .replace(/</g, '\\3c ')
44
+ .replace(/>/g, '\\3e ');
45
+ return `'${body}'`;
46
+ }
47
+
48
+ const clampWeight = (w: unknown): number => {
49
+ const n = Math.round(Number(w));
50
+ return Number.isFinite(n) && n > 0 ? Math.min(MAX_WEIGHT, Math.max(MIN_WEIGHT, n)) : DEFAULT_WEIGHT;
51
+ };
52
+
53
+ /** One `@font-face` per file, carrying its real weight and style — so bold is never synthesised. */
54
+ export function buildFontFaceCss(descriptors: ReadonlyArray<FontDescriptor> | null | undefined): string {
55
+ return (descriptors ?? [])
56
+ .filter(d => !!d && typeof d.family === 'string' && d.family.trim() !== '' && typeof d.url === 'string' && d.url !== '')
57
+ .map(d => {
58
+ const format = FONT_FORMATS.includes(d.format) ? ` format(${cssString(d.format)})` : '';
59
+ return [
60
+ '@font-face {',
61
+ ` font-family: ${cssString(d.family.trim())};`,
62
+ ` src: url(${cssString(d.url)})${format};`,
63
+ ` font-weight: ${clampWeight(d.weight)};`,
64
+ ` font-style: ${d.style === 'italic' ? 'italic' : 'normal'};`,
65
+ ' font-display: swap;',
66
+ '}',
67
+ ].join('\n');
68
+ })
69
+ .join('\n');
70
+ }
71
+
72
+ /** The family names in a CSS `font-family` stack, unquoted, in order. */
73
+ export function parseFontFamilies(stack: string): string[] {
74
+ return String(stack ?? '')
75
+ .split(',')
76
+ .map(f => f.trim().replace(/^(['"])(.*)\1$/, '$2').trim())
77
+ .filter(Boolean);
78
+ }
79
+
80
+ /**
81
+ * The Google css2 ids to load for a token set: every catalog family named by a font role token,
82
+ * one id per family (T7 — one `<link>` per family, so one bad id cannot sink the others).
83
+ */
84
+ export function fontsForTokens(tokens: ReadonlyArray<DesignTokenLike> | null | undefined): string[] {
85
+ const seen = new Set<string>();
86
+ const ids: string[] = [];
87
+ for (const role of FONT_FAMILY_TOKENS) {
88
+ const row = (tokens ?? []).find(t => t?.name === role);
89
+ for (const family of parseFontFamilies(row?.value ?? '')) {
90
+ const id = FONT_CATALOG[family];
91
+ if (id && !seen.has(family)) {
92
+ seen.add(family);
93
+ ids.push(id);
94
+ }
95
+ }
96
+ }
97
+ return ids;
98
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @vectoriox/iox-ui/design-core — the shared, FRAMEWORK-FREE core of the design system
3
+ * (design-system plan §3e): the token vocabulary, the flavor contract (generated 1:1 from
4
+ * iox-ai-guidance `flavor-spec.v1.json`), `buildFlavorTokens`, the token stylesheet compiler, the
5
+ * spring easing, the font catalog and face builder, and the seed/revert planners.
6
+ * Consumed by the builder, the SSR engine AND iox-cms (the server-side site build) — so nothing
7
+ * here may import Angular. The main entry re-exports all of it, so `@vectoriox/iox-ui` keeps working.
8
+ * ⚠️ Consumers wire the usual trio — ng-package raw-ts assets, jest moduleNameMapper, tsconfig
9
+ * paths — or `nest start` dies with ERR_REQUIRE_ESM while jest and build both pass.
10
+ */
11
+ export * from './flavor-spec.generated';
12
+ export * from './design-token.model';
13
+ export * from './css-names';
14
+ export * from './token-css';
15
+ export * from './flavor';
16
+ export * from './brand';
17
+ export * from './flavor-tokens';
18
+ export * from './flavor-seed';
19
+ export * from './spring';
20
+ export * from './fonts';
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A damped spring as a CSS `linear()` easing (design-system plan §3e) — the algorithm the spec's
3
+ * generator (`build-spec.mjs` `spring()`) uses to write `springs.lively`, so a spring computed at
4
+ * runtime is byte-identical to the one in the contract.
5
+ *
6
+ * `stiffness` is k (ω₀ = √k), `damping` the ratio ζ: < 1 under-damped, = 1 critically damped,
7
+ * > 1 over-damped. Both must be positive and finite — a zero or negative spring never settles.
8
+ * Duration = the last instant the curve is more than 0.1% away from rest, rounded up to 10ms.
9
+ */
10
+ const SETTLE_TOLERANCE = 0.001;
11
+ const SETTLE_HORIZON_S = 3;
12
+ const SETTLE_STEP_S = 0.001;
13
+ const SAMPLES = 40;
14
+ const DECIMALS = 4;
15
+ const ROUND_TO_MS = 10;
16
+
17
+ /** Displacement from rest → target (0 → 1) of a unit-mass spring released at rest. */
18
+ function springPosition(w0: number, damping: number): (t: number) => number {
19
+ if (damping < 1) {
20
+ const wd = w0 * Math.sqrt(1 - damping * damping);
21
+ return t => 1 - Math.exp(-damping * w0 * t) * (Math.cos(wd * t) + ((damping * w0) / wd) * Math.sin(wd * t));
22
+ }
23
+ if (damping === 1) return t => 1 - Math.exp(-w0 * t) * (1 + w0 * t);
24
+ // Over-damped: two real, negative roots. Written with exponentials of the roots, not cosh/sinh,
25
+ // which overflow for a stiff, heavily damped spring well inside the settle horizon.
26
+ const root = w0 * Math.sqrt(damping * damping - 1);
27
+ const r1 = -damping * w0 + root;
28
+ const r2 = -damping * w0 - root;
29
+ return t => 1 - (r2 * Math.exp(r1 * t) - r1 * Math.exp(r2 * t)) / (r2 - r1);
30
+ }
31
+
32
+ export interface LinearSpring {
33
+ easing: string;
34
+ duration: string;
35
+ }
36
+
37
+ export function springToLinear(stiffness: number, damping: number): LinearSpring {
38
+ if (!(Number.isFinite(stiffness) && stiffness > 0) || !(Number.isFinite(damping) && damping > 0)) {
39
+ throw new RangeError(`springToLinear: stiffness and damping must be > 0 (got ${stiffness}, ${damping})`);
40
+ }
41
+ const x = springPosition(Math.sqrt(stiffness), damping);
42
+ let settle = 0;
43
+ for (let t = 0; t < SETTLE_HORIZON_S; t += SETTLE_STEP_S) if (Math.abs(1 - x(t)) > SETTLE_TOLERANCE) settle = t;
44
+ const durationMs = Math.ceil((settle * 1000) / ROUND_TO_MS) * ROUND_TO_MS;
45
+ const points: number[] = [];
46
+ for (let i = 0; i <= SAMPLES; i++) points.push(+x((settle * i) / SAMPLES).toFixed(DECIMALS));
47
+ points[SAMPLES] = 1;
48
+ return { easing: `linear(${points.join(', ')})`, duration: `${durationMs}ms` };
49
+ }
@@ -0,0 +1,233 @@
1
+ import { SPEC_A11Y, SPEC_SCHEMES } from './flavor-spec.generated';
2
+
3
+ /**
4
+ * Design-token → CSS compilation, shared by BOTH renderers (flavors F0, design-system DS1).
5
+ *
6
+ * A token row is `{ name, value }` plus an optional per-scheme override `values.dark`.
7
+ * A value that references another token (`var(--iox-surface)`) passes through verbatim.
8
+ *
9
+ * Block order (design-system plan §3e, T8):
10
+ * 1. base `:root { --iox-*: … }`
11
+ * 2. schemes `.iox-scheme-<id> { overrides; every var()-referencing token re-declared }`
12
+ * 3. reduced motion `@media (prefers-reduced-motion: reduce)`
13
+ * 4. reduced transparency `@media (prefers-reduced-transparency: reduce)`
14
+ * 5. dark — LAST `@media (prefers-color-scheme: dark)`
15
+ *
16
+ * ⚠️ The appended-last contract: the dark block REDEFINES custom properties, so every consumer
17
+ * appends it AFTER all of its base rules — the engine pushes it after the page's css blocks, the
18
+ * builder registry keeps it as its last token rule (responsive A3 lesson).
19
+ */
20
+
21
+ /** The transport-agnostic token row. `source` marks seeded rows (`flavor:<id>@<ver>`). */
22
+ export interface DesignTokenLike {
23
+ name: string;
24
+ value: string;
25
+ /** Per-scheme overrides. Only `dark` exists today; absent means the base value everywhere. */
26
+ values?: { dark?: string };
27
+ type?: string;
28
+ source?: string;
29
+ }
30
+
31
+ export interface TokenCssOptions {
32
+ /** Selector that carries the variables instead of `:root` — a preview wrapper, a specimen. */
33
+ scope?: string;
34
+ }
35
+
36
+ export interface TokenCssBlocks {
37
+ /** Base, schemes and the two accessibility blocks — emitted BEFORE node rules. */
38
+ base: string;
39
+ /** The prefers-color-scheme block(s) — emitted AFTER every base rule. */
40
+ dark: string;
41
+ }
42
+
43
+ /** What `prefers-reduced-motion: reduce` collapses — the contract's complete list (`a11y.reducedMotion`). */
44
+ export const REDUCED_MOTION_OVERRIDES: Readonly<Record<string, string>> = SPEC_A11Y.reducedMotion;
45
+
46
+ /** What `prefers-reduced-transparency: reduce` makes solid — the contract's `a11y.reducedTransparency`. */
47
+ export const REDUCED_TRANSPARENCY_OVERRIDES: Readonly<Record<string, string>> = SPEC_A11Y.reducedTransparency;
48
+
49
+ const ROOT = ':root';
50
+ const DEFAULT_SCHEME = 'default';
51
+ const REFERENCE = 'var(';
52
+ const MEDIA_DARK = '(prefers-color-scheme: dark)';
53
+ const ACCESSIBILITY_MEDIA: ReadonlyArray<{ query: string; overrides: Readonly<Record<string, string>> }> = [
54
+ { query: '(prefers-reduced-motion: reduce)', overrides: REDUCED_MOTION_OVERRIDES },
55
+ { query: '(prefers-reduced-transparency: reduce)', overrides: REDUCED_TRANSPARENCY_OVERRIDES },
56
+ ];
57
+
58
+ const usable = (t: DesignTokenLike | null | undefined): t is DesignTokenLike =>
59
+ !!t && typeof t.name === 'string' && t.name !== '' &&
60
+ typeof t.value === 'string' && t.value !== '';
61
+
62
+ const darkOf = (t: DesignTokenLike): string | null => {
63
+ const dark = t.values?.dark;
64
+ return typeof dark === 'string' && dark !== '' ? dark : null;
65
+ };
66
+
67
+ const usableTokens = (tokens: ReadonlyArray<DesignTokenLike> | null | undefined): DesignTokenLike[] =>
68
+ (tokens ?? []).filter(usable);
69
+
70
+ const declarations = (entries: ReadonlyArray<[string, string]>, indent: string): string =>
71
+ entries.map(([name, value]) => `${indent}--iox-${name}: ${value};`).join('\n');
72
+
73
+ const rule = (selector: string, entries: ReadonlyArray<[string, string]>, indent = ''): string =>
74
+ entries.length ? `${indent}${selector} {\n${declarations(entries, indent + ' ')}\n${indent}}` : '';
75
+
76
+ const media = (query: string, rules: ReadonlyArray<string>): string => {
77
+ const body = rules.filter(Boolean);
78
+ return body.length ? `@media ${query} {\n${body.join('\n')}\n}` : '';
79
+ };
80
+
81
+ const schemeSelector = (id: string, scope?: string) =>
82
+ scope ? `${scope} .iox-scheme-${id}` : `.iox-scheme-${id}`;
83
+
84
+ const nonDefaultSchemes = (): ReadonlyArray<[string, Readonly<Record<string, string>>]> =>
85
+ Object.entries(SPEC_SCHEMES)
86
+ .filter(([id]) => id !== DEFAULT_SCHEME)
87
+ .map(([id, scheme]) => [id, scheme.set as Readonly<Record<string, string>>]);
88
+
89
+ /** `{ 'iox-brand': '#2f6f62', … }` — the builder registry's input shape for base values. */
90
+ export function tokensToVarMap(tokens: ReadonlyArray<DesignTokenLike> | null | undefined): Record<string, string> {
91
+ const map: Record<string, string> = {};
92
+ for (const t of usableTokens(tokens)) map[`iox-${t.name}`] = t.value;
93
+ return map;
94
+ }
95
+
96
+ /** Only the tokens that carry a dark override, as `{ 'iox-name': darkValue }`. */
97
+ export function tokensToDarkVarMap(tokens: ReadonlyArray<DesignTokenLike> | null | undefined): Record<string, string> {
98
+ const map: Record<string, string> = {};
99
+ for (const t of usableTokens(tokens)) {
100
+ const dark = darkOf(t);
101
+ if (dark !== null) map[`iox-${t.name}`] = dark;
102
+ }
103
+ return map;
104
+ }
105
+
106
+ const TOKEN_REF = /var\(\s*--iox-([\w-]+)\s*(?:,([^()]*))?\)/g;
107
+ const PLACEHOLDER = /\{\{\s*([\w-]+)\s*\}\}/g;
108
+
109
+ type Mode = 'light' | 'dark';
110
+
111
+ const modeValue = (t: DesignTokenLike, mode: Mode): string => (mode === 'dark' ? darkOf(t) ?? t.value : t.value);
112
+
113
+ /** Every token's ROOT value in one mode, with `var(--iox-…)` references resolved against the same
114
+ * set (recursively; a reference cycle or an unknown token is left as written). */
115
+ export function resolveTokenValues(
116
+ tokens: ReadonlyArray<DesignTokenLike> | null | undefined,
117
+ mode: Mode = 'light',
118
+ ): Record<string, string> {
119
+ const raw = new Map(usableTokens(tokens).map(t => [t.name, modeValue(t, mode)]));
120
+ const out: Record<string, string> = {};
121
+ const resolve = (name: string, trail: ReadonlySet<string>): string | null => {
122
+ if (name in out) return out[name];
123
+ const value = raw.get(name);
124
+ if (value === undefined || trail.has(name)) return null;
125
+ const next = new Set(trail).add(name);
126
+ return value.replace(TOKEN_REF, (ref, inner: string, fallback?: string) =>
127
+ resolve(inner, next) ?? (fallback !== undefined ? fallback.trim() : ref));
128
+ };
129
+ for (const name of raw.keys()) {
130
+ const value = resolve(name, new Set());
131
+ if (value !== null) out[name] = value;
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /** A scheme value with its `{{token}}` placeholders replaced by resolved root values — or null
137
+ * when a placeholder names a token the set does not have (the declaration is then omitted). */
138
+ function substitute(template: string, resolved: Readonly<Record<string, string>>): string | null {
139
+ let missing = false;
140
+ const value = template.replace(PLACEHOLDER, (_, name: string) => {
141
+ if (!(name in resolved)) missing = true;
142
+ return resolved[name] ?? '';
143
+ });
144
+ return missing ? null : value;
145
+ }
146
+
147
+ const schemeEntries = (set: Readonly<Record<string, string>>, resolved: Readonly<Record<string, string>>) =>
148
+ Object.entries(set)
149
+ .map(([name, template]): [string, string | null] => [name, substitute(template, resolved)])
150
+ .filter((e): e is [string, string] => e[1] !== null);
151
+
152
+ const hasPlaceholder = (value: string) => value.includes('{{');
153
+
154
+ /**
155
+ * Section colour schemes (design-system plan §3c). Two rules, both about WHERE a custom property
156
+ * resolves:
157
+ *
158
+ * - ⚠️ Custom properties resolve where they are DECLARED: `--iox-card-bg: var(--iox-surface)`
159
+ * declared on `:root` keeps `:root`'s surface inside `.iox-scheme-inverse`. So each scheme block
160
+ * carries the spec's overrides PLUS every other token whose value references a token,
161
+ * re-declared verbatim — re-resolving it in the section.
162
+ * - ⚠️ A scheme that SWAPS two tokens (Brand: accent ⇄ accent-ink) cannot write them as `var()`:
163
+ * on one element `accent: var(--iox-accent-ink)` + `accent-ink: var(--iox-accent)` is a cycle,
164
+ * and CSS makes both invalid. The contract writes `{{accent}}` instead — the token's ROOT value,
165
+ * resolved here at compile time (and again from dark values for the dark twin).
166
+ */
167
+ export function compileSchemeCss(tokens: ReadonlyArray<DesignTokenLike> | null | undefined, scope?: string): string {
168
+ const rows = usableTokens(tokens);
169
+ if (!rows.length) return '';
170
+ const resolved = resolveTokenValues(rows, 'light');
171
+ return nonDefaultSchemes().map(([id, set]) => rule(schemeSelector(id, scope), [
172
+ ...schemeEntries(set, resolved),
173
+ ...rows.filter(t => !(t.name in set) && t.value.includes(REFERENCE))
174
+ .map((t): [string, string] => [t.name, t.value]),
175
+ ])).filter(Boolean).join('\n');
176
+ }
177
+
178
+ /** The dark twin of both scheme rules: a re-declared token with a dark value would otherwise pin
179
+ * the LIGHT value inside the section, and a `{{token}}` swap was resolved from LIGHT values. */
180
+ function darkSchemeRules(rows: ReadonlyArray<DesignTokenLike>, scope: string | undefined): string[] {
181
+ const light = resolveTokenValues(rows, 'light');
182
+ const dark = resolveTokenValues(rows, 'dark');
183
+ const redeclared = rows.filter(t => {
184
+ const d = darkOf(t);
185
+ return d !== null && (t.value.includes(REFERENCE) || d.includes(REFERENCE));
186
+ });
187
+ return nonDefaultSchemes().map(([id, set]) => {
188
+ const swapped = Object.fromEntries(Object.entries(set).filter(([, v]) => hasPlaceholder(v)));
189
+ const lightSwap = new Map(schemeEntries(swapped, light));
190
+ return rule(schemeSelector(id, scope), [
191
+ ...schemeEntries(swapped, dark).filter(([name, value]) => lightSwap.get(name) !== value),
192
+ ...redeclared.filter(t => !(t.name in set)).map((t): [string, string] => [t.name, darkOf(t) as string]),
193
+ ], ' ');
194
+ });
195
+ }
196
+
197
+ function presentOverrides(rows: ReadonlyArray<DesignTokenLike>, overrides: Readonly<Record<string, string>>,
198
+ onlyWithDark: boolean): Array<[string, string]> {
199
+ return Object.entries(overrides).filter(([name]) => rows.some(t => t.name === name && (!onlyWithDark || darkOf(t) !== null)));
200
+ }
201
+
202
+ /** The token CSS as the two halves a renderer places around its node rules. */
203
+ export function compileTokenCssBlocks(
204
+ tokens: ReadonlyArray<DesignTokenLike> | null | undefined,
205
+ opts: TokenCssOptions = {},
206
+ ): TokenCssBlocks {
207
+ const rows = usableTokens(tokens);
208
+ const root = opts.scope ?? ROOT;
209
+ const base = [
210
+ rule(root, rows.map((t): [string, string] => [t.name, t.value])),
211
+ compileSchemeCss(rows, opts.scope),
212
+ ...ACCESSIBILITY_MEDIA.map(({ query, overrides }) =>
213
+ media(query, [rule(root, presentOverrides(rows, overrides, false), ' ')])),
214
+ ].filter(Boolean).join('\n');
215
+
216
+ const darkRows = rows.map((t): [string, string | null] => [t.name, darkOf(t)])
217
+ .filter((e): e is [string, string] => e[1] !== null);
218
+ const dark = darkRows.length ? [
219
+ media(MEDIA_DARK, [rule(root, darkRows, ' '), ...darkSchemeRules(rows, opts.scope)]),
220
+ // Glass carries dark glass values; without this the dark block (LAST) would out-rank the
221
+ // reduced-transparency swap and keep dark surfaces translucent.
222
+ ...ACCESSIBILITY_MEDIA.map(({ query, overrides }) =>
223
+ media(`${MEDIA_DARK} and ${query}`, [rule(root, presentOverrides(rows, overrides, true), ' ')])),
224
+ ].filter(Boolean).join('\n') : '';
225
+
226
+ return { base, dark };
227
+ }
228
+
229
+ /** One stylesheet string: base → schemes → reduced motion → reduced transparency → dark LAST. */
230
+ export function compileTokenCss(tokens: ReadonlyArray<DesignTokenLike> | null | undefined, opts: TokenCssOptions = {}): string {
231
+ const { base, dark } = compileTokenCssBlocks(tokens, opts);
232
+ return [base, dark].filter(Boolean).join('\n');
233
+ }