@link-foundation/ui-tokens 0.0.0-stage → 0.0.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,12 @@
1
+ import type { ResolvedTokens } from '@link-foundation/ui-tokens';
2
+
3
+ /**
4
+ * Build the tokens with Style Dictionary: they (not the other modes) are written as a DTCG
5
+ * 2025.10 file to a temporary directory, which is the `source` of the
6
+ * config. `style-dictionary` is an optional peer dependency.
7
+ */
8
+ export function buildWithStyleDictionary(
9
+ resolved: ResolvedTokens,
10
+ config: Record<string, unknown>,
11
+ options?: { StyleDictionary?: unknown; keepAliases?: boolean }
12
+ ): Promise<unknown>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * `buildWithStyleDictionary(resolved, config)`: run Style Dictionary
3
+ * (https://styledictionary.com) on the tokens, for the platforms this
4
+ * package does not write itself (Android XML, SCSS, Flutter, ...).
5
+ *
6
+ * The tokens are written as a DTCG 2025.10 file (`toDtcg`) to a temporary
7
+ * directory, which becomes the `source` of the Style Dictionary config;
8
+ * the directory is removed afterwards. Only the tokens of `resolved` are
9
+ * written, not the other modes: Style Dictionary has none, so a mode is
10
+ * built from `resolveTokens(sets, id, { mode })`. `style-dictionary` is an optional
11
+ * peer dependency: it is imported only here, only when called, and only
12
+ * when no `StyleDictionary` class is given.
13
+ */
14
+
15
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
16
+ import { tmpdir } from 'node:os';
17
+ import { join } from 'node:path';
18
+ import { toDtcg } from './export/dtcg.js';
19
+
20
+ /** @typedef {import('./types.js').ResolvedTokens} ResolvedTokens */
21
+
22
+ async function loadStyleDictionary() {
23
+ try {
24
+ return (await import('style-dictionary')).default;
25
+ } catch (error) {
26
+ throw new Error(
27
+ 'buildWithStyleDictionary needs the optional peer dependency style-dictionary: npm install --save-dev style-dictionary',
28
+ { cause: error }
29
+ );
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Build the tokens with Style Dictionary.
35
+ * @param {ResolvedTokens} resolved
36
+ * @param {Record<string, any>} config a Style Dictionary config without
37
+ * `source` (it is set to the generated token file): `{ platforms: {
38
+ * scss: { transformGroup: 'scss', buildPath: 'out/', files: [...] } } }`
39
+ * @param {{ StyleDictionary?: any, keepAliases?: boolean }} [options]
40
+ * `StyleDictionary` is the class to use (default: the installed
41
+ * `style-dictionary`); `keepAliases` is passed to `toDtcg`
42
+ * @returns {Promise<any>} the Style Dictionary instance after the build
43
+ */
44
+ export async function buildWithStyleDictionary(
45
+ resolved,
46
+ config,
47
+ { StyleDictionary, keepAliases = true } = {}
48
+ ) {
49
+ const SD = StyleDictionary ?? (await loadStyleDictionary());
50
+ const dir = await mkdtemp(join(tmpdir(), 'link-ui-tokens-'));
51
+ try {
52
+ const source = join(dir, 'tokens.json');
53
+ // Style Dictionary has no modes and reads a root $extensions as a
54
+ // group of tokens; build a mode from tokens resolved with `{ mode }`.
55
+ const tokens = toDtcg(resolved, { keepAliases });
56
+ delete tokens.$extensions;
57
+ await writeFile(source, `${JSON.stringify(tokens, null, 2)}\n`);
58
+ const sd = new SD({ ...config, source: [source] });
59
+ await sd.buildAllPlatforms();
60
+ return sd;
61
+ } finally {
62
+ await rm(dir, { recursive: true, force: true });
63
+ }
64
+ }
@@ -0,0 +1,12 @@
1
+ /** An inline, synchronous before-paint script. Storage is untrusted and optional. */
2
+ export function themeBootScript({ storageKey = 'ui-theme' } = {}) {
3
+ const key = JSON.stringify(storageKey)
4
+ .replace(/</gu, '\\u003c')
5
+ .replace(/\u2028/gu, '\\u2028')
6
+ .replace(/\u2029/gu, '\\u2029');
7
+ const script = `(function(){try{var v=JSON.parse(localStorage.getItem(${key})||'{}'),e=document.documentElement;if(typeof v.theme==='string'&&/^[a-zA-Z0-9_-]{1,80}$/.test(v.theme))e.setAttribute('data-theme',v.theme);if(['light','dark','system'].indexOf(v.scheme)>=0)e.setAttribute('data-scheme',v.scheme)}catch(e){}})();`;
8
+ if (new TextEncoder().encode(script).length > 1024) {
9
+ throw new RangeError('Boot script exceeds 1 KB');
10
+ }
11
+ return script;
12
+ }
@@ -0,0 +1,210 @@
1
+ import { themeExtrasCss } from './extras-css.js';
2
+ import { values } from '@link-foundation/ui-core';
3
+ import { compileCss } from '@link-foundation/ui-style';
4
+ import { toCss } from '../export/css.js';
5
+ import { cssVariable } from '../names.js';
6
+ import { resolveTokens } from '../resolve.js';
7
+ import { resolveThemeTokens, themeDiagnostic } from './model.js';
8
+ import { contrastRatio, ensureContrast } from './contrast.js';
9
+
10
+ const colorPair = (fg, bg) => fg?.type === 'color' && bg?.type === 'color';
11
+
12
+ /** Check every pair after aliases and all active modes have resolved. */
13
+ export function checkedTokens(theme, modes, options = {}) {
14
+ let tokens = resolveThemeTokens(theme, modes);
15
+ const report = (d) => {
16
+ options.diagnostics?.push(d);
17
+ options.onDiagnostic?.(d);
18
+ };
19
+ tokens.diagnostics.forEach(report);
20
+ for (const [on, fill, min = options.minContrast ?? 4.5] of theme.pairs) {
21
+ const fg = tokens.get(on),
22
+ bg = tokens.get(fill);
23
+ if (!colorPair(fg, bg)) {
24
+ report(
25
+ themeDiagnostic(
26
+ 'invalid-pair',
27
+ 'error',
28
+ 'Pair must reference two color tokens',
29
+ { theme: theme.id, on, fill, modes }
30
+ )
31
+ );
32
+ continue;
33
+ }
34
+ const result = ensureContrast(fg.value, bg.value, min);
35
+ if (result.adjusted) {
36
+ const value = values.parseColor(result.color);
37
+ tokens.set(fill, { ...bg, raw: value, value });
38
+ // Reuse the token resolver so direct, chained and composite aliases all
39
+ // see the corrected fill before checking subsequent pairs or exporting.
40
+ tokens = resolveTokens(
41
+ new Map([
42
+ [
43
+ theme.id,
44
+ {
45
+ id: theme.id,
46
+ extends: [],
47
+ modes: {},
48
+ tokens: [...tokens.values()].map((token) => ({
49
+ ...token,
50
+ value: token.raw,
51
+ })),
52
+ },
53
+ ],
54
+ ]),
55
+ theme.id
56
+ );
57
+ report(
58
+ themeDiagnostic(
59
+ 'contrast-adjusted',
60
+ options.strict ? 'error' : 'warning',
61
+ 'Adjusted filled accent to meet contrast',
62
+ { theme: theme.id, on, fill, modes, ratio: result.ratio }
63
+ )
64
+ );
65
+ }
66
+ }
67
+ // A later correction can affect an earlier pair through an alias. Check
68
+ // the final output too, including conflicting pairs that cannot be met.
69
+ for (const [on, fill, min = options.minContrast ?? 4.5] of theme.pairs) {
70
+ const fg = tokens.get(on),
71
+ bg = tokens.get(fill);
72
+ if (!colorPair(fg, bg)) {
73
+ continue;
74
+ }
75
+ const ratio = contrastRatio(fg.value, bg.value);
76
+ if (ratio < min) {
77
+ report(
78
+ themeDiagnostic(
79
+ 'contrast-unreachable',
80
+ 'error',
81
+ 'The declared foreground cannot reach the requested contrast',
82
+ { theme: theme.id, on, fill, modes, ratio }
83
+ )
84
+ );
85
+ }
86
+ }
87
+ // Emit resolved values, so adjustments and nested mode resets cannot leave stale aliases.
88
+ return new Map(
89
+ [...tokens].map(([path, t]) => [path, { ...t, raw: t.value }])
90
+ );
91
+ }
92
+
93
+ /** Escaped attribute strings, including the HTML raw-text closing delimiter. */
94
+ const quoted = (text) =>
95
+ `"${[...String(text)].map((c) => (/["\\<>\n\r\f]/u.test(c) ? `\\${c.codePointAt(0).toString(16)} ` : c)).join('')}"`;
96
+ const attr = (name, value) => `[data-${name}=${quoted(value)}]`;
97
+ const axis = (name, normal, active, feature, queryValue) => [
98
+ {
99
+ selector: `:is(${attr(name, normal)},:not([data-${name}]))`,
100
+ mode: null,
101
+ query: null,
102
+ },
103
+ { selector: attr(name, active), mode: active, query: null },
104
+ {
105
+ selector: attr(name, 'system'),
106
+ mode: null,
107
+ query: `not all and (${feature}: ${queryValue})`,
108
+ },
109
+ {
110
+ selector: attr(name, 'system'),
111
+ mode: active,
112
+ query: `(${feature}: ${queryValue})`,
113
+ },
114
+ ];
115
+ // Each query nests separately: conjunctions of `not all` are not valid CSS media lists.
116
+ const media = (css, queries) =>
117
+ queries.reduceRight((body, query) => `@media ${query} {\n${body}\n}`, css);
118
+
119
+ /** Scoped tokens for every explicit/system combination. No inherited dark residue. */
120
+ export function compileThemeCss(theme, options = {}) {
121
+ if (Array.isArray(theme)) {
122
+ return theme
123
+ .map((entry) =>
124
+ compileThemeCss(entry, {
125
+ ...options,
126
+ palettePack: true,
127
+ selector:
128
+ options.paletteSelector?.(entry.id) ?? attr('palette', entry.id),
129
+ })
130
+ )
131
+ .join('\n');
132
+ }
133
+ const root = options.selector ?? attr('theme', theme.id);
134
+ const axes = [
135
+ axis('scheme', 'light', 'dark', 'prefers-color-scheme', 'dark'),
136
+ axis('contrast', 'normal', 'more', 'prefers-contrast', 'more'),
137
+ axis('motion', 'full', 'reduced', 'prefers-reduced-motion', 'reduce'),
138
+ ];
139
+ const cache = new Map();
140
+ const css = [];
141
+ // A boundary with only data-theme still gets the light defaults.
142
+ const base = checkedTokens(theme, [], options);
143
+ cache.set('', base);
144
+ css.push(
145
+ toCss(base, {
146
+ selector: root,
147
+ channels: options.channels,
148
+ prefix: options.prefix,
149
+ })
150
+ );
151
+ for (const scheme of axes[0]) {
152
+ for (const contrast of axes[1]) {
153
+ for (const motion of axes[2]) {
154
+ const modes = [
155
+ scheme.mode,
156
+ contrast.mode === 'more' ? 'high-contrast' : null,
157
+ motion.mode,
158
+ ].filter(Boolean);
159
+ const key = modes.join('/');
160
+ if (!cache.has(key)) {
161
+ cache.set(key, checkedTokens(theme, modes, options));
162
+ }
163
+ const selector = `${
164
+ root
165
+ }:where(${scheme.selector}${contrast.selector}${motion.selector})`;
166
+ const block = toCss(cache.get(key), {
167
+ selector,
168
+ channels: options.channels,
169
+ prefix: options.prefix,
170
+ });
171
+ css.push(
172
+ media(
173
+ block,
174
+ [scheme.query, contrast.query, motion.query].filter(Boolean)
175
+ )
176
+ );
177
+ }
178
+ }
179
+ }
180
+ const forced = new Map([
181
+ ['color.surface', 'Canvas'],
182
+ ['color.on-surface', 'CanvasText'],
183
+ ['color.on-surface-variant', 'CanvasText'],
184
+ ['color.primary', 'Highlight'],
185
+ ['color.outline', 'CanvasText'],
186
+ ['color.on-primary', 'HighlightText'],
187
+ ['color.button-text', 'ButtonText'],
188
+ ...(theme.forcedColors ?? []),
189
+ ]);
190
+ css.push(
191
+ `@media (forced-colors: active) {\n${root} {\n${[...forced].map(([path, value]) => ` ${cssVariable(path, options.prefix)}: ${value};`).join('\n')}\n}\n}`
192
+ );
193
+ // @scope's lower boundary stops an outer theme's style rules at nested themes.
194
+ const style = compileCss(theme.styles, {
195
+ prefix: options.prefix,
196
+ scope: ':scope',
197
+ transparency: options.transparency,
198
+ reducedTransparency: options.reducedTransparency,
199
+ });
200
+ if (style) {
201
+ css.push(
202
+ `@scope (${root}) to (${options.palettePack ? '[data-theme], [data-palette]' : '[data-theme]'}) {\n${style}\n}`
203
+ );
204
+ }
205
+ const extras = themeExtrasCss(theme, root, options);
206
+ if (extras) {
207
+ css.push(extras);
208
+ }
209
+ return css.join('\n');
210
+ }
@@ -0,0 +1,78 @@
1
+ import { values } from '@link-foundation/ui-core';
2
+ const { parseColor, toHex, oklchToSrgb, srgbToOklch } = values;
3
+ const clamp = (n) => Math.max(0, Math.min(1, n));
4
+ const colorOf = (raw) => {
5
+ const color =
6
+ typeof raw === 'object' && raw?.type === 'color' ? raw : parseColor(raw);
7
+ if (!color) {
8
+ throw new TypeError('Expected a color');
9
+ }
10
+ return color.space === 'oklch' ? oklchToSrgb(color) : color;
11
+ };
12
+ const linear = (n) => (n <= 0.04045 ? n / 12.92 : ((n + 0.055) / 1.055) ** 2.4);
13
+ const luminance = (color) =>
14
+ [color.r, color.g, color.b]
15
+ .map(clamp)
16
+ .map(linear)
17
+ .reduce((sum, n, i) => sum + n * [0.2126, 0.7152, 0.0722][i], 0);
18
+
19
+ /** WCAG relative luminance, compositing translucent colors over an opaque canvas. */
20
+ export function contrastRatio(fg, bg) {
21
+ const front = colorOf(fg),
22
+ back = colorOf(bg);
23
+ const opaque = { ...back };
24
+ for (const channel of ['r', 'g', 'b']) {
25
+ opaque[channel] = clamp(back[channel]) * back.a + 1 - back.a;
26
+ }
27
+ const composed = { ...front };
28
+ for (const channel of ['r', 'g', 'b']) {
29
+ composed[channel] =
30
+ clamp(front[channel]) * front.a + opaque[channel] * (1 - front.a);
31
+ }
32
+ const a = luminance(composed),
33
+ b = luminance(opaque);
34
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
35
+ }
36
+
37
+ /** Search both OKLCH lightness directions, comparing the actual quantized output. */
38
+ export function ensureContrast(on, fill, min = 4.5) {
39
+ if (!Number.isFinite(min) || min < 1 || min > 21) {
40
+ throw new RangeError('Contrast must be between 1 and 21');
41
+ }
42
+ const original = colorOf(fill);
43
+ const ratio = contrastRatio(on, fill);
44
+ if (ratio >= min) {
45
+ return { color: toHex(original), adjusted: false, ratio };
46
+ }
47
+ const lch = srgbToOklch(original);
48
+ const candidates = [];
49
+ for (const end of [0, 1]) {
50
+ const at = (l) => toHex({ ...lch, l });
51
+ if (contrastRatio(on, at(end)) < min) {
52
+ continue;
53
+ }
54
+ let fail = lch.l,
55
+ pass = end;
56
+ for (let i = 0; i < 30; i++) {
57
+ const mid = (fail + pass) / 2;
58
+ if (contrastRatio(on, at(mid)) >= min) {
59
+ pass = mid;
60
+ } else {
61
+ fail = mid;
62
+ }
63
+ }
64
+ const color = at(pass);
65
+ candidates.push({
66
+ color,
67
+ adjusted: true,
68
+ ratio: contrastRatio(on, color),
69
+ distance: Math.abs(pass - lch.l),
70
+ });
71
+ }
72
+ candidates.sort((a, b) => a.distance - b.distance);
73
+ const best = candidates[0];
74
+ if (!best) {
75
+ return { color: toHex(original), adjusted: false, ratio };
76
+ }
77
+ return { color: best.color, adjusted: best.adjusted, ratio: best.ratio };
78
+ }
@@ -0,0 +1,27 @@
1
+ import { toDtcg } from '../export/dtcg.js';
2
+ import { checkedTokens } from './compile-css.js';
3
+
4
+ /** DTCG 2025.10 Resolver Module. Overlapping modes are explicit permutations. */
5
+ export function exportThemeResolver(theme) {
6
+ const contexts = {};
7
+ for (const [name, modes] of [
8
+ ['light', []],
9
+ ['dark', ['dark']],
10
+ ['high-contrast', ['high-contrast']],
11
+ ['dark-high-contrast', ['dark', 'high-contrast']],
12
+ ]) {
13
+ for (const reduced of [false, true]) {
14
+ const active = [...modes, ...(reduced ? ['reduced'] : [])];
15
+ contexts[name + (reduced ? '-reduced' : '')] = [
16
+ toDtcg(checkedTokens(theme, active), { keepAliases: false }),
17
+ ];
18
+ }
19
+ }
20
+ return {
21
+ $schema: 'https://www.designtokens.org/schemas/2025.10/resolver.json',
22
+ version: '2025.10',
23
+ name: theme.id,
24
+ modifiers: { mode: { contexts, default: 'light' } },
25
+ resolutionOrder: [{ $ref: '#/modifiers/mode' }],
26
+ };
27
+ }
@@ -0,0 +1,91 @@
1
+ import { cssVariable } from '../names.js';
2
+
3
+ /** Bounded analytical spring samples; response maps to #52's k=(2π/r)², c=2ζ√k, m=1. */
4
+ export function springLinear({ response, damping }) {
5
+ const omega = (2 * Math.PI) / response;
6
+ const decay = damping * omega;
7
+ const frequency = omega * Math.sqrt(1 - damping * damping);
8
+ const duration =
9
+ Math.log(1 / (0.0005 * Math.sqrt(1 - damping * damping))) / decay;
10
+ return `linear(${Array.from({ length: 41 }, (_, index) => {
11
+ if (index === 0) {
12
+ return '0';
13
+ }
14
+ if (index === 40) {
15
+ return '1';
16
+ }
17
+ const time = (duration * index) / 40;
18
+ return String(
19
+ Number(
20
+ (
21
+ 1 -
22
+ Math.exp(-decay * time) *
23
+ (Math.cos(frequency * time) +
24
+ (decay / frequency) * Math.sin(frequency * time))
25
+ ).toFixed(5)
26
+ )
27
+ );
28
+ }).join(', ')})`;
29
+ }
30
+
31
+ /** Optional type scale and spring metadata augment the ordinary theme rules. */
32
+ export function themeExtrasCss(theme, root, options) {
33
+ const variable = (path) => `var(${cssVariable(path, options.prefix)})`;
34
+ const css = [];
35
+ const springs = Object.entries(theme.springs ?? {});
36
+ if (springs.length) {
37
+ css.push(
38
+ `${root} {\n${springs.map(([name, spring]) => ` ${cssVariable(`motion.spring.${name}`, options.prefix)}: ${springLinear(spring)};`).join('\n')}\n}`
39
+ );
40
+ }
41
+ if (!theme.tokens.has('text.base.size')) {
42
+ return css.join('\n');
43
+ }
44
+ css.push(
45
+ `${root} { font-family: ${variable('font.family.text')}; font-size: ${variable('text.base.size')}; color: ${variable('color.on-surface')}; background-color: ${variable('color.surface')}; --ui-control-height: max(${variable('size.target.min')}, ${variable('size.control.height')}); --ui-control-corner: ${variable('shape.corner.small')}; --ui-control-border: 1px solid ${variable('color.separator')}; --ui-control-transition: ${variable('motion.duration.short')} ${variable('motion.spring.default')}; }`
46
+ );
47
+ const inner = [
48
+ `:scope ui-button [data-part="root"], :scope ui-switch [data-part="input"], :scope ui-text-field [data-part="input"], :scope ui-slider [data-part="thumb"], :scope ui-number-field [data-part="input"], :scope ui-radio [data-part="input"], :scope ui-select [data-part="input"] { min-height: max(${variable('size.target.min')}, ${variable('size.control.height')}); }`,
49
+ ];
50
+ for (const path of theme.tokens.keys()) {
51
+ if (
52
+ !path.startsWith('text.') ||
53
+ !path.endsWith('.size') ||
54
+ path === 'text.base.size'
55
+ ) {
56
+ continue;
57
+ }
58
+ const name = path.slice(5, -5);
59
+ if (!/^[a-z0-9-]+$/u.test(name)) {
60
+ continue;
61
+ }
62
+ inner.push(
63
+ `ui-text[text-style="${name}"] { font-size: calc(${variable(path)} / 1rem * ${variable('text.base.size')}); font-weight: ${variable(`text.${name}.weight`)}; }`
64
+ );
65
+ }
66
+ inner.push(`ui-radio-group[appearance="segmented"] { display: flex; flex-direction: row; padding: ${variable('space.x-small')}; border-radius: ${variable('shape.corner.medium')}; background: ${variable('color.grouped-background')}; }
67
+ ui-radio-group[appearance="segmented"] ui-radio [data-part="input"] { border-radius: ${variable('shape.corner.small')}; padding: ${variable('space.small')}; }
68
+ ui-radio-group[appearance="segmented"] ui-radio [aria-checked="true"] { background: ${variable('color.primary')}; color: ${variable('color.on-primary')}; }
69
+ ui-radio-group[appearance="segmented"] [data-part="indicator"] { display: none; }
70
+ ui-switch [data-part="thumb"] { transition: transform ${variable('motion.duration.medium')} ${variable('motion.spring.default')}, opacity ${variable('motion.duration.fade')} linear; }
71
+ ui-switch [aria-checked="true"] [data-part="thumb"] { transform: translateX(${variable('motion.switch.travel')}); }
72
+ ui-switch [data-part="track"] { position: relative; }
73
+ ui-slider { --ui-control-thumb-size: max(${variable('size.target.min')}, ${variable('size.control.height')}); }
74
+ ui-list > * { min-height: ${variable('size.list-row.height')}; }`);
75
+ const reduced = `ui-switch [data-part="thumb"], ui-switch [aria-checked="true"] [data-part="thumb"] { opacity: 0; transform: none; }
76
+ ui-switch [data-part="track"]::before, ui-switch [data-part="track"]::after { content: ""; position: absolute; top: 2px; width: 1.25rem; height: 1.25rem; border-radius: 50%; background: ${variable('color.on-primary')}; transition: opacity ${variable('motion.duration.fade')} linear; }
77
+ ui-switch [data-part="track"]::before { left: 2px; opacity: 1; }
78
+ ui-switch [data-part="track"]::after { right: 2px; opacity: 0; }
79
+ ui-switch [aria-checked="true"] [data-part="track"]::before { opacity: 0; }
80
+ ui-switch [aria-checked="true"] [data-part="track"]::after { opacity: 1; }`;
81
+ css.push(
82
+ `@scope (${root}) to (:scope [data-theme]) {\n${inner.join('\n')}\n}`
83
+ );
84
+ css.push(
85
+ `@scope (${root}[data-motion="reduced"]) to (:scope [data-theme]) {\n${reduced}\n}`
86
+ );
87
+ css.push(
88
+ `@media (prefers-reduced-motion: reduce) { @scope (${root}[data-motion="system"]) to (:scope [data-theme]) {\n${reduced}\n} }`
89
+ );
90
+ return css.join('\n');
91
+ }
@@ -0,0 +1,75 @@
1
+ import type {
2
+ TokenValue,
3
+ TokenSet,
4
+ ResolvedTokens,
5
+ } from '@link-foundation/ui-tokens';
6
+ import type { StyleRule } from '@link-foundation/ui-style';
7
+ export interface ThemeDiagnostic {
8
+ code: string;
9
+ severity: 'error' | 'warning' | 'info';
10
+ message: string;
11
+ at: Record<string, unknown>;
12
+ }
13
+ export interface TemplateNode {
14
+ name: string;
15
+ kind: string;
16
+ children: TemplateNode[];
17
+ }
18
+ export interface Theme {
19
+ id: string;
20
+ extends: string[];
21
+ tokens: Map<string, TokenValue>;
22
+ modes: Record<string, Map<string, TokenValue>>;
23
+ styles: StyleRule[];
24
+ templates: Map<string, TemplateNode>;
25
+ forcedColors: Map<string, string>;
26
+ pairs: [string, string, number?][];
27
+ springs?: Record<string, { response: number; damping: number }>;
28
+ defaults: Partial<
29
+ Record<'motion' | 'sound' | 'volume' | 'transparency' | 'menu', string>
30
+ >;
31
+ diagnostics: ThemeDiagnostic[];
32
+ set: TokenSet;
33
+ sets?: Map<string, TokenSet>;
34
+ chain?: Theme[];
35
+ }
36
+ export function loadThemes(text: string): {
37
+ themes: Theme[];
38
+ diagnostics: ThemeDiagnostic[];
39
+ };
40
+ export function resolveTheme(registry: Map<string, Theme>, id: string): Theme;
41
+ export function resolveThemeTokens(
42
+ theme: Theme,
43
+ modes?: string[]
44
+ ): ResolvedTokens;
45
+ export function contrastRatio(
46
+ fg: string | TokenValue,
47
+ bg: string | TokenValue
48
+ ): number;
49
+ export function ensureContrast(
50
+ on: string | TokenValue,
51
+ fill: string | TokenValue,
52
+ min?: number
53
+ ): { color: string; adjusted: boolean; ratio: number };
54
+ export interface ThemeCssOptions {
55
+ channels?: boolean;
56
+ selector?: string;
57
+ paletteSelector?: (palette: string) => string;
58
+ transparency?: 'on' | 'off';
59
+ reducedTransparency?: boolean;
60
+ prefix?: string;
61
+ strict?: boolean;
62
+ minContrast?: number;
63
+ diagnostics?: ThemeDiagnostic[];
64
+ onDiagnostic?: (diagnostic: ThemeDiagnostic) => void;
65
+ }
66
+ export function compileThemeCss(
67
+ theme: Theme | Theme[],
68
+ options?: ThemeCssOptions
69
+ ): string;
70
+ export function resolveTemplate(
71
+ themeChain: Theme | Theme[],
72
+ kind: string
73
+ ): TemplateNode | null;
74
+ export function themeBootScript(options?: { storageKey?: string }): string;
75
+ export function exportThemeResolver(theme: Theme): Record<string, unknown>;
@@ -0,0 +1,6 @@
1
+ export { loadThemes, resolveTheme, resolveThemeTokens } from './model.js';
2
+ export { contrastRatio, ensureContrast } from './contrast.js';
3
+ export { compileThemeCss } from './compile-css.js';
4
+ export { resolveTemplate } from './templates.js';
5
+ export { themeBootScript } from './boot.js';
6
+ export { exportThemeResolver } from './dtcg-resolver.js';