@cdx-ui/styles 0.0.1-beta.9 → 0.0.1-beta.91

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.
Files changed (71) hide show
  1. package/README.md +116 -20
  2. package/css/theme.css +201 -85
  3. package/css/vanilla.css +124 -54
  4. package/lib/commonjs/applyThemeOverride.js +154 -0
  5. package/lib/commonjs/applyThemeOverride.js.map +1 -0
  6. package/lib/commonjs/index.js +82 -0
  7. package/lib/commonjs/index.js.map +1 -1
  8. package/lib/commonjs/palette.js +262 -0
  9. package/lib/commonjs/palette.js.map +1 -0
  10. package/lib/commonjs/theming.js +255 -0
  11. package/lib/commonjs/theming.js.map +1 -0
  12. package/lib/commonjs/types.js +75 -0
  13. package/lib/commonjs/types.js.map +1 -0
  14. package/lib/commonjs/useCdxFonts.js +4 -231
  15. package/lib/commonjs/useCdxFonts.js.map +1 -1
  16. package/lib/commonjs/useForgeFonts.js +237 -0
  17. package/lib/commonjs/useForgeFonts.js.map +1 -0
  18. package/lib/module/applyThemeOverride.js +149 -0
  19. package/lib/module/applyThemeOverride.js.map +1 -0
  20. package/lib/module/index.js +11 -20
  21. package/lib/module/index.js.map +1 -1
  22. package/lib/module/palette.js +257 -0
  23. package/lib/module/palette.js.map +1 -0
  24. package/lib/module/theming.js +239 -0
  25. package/lib/module/theming.js.map +1 -0
  26. package/lib/module/types.js +71 -0
  27. package/lib/module/types.js.map +1 -0
  28. package/lib/module/useCdxFonts.js +3 -219
  29. package/lib/module/useCdxFonts.js.map +1 -1
  30. package/lib/module/useForgeFonts.js +223 -0
  31. package/lib/module/useForgeFonts.js.map +1 -0
  32. package/lib/runtime/prestige-vs-default.json +1 -0
  33. package/lib/runtime/pulse-vs-default.json +1 -0
  34. package/lib/runtime/token-to-css-var.json +672 -0
  35. package/lib/typescript/applyThemeOverride.d.ts +26 -0
  36. package/lib/typescript/applyThemeOverride.d.ts.map +1 -0
  37. package/lib/typescript/index.d.ts +8 -57
  38. package/lib/typescript/index.d.ts.map +1 -1
  39. package/lib/typescript/palette.d.ts +60 -0
  40. package/lib/typescript/palette.d.ts.map +1 -0
  41. package/lib/typescript/theming.d.ts +40 -0
  42. package/lib/typescript/theming.d.ts.map +1 -0
  43. package/lib/typescript/types.d.ts +90 -0
  44. package/lib/typescript/types.d.ts.map +1 -0
  45. package/lib/typescript/useCdxFonts.d.ts +3 -11
  46. package/lib/typescript/useCdxFonts.d.ts.map +1 -1
  47. package/lib/typescript/useForgeFonts.d.ts +12 -0
  48. package/lib/typescript/useForgeFonts.d.ts.map +1 -0
  49. package/package.json +27 -8
  50. package/runtime/prestige-vs-default.json +1 -0
  51. package/runtime/pulse-vs-default.json +1 -0
  52. package/runtime/token-to-css-var.json +672 -0
  53. package/src/__tests__/applyThemeOverride.test.ts +552 -0
  54. package/src/__tests__/generateColorScale.test.ts +296 -0
  55. package/src/__tests__/presetJson.test.ts +120 -0
  56. package/src/__tests__/sd.config.test.ts +856 -0
  57. package/src/__tests__/theming.test.ts +647 -0
  58. package/src/__tests__/types.test.ts +72 -0
  59. package/src/__tests__/useCdxFonts.test.ts +27 -0
  60. package/src/__tests__/useForgeFonts.test.ts +226 -0
  61. package/src/applyThemeOverride.ts +139 -0
  62. package/src/index.ts +36 -60
  63. package/src/palette.ts +307 -0
  64. package/src/theming.ts +268 -0
  65. package/src/types.ts +112 -0
  66. package/src/useCdxFonts.ts +3 -229
  67. package/src/useForgeFonts.ts +230 -0
  68. package/tokens/presets/.manifest.json +3 -3
  69. package/tokens/presets/poise.json +319 -39
  70. package/tokens/presets/prestige.json +1 -1
  71. package/tokens/presets/pulse.json +1 -1
package/src/palette.ts ADDED
@@ -0,0 +1,307 @@
1
+ import { BackgroundColor, Color, Theme, type CssColor } from '@adobe/leonardo-contrast-colors';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Types
5
+ // ---------------------------------------------------------------------------
6
+
7
+ /** Palette step keys produced by `generateColorScale`. */
8
+ export type PaletteStep =
9
+ | '50'
10
+ | '100'
11
+ | '200'
12
+ | '300'
13
+ | '400'
14
+ | '500'
15
+ | '600'
16
+ | '700'
17
+ | '800'
18
+ | '900'
19
+ | '950'
20
+ | 'input';
21
+
22
+ /** Token category that supports palette generation. */
23
+ export type PaletteCategory = 'brand' | 'accent' | 'base';
24
+
25
+ /** Map of palette step → resolved hex color. */
26
+ export type PaletteScale = Record<PaletteStep, string>;
27
+
28
+ /** Map of token dot-path → resolved hex color (e.g. `color.brand.500` → `#548cdc`). */
29
+ export type PaletteTokenMap = Record<string, string>;
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Constants
33
+ // ---------------------------------------------------------------------------
34
+
35
+ const REFERENCE_BACKGROUND = '#ffffff';
36
+
37
+ const PALETTE_STEPS = [
38
+ '50',
39
+ '100',
40
+ '200',
41
+ '300',
42
+ '400',
43
+ '500',
44
+ '600',
45
+ '700',
46
+ '800',
47
+ '900',
48
+ '950',
49
+ ] as const;
50
+
51
+ /**
52
+ * Contrast ratios for each palette step against white (#ffffff).
53
+ *
54
+ * Step 700 targets WCAG AA for normal text (≥ 4.5:1).
55
+ */
56
+ const CONTRAST_RATIOS: Record<(typeof PALETTE_STEPS)[number], number> = {
57
+ '50': 1.04,
58
+ '100': 1.16,
59
+ '200': 1.46,
60
+ '300': 1.85,
61
+ '400': 2.45,
62
+ '500': 3.4,
63
+ '600': 4.8,
64
+ '700': 6.4,
65
+ '800': 8.6,
66
+ '900': 12,
67
+ '950': 16.8,
68
+ };
69
+
70
+ const HEX_REGEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Validation
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /**
77
+ * Validate and normalise a hex color string.
78
+ *
79
+ * Accepts `#RGB` (4 chars) or `#RRGGBB` (7 chars). Throws a descriptive
80
+ * `TypeError` for any other input.
81
+ *
82
+ * @returns The normalised 7-character hex string (e.g. `#aabbcc`).
83
+ */
84
+ function validateHex(hex: string): CssColor {
85
+ if (typeof hex !== 'string') {
86
+ throw new TypeError(`Invalid hex color: expected a string, received ${typeof hex}`);
87
+ }
88
+
89
+ if (!HEX_REGEX.test(hex)) {
90
+ throw new TypeError(
91
+ `Invalid hex color "${hex}": must be a 4-character (#RGB) or 7-character (#RRGGBB) hex string starting with "#"`,
92
+ );
93
+ }
94
+
95
+ if (hex.length === 4) {
96
+ const [, r, g, b] = hex;
97
+ return `#${r}${r}${g}${g}${b}${b}`.toLowerCase() as CssColor;
98
+ }
99
+
100
+ return hex.toLowerCase() as CssColor;
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // Core generation — wraps Leonardo behind a thin interface
105
+ // ---------------------------------------------------------------------------
106
+
107
+ /**
108
+ * Generate an 11-step contrast-based color scale from a single hex color.
109
+ *
110
+ * Uses `@adobe/leonardo-contrast-colors` internally. The generation algorithm
111
+ * is wrapped behind this function so the underlying library is swappable
112
+ * without changing the public API.
113
+ *
114
+ * @param hex - A valid hex color string (`#RGB` or `#RRGGBB`).
115
+ * @param category - The token namespace (`'brand'` or `'accent'`).
116
+ * @returns A `PaletteTokenMap` keyed by token dot-paths
117
+ * (e.g. `"color.brand.50"` through `"color.brand.950"` plus `"color.brand.input"`).
118
+ */
119
+ export function generateColorScale(hex: string, category: PaletteCategory): PaletteTokenMap {
120
+ const normalised = validateHex(hex);
121
+
122
+ const ratiosObject: Record<string, number> = {};
123
+ for (const step of PALETTE_STEPS) {
124
+ ratiosObject[step] = CONTRAST_RATIOS[step];
125
+ }
126
+
127
+ const color = new Color({
128
+ name: 'palette',
129
+ colorKeys: [normalised],
130
+ colorSpace: 'CAM02p',
131
+ ratios: ratiosObject,
132
+ smooth: true,
133
+ output: 'HEX',
134
+ });
135
+
136
+ const bg = new BackgroundColor({
137
+ name: 'background',
138
+ colorKeys: [REFERENCE_BACKGROUND],
139
+ colorSpace: 'CAM02p',
140
+ smooth: true,
141
+ ratios: [],
142
+ output: 'HEX',
143
+ });
144
+
145
+ const theme = new Theme({
146
+ colors: [color],
147
+ backgroundColor: bg,
148
+ lightness: 100,
149
+ contrast: 1,
150
+ saturation: 100,
151
+ output: 'HEX',
152
+ formula: 'wcag2',
153
+ });
154
+
155
+ const pairs = theme.contrastColorPairs;
156
+
157
+ const tokenPrefix = `color.${category}`;
158
+ const result: PaletteTokenMap = {};
159
+
160
+ for (const step of PALETTE_STEPS) {
161
+ result[`${tokenPrefix}.${step}`] = pairs[step].toLowerCase();
162
+ }
163
+
164
+ result[`${tokenPrefix}.input`] = normalised;
165
+
166
+ return result;
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Base color-key derivation
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /** Saturation (0–1) applied to the brand hue to produce the base color key. */
174
+ const BASE_SATURATION = 0.05;
175
+
176
+ /** Convert a normalised hex string to HSL (`h` in degrees, `s`/`l` in 0–1). */
177
+ function hexToHsl(hex: CssColor): { h: number; s: number; l: number } {
178
+ const r = parseInt(hex.slice(1, 3), 16) / 255;
179
+ const g = parseInt(hex.slice(3, 5), 16) / 255;
180
+ const b = parseInt(hex.slice(5, 7), 16) / 255;
181
+
182
+ const max = Math.max(r, g, b);
183
+ const min = Math.min(r, g, b);
184
+ const delta = max - min;
185
+ const l = (max + min) / 2;
186
+
187
+ let h = 0;
188
+ let s = 0;
189
+ if (delta !== 0) {
190
+ s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
191
+ switch (max) {
192
+ case r:
193
+ h = (g - b) / delta + (g < b ? 6 : 0);
194
+ break;
195
+ case g:
196
+ h = (b - r) / delta + 2;
197
+ break;
198
+ default:
199
+ h = (r - g) / delta + 4;
200
+ break;
201
+ }
202
+ h *= 60;
203
+ }
204
+
205
+ return { h, s, l };
206
+ }
207
+
208
+ /** Convert HSL (`h` in degrees, `s`/`l` in 0–1) to a normalised hex string. */
209
+ function hslToHex({ h, s, l }: { h: number; s: number; l: number }): CssColor {
210
+ const c = (1 - Math.abs(2 * l - 1)) * s;
211
+ const hp = (((h % 360) + 360) % 360) / 60;
212
+ const x = c * (1 - Math.abs((hp % 2) - 1));
213
+
214
+ let r = 0;
215
+ let g = 0;
216
+ let b = 0;
217
+ if (hp < 1) [r, g, b] = [c, x, 0];
218
+ else if (hp < 2) [r, g, b] = [x, c, 0];
219
+ else if (hp < 3) [r, g, b] = [0, c, x];
220
+ else if (hp < 4) [r, g, b] = [0, x, c];
221
+ else if (hp < 5) [r, g, b] = [x, 0, c];
222
+ else [r, g, b] = [c, 0, x];
223
+
224
+ const m = l - c / 2;
225
+ const toHex = (v: number) =>
226
+ Math.round((v + m) * 255)
227
+ .toString(16)
228
+ .padStart(2, '0');
229
+
230
+ return `#${toHex(r)}${toHex(g)}${toHex(b)}` as CssColor;
231
+ }
232
+
233
+ /**
234
+ * Derive the base palette color key from a brand color.
235
+ *
236
+ * The base scale shares the brand's hue and lightness but is nearly neutral:
237
+ * the brand color is converted to HSL and its saturation is lowered to
238
+ * {@link BASE_SATURATION} (5%). The resulting hex is the color key fed to
239
+ * {@link generateColorScale} for the `base` category.
240
+ *
241
+ * @param brandHex - A valid hex color string (`#RGB` or `#RRGGBB`).
242
+ * @returns The normalised hex color key for the base scale.
243
+ */
244
+ export function deriveBaseColorKey(brandHex: string): string {
245
+ const { h, l } = hexToHsl(validateHex(brandHex));
246
+ return hslToHex({ h, s: BASE_SATURATION, l });
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Convenience wrapper
251
+ // ---------------------------------------------------------------------------
252
+
253
+ /**
254
+ * Colour-input keys whose token path starts with `color.` — these trigger
255
+ * palette generation. Mirrors the colour entries from `INPUT_TOKEN_MAP`
256
+ * (defined in the package barrel) without creating a circular import.
257
+ *
258
+ * Keep in sync with `INPUT_TOKEN_MAP` in `./index.ts`.
259
+ */
260
+ const COLOR_INPUT_ENTRIES: readonly (readonly [string, string])[] = [
261
+ ['brandPrimary', 'color.brand'],
262
+ ['accentPrimary', 'color.accent'],
263
+ ['basePrimary', 'color.base'],
264
+ ] as const;
265
+
266
+ /**
267
+ * Generate palettes for all colour inputs in a theme override `inputs` object.
268
+ *
269
+ * Iterates over known colour-input keys that map to a `color.*` token
270
+ * namespace. For each matching key present in `inputs`, runs
271
+ * `generateColorScale` and merges the results into a single flat map of
272
+ * token dot-paths to hex values — ready for the S5 override application
273
+ * merge step.
274
+ *
275
+ * Non-colour inputs (e.g. `displayFont`) are silently skipped.
276
+ *
277
+ * @param inputs - The `inputs` object from a `ThemeOverride`.
278
+ * @returns A merged `Record<string, string>` of all generated token
279
+ * dot-paths to hex values.
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * const inputs = { brandPrimary: '#0052cc', accentPrimary: '#FF8C42', displayFont: 'Poppins' };
284
+ * const result = generatePalettesFromInputs(inputs);
285
+ * // {
286
+ * // "color.brand.50": "#...", …, "color.brand.input": "#0052cc",
287
+ * // "color.accent.50": "#...", …, "color.accent.input": "#ff8c42"
288
+ * // }
289
+ * ```
290
+ */
291
+ export function generatePalettesFromInputs(
292
+ inputs: Record<string, string | number>,
293
+ ): PaletteTokenMap {
294
+ const result: PaletteTokenMap = {};
295
+
296
+ for (const [inputKey, tokenPath] of COLOR_INPUT_ENTRIES) {
297
+ const value = inputs[inputKey];
298
+ if (typeof value !== 'string') continue;
299
+
300
+ const category = tokenPath.replace('color.', '') as PaletteCategory;
301
+ const scale = generateColorScale(value, category);
302
+
303
+ Object.assign(result, scale);
304
+ }
305
+
306
+ return result;
307
+ }
package/src/theming.ts ADDED
@@ -0,0 +1,268 @@
1
+ import { generatePalettesFromInputs } from './palette';
2
+ import {
3
+ INPUT_TOKEN_MAP,
4
+ SUPPORTED_OVERRIDE_SCHEMA_VERSIONS,
5
+ type Mode,
6
+ type Platform,
7
+ type ThemeOverride,
8
+ type TokenGroup,
9
+ type TokenValue,
10
+ } from './types';
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Re-export orchestrator
14
+ // ---------------------------------------------------------------------------
15
+
16
+ export { applyThemeOverride, DEFAULT_PRESET } from './applyThemeOverride';
17
+ export type { ApplyThemeOverrideOptions, ApplyThemeOverrideResult } from './applyThemeOverride';
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Types
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /** Per-mode CSS variable maps ready for `Uniwind.updateCSSVariables`. */
24
+ export interface CssVariableMaps {
25
+ light: Record<string, string>;
26
+ dark: Record<string, string>;
27
+ }
28
+
29
+ /** Runtime map: token dot-paths → CSS custom property names. */
30
+ export type RuntimeMap = Record<string, string>;
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Schema version gate
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Check whether a `ThemeOverride`'s schema version is supported by the current
38
+ * build of `@cdx-ui/styles`.
39
+ */
40
+ export function isSchemaVersionSupported(override: ThemeOverride): boolean {
41
+ const version = override.$extensions['com.forge.ui.themeOverride'].schemaVersion;
42
+ return SUPPORTED_OVERRIDE_SCHEMA_VERSIONS.includes(version);
43
+ }
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // DTCG tree walker
47
+ // ---------------------------------------------------------------------------
48
+
49
+ function isTokenValue(node: unknown): node is TokenValue {
50
+ return typeof node === 'object' && node !== null && '$value' in node && '$type' in node;
51
+ }
52
+
53
+ /**
54
+ * Recursively walk a nested DTCG object and collect all `$value` leaves with
55
+ * their full dot-path.
56
+ */
57
+ function flattenDtcg(
58
+ node: TokenGroup,
59
+ prefix: string,
60
+ result: Record<string, string | number>,
61
+ ): void {
62
+ for (const key of Object.keys(node)) {
63
+ if (key.startsWith('$')) continue;
64
+
65
+ const child = node[key];
66
+ const path = prefix ? `${prefix}.${key}` : key;
67
+
68
+ if (isTokenValue(child)) {
69
+ result[path] = child.$value;
70
+ } else if (typeof child === 'object' && child !== null) {
71
+ flattenDtcg(child, path, result);
72
+ }
73
+ }
74
+ }
75
+
76
+ // ---------------------------------------------------------------------------
77
+ // Shared mode-bucketing
78
+ // ---------------------------------------------------------------------------
79
+
80
+ function bucketByMode(
81
+ flatTokens: Record<string, string | number>,
82
+ runtimeMap: RuntimeMap,
83
+ runtimePlatform: Platform,
84
+ ): CssVariableMaps {
85
+ const light: Record<string, string> = {};
86
+ const dark: Record<string, string> = {};
87
+
88
+ for (const [dotPath, value] of Object.entries(flatTokens)) {
89
+ const strValue = String(value);
90
+
91
+ if (dotPath.startsWith('modes.light.')) {
92
+ const cssVar = runtimeMap[dotPath];
93
+ if (cssVar) light[cssVar] = strValue;
94
+ } else if (dotPath.startsWith('modes.dark.')) {
95
+ const cssVar = runtimeMap[dotPath];
96
+ if (cssVar) dark[cssVar] = strValue;
97
+ } else if (dotPath.startsWith('platform.')) {
98
+ const segments = dotPath.split('.');
99
+ const platform = segments[1];
100
+ if (platform !== runtimePlatform) continue;
101
+
102
+ const cssVar = runtimeMap[dotPath];
103
+ if (cssVar) {
104
+ light[cssVar] = strValue;
105
+ dark[cssVar] = strValue;
106
+ }
107
+ } else {
108
+ const cssVar = runtimeMap[dotPath];
109
+ if (cssVar) {
110
+ light[cssVar] = strValue;
111
+ dark[cssVar] = strValue;
112
+ }
113
+ }
114
+ }
115
+
116
+ return { light, dark };
117
+ }
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // Preset patch → Uniwind maps
121
+ // ---------------------------------------------------------------------------
122
+
123
+ /**
124
+ * Convert a nested DTCG preset patch (sparse, `$type`/`$value` leaves) into
125
+ * per-mode CSS variable maps suitable for `Uniwind.updateCSSVariables`.
126
+ *
127
+ * @param patch - A sparse DTCG token object (preset patch).
128
+ * @param runtimeMap - The generated token-to-CSS-var mapping.
129
+ * @param runtimePlatform - Current platform (`'web' | 'ios' | 'android'`).
130
+ */
131
+ export function presetPatchToUniwindMaps(
132
+ patch: TokenGroup,
133
+ runtimeMap: RuntimeMap,
134
+ runtimePlatform: Platform,
135
+ ): CssVariableMaps {
136
+ const flat: Record<string, string | number> = {};
137
+ flattenDtcg(patch, '', flat);
138
+ return bucketByMode(flat, runtimeMap, runtimePlatform);
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // FI override → Uniwind maps
143
+ // ---------------------------------------------------------------------------
144
+
145
+ /**
146
+ * Non-color input keys from INPUT_TOKEN_MAP whose token path does NOT start
147
+ * with `color.`. These are handled separately from palette generation.
148
+ */
149
+ const FONT_INPUT_ENTRIES: readonly (readonly [string, string])[] = (
150
+ Object.entries(INPUT_TOKEN_MAP) as [string, string][]
151
+ ).filter(([, tokenPath]) => !tokenPath.startsWith('color.'));
152
+
153
+ /**
154
+ * Matches a token-reference alias value such as `{color.brand.700}` and
155
+ * captures the referenced token dot-path.
156
+ */
157
+ const TOKEN_ALIAS_REGEX = /^\{([^}]+)\}$/;
158
+
159
+ /**
160
+ * Resolve an `overrides.{mode}` value into the string written to the CSS
161
+ * variable map.
162
+ *
163
+ * - **Token-reference alias** (`{color.brand.700}`) → resolves the referenced
164
+ * token path via the runtime map and returns a CSS `var()` reference
165
+ * (`var(--color-brand-700)`), so the override tracks its source through the
166
+ * cascade — the same mechanism the base theme uses for its semantic tokens.
167
+ * Returns `null` when the referenced path is absent from the runtime map
168
+ * (e.g. a non-primitive target), so the caller skips it; this enforces the
169
+ * primitive-only alias constraint at the resolution layer.
170
+ * - **Literal value** (`#F5F7F6`, `8`) → returned as-is (stringified).
171
+ *
172
+ * @see docs/internal/token-architecture/16-override-structure.md — Token-reference aliases vs. literal values
173
+ */
174
+ function resolveOverrideValue(value: string | number, runtimeMap: RuntimeMap): string | null {
175
+ if (typeof value === 'string') {
176
+ const aliasMatch = TOKEN_ALIAS_REGEX.exec(value);
177
+ if (aliasMatch) {
178
+ const referencedPath = aliasMatch[1].trim();
179
+ const targetCssVar = runtimeMap[referencedPath];
180
+ return targetCssVar ? `var(${targetCssVar})` : null;
181
+ }
182
+ }
183
+ return String(value);
184
+ }
185
+
186
+ /**
187
+ * Convert a hybrid FI override (`ThemeOverride`) into per-mode CSS variable
188
+ * maps suitable for `Uniwind.updateCSSVariables`.
189
+ *
190
+ * Processing:
191
+ * 1. Generate palettes from color `inputs` (via S4).
192
+ * 2. Map font inputs to token paths.
193
+ * 3. For each mode, merge palette + fonts + explicit `overrides.{mode}` entries.
194
+ * 4. Map all token dot-paths to CSS variable names via runtime map.
195
+ *
196
+ * @param override - A `ThemeOverride` object.
197
+ * @param runtimeMap - The generated token-to-CSS-var mapping.
198
+ * @param runtimePlatform - Current platform (`'web' | 'ios' | 'android'`).
199
+ */
200
+ export function themeOverrideToUniwindMaps(
201
+ override: ThemeOverride,
202
+ runtimeMap: RuntimeMap,
203
+ // runtimePlatform: Platform,
204
+ ): CssVariableMaps {
205
+ const light: Record<string, string> = {};
206
+ const dark: Record<string, string> = {};
207
+
208
+ const inputs = override.inputs;
209
+ const overrides = override.overrides;
210
+
211
+ if (!inputs && !overrides) {
212
+ return { light, dark };
213
+ }
214
+
215
+ // --- Palette generation from colour inputs ---
216
+ let paletteTokens: Record<string, string> = {};
217
+ if (inputs) {
218
+ paletteTokens = generatePalettesFromInputs(inputs);
219
+ }
220
+
221
+ // --- Font input mapping ---
222
+ const fontTokens: Record<string, string> = {};
223
+ if (inputs) {
224
+ for (const [inputKey, tokenPath] of FONT_INPUT_ENTRIES) {
225
+ const value = inputs[inputKey];
226
+ if (value !== undefined) {
227
+ fontTokens[tokenPath] = String(value);
228
+ }
229
+ }
230
+ }
231
+
232
+ // --- Merge per mode ---
233
+ const modes: Mode[] = ['light', 'dark'];
234
+
235
+ for (const mode of modes) {
236
+ const bucket = mode === 'light' ? light : dark;
237
+
238
+ // 1. Palette-generated primitives (mode-independent → both buckets)
239
+ for (const [dotPath, hexValue] of Object.entries(paletteTokens)) {
240
+ const cssVar = runtimeMap[dotPath];
241
+ if (cssVar) bucket[cssVar] = hexValue;
242
+ }
243
+
244
+ // 2. Font input mappings (mode-independent → both buckets)
245
+ for (const [tokenPath, value] of Object.entries(fontTokens)) {
246
+ const modePrefixed = `modes.${mode}.${tokenPath}`;
247
+ const cssVar = runtimeMap[modePrefixed] ?? runtimeMap[tokenPath];
248
+ if (cssVar) bucket[cssVar] = value;
249
+ }
250
+
251
+ // 3. Explicit per-mode overrides (wins on collision). Values may be
252
+ // token-reference aliases (resolved to a CSS var() reference) or
253
+ // literals; see resolveOverrideValue.
254
+ const modeOverrides = overrides?.[mode];
255
+ if (modeOverrides) {
256
+ for (const [dotPath, value] of Object.entries(modeOverrides)) {
257
+ const modePrefixed = `modes.${mode}.${dotPath}`;
258
+ const cssVar = runtimeMap[modePrefixed] ?? runtimeMap[dotPath];
259
+ if (!cssVar) continue;
260
+
261
+ const resolved = resolveOverrideValue(value, runtimeMap);
262
+ if (resolved !== null) bucket[cssVar] = resolved;
263
+ }
264
+ }
265
+ }
266
+
267
+ return { light, dark };
268
+ }
package/src/types.ts ADDED
@@ -0,0 +1,112 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Types
3
+ // ---------------------------------------------------------------------------
4
+
5
+ /** A DTCG token leaf node. */
6
+ export interface TokenValue {
7
+ $type: string;
8
+ $value: string | number;
9
+ $extensions?: Record<string, unknown>;
10
+ }
11
+
12
+ /** Recursive token group — every non-leaf node in a theme object. */
13
+ export interface TokenGroup {
14
+ [key: string]: TokenValue | TokenGroup;
15
+ }
16
+
17
+ /** The three built-in Forge UI theme presets. */
18
+ export type Preset = 'poise' | 'prestige' | 'pulse';
19
+
20
+ /** Theme metadata stored under `$extensions.com.forge.ui.theme`. */
21
+ export interface ThemeMetadata {
22
+ name: string;
23
+ preset: Preset;
24
+ schemaVersion: string;
25
+ }
26
+
27
+ /** Override metadata stored under `$extensions.com.forge.ui.themeOverride`. */
28
+ export interface ThemeOverrideMetadata {
29
+ basePreset: Preset;
30
+ schemaVersion: string;
31
+ }
32
+
33
+ /**
34
+ * A complete Forge UI theme object (DTCG-compatible).
35
+ *
36
+ * Presets (Poise, Prestige, Pulse) are full theme objects. At runtime the
37
+ * build-time default preset is augmented by FI overrides via
38
+ * `applyThemeOverrides`.
39
+ */
40
+ export type ThemeObject = TokenGroup & {
41
+ $extensions: {
42
+ 'com.forge.ui.theme': ThemeMetadata;
43
+ [key: string]: unknown;
44
+ };
45
+ modes: {
46
+ light: TokenGroup;
47
+ dark: TokenGroup;
48
+ };
49
+ platform: {
50
+ web: TokenGroup;
51
+ ios: TokenGroup;
52
+ android: TokenGroup;
53
+ };
54
+ };
55
+
56
+ /**
57
+ * A theme override using the hybrid input + semantic structure.
58
+ *
59
+ * - `inputs` — flat map of abstract FI-selected brand values (e.g.
60
+ * `brandPrimary`, `displayFont`). Palette generation expands these into
61
+ * full token scales at runtime.
62
+ * - `overrides` — per-mode flat maps of token dot-paths to resolved values
63
+ * for direct semantic token overrides beyond what inputs generate.
64
+ * - `$extensions` — required metadata including base preset and schema version.
65
+ */
66
+ export interface ThemeOverride {
67
+ $extensions: {
68
+ 'com.forge.ui.themeOverride': ThemeOverrideMetadata;
69
+ [key: string]: unknown;
70
+ };
71
+ inputs?: Record<string, string | number>;
72
+ overrides?: Partial<Record<Mode, Record<string, string | number>>>;
73
+ }
74
+
75
+ export type Mode = 'light' | 'dark';
76
+ export type Platform = 'web' | 'ios' | 'android';
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // Constants
80
+ // ---------------------------------------------------------------------------
81
+
82
+ /** Current override schema version. Consuming apps gate compatibility on this. */
83
+ export const OVERRIDE_SCHEMA_VERSION = '1.0.0' as const;
84
+
85
+ /**
86
+ * Schema versions that consuming apps accept. Includes the current version and
87
+ * may include the immediately prior version during transition windows.
88
+ * @see docs/internal/token-architecture/16-override-structure.md § 4
89
+ */
90
+ export const SUPPORTED_OVERRIDE_SCHEMA_VERSIONS: readonly string[] = ['1.0.0'] as const;
91
+
92
+ /**
93
+ * Schema-level mapping from known input keys to the token path pattern each
94
+ * affects. Used by override application (S5) to route inputs to the correct
95
+ * palette/token namespace. Distinct from the full runtime map (S3).
96
+ */
97
+ export const INPUT_TOKEN_MAP = {
98
+ brandPrimary: 'color.brand',
99
+ accentPrimary: 'color.accent',
100
+ basePrimary: 'color.base',
101
+ displayFont: 'font.display',
102
+ } as const satisfies Record<string, string>;
103
+
104
+ /**
105
+ * Allowed display font families per preset, consumed by the theme editor for
106
+ * font selection and by consuming apps for validation.
107
+ */
108
+ export const presetFonts: Record<Preset, readonly string[]> = {
109
+ poise: ['Crimson Pro', 'Bitter', 'DM Sans'],
110
+ prestige: ['Libre Caslon Text', 'Cormorant', 'Libre Franklin'],
111
+ pulse: ['Outfit', 'Manrope', 'Public Sans'],
112
+ } as const;