@cognitap/radiant 0.0.3 → 0.0.4

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 (56) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +19 -15
  3. package/dist/library/color/colorFamilies.d.ts +3 -0
  4. package/dist/library/color/colorFamilies.d.ts.map +1 -0
  5. package/dist/library/color/colorFamilies.js +20 -0
  6. package/dist/library/color/colorFamilies.js.map +1 -0
  7. package/dist/library/color/generateColorWall.d.ts +54 -0
  8. package/dist/library/color/generateColorWall.d.ts.map +1 -0
  9. package/dist/library/color/generateColorWall.js +231 -0
  10. package/dist/library/color/generateColorWall.js.map +1 -0
  11. package/dist/library/color/index.d.ts +5 -0
  12. package/dist/library/color/index.d.ts.map +1 -0
  13. package/dist/library/color/index.js +3 -0
  14. package/dist/library/color/index.js.map +1 -0
  15. package/dist/library/color/oklch.d.ts +17 -0
  16. package/dist/library/color/oklch.d.ts.map +1 -0
  17. package/dist/library/color/oklch.js +79 -0
  18. package/dist/library/color/oklch.js.map +1 -0
  19. package/dist/library/color/recommendColorPalette.d.ts +65 -0
  20. package/dist/library/color/recommendColorPalette.d.ts.map +1 -0
  21. package/dist/library/color/recommendColorPalette.js +263 -0
  22. package/dist/library/color/recommendColorPalette.js.map +1 -0
  23. package/dist/library/index.d.ts +8 -2
  24. package/dist/library/index.d.ts.map +1 -1
  25. package/dist/library/index.js +4 -1
  26. package/dist/library/index.js.map +1 -1
  27. package/dist/library/styles.css +1 -1
  28. package/dist/library/themes/index.d.ts +4 -0
  29. package/dist/library/themes/index.d.ts.map +1 -1
  30. package/dist/library/themes/index.js +2 -0
  31. package/dist/library/themes/index.js.map +1 -1
  32. package/dist/library/themes/themeDocument.d.ts +16 -0
  33. package/dist/library/themes/themeDocument.d.ts.map +1 -0
  34. package/dist/library/themes/themeDocument.js +307 -0
  35. package/dist/library/themes/themeDocument.js.map +1 -0
  36. package/dist/library/themes/themeDocumentTypes.d.ts +69 -0
  37. package/dist/library/themes/themeDocumentTypes.d.ts.map +1 -0
  38. package/dist/library/themes/themeDocumentTypes.js +2 -0
  39. package/dist/library/themes/themeDocumentTypes.js.map +1 -0
  40. package/dist/library/themes/updateThemeAppearance.d.ts +29 -0
  41. package/dist/library/themes/updateThemeAppearance.d.ts.map +1 -0
  42. package/dist/library/themes/updateThemeAppearance.js +138 -0
  43. package/dist/library/themes/updateThemeAppearance.js.map +1 -0
  44. package/docs/system.md +13 -0
  45. package/docs/theming.md +412 -0
  46. package/package.json +11 -4
  47. package/src/color/colorFamilies.ts +19 -0
  48. package/src/color/generateColorWall.ts +358 -0
  49. package/src/color/index.ts +11 -0
  50. package/src/color/oklch.ts +95 -0
  51. package/src/color/recommendColorPalette.ts +375 -0
  52. package/src/index.ts +37 -0
  53. package/src/themes/index.ts +24 -0
  54. package/src/themes/themeDocument.ts +340 -0
  55. package/src/themes/themeDocumentTypes.ts +76 -0
  56. package/src/themes/updateThemeAppearance.ts +172 -0
@@ -0,0 +1,340 @@
1
+ import { defineTheme, type Theme, type ThemeDefinition, type ThemeLayer } from './defineTheme.js'
2
+ import { freezeTree, tokenDefaults } from './tokens.js'
3
+ import type {
4
+ ThemeColorSection,
5
+ ThemeDocument,
6
+ ThemeSectionExport,
7
+ ThemeSectionName,
8
+ ThemeSections
9
+ } from './themeDocumentTypes.js'
10
+
11
+ export type * from './themeDocumentTypes.js'
12
+
13
+ const sectionNames: readonly ThemeSectionName[] = [
14
+ ...Object.keys(tokenDefaults.light),
15
+ 'components'
16
+ ] as ThemeSectionName[]
17
+ const stops = new Set([50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950])
18
+ type RecordValue = Record<string, unknown>
19
+
20
+ function record(value: unknown, path: string): asserts value is RecordValue {
21
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
22
+ throw new TypeError(`${path} must be an object.`)
23
+ }
24
+ }
25
+
26
+ function keys(value: RecordValue, allowed: readonly string[], path: string) {
27
+ for (const key of Object.keys(value)) {
28
+ if (!allowed.includes(key)) throw new TypeError(`Unknown key: ${path}.${key}.`)
29
+ }
30
+ }
31
+
32
+ function textValue(value: unknown, path: string) {
33
+ if (typeof value !== 'string' || !value.trim()) {
34
+ throw new TypeError(`${path} must be a nonempty string.`)
35
+ }
36
+ }
37
+
38
+ function choice(value: unknown, allowed: readonly unknown[], path: string) {
39
+ if (!allowed.includes(value)) {
40
+ throw new TypeError(`${path} must be one of: ${allowed.join(', ')}.`)
41
+ }
42
+ }
43
+
44
+ function list(value: unknown, path: string): asserts value is unknown[] {
45
+ if (!Array.isArray(value)) throw new TypeError(`${path} must be an array.`)
46
+ }
47
+
48
+ function unique(value: unknown, seen: Set<unknown>, path: string) {
49
+ if (seen.has(value)) throw new TypeError(`Duplicate value at ${path}: ${String(value)}.`)
50
+ seen.add(value)
51
+ }
52
+
53
+ /** Copy data without running getters/toJSON or silently losing functions and binaries. */
54
+ function jsonCopy(value: unknown, path: string, ancestors = new Set<object>()): unknown {
55
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
56
+ if (typeof value === 'number' && Number.isFinite(value)) return value === 0 ? 0 : value
57
+ if (!value || typeof value !== 'object')
58
+ throw new TypeError(`${path} must contain JSON data only.`)
59
+ if (ancestors.has(value)) throw new TypeError(`Circular reference at ${path}.`)
60
+ const array = Array.isArray(value)
61
+ const prototype = Object.getPrototypeOf(value)
62
+ if (
63
+ array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null
64
+ ) {
65
+ throw new TypeError(`${path} must contain plain JSON objects, not class instances or binaries.`)
66
+ }
67
+ ancestors.add(value)
68
+ const result: RecordValue | unknown[] = array ? [] : {}
69
+ if (Object.getOwnPropertySymbols(value).length)
70
+ throw new TypeError(`${path} cannot contain symbol keys.`)
71
+ const descriptors = Object.getOwnPropertyDescriptors(value)
72
+ for (const key of Object.keys(descriptors).sort()) {
73
+ if (array && key === 'length') continue
74
+ if (['__proto__', 'constructor', 'prototype'].includes(key))
75
+ throw new TypeError(`Forbidden key: ${path}.${key}.`)
76
+ const descriptor = descriptors[key]
77
+ if (!('value' in descriptor) || !descriptor.enumerable) {
78
+ throw new TypeError(`${path}.${key} must be an enumerable data property.`)
79
+ }
80
+ if (array && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length)) {
81
+ throw new TypeError(`${path}.${key} is not an array index.`)
82
+ }
83
+ // Optional object properties follow JSON omission rules; array holes/undefined are invalid.
84
+ if (descriptor.value === undefined && !array) continue
85
+ const copy = jsonCopy(descriptor.value, `${path}.${key}`, ancestors)
86
+ Object.defineProperty(result, key, {
87
+ value: copy,
88
+ enumerable: true,
89
+ writable: true,
90
+ configurable: true
91
+ })
92
+ }
93
+ if (array && Object.keys(result).length !== value.length)
94
+ throw new TypeError(`${path} cannot contain array holes.`)
95
+ ancestors.delete(value)
96
+ return result
97
+ }
98
+
99
+ function validateColor(value: RecordValue, path: string) {
100
+ if (value.brand !== undefined) {
101
+ record(value.brand, `${path}.brand`)
102
+ keys(value.brand, ['value', 'gamut', 'srgbFallback'], `${path}.brand`)
103
+ textValue(value.brand.value, `${path}.brand.value`)
104
+ choice(value.brand.gamut, ['srgb', 'display-p3'], `${path}.brand.gamut`)
105
+ if (value.brand.srgbFallback !== undefined)
106
+ textValue(value.brand.srgbFallback, `${path}.brand.srgbFallback`)
107
+ if (value.fidelity === undefined) value.fidelity = 'anchored'
108
+ }
109
+ if (value.fidelity !== undefined)
110
+ choice(value.fidelity, ['anchored', 'unanchored'], `${path}.fidelity`)
111
+ if (value.palettes !== undefined) {
112
+ list(value.palettes, `${path}.palettes`)
113
+ const ids = new Set<unknown>()
114
+ for (const [i, palette] of value.palettes.entries()) {
115
+ const p = `${path}.palettes.${i}`
116
+ record(palette, p)
117
+ keys(palette, ['id', 'name', 'swatches'], p)
118
+ textValue(palette.id, `${p}.id`)
119
+ textValue(palette.name, `${p}.name`)
120
+ unique(palette.id, ids, `${p}.id`)
121
+ list(palette.swatches, `${p}.swatches`)
122
+ if (!palette.swatches.length) throw new TypeError(`${p}.swatches must not be empty.`)
123
+ const seen = new Set<unknown>()
124
+ for (const [j, swatch] of palette.swatches.entries()) {
125
+ const s = `${p}.swatches.${j}`
126
+ record(swatch, s)
127
+ keys(swatch, ['stop', 'value', 'srgbFallback'], s)
128
+ if (!stops.has(swatch.stop as number))
129
+ throw new TypeError(`${s}.stop must be a numbered color stop (50–950).`)
130
+ unique(swatch.stop, seen, `${s}.stop`)
131
+ textValue(swatch.value, `${s}.value`)
132
+ if (swatch.srgbFallback !== undefined) textValue(swatch.srgbFallback, `${s}.srgbFallback`)
133
+ }
134
+ }
135
+ }
136
+ if (value.anchor !== undefined) {
137
+ record(value.anchor, `${path}.anchor`)
138
+ keys(value.anchor, ['paletteId', 'stop'], `${path}.anchor`)
139
+ textValue(value.anchor.paletteId, `${path}.anchor.paletteId`)
140
+ if (!stops.has(value.anchor.stop as number))
141
+ throw new TypeError(`${path}.anchor.stop must be a numbered color stop (50–950).`)
142
+ const color = value as ThemeColorSection
143
+ const swatch = color.palettes
144
+ ?.find(p => p.id === color.anchor!.paletteId)
145
+ ?.swatches.find(s => s.stop === color.anchor!.stop)
146
+ if (!color.brand || color.fidelity !== 'anchored' || swatch?.value !== color.brand.value) {
147
+ throw new TypeError(
148
+ `${path}.anchor must reference a swatch containing the exact brand.value with anchored fidelity. Regenerate or replace the color section.`
149
+ )
150
+ }
151
+ }
152
+ }
153
+
154
+ function validateFonts(value: unknown, path: string) {
155
+ list(value, path)
156
+ const ids = new Set<unknown>()
157
+ for (const [i, font] of value.entries()) {
158
+ const p = `${path}.${i}`
159
+ record(font, p)
160
+ keys(font, ['id', 'family', 'source', 'weights', 'styles'], p)
161
+ textValue(font.id, `${p}.id`)
162
+ textValue(font.family, `${p}.family`)
163
+ unique(font.id, ids, `${p}.id`)
164
+ choice(font.source, ['system', 'catalog', 'local'], `${p}.source`)
165
+ for (const key of ['weights', 'styles']) {
166
+ if (font[key] === undefined) continue
167
+ list(font[key], `${p}.${key}`)
168
+ const seen = new Set<unknown>()
169
+ for (const [j, item] of font[key].entries()) {
170
+ const at = `${p}.${key}.${j}`
171
+ if (key === 'styles') choice(item, ['normal', 'italic'], at)
172
+ else if (typeof item !== 'number' || item < 1 || item > 1000)
173
+ throw new TypeError(`${at} must be a weight from 1 to 1000.`)
174
+ unique(item, seen, at)
175
+ }
176
+ }
177
+ }
178
+ }
179
+
180
+ function toDefinition(sections: ThemeSections, id: string, name: string): ThemeDefinition {
181
+ const common: { tokens: RecordValue; components?: ThemeLayer['components'] } = { tokens: {} }
182
+ const modes = { light: { tokens: {} } as typeof common, dark: { tokens: {} } as typeof common }
183
+ for (const sectionName of sectionNames) {
184
+ const section = sections[sectionName]
185
+ if (!section) continue
186
+ for (const mode of ['common', 'light', 'dark'] as const) {
187
+ const values = mode === 'common' ? section.values : section.modes?.[mode]
188
+ if (values === undefined) continue
189
+ const layer = mode === 'common' ? common : modes[mode]
190
+ if (sectionName === 'components') layer.components = values as ThemeLayer['components']
191
+ else layer.tokens[sectionName] = values
192
+ }
193
+ }
194
+ return { id, name, ...common, modes }
195
+ }
196
+
197
+ /** Read JSON.parse output (or data objects); unknown versions/keys fail with a path. */
198
+ export function parseThemeDocument(input: unknown): ThemeDocument | ThemeSectionExport {
199
+ const value = jsonCopy(input, 'document')
200
+ record(value, 'document')
201
+ choice(value.kind, ['radiant-theme', 'radiant-theme-sections'], 'document.kind')
202
+ if (value.version !== 1)
203
+ throw new TypeError(
204
+ `Unsupported document.version: ${String(value.version)}. Expected 1; migrate the configuration before importing.`
205
+ )
206
+ const full = value.kind === 'radiant-theme'
207
+ keys(
208
+ value,
209
+ full ? ['kind', 'version', 'id', 'name', 'sections'] : ['kind', 'version', 'sections'],
210
+ 'document'
211
+ )
212
+ record(value.sections, 'document.sections')
213
+ keys(value.sections, sectionNames, 'document.sections')
214
+ for (const [name, section] of Object.entries(value.sections)) {
215
+ const path = `document.sections.${name}`
216
+ record(section, path)
217
+ keys(
218
+ section,
219
+ [
220
+ 'values',
221
+ 'modes',
222
+ ...(name === 'color'
223
+ ? ['brand', 'fidelity', 'palettes', 'anchor']
224
+ : name === 'typography'
225
+ ? ['fonts']
226
+ : [])
227
+ ],
228
+ path
229
+ )
230
+ if (section.modes !== undefined) {
231
+ record(section.modes, `${path}.modes`)
232
+ keys(section.modes, ['light', 'dark'], `${path}.modes`)
233
+ }
234
+ if (name === 'color') validateColor(section, path)
235
+ if (name === 'typography' && section.fonts !== undefined)
236
+ validateFonts(section.fonts, `${path}.fonts`)
237
+ }
238
+ // Reuse the canonical token/component validation and resolution; no second token schema.
239
+ defineTheme(
240
+ toDefinition(
241
+ value.sections as ThemeSections,
242
+ full ? (value.id as string) : 'section-export',
243
+ full ? (value.name as string) : 'Section export'
244
+ )
245
+ )
246
+ return freezeTree(jsonCopy(value, 'document') as object) as ThemeDocument | ThemeSectionExport
247
+ }
248
+
249
+ /** Validate and detach an immutable, portable authoring snapshot. */
250
+ export function defineThemeDocument(document: ThemeDocument): ThemeDocument {
251
+ const result = parseThemeDocument(document)
252
+ if (result.kind !== 'radiant-theme')
253
+ throw new TypeError('Expected a radiant-theme document with id and name.')
254
+ return result
255
+ }
256
+
257
+ /** Compile only authored semantic values through the existing application theme runtime. */
258
+ export function compileThemeDocument(document: ThemeDocument): Theme {
259
+ const validated = defineThemeDocument(document)
260
+ return defineTheme(toDefinition(validated.sections, validated.id, validated.name))
261
+ }
262
+
263
+ function merge(base: unknown, patch: unknown): unknown {
264
+ if (
265
+ !base ||
266
+ !patch ||
267
+ typeof base !== 'object' ||
268
+ typeof patch !== 'object' ||
269
+ Array.isArray(base) ||
270
+ Array.isArray(patch)
271
+ )
272
+ return patch
273
+ const result: RecordValue = { ...base }
274
+ for (const [key, value] of Object.entries(patch)) result[key] = merge(result[key], value)
275
+ return result
276
+ }
277
+
278
+ /** Merge leaves/replace arrays, or replace only supplied sections. Empty replacement resets. */
279
+ export function updateThemeDocument(
280
+ document: ThemeDocument,
281
+ sections: ThemeSections,
282
+ mode: 'merge' | 'replace' = 'merge'
283
+ ): ThemeDocument {
284
+ const base = defineThemeDocument(document)
285
+ choice(mode, ['merge', 'replace'], 'update mode')
286
+ // Check the patch's JSON boundary before merging, including keys a spread would discard.
287
+ const patch = jsonCopy(sections, 'sections')
288
+ record(patch, 'sections')
289
+ keys(patch, sectionNames, 'sections')
290
+ const next = { ...base.sections } as RecordValue
291
+ for (const [name, section] of Object.entries(patch))
292
+ next[name] = mode === 'replace' ? section : merge(next[name], section)
293
+ return defineThemeDocument({ ...base, sections: next })
294
+ }
295
+
296
+ /** Export exactly these sections, with no document identity or implicit component exceptions. */
297
+ export function exportThemeSections(
298
+ document: ThemeDocument,
299
+ names: readonly ThemeSectionName[]
300
+ ): ThemeSectionExport {
301
+ const base = defineThemeDocument(document)
302
+ list(names, 'section names')
303
+ const sections: RecordValue = {}
304
+ for (const name of names) {
305
+ choice(name, sectionNames, 'section name')
306
+ if (base.sections[name] !== undefined) sections[name] = base.sections[name]
307
+ }
308
+ return parseThemeDocument({
309
+ kind: 'radiant-theme-sections',
310
+ version: 1,
311
+ sections
312
+ }) as ThemeSectionExport
313
+ }
314
+
315
+ /** Bring existing authored themes into the workshop without materialising defaults as overrides. */
316
+ export function themeDocumentFromDefinition(definition: ThemeDefinition): ThemeDocument {
317
+ const copy = jsonCopy(definition, 'theme') as ThemeDefinition
318
+ defineTheme(copy)
319
+ const sections: RecordValue = {}
320
+ for (const name of sectionNames) {
321
+ const section: RecordValue = {}
322
+ const values = name === 'components' ? copy.components : copy.tokens?.[name]
323
+ if (values !== undefined) section.values = values
324
+ const modes: RecordValue = {}
325
+ for (const mode of ['light', 'dark'] as const) {
326
+ const values =
327
+ name === 'components' ? copy.modes?.[mode]?.components : copy.modes?.[mode]?.tokens?.[name]
328
+ if (values !== undefined) modes[mode] = values
329
+ }
330
+ if (Object.keys(modes).length) section.modes = modes
331
+ if (Object.keys(section).length) sections[name] = section
332
+ }
333
+ return defineThemeDocument({
334
+ kind: 'radiant-theme',
335
+ version: 1,
336
+ id: copy.id,
337
+ name: copy.name,
338
+ sections
339
+ })
340
+ }
@@ -0,0 +1,76 @@
1
+ import type { ThemeComponentOverrides } from './components.js'
2
+ import type { ThemeTokens } from './tokens.js'
3
+
4
+ /** One existing token group, with independently authored mode layers. */
5
+ export interface ThemeSection<T> {
6
+ readonly values?: T
7
+ readonly modes?: { readonly light?: T; readonly dark?: T }
8
+ }
9
+
10
+ export type ThemeColorStop = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950
11
+
12
+ export interface ThemeBrandSource {
13
+ /** Unmodified source text. A mapped fallback never replaces this value. */
14
+ readonly value: string
15
+ readonly gamut: 'srgb' | 'display-p3'
16
+ readonly srgbFallback?: string
17
+ }
18
+
19
+ export interface ThemePalette {
20
+ readonly id: string
21
+ readonly name: string
22
+ readonly swatches: readonly {
23
+ readonly stop: ThemeColorStop
24
+ readonly value: string
25
+ readonly srgbFallback?: string
26
+ }[]
27
+ }
28
+
29
+ export interface ThemeColorSection extends ThemeSection<ThemeTokens['color']> {
30
+ readonly brand?: ThemeBrandSource
31
+ /** Defaults to anchored when a brand is present. Generation belongs to the color engine. */
32
+ readonly fidelity?: 'anchored' | 'unanchored'
33
+ readonly palettes?: readonly ThemePalette[]
34
+ /** Optional until generation; references the exact original, never its fallback. */
35
+ readonly anchor?: { readonly paletteId: string; readonly stop: ThemeColorStop }
36
+ }
37
+
38
+ /** Portable descriptors only. The consuming application owns loading and local availability. */
39
+ export interface ThemeFontMetadata {
40
+ readonly id: string
41
+ readonly family: string
42
+ readonly source: 'system' | 'catalog' | 'local'
43
+ readonly weights?: readonly number[]
44
+ readonly styles?: readonly ('normal' | 'italic')[]
45
+ }
46
+
47
+ export interface ThemeTypographySection extends ThemeSection<ThemeTokens['typography']> {
48
+ readonly fonts?: readonly ThemeFontMetadata[]
49
+ }
50
+
51
+ /** Token groups are the extension seams for richer typesetting and spring authoring. */
52
+ export type ThemeSections = {
53
+ readonly [K in keyof ThemeTokens]?: K extends 'color'
54
+ ? ThemeColorSection
55
+ : K extends 'typography'
56
+ ? ThemeTypographySection
57
+ : ThemeSection<ThemeTokens[K]>
58
+ } & {
59
+ readonly components?: ThemeSection<ThemeComponentOverrides>
60
+ }
61
+ export type ThemeSectionName = keyof ThemeSections
62
+
63
+ export interface ThemeDocument {
64
+ readonly kind: 'radiant-theme'
65
+ readonly version: 1
66
+ readonly id: string
67
+ readonly name: string
68
+ readonly sections: ThemeSections
69
+ }
70
+
71
+ /** A selective export has no identity and cannot accidentally replace an entire document. */
72
+ export interface ThemeSectionExport {
73
+ readonly kind: 'radiant-theme-sections'
74
+ readonly version: 1
75
+ readonly sections: ThemeSections
76
+ }
@@ -0,0 +1,172 @@
1
+ import type { ColorPalette } from '../color/recommendColorPalette.js'
2
+ import { tokenDefaults, type ThemeTokens } from './tokens.js'
3
+ import { defineThemeDocument, updateThemeDocument } from './themeDocument.js'
4
+ import type { ThemeDocument, ThemeSection } from './themeDocumentTypes.js'
5
+
6
+ /** Bounded workshop controls; dimensions are derived from the neutral baseline, not compounded. */
7
+ export interface ThemeGeometrySettings {
8
+ /** 0.5–2; scales shared gaps and panel padding, retaining rem units. */
9
+ readonly spacing?: number
10
+ /** 0.75–1.5; scales all three control heights, inline padding and indicators, not fonts. */
11
+ readonly density?: number
12
+ /** Pixels, 0–32. Checkbox still caps its inherited radius; Radio stays circular. */
13
+ readonly controlRadius?: number
14
+ /** Pixels, 0–48. */
15
+ readonly surfaceRadius?: number
16
+ /** Pixels, 0–4. */
17
+ readonly controlBorderWidth?: number
18
+ readonly surfaceBorderWidth?: number
19
+ readonly borderStyle?: 'solid' | 'dashed' | 'dotted'
20
+ /** 0 = none, 1 = baseline, 2 = raised, 3 = floating. Passive and overlay shadows only. */
21
+ readonly elevation?: 0 | 1 | 2 | 3
22
+ /** 0–0.9; black modal backdrop. Panel filtering remains a component exception. */
23
+ readonly backdropOpacity?: number
24
+ }
25
+
26
+ export interface ThemeAppearanceSettings {
27
+ readonly version?: 1
28
+ readonly palette?: Pick<ColorPalette, 'version' | 'color' | 'surface'>
29
+ readonly geometry?: ThemeSection<ThemeGeometrySettings>
30
+ }
31
+
32
+ const bounds = {
33
+ spacing: [0.5, 2],
34
+ density: [0.75, 1.5],
35
+ controlRadius: [0, 32],
36
+ surfaceRadius: [0, 48],
37
+ controlBorderWidth: [0, 4],
38
+ surfaceBorderWidth: [0, 4],
39
+ elevation: [0, 3],
40
+ backdropOpacity: [0, 0.9]
41
+ } as const
42
+ function record(value: unknown, path: string): asserts value is Record<string, unknown> {
43
+ if (!value || typeof value !== 'object' || Array.isArray(value))
44
+ throw new TypeError(`${path} must be an object.`)
45
+ }
46
+ function keys(value: object, allowed: readonly string[], path: string) {
47
+ for (const key of Object.keys(value))
48
+ if (!allowed.includes(key)) throw new TypeError(`Unknown ${path}.${key}.`)
49
+ }
50
+ function validate(value: unknown, path: string): asserts value is ThemeGeometrySettings {
51
+ record(value, path)
52
+ keys(value, [...Object.keys(bounds), 'borderStyle'], path)
53
+ for (const [key, item] of Object.entries(value)) {
54
+ if (item === undefined) continue
55
+ if (key === 'borderStyle') {
56
+ if (typeof item === 'string' && ['solid', 'dashed', 'dotted'].includes(item)) continue
57
+ } else {
58
+ const [min, max] = bounds[key as keyof typeof bounds]
59
+ if (
60
+ typeof item === 'number' &&
61
+ Number.isFinite(item) &&
62
+ item >= min &&
63
+ item <= max &&
64
+ (key !== 'elevation' || Number.isInteger(item))
65
+ )
66
+ continue
67
+ throw new TypeError(
68
+ `${path}.${key} must be a finite number from ${min} to ${max}${key === 'elevation' ? ' (integer)' : ''}.`
69
+ )
70
+ }
71
+ throw new TypeError(`${path}.borderStyle must be solid, dashed or dotted.`)
72
+ }
73
+ }
74
+ const scaled = (rem: string, factor: number) =>
75
+ `${Number((parseFloat(rem) * factor).toFixed(6))}rem`
76
+
77
+ function geometryTokens(settings: ThemeGeometrySettings, mode: 'light' | 'dark'): ThemeTokens {
78
+ const base = tokenDefaults[mode]
79
+ const spacing: Record<string, string> = {}
80
+ const control: Record<string, unknown> = {}
81
+ const surface: Record<string, string> = {}
82
+ if (settings.spacing !== undefined) {
83
+ for (const [key, value] of Object.entries(base.spacing))
84
+ spacing[key] = scaled(value, settings.spacing)
85
+ for (const key of ['padding', 'gap'] as const)
86
+ surface[key] = scaled(base.surface[key], settings.spacing)
87
+ }
88
+ if (settings.density !== undefined)
89
+ for (const size of ['small', 'medium', 'large'] as const) {
90
+ const metrics: Record<string, string> = {}
91
+ for (const key of ['height', 'paddingInline', 'indicatorSize'] as const)
92
+ metrics[key] = scaled(base.control[size][key], settings.density)
93
+ control[size] = metrics
94
+ }
95
+ for (const [key, target] of [
96
+ ['Radius', 'radius'],
97
+ ['BorderWidth', 'borderWidth']
98
+ ] as const) {
99
+ const a = settings[`control${key}`],
100
+ b = settings[`surface${key}`]
101
+ if (a !== undefined) control[target] = `${a}px`
102
+ if (b !== undefined) surface[target] = `${b}px`
103
+ }
104
+ if (settings.borderStyle !== undefined)
105
+ control.borderStyle = surface.borderStyle = settings.borderStyle
106
+ if (settings.elevation !== undefined) {
107
+ const level = settings.elevation
108
+ surface.shadow =
109
+ level === 0
110
+ ? 'none'
111
+ : level === 1
112
+ ? base.surface.shadow
113
+ : `0 ${level * 2}px ${level * 6}px -2px rgb(0 0 0 / ${mode === 'light' ? 0.12 : 0.4})`
114
+ surface.overlayShadow =
115
+ level === 0
116
+ ? 'none'
117
+ : level === 1
118
+ ? base.surface.overlayShadow
119
+ : `0 ${level * 12}px ${level * 32}px -16px rgb(0 0 0 / ${mode === 'light' ? 0.3 : 0.6})`
120
+ }
121
+ if (settings.backdropOpacity !== undefined)
122
+ surface.backdrop = `rgb(0 0 0 / ${settings.backdropOpacity})`
123
+ return {
124
+ ...(Object.keys(spacing).length ? { spacing } : {}),
125
+ ...(Object.keys(control).length ? { control } : {}),
126
+ ...(Object.keys(surface).length ? { surface } : {})
127
+ }
128
+ }
129
+
130
+ /** Apply generated color/canvas atomically and geometry leaves without erasing authored exceptions. */
131
+ export function updateThemeAppearance(
132
+ document: ThemeDocument,
133
+ settings: ThemeAppearanceSettings
134
+ ): ThemeDocument {
135
+ record(settings, 'appearance')
136
+ keys(settings, ['version', 'palette', 'geometry'], 'appearance')
137
+ if (settings.version !== undefined && settings.version !== 1)
138
+ throw new TypeError('Unsupported appearance.version; expected 1.')
139
+ let next = defineThemeDocument(document)
140
+ if (settings.palette !== undefined) {
141
+ record(settings.palette, 'appearance.palette')
142
+ if (settings.palette.version !== 1) throw new TypeError('appearance.palette.version must be 1.')
143
+ record(settings.palette.color, 'appearance.palette.color')
144
+ record(settings.palette.surface, 'appearance.palette.surface')
145
+ next = updateThemeDocument(next, { color: settings.palette.color }, 'replace')
146
+ next = updateThemeDocument(next, { surface: settings.palette.surface })
147
+ }
148
+ const geometry = settings.geometry
149
+ if (geometry === undefined) return next
150
+ record(geometry, 'appearance.geometry')
151
+ keys(geometry, ['values', 'modes'], 'appearance.geometry')
152
+ if (geometry.values !== undefined) validate(geometry.values, 'appearance.geometry.values')
153
+ if (geometry.modes !== undefined) {
154
+ record(geometry.modes, 'appearance.geometry.modes')
155
+ keys(geometry.modes, ['light', 'dark'], 'appearance.geometry.modes')
156
+ }
157
+ for (const mode of ['light', 'dark'] as const) {
158
+ if (geometry.modes?.[mode] !== undefined)
159
+ validate(geometry.modes[mode], `appearance.geometry.modes.${mode}`)
160
+ const values = { ...geometry.values }
161
+ for (const [key, value] of Object.entries(geometry.modes?.[mode] ?? {}))
162
+ if (value !== undefined) Object.assign(values, { [key]: value })
163
+ const tokens = geometryTokens(values, mode)
164
+ next = updateThemeDocument(
165
+ next,
166
+ Object.fromEntries(
167
+ Object.entries(tokens).map(([group, value]) => [group, { modes: { [mode]: value } }])
168
+ )
169
+ )
170
+ }
171
+ return next
172
+ }