@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,262 @@
1
+ /** Theme packages are data. Token inheritance and aliases use the token resolver. */
2
+ import { parseNested, formatLinks } from '@link-foundation/ui-core';
3
+ import { readStyles } from '@link-foundation/ui-style';
4
+ import { readTokens, isTokenPath } from '../model.js';
5
+ import { resolveTokens, chainOf } from '../resolve.js';
6
+ import { readTemplate } from './templates.js';
7
+ import { isSpringToken, readSpring } from './springs.js';
8
+
9
+ export const themeDiagnostic = (code, severity, message, at = {}) => ({
10
+ code,
11
+ severity,
12
+ message,
13
+ at,
14
+ });
15
+ const head = (link) => link.values[0]?.id;
16
+ const raw = (link) =>
17
+ link.values.length === 0 ? link.id : link.values.map(raw);
18
+ const values = (tokens) =>
19
+ new Map([...tokens].map(([path, token]) => [path, token.value]));
20
+ const systemColors = new Set([
21
+ 'Canvas',
22
+ 'CanvasText',
23
+ 'Highlight',
24
+ 'HighlightText',
25
+ 'GrayText',
26
+ 'ButtonText',
27
+ 'ButtonFace',
28
+ ]);
29
+ const defaults = new Set(['motion', 'sound', 'volume', 'transparency', 'menu']);
30
+
31
+ /** Inspect every value, including nested template/style links, before interpreting it. */
32
+ function safe(link, diagnostics, id) {
33
+ let ok = true;
34
+ if (
35
+ head(link) === 'script' ||
36
+ (link.values.length === 0 && link.id === 'script') ||
37
+ (typeof link.id === 'string' && /javascript:|expression\(/iu.test(link.id))
38
+ ) {
39
+ diagnostics.push(
40
+ themeDiagnostic(
41
+ 'unsafe-theme',
42
+ 'error',
43
+ 'Executable theme content rejected',
44
+ { theme: id }
45
+ )
46
+ );
47
+ return false;
48
+ }
49
+ for (const value of link.values) {
50
+ if (!safe(value, diagnostics, id)) {
51
+ ok = false;
52
+ }
53
+ }
54
+ return ok;
55
+ }
56
+
57
+ function readForcedColor(args, theme, diagnostics) {
58
+ if (args.length === 2 && isTokenPath(args[0]) && systemColors.has(args[1])) {
59
+ theme.forcedColors.set(args[0], args[1]);
60
+ } else {
61
+ diagnostics.push(
62
+ themeDiagnostic(
63
+ 'invalid-forced-color',
64
+ 'error',
65
+ 'Expected a token path and CSS system color'
66
+ )
67
+ );
68
+ }
69
+ }
70
+
71
+ function readPair(args, theme, diagnostics) {
72
+ const [on, fill, limit] = args;
73
+ const min =
74
+ limit?.[0] === 'min' && limit.length === 2 ? Number(limit[1]) : NaN;
75
+ if (args.length === 2) {
76
+ theme.pairs.push([on, fill]);
77
+ } else if (
78
+ args.length === 3 &&
79
+ Number.isFinite(min) &&
80
+ min >= 1 &&
81
+ min <= 21
82
+ ) {
83
+ theme.pairs.push([on, fill, min]);
84
+ } else {
85
+ diagnostics.push(
86
+ themeDiagnostic('invalid-pair', 'error', 'Invalid pair contrast minimum')
87
+ );
88
+ }
89
+ }
90
+
91
+ function addSpring(args, theme, diagnostics) {
92
+ const spring = readSpring(args);
93
+ if (spring) {
94
+ theme.springs[spring.name] = spring.value;
95
+ } else {
96
+ diagnostics.push(
97
+ themeDiagnostic(
98
+ 'invalid-spring',
99
+ 'error',
100
+ 'Spring needs a name, response in (0,10] seconds and damping in (0,1)'
101
+ )
102
+ );
103
+ }
104
+ }
105
+
106
+ function readThemeChild(child, theme, tokenLinks, diagnostics) {
107
+ const [name, ...args] = raw(child);
108
+ if (name === 'token' && isSpringToken(args)) {
109
+ addSpring(args, theme, diagnostics);
110
+ } else if (name === 'token' || name === 'extends' || name === 'mode') {
111
+ tokenLinks.push(raw(child));
112
+ }
113
+ if (name === 'motion' && args.length > 1) {
114
+ tokenLinks.push(['mode', 'reduced', ...args.slice(1)]);
115
+ }
116
+ if (defaults.has(name) && args.length === 1) {
117
+ theme.defaults[name] = args[0];
118
+ }
119
+ if (name === 'forced-color') {
120
+ readForcedColor(args, theme, diagnostics);
121
+ }
122
+ if (name === 'pair') {
123
+ readPair(args, theme, diagnostics);
124
+ }
125
+ if (name === 'template') {
126
+ const template = readTemplate(args.slice(1), diagnostics);
127
+ if (template !== null) {
128
+ theme.templates.set(args[0], template);
129
+ }
130
+ }
131
+ if (name === 'style') {
132
+ const result = readStyles(
133
+ formatLinks([
134
+ {
135
+ id: `${theme.id}-style-${theme.styles.length}`,
136
+ values: ['style', ...args],
137
+ },
138
+ ])
139
+ );
140
+ theme.styles.push(...result.rules);
141
+ diagnostics.push(...result.diagnostics);
142
+ }
143
+ }
144
+
145
+ /** @param {string} linoText @returns {{themes: object[], diagnostics: object[]}} */
146
+ export function loadThemes(linoText) {
147
+ const diagnostics = [];
148
+ const themes = [];
149
+ let links;
150
+ try {
151
+ links = parseNested(linoText);
152
+ } catch (error) {
153
+ return {
154
+ themes,
155
+ diagnostics: [themeDiagnostic('syntax-error', 'error', error.message)],
156
+ };
157
+ }
158
+ for (const link of links) {
159
+ if (head(link) !== 'theme' || link.id === null) {
160
+ continue;
161
+ }
162
+ const theme = {
163
+ id: link.id,
164
+ extends: [],
165
+ tokens: new Map(),
166
+ modes: Object.create(null),
167
+ styles: [],
168
+ templates: new Map(),
169
+ forcedColors: new Map(),
170
+ pairs: [],
171
+ defaults: {},
172
+ springs: {},
173
+ diagnostics: [],
174
+ };
175
+ const tokenLinks = [];
176
+ for (const child of link.values.slice(1)) {
177
+ if (safe(child, diagnostics, link.id)) {
178
+ readThemeChild(child, theme, tokenLinks, diagnostics);
179
+ }
180
+ }
181
+ const result = readTokens(
182
+ formatLinks([{ id: theme.id, values: ['theme', ...tokenLinks] }])
183
+ );
184
+ diagnostics.push(...result.diagnostics);
185
+ theme.set = result.sets.get(theme.id);
186
+ if (!theme.set) {
187
+ continue;
188
+ }
189
+ theme.extends = theme.set.extends;
190
+ theme.tokens = values(new Map(theme.set.tokens.map((t) => [t.path, t])));
191
+ for (const [mode, tokens] of Object.entries(theme.set.modes)) {
192
+ theme.modes[mode] = values(new Map(tokens.map((t) => [t.path, t])));
193
+ }
194
+ themes.push(theme);
195
+ }
196
+ return { themes, diagnostics };
197
+ }
198
+
199
+ /** Merge metadata in the same deterministic parent order as token inheritance. */
200
+ export function resolveTheme(registry, id) {
201
+ const sets = new Map([...registry].map(([key, theme]) => [key, theme.set]));
202
+ const diagnostics = [];
203
+ const chain = chainOf(sets, id, diagnostics).map((set) =>
204
+ registry.get(set.id)
205
+ );
206
+ const resolved = resolveTokens(sets, id);
207
+ diagnostics.push(...resolved.diagnostics);
208
+ const theme = {
209
+ id,
210
+ extends: [],
211
+ tokens: values(resolved),
212
+ modes: Object.create(null),
213
+ styles: [],
214
+ templates: new Map(),
215
+ forcedColors: new Map(),
216
+ pairs: [],
217
+ defaults: {},
218
+ springs: {},
219
+ diagnostics,
220
+ set: registry.get(id)?.set,
221
+ sets,
222
+ chain,
223
+ };
224
+ for (const parent of chain) {
225
+ theme.styles.push(...parent.styles);
226
+ for (const [kind, template] of parent.templates) {
227
+ theme.templates.set(kind, template);
228
+ }
229
+ for (const pair of parent.pairs) {
230
+ if (!theme.pairs.some((p) => p.join('\0') === pair.join('\0'))) {
231
+ theme.pairs.push(pair);
232
+ }
233
+ }
234
+ for (const [path, value] of parent.forcedColors ?? []) {
235
+ theme.forcedColors.set(path, value);
236
+ }
237
+ Object.assign(theme.defaults, parent.defaults);
238
+ Object.assign(theme.springs, parent.springs);
239
+ }
240
+ for (const name of resolved.modes.keys()) {
241
+ theme.modes[name] = values(resolveTokens(sets, id, { mode: name }));
242
+ }
243
+ theme.diagnostics = [
244
+ ...new Map(diagnostics.map((d) => [JSON.stringify(d), d])).values(),
245
+ ];
246
+ return theme;
247
+ }
248
+
249
+ /** Resolve a combined scheme, contrast and motion without a second alias resolver. */
250
+ export function resolveThemeTokens(theme, modes = []) {
251
+ const sets = theme.sets ?? new Map([[theme.id, theme.set]]);
252
+ const combined = new Map(
253
+ [...sets].map(([id, set]) => [
254
+ id,
255
+ {
256
+ ...set,
257
+ modes: { combined: modes.flatMap((name) => set.modes[name] ?? []) },
258
+ },
259
+ ])
260
+ );
261
+ return resolveTokens(combined, theme.id, { mode: 'combined' });
262
+ }
@@ -0,0 +1,35 @@
1
+ /** Theme-specific spring metadata is separate from DTCG primitive tokens. */
2
+ export function isSpringToken(args) {
3
+ return (
4
+ typeof args[0] === 'string' &&
5
+ args[0].startsWith('motion.spring.') &&
6
+ Array.isArray(args[1]) &&
7
+ args[1][0] === 'spring'
8
+ );
9
+ }
10
+
11
+ export function readSpring(args) {
12
+ const fields = args[1].slice(1);
13
+ if (
14
+ args.length !== 2 ||
15
+ fields.length !== 2 ||
16
+ !fields.every((field) => Array.isArray(field) && field.length === 2) ||
17
+ new Set(fields.map((field) => field[0])).size !== 2
18
+ ) {
19
+ return null;
20
+ }
21
+ const { response, damping } = Object.fromEntries(fields);
22
+ const seconds =
23
+ typeof response === 'string' && response.endsWith('s')
24
+ ? Number(response.slice(0, -1))
25
+ : NaN;
26
+ const ratio = Number(damping);
27
+ const name = args[0].slice('motion.spring.'.length);
28
+ return /^[a-z][a-z0-9-]*$/u.test(name) &&
29
+ seconds > 0 &&
30
+ seconds <= 10 &&
31
+ ratio > 0 &&
32
+ ratio < 1
33
+ ? { name, value: { response: seconds, damping: ratio } }
34
+ : null;
35
+ }
@@ -0,0 +1,71 @@
1
+ /** Open UI anatomy for the first template consumer. No executable templates. */
2
+ const PARTS = new Set([
3
+ 'root',
4
+ 'label',
5
+ 'icon',
6
+ 'indicator',
7
+ 'input',
8
+ 'track',
9
+ 'thumb',
10
+ ]);
11
+ const KINDS = new Set(['box', 'text', 'icon']);
12
+
13
+ export function readTemplate(links, diagnostics) {
14
+ const names = new Set();
15
+ const read = (link) => {
16
+ const [head, name, ...body] = link;
17
+ const kind =
18
+ body.find((item) => Array.isArray(item) && item[0] === 'kind')?.[1] ??
19
+ 'box';
20
+ if (
21
+ head !== 'part' ||
22
+ !PARTS.has(name) ||
23
+ names.has(name) ||
24
+ !KINDS.has(kind)
25
+ ) {
26
+ diagnostics.push({
27
+ code: 'unknown-part',
28
+ severity: 'error',
29
+ message: `Invalid template part: ${name}`,
30
+ at: { part: name },
31
+ });
32
+ return null;
33
+ }
34
+ names.add(name);
35
+ const children = body
36
+ .filter((item) => Array.isArray(item) && item[0] === 'part')
37
+ .map(read);
38
+ return children.some((child) => child === null)
39
+ ? null
40
+ : { name, kind, children };
41
+ };
42
+ const parts = links.map(read);
43
+ if (parts.some((p) => p === null)) {
44
+ return null;
45
+ }
46
+ const root = parts.find((p) => p.name === 'root');
47
+ if (!root || !names.has('label')) {
48
+ diagnostics.push({
49
+ code: 'missing-part',
50
+ severity: 'error',
51
+ message: 'Button templates require root and label parts',
52
+ at: {},
53
+ });
54
+ return null;
55
+ }
56
+ // The compact syntax lists siblings after root; the root owns those parts.
57
+ root.children.push(...parts.filter((p) => p !== root));
58
+ return root;
59
+ }
60
+
61
+ /** Child themes win. Templates are selected when mounting; switching only changes CSS. */
62
+ export function resolveTemplate(themeChain, kind) {
63
+ const chain = Array.isArray(themeChain) ? themeChain : [themeChain];
64
+ for (const theme of [...chain].reverse()) {
65
+ const template = theme?.templates.get(kind);
66
+ if (template) {
67
+ return template;
68
+ }
69
+ }
70
+ return null;
71
+ }
package/src/types.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Shared JSDoc types of `@link-foundation/ui-tokens` (the same types are
3
+ * declared for TypeScript in index.d.ts).
4
+ */
5
+
6
+ /**
7
+ * @typedef {import('@link-foundation/ui-core').Diagnostic} Diagnostic
8
+ * @typedef {import('@link-foundation/ui-core').values.TypedValue} TypedValue
9
+ */
10
+
11
+ /**
12
+ * A token value: a ui-core typed value (`color`, `dimension`, `duration`,
13
+ * `number`, `token-ref`) or one of the token types `fontFamily`,
14
+ * `fontWeight`, `cubicBezier`, `shadow`, `typography`.
15
+ * @typedef {TypedValue
16
+ * | { type: 'fontFamily', value: string|string[] }
17
+ * | { type: 'fontWeight', value: number|string }
18
+ * | { type: 'cubicBezier', value: number[] }
19
+ * | { type: 'shadow', value: object|object[] }
20
+ * | { type: 'typography', value: Record<string, TokenValue> }} TokenValue
21
+ */
22
+
23
+ /**
24
+ * @typedef {object} Token
25
+ * @property {string} path `color.on-primary`
26
+ * @property {string} type the declared type, or the type read from the
27
+ * value; `null` for an alias without `(type ...)`
28
+ * @property {TokenValue} value as written; an alias is a `token-ref`
29
+ * @property {string} [sourceValue] original exchange value
30
+ * @property {string} [fluent] original Fluent alias name
31
+ * @property {string} [description]
32
+ * @property {string} [m3] original Material 3 token name
33
+ * @property {string} [mode] the mode of a `(mode NAME ...)` token
34
+ */
35
+
36
+ /**
37
+ * @typedef {object} TokenSet
38
+ * @property {string} id
39
+ * @property {string[]} extends
40
+ * @property {Token[]} tokens
41
+ * @property {Record<string, Token[]>} modes
42
+ */
43
+
44
+ /**
45
+ * @typedef {object} ResolvedToken
46
+ * @property {string} path
47
+ * @property {string} type
48
+ * @property {TokenValue} value fully resolved: no alias left
49
+ * @property {TokenValue} raw as written, aliases kept
50
+ * @property {string} [alias] the path a whole-token alias points to
51
+ * @property {string} [sourceValue] original exchange value
52
+ * @property {string} [fluent] original Fluent alias name
53
+ * @property {string} [description]
54
+ * @property {string} [m3] original Material 3 token name
55
+ * @property {string} set the set that defines the token
56
+ * @property {string} [mode] the mode whose override defines the token
57
+ */
58
+
59
+ /**
60
+ * `Map<path, ResolvedToken>` in definition order, plus what the resolver
61
+ * found out.
62
+ * @typedef {Map<string, ResolvedToken> & {
63
+ * setId: string,
64
+ * mode: string|null,
65
+ * modes: Map<string, Map<string, ResolvedToken>>,
66
+ * diagnostics: Diagnostic[],
67
+ * }} ResolvedTokens
68
+ */
69
+
70
+ export {};