@filipgutica/design-system 1.0.39 → 1.0.41

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.
@@ -8,8 +8,9 @@
8
8
  * pair, fonts, and base radius. This file carries the default theme. Another theme keeps this file
9
9
  * unchanged and loads its themes/<id>.css after it, on :root; that file may also set
10
10
  * the theme's neutrals. A new project can set the identity lines on :root in its own
11
- * stylesheet the same way. The dark blocks switch --color-project to
12
- * --color-project-dark, so the override needs no dark rule. Check --color-accent-text,
11
+ * stylesheet the same way. The dark blocks switch --color-accent to
12
+ * --color-project-dark, so the hue pair needs no dark rule: one :root rule works after this file,
13
+ * in its cascade layer or in a later one. Check --color-accent-text,
13
14
  * --color-nav-current-text, and --color-segmented-current-text at 4.5:1 on the new hue
14
15
  * and override them when they fall short. A theme file sets the last two for you; its
15
16
  * hue must carry --color-accent-text itself, which the contrast tests check.
@@ -25,16 +26,17 @@
25
26
  * "light" on any element below <html>, or a .dark class on <html> or below it,
26
27
  * themes that subtree; the subtree blocks at the end redeclare what each mode
27
28
  * changes, and the subtree takes its mode's text colour. data-theme="light" wins over
28
- * .dark on one element. A theme written by hand repeats its light values on
29
- * :root [data-theme="light"] and its dark values on the dark subtree block's selectors,
30
- * so they hold in a subtree too. A theme file does this for you.
29
+ * .dark on one element. A theme written by hand that sets neutrals or text on the hue repeats
30
+ * those light values on :root [data-theme="light"] and the dark ones on the dark subtree block's
31
+ * selectors, so they hold in a subtree too; the hue pair needs no repeat. A theme file does this for you.
31
32
  */
32
33
 
33
34
  :root {
34
35
  color-scheme: light;
35
36
 
36
37
  /* Identity layer: a project swaps these five lines. --color-project is the light-theme hue;
37
- --color-project-dark is the dark-theme hue, also used on terminal captures in both themes.
38
+ --color-project-dark is the dark-theme hue, also used on terminal captures in both themes. Neither changes
39
+ with the mode: --color-accent takes one or the other.
38
40
  --radius-base sets every corner but the pill and the circle. */
39
41
  --color-project: #4b45d1;
40
42
  --color-project-dark: #a5a1ff;
@@ -210,7 +212,6 @@
210
212
  @media (prefers-color-scheme: dark) {
211
213
  :root:not([data-theme="light"]) {
212
214
  color-scheme: dark;
213
- --color-project: var(--color-project-dark);
214
215
  --color-bg: #0d1012;
215
216
  --color-surface: #13171a;
216
217
  --color-surface-raised: #181d21;
@@ -226,6 +227,7 @@
226
227
  --color-text: #e6e9eb;
227
228
  --color-muted: #9aa3ab;
228
229
  --color-overlay: rgb(0 0 0 / 62%);
230
+ --color-accent: var(--color-project-dark);
229
231
  --color-link: #67c1df;
230
232
  --color-success: #4cc38a;
231
233
  --color-warning: #e2a54b;
@@ -250,7 +252,6 @@
250
252
 
251
253
  :root[data-theme="dark"] {
252
254
  color-scheme: dark;
253
- --color-project: var(--color-project-dark);
254
255
  --color-bg: #0d1012;
255
256
  --color-surface: #13171a;
256
257
  --color-surface-raised: #181d21;
@@ -266,6 +267,7 @@
266
267
  --color-text: #e6e9eb;
267
268
  --color-muted: #9aa3ab;
268
269
  --color-overlay: rgb(0 0 0 / 62%);
270
+ --color-accent: var(--color-project-dark);
269
271
  --color-link: #67c1df;
270
272
  --color-success: #4cc38a;
271
273
  --color-warning: #e2a54b;
@@ -294,7 +296,6 @@
294
296
 
295
297
  :root.dark:not(:where([data-theme="light"])), :root [data-theme="dark"], :root .dark:not(:where([data-theme="light"])) {
296
298
  color-scheme: dark;
297
- --color-project: var(--color-project-dark);
298
299
  --color-bg: #0d1012;
299
300
  --color-surface: #13171a;
300
301
  --color-surface-raised: #181d21;
@@ -314,7 +315,7 @@
314
315
  --color-text: #e6e9eb;
315
316
  --color-muted: #9aa3ab;
316
317
  --color-overlay: rgb(0 0 0 / 62%);
317
- --color-accent: var(--color-project);
318
+ --color-accent: var(--color-project-dark);
318
319
  --color-accent-text: var(--color-bg);
319
320
  --color-accent-hover: var(--color-text);
320
321
  --color-button-hover: color-mix(in srgb, var(--color-accent) 85%, var(--color-text));
@@ -355,7 +356,6 @@
355
356
 
356
357
  :root [data-theme="light"] {
357
358
  color-scheme: light;
358
- --color-project: #4b45d1;
359
359
  --color-bg: #f4f5f6;
360
360
  --color-surface: #e9ebed;
361
361
  --color-surface-raised: #fbfbfc;
@@ -414,6 +414,13 @@
414
414
  --shadow-field-focus-invalid: inset 0 0 0 2px color-mix(in srgb, var(--color-error) 18%, transparent);
415
415
  }
416
416
 
417
+ /* Touch: at tablet width, controls of every size grow to --control-touch (components.md, Rules for every
418
+ control), so a component sized from --control-sm, --control-md, or --control-lg needs no touch rule of its own.
419
+ A size specimen that must keep its size sets the three back on itself. */
420
+ @media (max-width: 800px) {
421
+ :root { --control-sm: var(--control-touch); --control-md: var(--control-touch); --control-lg: var(--control-touch); }
422
+ }
423
+
417
424
  /* Minimal base. Component styles live in components.html. The base sits in a layer, so any
418
425
  page or component rule outranks it whatever its specificity. A layered !important outranks an
419
426
  unlayered one, so reduced-motion exceptions belong here too. */
@@ -439,6 +446,14 @@ body { background: var(--color-bg); color: var(--color-text); }
439
446
  a:hover { text-decoration: underline; }
440
447
  p a, dd a { text-decoration: underline; text-underline-offset: 0.18em; }
441
448
  :focus-visible { outline: var(--focus-width) solid var(--color-focus); outline-offset: var(--focus-offset); }
449
+ /* Enabled controls, and a label that wraps or follows an enabled choice, show the pointer. :where() keeps it
450
+ weightless, so a component's cursor, such as a busy button's wait, wins. Disabled controls keep the
451
+ not-allowed cursor their component sets (components.md, Disabled). An editable combobox keeps the text cursor. */
452
+ :where(button, select, summary, [role="button"], [role="tab"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="option"], [role="switch"], [role="checkbox"], [role="radio"], [role="combobox"]:read-only:not(input, textarea), input:is([type="checkbox"], [type="radio"], [type="range"], [type="file"], [type="color"])):where(:not(:disabled, [aria-disabled="true"], [data-disabled])),
453
+ :where(label:has(:is(input:is([type="checkbox"], [type="radio"]), [role="switch"], [role="checkbox"], [role="radio"]):not(:disabled, [aria-disabled="true"], [data-disabled]))),
454
+ :where(:is(input:is([type="checkbox"], [type="radio"]), [role="switch"], [role="checkbox"], [role="radio"]):not(:disabled, [aria-disabled="true"], [data-disabled]) + label) { cursor: pointer; }
455
+ /* The file input's chooser button is its own box, so it takes the input's cursor. */
456
+ :where(input[type="file"]:not(:disabled, [aria-disabled="true"], [data-disabled]))::file-selector-button { cursor: inherit; }
442
457
  @media (prefers-reduced-motion: reduce) {
443
458
  *, *::before, *::after { transition-duration: 0ms !important; animation-duration: 0ms !important; scroll-behavior: auto !important; }
444
459
  /* A busy spinner slows instead of stopping, so the busy state stays visible. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@filipgutica/design-system",
3
- "version": "1.0.39",
3
+ "version": "1.0.41",
4
4
  "description": "Filip's design language, tokens, and component catalogue for any framework",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -21,6 +21,10 @@
21
21
  "types": "./theme-mapper/index.d.ts",
22
22
  "default": "./theme-mapper/index.js"
23
23
  },
24
+ "./theme-builder": {
25
+ "types": "./theme-mapper/theme-builder.d.ts",
26
+ "default": "./theme-mapper/theme-builder.js"
27
+ },
24
28
  "./open-vsx": {
25
29
  "types": "./open-vsx/index.d.ts",
26
30
  "default": "./open-vsx/index.js"
@@ -1,2 +1,4 @@
1
1
  /** The core tokens: every theme's base. @type {import('./engine.js').TokenSource} */
2
2
  export const core: import("./engine.js").TokenSource;
3
+ /** The default theme's inputs, which tokens.css carries. @type {import('./engine.js').ThemeInputs} */
4
+ export const defaultTheme: import("./engine.js").ThemeInputs;
@@ -1,4 +1,4 @@
1
- // Generated from tokens/core.json by scripts/build-tokens.mjs. Do not edit.
1
+ // Generated from tokens/core.json and the default theme by scripts/build-tokens.mjs. Do not edit.
2
2
  /** The core tokens: every theme's base. @type {import('./engine.js').TokenSource} */
3
3
  export const core = {
4
4
  "groups": [
@@ -82,7 +82,10 @@ export const core = {
82
82
  },
83
83
  {
84
84
  "tokens": {
85
- "color-accent": "{color-project}",
85
+ "color-accent": [
86
+ "{color-project}",
87
+ "{color-project-dark}"
88
+ ],
86
89
  "color-accent-text": "{color-bg}",
87
90
  "color-accent-hover": "{color-text}",
88
91
  "color-button-hover": "color-mix(in srgb, {color-accent} 85%, {color-text})",
@@ -288,3 +291,11 @@ export const core = {
288
291
  }
289
292
  ]
290
293
  }
294
+
295
+ /** The default theme's inputs, which tokens.css carries. @type {import('./engine.js').ThemeInputs} */
296
+ export const defaultTheme = {
297
+ "hue": {
298
+ "light": "#4b45d1",
299
+ "dark": "#a5a1ff"
300
+ }
301
+ }
@@ -0,0 +1,19 @@
1
+ export function block(indent: string, declarations: Declarations): string[];
2
+ export function darkOverrides(names: string[], resolve: Resolve): Declarations;
3
+ export function standaloneResolver(data: TokenSource): Resolve;
4
+ export function standaloneNames(data: TokenSource): string[];
5
+ export function subtreeNames(data: TokenSource): string[];
6
+ export function subtreeBlocks(blocks: {
7
+ dark: Declarations;
8
+ light: Declarations;
9
+ }, { scheme }?: {
10
+ scheme?: boolean;
11
+ }): string[];
12
+ export function renderThemeCss({ name, data, source }: {
13
+ name: string;
14
+ data: TokenSource;
15
+ source: string;
16
+ }, defaultData: TokenSource): string;
17
+ export type TokenSource = import("./engine.js").TokenSource;
18
+ export type Declarations = [string, string][];
19
+ export type Resolve = (name: string, mode: number) => string;
@@ -0,0 +1,151 @@
1
+ // The CSS that the token build and the theme builder share: tokens as custom properties, the dark overrides, the
2
+ // subtree blocks, and a theme's CSS. Not a package entry: the token build imports it, and so does theme-builder.js.
3
+ import { DARK, LIGHT, flatTokens, reference, valueFor } from './engine.js'
4
+
5
+ /** @typedef {import('./engine.js').TokenSource} TokenSource */
6
+ /** @typedef {[string, string][]} Declarations */
7
+ /** @typedef {(name: string, mode: number) => string} Resolve */
8
+
9
+ /**
10
+ * @param {string} indent
11
+ * @param {Declarations} declarations
12
+ */
13
+ export const block = (indent, declarations) => declarations.map(([name, value]) => `${indent}${name}: ${value};`)
14
+
15
+ /**
16
+ * Dark blocks list only what differs from light, compared after references resolve.
17
+ * @param {string[]} names
18
+ * @param {Resolve} resolve
19
+ * @returns {Declarations}
20
+ */
21
+ export const darkOverrides = (names, resolve) => names
22
+ .map((name) => [name, resolve(name, LIGHT), resolve(name, DARK)])
23
+ .filter(([, light, dark]) => light !== dark)
24
+ .map(([name, , dark]) => [name, dark])
25
+
26
+ /**
27
+ * A token's value in one mode, with each reference written as var().
28
+ * @param {TokenSource} data
29
+ * @returns {Resolve}
30
+ */
31
+ export const standaloneResolver = (data) => {
32
+ const tokens = flatTokens(data)
33
+ return (name, mode) => valueFor(tokens, name, mode).replace(reference, (_, target) => `var(--${target})`)
34
+ }
35
+
36
+ /** @param {TokenSource} data */
37
+ export const standaloneNames = (data) => Object.keys(flatTokens(data))
38
+
39
+ // Subtree themes: data-theme="dark" or "light" on any element below <html>, and a .dark class on <html> or
40
+ // below it, theme that element's subtree. A custom property resolves on the element that declares it, so a
41
+ // subtree block declares every token whose value differs between the modes and every token that refers to
42
+ // one, directly or through others; tokens that are the same in both modes inherit. Each selector carries a
43
+ // :root, so it outranks a theme's or a page's bare :root inputs, as the root dark rules do. On an element with
44
+ // both, data-theme="light" wins over .dark; :not(:where()) keeps that exclusion from adding specificity.
45
+ /** @type {{ dark: string[], light: string[] }} */
46
+ const SUBTREE = {
47
+ dark: [':root.dark:not(:where([data-theme="light"]))', ':root [data-theme="dark"]', ':root .dark:not(:where([data-theme="light"]))'],
48
+ light: [':root [data-theme="light"]'],
49
+ }
50
+
51
+ /** @param {TokenSource} data */
52
+ export const subtreeNames = (data) => {
53
+ const tokens = flatTokens(data)
54
+ /** @type {Map<string, boolean>} */
55
+ const memo = new Map()
56
+ /**
57
+ * @param {string} name
58
+ * @returns {boolean}
59
+ */
60
+ const followsMode = (name) => {
61
+ if (!memo.has(name)) {
62
+ memo.set(name, false)
63
+ const [light, dark] = [LIGHT, DARK].map((mode) => valueFor(tokens, name, mode))
64
+ memo.set(name, light !== dark || [...`${light} ${dark}`.matchAll(reference)].some(([, target]) => followsMode(target)))
65
+ }
66
+ return memo.get(name) ?? false
67
+ }
68
+ return Object.keys(tokens).filter(followsMode)
69
+ }
70
+
71
+ /**
72
+ * @param {{ dark: Declarations, light: Declarations }} blocks
73
+ * @param {{ scheme?: boolean }} [options]
74
+ */
75
+ export const subtreeBlocks = (blocks, { scheme = false } = {}) => /** @type {const} */ (['dark', 'light'])
76
+ .filter((mode) => blocks[mode].length > 0)
77
+ .flatMap((mode) => [
78
+ '',
79
+ `${SUBTREE[mode].join(', ')} {`,
80
+ ...(scheme ? [` color-scheme: ${mode};`] : []),
81
+ ...block(' ', blocks[mode]),
82
+ '}',
83
+ ])
84
+
85
+ /**
86
+ * What one theme changes from tokens.css, to load after it on :root: its identity inputs, then every other
87
+ * token whose light value differs. In tokens.css's cascade layer, tokens.css's dark rules outrank the theme's
88
+ * bare :root; in a later layer, the theme's :root outranks them. So the theme's dark blocks, with the same
89
+ * selectors, set each token whose dark value would come out wrong in either placement. A hue-only theme needs
90
+ * none: tokens.css's dark blocks already switch the accent to --color-project-dark. Its subtree blocks, after
91
+ * those, set each token whose value in that mode differs from what tokens.css's subtree blocks declare, such as
92
+ * the neutrals, and, because the dark one also matches :root.dark, each token the theme's :root would get wrong
93
+ * there.
94
+ * @param {{ name: string, data: TokenSource, source: string }} theme `source` names the theme file in the first comment line.
95
+ * @param {TokenSource} defaultData The default theme's tokens, which tokens.css carries.
96
+ */
97
+ export const renderThemeCss = ({ name, data, source }, defaultData) => {
98
+ const resolve = standaloneResolver(data)
99
+ const resolveDefault = standaloneResolver(defaultData)
100
+ const names = standaloneNames(data)
101
+ const identity = data.groups.filter(({ identity: isIdentity }) => isIdentity).flatMap(({ tokens }) => Object.keys(tokens))
102
+ const root = [...identity, ...names.filter((token) => !identity.includes(token) && resolve(token, LIGHT) !== resolveDefault(token, LIGHT))]
103
+ const rootLight = new Map(root.map((token) => [token, resolve(token, LIGHT)]))
104
+ const defaultDark = new Map(darkOverrides(names, resolveDefault))
105
+ /**
106
+ * The token's value on a dark :root without the theme's dark blocks: in tokens.css's layer, then in a later one.
107
+ * @param {string} token
108
+ */
109
+ const seenInDark = (token) => [
110
+ defaultDark.get(token) ?? rootLight.get(token) ?? resolveDefault(token, LIGHT),
111
+ rootLight.get(token) ?? defaultDark.get(token) ?? resolveDefault(token, LIGHT),
112
+ ]
113
+ /** @type {Declarations} */
114
+ const dark = names.filter((token) => seenInDark(token).some((seen) => seen !== resolve(token, DARK))).map((token) => [`--${token}`, resolve(token, DARK)])
115
+ const defaultSubtree = new Set(subtreeNames(defaultData))
116
+ const subtree = new Set([...defaultSubtree, ...subtreeNames(data)])
117
+ /**
118
+ * @param {number} mode
119
+ * @returns {Declarations}
120
+ */
121
+ const subtreeIn = (mode) => names
122
+ .filter((token) => subtree.has(token) && !(defaultSubtree.has(token) && resolve(token, mode) === resolveDefault(token, mode)
123
+ && (mode === LIGHT || (rootLight.get(token) ?? resolve(token, DARK)) === resolve(token, DARK))))
124
+ .map((token) => [`--${token}`, resolve(token, mode)])
125
+ /** @param {string} text */
126
+ const commentSafe = (text) => text.replaceAll('*/', '*\\/')
127
+ return [
128
+ `/* Generated from ${commentSafe(source)} by the theme builder in @filipgutica/design-system. Do not edit.`,
129
+ ` * The ${commentSafe(name)} theme for tokens.css. Load after tokens.css, in its cascade layer or a later one, on :root`,
130
+ ' * only: the tokens that follow the theme resolve on :root, so a theme scoped to an element below it changes',
131
+ " * its inputs there, but the accent, focus ring, and selection keep the default theme's colours. */",
132
+ '',
133
+ ':root {',
134
+ ...block(' ', root.map((token) => [`--${token}`, resolve(token, LIGHT)])),
135
+ '}',
136
+ ...(dark.length === 0 ? [] : [
137
+ '',
138
+ '@media (prefers-color-scheme: dark) {',
139
+ ' :root:not([data-theme="light"]) {',
140
+ ...block(' ', dark),
141
+ ' }',
142
+ '}',
143
+ '',
144
+ ':root[data-theme="dark"] {',
145
+ ...block(' ', dark),
146
+ '}',
147
+ ]),
148
+ ...subtreeBlocks({ dark: subtreeIn(DARK), light: subtreeIn(LIGHT) }),
149
+ '',
150
+ ].join('\n')
151
+ }
@@ -238,7 +238,7 @@ export const applyTheme = (core, theme) => {
238
238
  const data = JSON.parse(JSON.stringify(core))
239
239
  const identity = data.groups.find(({ identity: isIdentity }) => isIdentity)?.tokens
240
240
  if (!identity) throw new Error('The token source has no identity group')
241
- identity['color-project'] = [theme.hue.light, '{color-project-dark}']
241
+ identity['color-project'] = theme.hue.light
242
242
  identity['color-project-dark'] = theme.hue.dark
243
243
  if (theme.fonts?.ui) identity['font-ui'] = theme.fonts.ui
244
244
  if (theme.fonts?.mono) identity['font-mono'] = theme.fonts.mono
@@ -0,0 +1,12 @@
1
+ /** @typedef {import('./theme-file.js').ThemeFile} ThemeFile */
2
+ /** A theme file that the builder cannot take. `problems` lists each problem, as `parseTheme` reports it. */
3
+ export class ThemeFileError extends Error {
4
+ /** @param {string[]} problems */
5
+ constructor(problems: string[]);
6
+ problems: string[];
7
+ }
8
+ export function themeCss(file: unknown, { source }?: {
9
+ source?: string;
10
+ }): string;
11
+ export type ThemeFile = import("./theme-file.js").ThemeFile;
12
+ export { THEME_EXTENSION, parseTheme } from "./theme-file.js";
@@ -0,0 +1,36 @@
1
+ // @filipgutica/design-system/theme-builder: a theme file to the CSS that loads after tokens.css, the same CSS the
2
+ // package's own themes/*.css come from. No framework and no runtime dependencies. theme-file.js describes the
3
+ // theme file format.
4
+ import { core, defaultTheme } from './core.js'
5
+ import { applyTheme } from './engine.js'
6
+ import { renderThemeCss } from './css.js'
7
+ import { parseTheme } from './theme-file.js'
8
+
9
+ export { THEME_EXTENSION, parseTheme } from './theme-file.js'
10
+
11
+ /** @typedef {import('./theme-file.js').ThemeFile} ThemeFile */
12
+
13
+ /** A theme file that the builder cannot take. `problems` lists each problem, as `parseTheme` reports it. */
14
+ export class ThemeFileError extends Error {
15
+ /** @param {string[]} problems */
16
+ constructor(problems) {
17
+ super(`The theme file has problems:\n ${problems.join('\n ')}`)
18
+ this.name = 'ThemeFileError'
19
+ this.problems = problems
20
+ }
21
+ }
22
+
23
+ /**
24
+ * The CSS for a theme file, to load after tokens.css, in its cascade layer or a later one: the theme's inputs on
25
+ * :root, and the mode and subtree blocks for any neutrals or text on the hue it sets. It is the CSS the package's
26
+ * themes/*.css come from.
27
+ * @param {unknown} file The theme file's parsed JSON.
28
+ * @param {{ source?: string }} [options] `source` names the file in the CSS's first comment line.
29
+ * @returns {string}
30
+ * @throws {ThemeFileError} When the file has a problem.
31
+ */
32
+ export const themeCss = (file, { source = 'a theme file' } = {}) => {
33
+ const { problems, inputs } = parseTheme(file)
34
+ if (inputs === undefined) throw new ThemeFileError(problems)
35
+ return renderThemeCss({ name: inputs.name, data: applyTheme(core, inputs), source }, applyTheme(core, defaultTheme))
36
+ }
@@ -0,0 +1,61 @@
1
+ /** @typedef {import('./engine.js').ModePair} ModePair */
2
+ /** @typedef {{ [key: string]: unknown }} JsonObject */
3
+ /**
4
+ * A theme file's inputs, in the shape the theme engine takes, with its name and note.
5
+ * @typedef {object} ThemeFile
6
+ * @property {string} name
7
+ * @property {string} note
8
+ * @property {ModePair} hue `color-project` in light and in dark.
9
+ * @property {{ ui?: string, mono?: string }} [fonts] The two font stacks, as CSS.
10
+ * @property {string} [radius] `radius-base`, as a CSS length.
11
+ * @property {{ light: Record<string, string>, dark: Record<string, string> }} [neutrals] Every NEUTRALS token, per mode.
12
+ * @property {{ light?: Record<string, string>, dark?: Record<string, string> }} [textOnHue] TEXT_ON_HUE_TOKENS the
13
+ * file sets, per mode.
14
+ */
15
+ /** The $extensions namespace that holds a theme's name. */
16
+ export const THEME_EXTENSION: "io.github.filipgutica.design-system";
17
+ export function parseTheme(file: unknown): {
18
+ problems: string[];
19
+ inputs?: ThemeFile;
20
+ };
21
+ export type ModePair = import("./engine.js").ModePair;
22
+ export type JsonObject = {
23
+ [key: string]: unknown;
24
+ };
25
+ /**
26
+ * A theme file's inputs, in the shape the theme engine takes, with its name and note.
27
+ */
28
+ export type ThemeFile = {
29
+ name: string;
30
+ note: string;
31
+ /**
32
+ * `color-project` in light and in dark.
33
+ */
34
+ hue: ModePair;
35
+ /**
36
+ * The two font stacks, as CSS.
37
+ */
38
+ fonts?: {
39
+ ui?: string;
40
+ mono?: string;
41
+ } | undefined;
42
+ /**
43
+ * `radius-base`, as a CSS length.
44
+ */
45
+ radius?: string | undefined;
46
+ /**
47
+ * Every NEUTRALS token, per mode.
48
+ */
49
+ neutrals?: {
50
+ light: Record<string, string>;
51
+ dark: Record<string, string>;
52
+ } | undefined;
53
+ /**
54
+ * TEXT_ON_HUE_TOKENS the
55
+ * file sets, per mode.
56
+ */
57
+ textOnHue?: {
58
+ light?: Record<string, string>;
59
+ dark?: Record<string, string>;
60
+ } | undefined;
61
+ };
@@ -0,0 +1,193 @@
1
+ // The theme file parser that the token build and the theme builder share. Not a package entry: theme-builder.js
2
+ // re-exports it. It needs no core tokens, so the token build can read the theme files before it writes core.js.
3
+ //
4
+ // A theme file is a W3C Design Tokens file (Format and Color modules 2025.10) that holds only the theme's inputs:
5
+ // - $description: a note about the theme, and $extensions["io.github.filipgutica.design-system"].name: its name.
6
+ // - A `light` and a `dark` group of color tokens: `color-project`, the hue (required); optionally the whole set of
7
+ // neutrals (NEUTRALS); and optionally the text on the hue's fills (TEXT_ON_HUE_TOKENS) for a hue that cannot carry
8
+ // the default.
9
+ // - Optionally `font-ui` and `font-mono` (fontFamily tokens) and `radius-base` (a dimension token in px or rem).
10
+ // Colours are opaque sRGB. A token's $type is its own, else its group's, else the file's.
11
+ import { NEUTRALS, TEXT_ON_HUE_TOKENS } from './engine.js'
12
+
13
+ /** @typedef {import('./engine.js').ModePair} ModePair */
14
+ /** @typedef {{ [key: string]: unknown }} JsonObject */
15
+ /**
16
+ * A theme file's inputs, in the shape the theme engine takes, with its name and note.
17
+ * @typedef {object} ThemeFile
18
+ * @property {string} name
19
+ * @property {string} note
20
+ * @property {ModePair} hue `color-project` in light and in dark.
21
+ * @property {{ ui?: string, mono?: string }} [fonts] The two font stacks, as CSS.
22
+ * @property {string} [radius] `radius-base`, as a CSS length.
23
+ * @property {{ light: Record<string, string>, dark: Record<string, string> }} [neutrals] Every NEUTRALS token, per mode.
24
+ * @property {{ light?: Record<string, string>, dark?: Record<string, string> }} [textOnHue] TEXT_ON_HUE_TOKENS the
25
+ * file sets, per mode.
26
+ */
27
+
28
+ /** The $extensions namespace that holds a theme's name. */
29
+ export const THEME_EXTENSION = 'io.github.filipgutica.design-system'
30
+ /** @type {('light' | 'dark')[]} */
31
+ const MODES = ['light', 'dark']
32
+ /** @type {[string, 'ui' | 'mono'][]} */
33
+ const FONTS = [['font-ui', 'ui'], ['font-mono', 'mono']]
34
+ const RADIUS = 'radius-base'
35
+ // Properties the build ignores: they describe a token or group and change no value. Any other $ property,
36
+ // such as $value on a group, $extends, or $ref, is a problem rather than silently skipped.
37
+ const METADATA = ['$description', '$extensions', '$deprecated']
38
+
39
+ /**
40
+ * @param {unknown} value
41
+ * @returns {value is JsonObject}
42
+ */
43
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
44
+
45
+ /**
46
+ * A colour token's value as #rrggbb, or the problem with it: the build takes opaque sRGB only, and a hex
47
+ * fallback, when given, must agree with the components.
48
+ * @param {unknown} value
49
+ * @returns {[string] | [undefined, string]}
50
+ */
51
+ const srgbHex = (value) => {
52
+ if (!isObject(value) || value.colorSpace !== 'srgb') return [undefined, 'is not an srgb colour']
53
+ const { components, alpha = 1, hex } = value
54
+ if (!Array.isArray(components) || components.length !== 3 || !components.every((c) => typeof c === 'number' && c >= 0 && c <= 1)) {
55
+ return [undefined, 'needs three components from 0 to 1']
56
+ }
57
+ if (alpha !== 1) return [undefined, 'is not opaque']
58
+ const derived = `#${components.map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')}`
59
+ if (hex !== undefined && typeof hex !== 'string') return [undefined, 'has a hex that is not a string']
60
+ if (hex !== undefined && hex.toLowerCase() !== derived) return [undefined, `has hex ${hex}, but its components are ${derived}`]
61
+ return [derived]
62
+ }
63
+
64
+ /**
65
+ * @param {unknown} value
66
+ * @returns {value is string | string[]}
67
+ */
68
+ const isFontFamily = (value) => [value].flat().length > 0
69
+ && [value].flat().every((name) => typeof name === 'string' && name !== '' && !/[\u0000-\u001f]/.test(name))
70
+ // A fontFamily value as a CSS font stack. A name that is a CSS identifier stays bare, so generic families
71
+ // and keywords such as sans-serif and -apple-system keep their meaning; any other name, such as one with
72
+ // a space or one that starts with a digit, is a quoted string with its quotes and backslashes escaped, and its
73
+ // braces as code points, which the token engine would otherwise read as a reference. A CSS-wide keyword, or
74
+ // `default`, would make the whole list invalid, so it is quoted too.
75
+ const CSS_WIDE = ['initial', 'inherit', 'unset', 'revert', 'revert-layer', 'revert-rule', 'default']
76
+ /** @param {string | string[]} value */
77
+ const fontStack = (value) => [value].flat()
78
+ .map((name) => (/^-?[A-Za-z_][\w-]*$/.test(name) && !CSS_WIDE.includes(name.toLowerCase())
79
+ ? name
80
+ : `"${name.replace(/[\\"]/g, '\\$&').replaceAll('{', '\\7b ').replaceAll('}', '\\7d ')}"`)).join(', ')
81
+
82
+ /**
83
+ * A dimension value ({ value, unit }) as a CSS length. The base radius takes px or rem, and no negative size.
84
+ * @param {unknown} value
85
+ * @returns {value is { value: number, unit: string }}
86
+ */
87
+ const isLength = (value) => isObject(value) && Object.keys(value).length === 2 && (value.unit === 'px' || value.unit === 'rem')
88
+ && typeof value.value === 'number' && Number.isFinite(value.value) && value.value >= 0
89
+
90
+ /** @param {JsonObject[]} layers */
91
+ const typeOf = (...layers) => layers.find((layer) => '$type' in layer)?.$type
92
+
93
+ /**
94
+ * A theme file's inputs and its problems: no name or note, a key a theme cannot set, a token of the wrong type, a
95
+ * colour the build cannot take, a missing hue, or neutrals that are not the whole set in both modes. `inputs` is
96
+ * there only when there is no problem.
97
+ * @param {unknown} file The theme file's parsed JSON.
98
+ * @returns {{ problems: string[], inputs?: ThemeFile }}
99
+ */
100
+ export const parseTheme = (file) => {
101
+ if (!isObject(file)) return { problems: ['is not a JSON object'] }
102
+ /** @type {string[]} */
103
+ const problems = []
104
+ const extension = isObject(file.$extensions) ? file.$extensions[THEME_EXTENSION] : undefined
105
+ const name = isObject(extension) && typeof extension.name === 'string' && extension.name ? extension.name : undefined
106
+ if (name === undefined) problems.push(`no $extensions["${THEME_EXTENSION}"].name`)
107
+ const note = typeof file.$description === 'string' && file.$description ? file.$description : undefined
108
+ if (note === undefined) problems.push('no $description')
109
+ for (const key of Object.keys(file)) {
110
+ if (![...METADATA, '$type', ...MODES, ...FONTS.map(([token]) => token), RADIUS].includes(key)) problems.push(`${key} is not a theme input`)
111
+ }
112
+
113
+ const colourInputs = [...NEUTRALS, 'color-project', ...TEXT_ON_HUE_TOKENS]
114
+ /** @type {Record<string, JsonObject>} */
115
+ const groups = {}
116
+ /** @type {Record<string, Record<string, string>>} */
117
+ const colours = {}
118
+ for (const mode of MODES) {
119
+ const raw = file[mode]
120
+ const group = isObject(raw) ? raw : {}
121
+ groups[mode] = group
122
+ /** @type {Record<string, string>} */
123
+ const values = {}
124
+ if (mode in file && !isObject(raw)) problems.push(`${mode} is not a group`)
125
+ for (const [token, entry] of Object.entries(group)) {
126
+ if (token.startsWith('$')) {
127
+ if (![...METADATA, '$type'].includes(token)) problems.push(`${mode}.${token} is not supported in a theme file`)
128
+ continue
129
+ }
130
+ if (!colourInputs.includes(token)) { problems.push(`${mode}.${token} is not a theme input`); continue }
131
+ if (!isObject(entry) || !('$value' in entry)) { problems.push(`${mode}.${token} is not a token`); continue }
132
+ const unsupported = Object.keys(entry).filter((key) => ![...METADATA, '$type', '$value'].includes(key))
133
+ if (unsupported.length > 0) { problems.push(`${mode}.${token} has ${unsupported.join(', ')}, which a theme file does not support`); continue }
134
+ const [hex, problem] = srgbHex(entry.$value)
135
+ if (typeOf(entry, group, file) !== 'color') problems.push(`${mode}.${token} is not a color token`)
136
+ else if (problem) problems.push(`${mode}.${token} ${problem}`)
137
+ else if (hex) values[token] = hex
138
+ }
139
+ if (!('color-project' in group)) problems.push(`no ${mode}.color-project`)
140
+ colours[mode] = values
141
+ }
142
+ const hasNeutrals = MODES.some((mode) => NEUTRALS.some((token) => token in groups[mode]))
143
+ if (hasNeutrals) {
144
+ for (const mode of MODES) for (const token of NEUTRALS) if (!(token in groups[mode])) problems.push(`no ${mode}.${token}: neutrals are a whole set in both modes`)
145
+ }
146
+
147
+ /** @type {{ ui?: string, mono?: string }} */
148
+ const fonts = {}
149
+ for (const [token, font] of FONTS) {
150
+ if (!(token in file)) continue
151
+ const entry = file[token]
152
+ const unsupported = isObject(entry) ? Object.keys(entry).filter((key) => ![...METADATA, '$type', '$value'].includes(key)) : []
153
+ if (!isObject(entry) || !('$value' in entry)) problems.push(`${token} is not a token`)
154
+ else if (unsupported.length > 0) problems.push(`${token} has ${unsupported.join(', ')}, which a theme file does not support`)
155
+ else if (typeOf(entry, file) !== 'fontFamily') problems.push(`${token} is not a fontFamily token`)
156
+ else if (!isFontFamily(entry.$value)) problems.push(`${token} is not a font name or a list of them`)
157
+ else fonts[font] = fontStack(entry.$value)
158
+ }
159
+
160
+ /** @type {string | undefined} */
161
+ let radius
162
+ if (RADIUS in file) {
163
+ const entry = file[RADIUS]
164
+ const unsupported = isObject(entry) ? Object.keys(entry).filter((key) => ![...METADATA, '$type', '$value'].includes(key)) : []
165
+ if (!isObject(entry) || !('$value' in entry)) problems.push(`${RADIUS} is not a token`)
166
+ else if (unsupported.length > 0) problems.push(`${RADIUS} has ${unsupported.join(', ')}, which a theme file does not support`)
167
+ else if (typeOf(entry, file) !== 'dimension') problems.push(`${RADIUS} is not a dimension token`)
168
+ else if (!isLength(entry.$value)) problems.push(`${RADIUS} is not a px or rem length of 0 or more`)
169
+ else radius = `${entry.$value.value}${entry.$value.unit}`
170
+ }
171
+
172
+ /** @param {string[]} tokens */
173
+ const modeValues = (tokens) => ({
174
+ light: Object.fromEntries(tokens.filter((token) => token in colours.light).map((token) => [token, colours.light[token]])),
175
+ dark: Object.fromEntries(tokens.filter((token) => token in colours.dark).map((token) => [token, colours.dark[token]])),
176
+ })
177
+ const textOnHue = modeValues(TEXT_ON_HUE_TOKENS)
178
+ const hasTextOnHue = Object.keys(textOnHue.light).length + Object.keys(textOnHue.dark).length > 0
179
+ const hue = { light: colours.light['color-project'], dark: colours.dark['color-project'] }
180
+ if (problems.length > 0 || name === undefined || note === undefined || hue.light === undefined || hue.dark === undefined) return { problems }
181
+ return {
182
+ problems,
183
+ inputs: {
184
+ name,
185
+ note,
186
+ hue: { light: hue.light, dark: hue.dark },
187
+ ...(Object.keys(fonts).length > 0 && { fonts }),
188
+ ...(radius !== undefined && { radius }),
189
+ ...(hasNeutrals && { neutrals: modeValues(NEUTRALS) }),
190
+ ...(hasTextOnHue && { textOnHue }),
191
+ },
192
+ }
193
+ }