@cognitap/radiant 0.0.3 → 0.0.5

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 (118) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +28 -15
  3. package/dist/library/Card.d.ts.map +1 -1
  4. package/dist/library/Card.js +8 -6
  5. package/dist/library/Card.js.map +1 -1
  6. package/dist/library/Checkbox.js +2 -2
  7. package/dist/library/Checkbox.js.map +1 -1
  8. package/dist/library/Collapsible.d.ts.map +1 -1
  9. package/dist/library/Collapsible.js +5 -4
  10. package/dist/library/Collapsible.js.map +1 -1
  11. package/dist/library/Dialog.d.ts.map +1 -1
  12. package/dist/library/Dialog.js +8 -6
  13. package/dist/library/Dialog.js.map +1 -1
  14. package/dist/library/Field.js +4 -4
  15. package/dist/library/Field.js.map +1 -1
  16. package/dist/library/Input.d.ts.map +1 -1
  17. package/dist/library/Input.js +4 -3
  18. package/dist/library/Input.js.map +1 -1
  19. package/dist/library/Link.d.ts.map +1 -1
  20. package/dist/library/Link.js +0 -1
  21. package/dist/library/Link.js.map +1 -1
  22. package/dist/library/RadioGroup.js +2 -2
  23. package/dist/library/RadioGroup.js.map +1 -1
  24. package/dist/library/ThemeScope.js +1 -1
  25. package/dist/library/ThemeScope.js.map +1 -1
  26. package/dist/library/actionStyles.js +2 -2
  27. package/dist/library/actionStyles.js.map +1 -1
  28. package/dist/library/cn.d.ts +2 -1
  29. package/dist/library/cn.d.ts.map +1 -1
  30. package/dist/library/cn.js +22 -1
  31. package/dist/library/cn.js.map +1 -1
  32. package/dist/library/color/colorFamilies.d.ts +3 -0
  33. package/dist/library/color/colorFamilies.d.ts.map +1 -0
  34. package/dist/library/color/colorFamilies.js +20 -0
  35. package/dist/library/color/colorFamilies.js.map +1 -0
  36. package/dist/library/color/generateColorWall.d.ts +54 -0
  37. package/dist/library/color/generateColorWall.d.ts.map +1 -0
  38. package/dist/library/color/generateColorWall.js +231 -0
  39. package/dist/library/color/generateColorWall.js.map +1 -0
  40. package/dist/library/color/index.d.ts +5 -0
  41. package/dist/library/color/index.d.ts.map +1 -0
  42. package/dist/library/color/index.js +3 -0
  43. package/dist/library/color/index.js.map +1 -0
  44. package/dist/library/color/oklch.d.ts +17 -0
  45. package/dist/library/color/oklch.d.ts.map +1 -0
  46. package/dist/library/color/oklch.js +79 -0
  47. package/dist/library/color/oklch.js.map +1 -0
  48. package/dist/library/color/recommendColorPalette.d.ts +65 -0
  49. package/dist/library/color/recommendColorPalette.d.ts.map +1 -0
  50. package/dist/library/color/recommendColorPalette.js +263 -0
  51. package/dist/library/color/recommendColorPalette.js.map +1 -0
  52. package/dist/library/index.d.ts +10 -2
  53. package/dist/library/index.d.ts.map +1 -1
  54. package/dist/library/index.js +5 -1
  55. package/dist/library/index.js.map +1 -1
  56. package/dist/library/styles.css +1 -1
  57. package/dist/library/themes/defineTheme.d.ts.map +1 -1
  58. package/dist/library/themes/defineTheme.js +5 -1
  59. package/dist/library/themes/defineTheme.js.map +1 -1
  60. package/dist/library/themes/index.d.ts +4 -0
  61. package/dist/library/themes/index.d.ts.map +1 -1
  62. package/dist/library/themes/index.js +2 -0
  63. package/dist/library/themes/index.js.map +1 -1
  64. package/dist/library/themes/themeDocument.d.ts +16 -0
  65. package/dist/library/themes/themeDocument.d.ts.map +1 -0
  66. package/dist/library/themes/themeDocument.js +332 -0
  67. package/dist/library/themes/themeDocument.js.map +1 -0
  68. package/dist/library/themes/themeDocumentTypes.d.ts +80 -0
  69. package/dist/library/themes/themeDocumentTypes.d.ts.map +1 -0
  70. package/dist/library/themes/themeDocumentTypes.js +2 -0
  71. package/dist/library/themes/themeDocumentTypes.js.map +1 -0
  72. package/dist/library/themes/tokens.d.ts +7 -0
  73. package/dist/library/themes/tokens.d.ts.map +1 -1
  74. package/dist/library/themes/tokens.js +99 -0
  75. package/dist/library/themes/tokens.js.map +1 -1
  76. package/dist/library/themes/updateThemeAppearance.d.ts +29 -0
  77. package/dist/library/themes/updateThemeAppearance.d.ts.map +1 -0
  78. package/dist/library/themes/updateThemeAppearance.js +138 -0
  79. package/dist/library/themes/updateThemeAppearance.js.map +1 -0
  80. package/dist/library/typography/index.d.ts +72 -0
  81. package/dist/library/typography/index.d.ts.map +1 -0
  82. package/dist/library/typography/index.js +160 -0
  83. package/dist/library/typography/index.js.map +1 -0
  84. package/dist/library/typography/types.d.ts +78 -0
  85. package/dist/library/typography/types.d.ts.map +1 -0
  86. package/dist/library/typography/types.js +2 -0
  87. package/dist/library/typography/types.js.map +1 -0
  88. package/docs/system.md +20 -0
  89. package/docs/theming.md +616 -0
  90. package/package.json +17 -5
  91. package/src/Card.tsx +8 -6
  92. package/src/Checkbox.tsx +2 -2
  93. package/src/Collapsible.tsx +5 -4
  94. package/src/Dialog.tsx +8 -6
  95. package/src/Field.tsx +4 -4
  96. package/src/Input.tsx +4 -3
  97. package/src/Link.tsx +0 -1
  98. package/src/RadioGroup.tsx +2 -2
  99. package/src/ThemeScope.tsx +1 -1
  100. package/src/actionStyles.ts +2 -2
  101. package/src/cn.ts +25 -1
  102. package/src/color/colorFamilies.ts +19 -0
  103. package/src/color/generateColorWall.ts +358 -0
  104. package/src/color/index.ts +11 -0
  105. package/src/color/oklch.ts +95 -0
  106. package/src/color/recommendColorPalette.ts +375 -0
  107. package/src/index.ts +40 -0
  108. package/src/styles.css +1 -0
  109. package/src/themes/baseline.css +131 -0
  110. package/src/themes/defineTheme.ts +5 -1
  111. package/src/themes/index.ts +25 -0
  112. package/src/themes/themeDocument.ts +370 -0
  113. package/src/themes/themeDocumentTypes.ts +88 -0
  114. package/src/themes/tokens.ts +137 -0
  115. package/src/themes/updateThemeAppearance.ts +172 -0
  116. package/src/typography/index.ts +199 -0
  117. package/src/typography/types.ts +92 -0
  118. package/src/typography.css +336 -0
@@ -0,0 +1,370 @@
1
+ import { defineTheme, type Theme, type ThemeDefinition, type ThemeLayer } from './defineTheme.js'
2
+ import { freezeTree, tokenDefaults } from './tokens.js'
3
+ import { generateTypography } from '../typography/index.js'
4
+ import type {
5
+ ThemeColorSection,
6
+ ThemeDocument,
7
+ ThemeSectionExport,
8
+ ThemeSectionName,
9
+ ThemeSections
10
+ } from './themeDocumentTypes.js'
11
+
12
+ export type * from './themeDocumentTypes.js'
13
+
14
+ const sectionNames: readonly ThemeSectionName[] = [
15
+ ...Object.keys(tokenDefaults.light),
16
+ 'components'
17
+ ] as ThemeSectionName[]
18
+ const stops = new Set([50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950])
19
+ type RecordValue = Record<string, unknown>
20
+
21
+ function record(value: unknown, path: string): asserts value is RecordValue {
22
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
23
+ throw new TypeError(`${path} must be an object.`)
24
+ }
25
+ }
26
+
27
+ function keys(value: RecordValue, allowed: readonly string[], path: string) {
28
+ for (const key of Object.keys(value)) {
29
+ if (!allowed.includes(key)) throw new TypeError(`Unknown key: ${path}.${key}.`)
30
+ }
31
+ }
32
+
33
+ function textValue(value: unknown, path: string) {
34
+ if (typeof value !== 'string' || !value.trim()) {
35
+ throw new TypeError(`${path} must be a nonempty string.`)
36
+ }
37
+ }
38
+
39
+ function choice(value: unknown, allowed: readonly unknown[], path: string) {
40
+ if (!allowed.includes(value)) {
41
+ throw new TypeError(`${path} must be one of: ${allowed.join(', ')}.`)
42
+ }
43
+ }
44
+
45
+ function list(value: unknown, path: string): asserts value is unknown[] {
46
+ if (!Array.isArray(value)) throw new TypeError(`${path} must be an array.`)
47
+ }
48
+
49
+ function unique(value: unknown, seen: Set<unknown>, path: string) {
50
+ if (seen.has(value)) throw new TypeError(`Duplicate value at ${path}: ${String(value)}.`)
51
+ seen.add(value)
52
+ }
53
+
54
+ /** Copy data without running getters/toJSON or silently losing functions and binaries. */
55
+ function jsonCopy(value: unknown, path: string, ancestors = new Set<object>()): unknown {
56
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
57
+ if (typeof value === 'number' && Number.isFinite(value)) return value === 0 ? 0 : value
58
+ if (!value || typeof value !== 'object')
59
+ throw new TypeError(`${path} must contain JSON data only.`)
60
+ if (ancestors.has(value)) throw new TypeError(`Circular reference at ${path}.`)
61
+ const array = Array.isArray(value)
62
+ const prototype = Object.getPrototypeOf(value)
63
+ if (
64
+ array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null
65
+ ) {
66
+ throw new TypeError(`${path} must contain plain JSON objects, not class instances or binaries.`)
67
+ }
68
+ ancestors.add(value)
69
+ const result: RecordValue | unknown[] = array ? [] : {}
70
+ if (Object.getOwnPropertySymbols(value).length)
71
+ throw new TypeError(`${path} cannot contain symbol keys.`)
72
+ const descriptors = Object.getOwnPropertyDescriptors(value)
73
+ for (const key of Object.keys(descriptors).sort()) {
74
+ if (array && key === 'length') continue
75
+ if (['__proto__', 'constructor', 'prototype'].includes(key))
76
+ throw new TypeError(`Forbidden key: ${path}.${key}.`)
77
+ const descriptor = descriptors[key]
78
+ if (!('value' in descriptor) || !descriptor.enumerable) {
79
+ throw new TypeError(`${path}.${key} must be an enumerable data property.`)
80
+ }
81
+ if (array && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length)) {
82
+ throw new TypeError(`${path}.${key} is not an array index.`)
83
+ }
84
+ // Optional object properties follow JSON omission rules; array holes/undefined are invalid.
85
+ if (descriptor.value === undefined && !array) continue
86
+ const copy = jsonCopy(descriptor.value, `${path}.${key}`, ancestors)
87
+ Object.defineProperty(result, key, {
88
+ value: copy,
89
+ enumerable: true,
90
+ writable: true,
91
+ configurable: true
92
+ })
93
+ }
94
+ if (array && Object.keys(result).length !== value.length)
95
+ throw new TypeError(`${path} cannot contain array holes.`)
96
+ ancestors.delete(value)
97
+ return result
98
+ }
99
+
100
+ function validateColor(value: RecordValue, path: string) {
101
+ if (value.brand !== undefined) {
102
+ record(value.brand, `${path}.brand`)
103
+ keys(value.brand, ['value', 'gamut', 'srgbFallback'], `${path}.brand`)
104
+ textValue(value.brand.value, `${path}.brand.value`)
105
+ choice(value.brand.gamut, ['srgb', 'display-p3'], `${path}.brand.gamut`)
106
+ if (value.brand.srgbFallback !== undefined)
107
+ textValue(value.brand.srgbFallback, `${path}.brand.srgbFallback`)
108
+ if (value.fidelity === undefined) value.fidelity = 'anchored'
109
+ }
110
+ if (value.fidelity !== undefined)
111
+ choice(value.fidelity, ['anchored', 'unanchored'], `${path}.fidelity`)
112
+ if (value.palettes !== undefined) {
113
+ list(value.palettes, `${path}.palettes`)
114
+ const ids = new Set<unknown>()
115
+ for (const [i, palette] of value.palettes.entries()) {
116
+ const p = `${path}.palettes.${i}`
117
+ record(palette, p)
118
+ keys(palette, ['id', 'name', 'swatches'], p)
119
+ textValue(palette.id, `${p}.id`)
120
+ textValue(palette.name, `${p}.name`)
121
+ unique(palette.id, ids, `${p}.id`)
122
+ list(palette.swatches, `${p}.swatches`)
123
+ if (!palette.swatches.length) throw new TypeError(`${p}.swatches must not be empty.`)
124
+ const seen = new Set<unknown>()
125
+ for (const [j, swatch] of palette.swatches.entries()) {
126
+ const s = `${p}.swatches.${j}`
127
+ record(swatch, s)
128
+ keys(swatch, ['stop', 'value', 'srgbFallback'], s)
129
+ if (!stops.has(swatch.stop as number))
130
+ throw new TypeError(`${s}.stop must be a numbered color stop (50–950).`)
131
+ unique(swatch.stop, seen, `${s}.stop`)
132
+ textValue(swatch.value, `${s}.value`)
133
+ if (swatch.srgbFallback !== undefined) textValue(swatch.srgbFallback, `${s}.srgbFallback`)
134
+ }
135
+ }
136
+ }
137
+ if (value.anchor !== undefined) {
138
+ record(value.anchor, `${path}.anchor`)
139
+ keys(value.anchor, ['paletteId', 'stop'], `${path}.anchor`)
140
+ textValue(value.anchor.paletteId, `${path}.anchor.paletteId`)
141
+ if (!stops.has(value.anchor.stop as number))
142
+ throw new TypeError(`${path}.anchor.stop must be a numbered color stop (50–950).`)
143
+ const color = value as ThemeColorSection
144
+ const swatch = color.palettes
145
+ ?.find(p => p.id === color.anchor!.paletteId)
146
+ ?.swatches.find(s => s.stop === color.anchor!.stop)
147
+ if (!color.brand || color.fidelity !== 'anchored' || swatch?.value !== color.brand.value) {
148
+ throw new TypeError(
149
+ `${path}.anchor must reference a swatch containing the exact brand.value with anchored fidelity. Regenerate or replace the color section.`
150
+ )
151
+ }
152
+ }
153
+ }
154
+
155
+ function validateFonts(value: unknown, path: string) {
156
+ list(value, path)
157
+ const ids = new Set<unknown>()
158
+ for (const [i, font] of value.entries()) {
159
+ const p = `${path}.${i}`
160
+ record(font, p)
161
+ keys(font, ['id', 'family', 'source', 'weights', 'styles', 'axes'], p)
162
+ textValue(font.id, `${p}.id`)
163
+ textValue(font.family, `${p}.family`)
164
+ unique(font.id, ids, `${p}.id`)
165
+ choice(font.source, ['system', 'catalog', 'local'], `${p}.source`)
166
+ if (font.axes !== undefined) {
167
+ list(font.axes, `${p}.axes`)
168
+ if (font.axes.length > 32) throw new TypeError(`${p}.axes supports at most 32 axes.`)
169
+ const tags = new Set<unknown>()
170
+ for (const [j, axis] of font.axes.entries()) {
171
+ const at = `${p}.axes.${j}`
172
+ record(axis, at)
173
+ keys(axis, ['tag', 'min', 'default', 'max'], at)
174
+ if (typeof axis.tag !== 'string' || !/^[A-Za-z][A-Za-z0-9]{3}$/.test(axis.tag))
175
+ throw new TypeError(
176
+ `${at}.tag must contain four ASCII letters/digits, starting with a letter.`
177
+ )
178
+ unique(axis.tag, tags, `${at}.tag`)
179
+ for (const key of ['min', 'default', 'max'])
180
+ if (
181
+ typeof axis[key] !== 'number' ||
182
+ !Number.isFinite(axis[key]) ||
183
+ Math.abs(axis[key]) > 1000000
184
+ )
185
+ throw new TypeError(
186
+ `${at}.${key} must be a finite number between -1000000 and 1000000.`
187
+ )
188
+ if (Number(axis.min) > Number(axis.default) || Number(axis.default) > Number(axis.max))
189
+ throw new TypeError(`${at} must satisfy min <= default <= max.`)
190
+ }
191
+ }
192
+ for (const key of ['weights', 'styles']) {
193
+ if (font[key] === undefined) continue
194
+ list(font[key], `${p}.${key}`)
195
+ const seen = new Set<unknown>()
196
+ for (const [j, item] of font[key].entries()) {
197
+ const at = `${p}.${key}.${j}`
198
+ if (key === 'styles') choice(item, ['normal', 'italic'], at)
199
+ else if (typeof item !== 'number' || !Number.isFinite(item) || item < 1 || item > 1000)
200
+ throw new TypeError(`${at} must be a weight from 1 to 1000.`)
201
+ unique(item, seen, at)
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ function toDefinition(sections: ThemeSections, id: string, name: string): ThemeDefinition {
208
+ const common: { tokens: RecordValue; components?: ThemeLayer['components'] } = { tokens: {} }
209
+ const modes = { light: { tokens: {} } as typeof common, dark: { tokens: {} } as typeof common }
210
+ for (const sectionName of sectionNames) {
211
+ const section = sections[sectionName]
212
+ if (!section) continue
213
+ if (sectionName === 'typography' && sections.typography?.typesetting !== undefined) {
214
+ common.tokens.typography = generateTypography(sections.typography.typesetting).tokens
215
+ }
216
+ for (const mode of ['common', 'light', 'dark'] as const) {
217
+ const values = mode === 'common' ? section.values : section.modes?.[mode]
218
+ if (values === undefined) continue
219
+ const layer = mode === 'common' ? common : modes[mode]
220
+ if (sectionName === 'components') layer.components = values as ThemeLayer['components']
221
+ else layer.tokens[sectionName] = merge(layer.tokens[sectionName], values)
222
+ }
223
+ }
224
+ return { id, name, ...common, modes }
225
+ }
226
+
227
+ /** Read JSON.parse output (or data objects); unknown versions/keys fail with a path. */
228
+ export function parseThemeDocument(input: unknown): ThemeDocument | ThemeSectionExport {
229
+ const value = jsonCopy(input, 'document')
230
+ record(value, 'document')
231
+ choice(value.kind, ['radiant-theme', 'radiant-theme-sections'], 'document.kind')
232
+ if (value.version !== 1)
233
+ throw new TypeError(
234
+ `Unsupported document.version: ${String(value.version)}. Expected 1; migrate the configuration before importing.`
235
+ )
236
+ const full = value.kind === 'radiant-theme'
237
+ keys(
238
+ value,
239
+ full ? ['kind', 'version', 'id', 'name', 'sections'] : ['kind', 'version', 'sections'],
240
+ 'document'
241
+ )
242
+ record(value.sections, 'document.sections')
243
+ keys(value.sections, sectionNames, 'document.sections')
244
+ for (const [name, section] of Object.entries(value.sections)) {
245
+ const path = `document.sections.${name}`
246
+ record(section, path)
247
+ keys(
248
+ section,
249
+ [
250
+ 'values',
251
+ 'modes',
252
+ ...(name === 'color'
253
+ ? ['brand', 'fidelity', 'palettes', 'anchor']
254
+ : name === 'typography'
255
+ ? ['fonts', 'typesetting']
256
+ : [])
257
+ ],
258
+ path
259
+ )
260
+ if (section.modes !== undefined) {
261
+ record(section.modes, `${path}.modes`)
262
+ keys(section.modes, ['light', 'dark'], `${path}.modes`)
263
+ }
264
+ if (name === 'color') validateColor(section, path)
265
+ if (name === 'typography' && section.fonts !== undefined)
266
+ validateFonts(section.fonts, `${path}.fonts`)
267
+ }
268
+ // Reuse the canonical token/component validation and resolution; no second token schema.
269
+ defineTheme(
270
+ toDefinition(
271
+ value.sections as ThemeSections,
272
+ full ? (value.id as string) : 'section-export',
273
+ full ? (value.name as string) : 'Section export'
274
+ )
275
+ )
276
+ return freezeTree(jsonCopy(value, 'document') as object) as ThemeDocument | ThemeSectionExport
277
+ }
278
+
279
+ /** Validate and detach an immutable, portable authoring snapshot. */
280
+ export function defineThemeDocument(document: ThemeDocument): ThemeDocument {
281
+ const result = parseThemeDocument(document)
282
+ if (result.kind !== 'radiant-theme')
283
+ throw new TypeError('Expected a radiant-theme document with id and name.')
284
+ return result
285
+ }
286
+
287
+ /** Compile only authored semantic values through the existing application theme runtime. */
288
+ export function compileThemeDocument(document: ThemeDocument): Theme {
289
+ const validated = defineThemeDocument(document)
290
+ return defineTheme(toDefinition(validated.sections, validated.id, validated.name))
291
+ }
292
+
293
+ function merge(base: unknown, patch: unknown): unknown {
294
+ if (
295
+ !base ||
296
+ !patch ||
297
+ typeof base !== 'object' ||
298
+ typeof patch !== 'object' ||
299
+ Array.isArray(base) ||
300
+ Array.isArray(patch)
301
+ )
302
+ return patch
303
+ const result: RecordValue = { ...base }
304
+ for (const [key, value] of Object.entries(patch)) result[key] = merge(result[key], value)
305
+ return result
306
+ }
307
+
308
+ /** Merge leaves/replace arrays, or replace only supplied sections. Empty replacement resets. */
309
+ export function updateThemeDocument(
310
+ document: ThemeDocument,
311
+ sections: ThemeSections,
312
+ mode: 'merge' | 'replace' = 'merge'
313
+ ): ThemeDocument {
314
+ const base = defineThemeDocument(document)
315
+ choice(mode, ['merge', 'replace'], 'update mode')
316
+ // Check the patch's JSON boundary before merging, including keys a spread would discard.
317
+ const patch = jsonCopy(sections, 'sections')
318
+ record(patch, 'sections')
319
+ keys(patch, sectionNames, 'sections')
320
+ const next = { ...base.sections } as RecordValue
321
+ for (const [name, section] of Object.entries(patch))
322
+ next[name] = mode === 'replace' ? section : merge(next[name], section)
323
+ return defineThemeDocument({ ...base, sections: next })
324
+ }
325
+
326
+ /** Export exactly these sections, with no document identity or implicit component exceptions. */
327
+ export function exportThemeSections(
328
+ document: ThemeDocument,
329
+ names: readonly ThemeSectionName[]
330
+ ): ThemeSectionExport {
331
+ const base = defineThemeDocument(document)
332
+ list(names, 'section names')
333
+ const sections: RecordValue = {}
334
+ for (const name of names) {
335
+ choice(name, sectionNames, 'section name')
336
+ if (base.sections[name] !== undefined) sections[name] = base.sections[name]
337
+ }
338
+ return parseThemeDocument({
339
+ kind: 'radiant-theme-sections',
340
+ version: 1,
341
+ sections
342
+ }) as ThemeSectionExport
343
+ }
344
+
345
+ /** Bring existing authored themes into the workshop without materialising defaults as overrides. */
346
+ export function themeDocumentFromDefinition(definition: ThemeDefinition): ThemeDocument {
347
+ const copy = jsonCopy(definition, 'theme') as ThemeDefinition
348
+ defineTheme(copy)
349
+ const sections: RecordValue = {}
350
+ for (const name of sectionNames) {
351
+ const section: RecordValue = {}
352
+ const values = name === 'components' ? copy.components : copy.tokens?.[name]
353
+ if (values !== undefined) section.values = values
354
+ const modes: RecordValue = {}
355
+ for (const mode of ['light', 'dark'] as const) {
356
+ const values =
357
+ name === 'components' ? copy.modes?.[mode]?.components : copy.modes?.[mode]?.tokens?.[name]
358
+ if (values !== undefined) modes[mode] = values
359
+ }
360
+ if (Object.keys(modes).length) section.modes = modes
361
+ if (Object.keys(section).length) sections[name] = section
362
+ }
363
+ return defineThemeDocument({
364
+ kind: 'radiant-theme',
365
+ version: 1,
366
+ id: copy.id,
367
+ name: copy.name,
368
+ sections
369
+ })
370
+ }
@@ -0,0 +1,88 @@
1
+ import type { ThemeComponentOverrides } from './components.js'
2
+ import type { ThemeTokens } from './tokens.js'
3
+ import type { TypographyInput } from '../typography/types.js'
4
+
5
+ /** One existing token group, with independently authored mode layers. */
6
+ export interface ThemeSection<T> {
7
+ readonly values?: T
8
+ readonly modes?: { readonly light?: T; readonly dark?: T }
9
+ }
10
+
11
+ export type ThemeColorStop = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950
12
+
13
+ export interface ThemeBrandSource {
14
+ /** Unmodified source text. A mapped fallback never replaces this value. */
15
+ readonly value: string
16
+ readonly gamut: 'srgb' | 'display-p3'
17
+ readonly srgbFallback?: string
18
+ }
19
+
20
+ export interface ThemePalette {
21
+ readonly id: string
22
+ readonly name: string
23
+ readonly swatches: readonly {
24
+ readonly stop: ThemeColorStop
25
+ readonly value: string
26
+ readonly srgbFallback?: string
27
+ }[]
28
+ }
29
+
30
+ export interface ThemeColorSection extends ThemeSection<ThemeTokens['color']> {
31
+ readonly brand?: ThemeBrandSource
32
+ /** Defaults to anchored when a brand is present. Generation belongs to the color engine. */
33
+ readonly fidelity?: 'anchored' | 'unanchored'
34
+ readonly palettes?: readonly ThemePalette[]
35
+ /** Optional until generation; references the exact original, never its fallback. */
36
+ readonly anchor?: { readonly paletteId: string; readonly stop: ThemeColorStop }
37
+ }
38
+
39
+ /** Available OpenType axis range, never a font file or a trial-only setting. */
40
+ export interface ThemeFontAxis {
41
+ readonly tag: string
42
+ readonly min: number
43
+ readonly default: number
44
+ readonly max: number
45
+ }
46
+
47
+ /** Portable descriptors only. The consuming application owns loading and local availability. */
48
+ export interface ThemeFontMetadata {
49
+ readonly id: string
50
+ readonly family: string
51
+ readonly source: 'system' | 'catalog' | 'local'
52
+ readonly weights?: readonly number[]
53
+ readonly styles?: readonly ('normal' | 'italic')[]
54
+ readonly axes?: readonly ThemeFontAxis[]
55
+ }
56
+
57
+ export interface ThemeTypographySection extends ThemeSection<ThemeTokens['typography']> {
58
+ readonly fonts?: readonly ThemeFontMetadata[]
59
+ /** Generated defaults; explicit values and mode values override these leaves. */
60
+ readonly typesetting?: TypographyInput
61
+ }
62
+
63
+ /** Token groups are the extension seams for richer typesetting and spring authoring. */
64
+ export type ThemeSections = {
65
+ readonly [K in keyof ThemeTokens]?: K extends 'color'
66
+ ? ThemeColorSection
67
+ : K extends 'typography'
68
+ ? ThemeTypographySection
69
+ : ThemeSection<ThemeTokens[K]>
70
+ } & {
71
+ readonly components?: ThemeSection<ThemeComponentOverrides>
72
+ }
73
+ export type ThemeSectionName = keyof ThemeSections
74
+
75
+ export interface ThemeDocument {
76
+ readonly kind: 'radiant-theme'
77
+ readonly version: 1
78
+ readonly id: string
79
+ readonly name: string
80
+ readonly sections: ThemeSections
81
+ }
82
+
83
+ /** A selective export has no identity and cannot accidentally replace an entire document. */
84
+ export interface ThemeSectionExport {
85
+ readonly kind: 'radiant-theme-sections'
86
+ readonly version: 1
87
+ readonly sections: ThemeSections
88
+ }
@@ -1,3 +1,105 @@
1
+ import type {
2
+ TypographyProseRhythm,
3
+ TypographyUIRhythm,
4
+ TypographyStyle,
5
+ TypographyRole,
6
+ TypographyTokens,
7
+ TypographyAssignment
8
+ } from '../typography/types.js'
9
+
10
+ /** Canonical calculations live beside the defaults so source CSS generation stays self-contained. */
11
+ export function typographyStyles(
12
+ prose: TypographyProseRhythm,
13
+ ui: TypographyUIRhythm
14
+ ): Record<TypographyRole, TypographyStyle> {
15
+ const { size: r, lineHeight, measure, headingScale: q } = prose
16
+ const u = ui.size
17
+ const style = (
18
+ assignment: TypographyAssignment,
19
+ narrow: number,
20
+ wide: number,
21
+ weight: number,
22
+ leading: number,
23
+ tracking = 0,
24
+ width = 0
25
+ ): TypographyStyle => ({
26
+ assignment,
27
+ narrow,
28
+ wide,
29
+ weight,
30
+ lineHeight: leading,
31
+ tracking,
32
+ measure: width
33
+ })
34
+ return {
35
+ 'prose-title': style('headings', r * q ** 3, r * q ** 5, 600, 1.12, -0.025, 22),
36
+ 'prose-heading': style('headings', r * q, r * q ** 2, 600, 1.25, -0.015, 30),
37
+ 'prose-subheading': style('headings', r * 1.1, r * q, 600, 1.3, -0.01, 36),
38
+ 'prose-body': style('body', r, r, 400, lineHeight, 0, measure),
39
+ 'prose-lead': style('body', r * 1.125, r * 1.125, 400, 1.5, 0, 55),
40
+ 'prose-small': style('body', r * 0.8, r * 0.8, 400, 1.5, 0, measure),
41
+ 'prose-quote': style('body', r * 1.25, r * 1.25, 400, 1.4, -0.01, measure),
42
+ 'ui-title': style('ui', u * 1.25, u * 1.25, 600, 1.3, -0.015),
43
+ 'ui-body': style('ui', u, u, 400, ui.lineHeight),
44
+ 'ui-label': style('ui', u, u, 500, 1.4),
45
+ 'ui-supporting': style('ui', u * 0.9375, u * 0.9375, 400, 1.5),
46
+ 'ui-caption': style('ui', u * 0.875, u * 0.875, 400, 1.5),
47
+ 'ui-metric': style('ui', u * 2, u * 2, 600, 1.15, -0.03),
48
+ 'ui-eyebrow': style('ui', u * 0.75, u * 0.75, 600, 1.4, 0.1),
49
+ display: style('headings', r * q ** 3, r * q ** 6, 600, 1.06, -0.035, 18),
50
+ code: style('code', 14, 14, 400, 1.65, 0, 80)
51
+ }
52
+ }
53
+
54
+ const baselineProse: TypographyProseRhythm = {
55
+ size: 20,
56
+ lineHeight: 1.6,
57
+ paragraphSpacing: 1.25,
58
+ measure: 64,
59
+ headingScale: 1.25
60
+ }
61
+ export const typographyRoles = Object.freeze(
62
+ Object.keys(typographyStyles(baselineProse, { size: 16, lineHeight: 1.5 })) as TypographyRole[]
63
+ )
64
+
65
+ function decimal(value: number): string {
66
+ return String(Number(value.toFixed(8)))
67
+ }
68
+
69
+ export function typographyTokens(
70
+ styles: Readonly<Record<TypographyRole, TypographyStyle>>,
71
+ families: Readonly<Record<TypographyAssignment, string>>,
72
+ flow: number
73
+ ): TypographyTokens {
74
+ const roles = {} as Record<TypographyRole, TypographyTokens['roles'][TypographyRole]>
75
+ for (const role of typographyRoles) {
76
+ const s = styles[role]
77
+ const slope = (s.wide - s.narrow) / 512
78
+ const intercept = s.narrow / 16 - slope * 24
79
+ const size = `${decimal(s.narrow / 16)}rem`
80
+ roles[role] = {
81
+ family: families[s.assignment],
82
+ size,
83
+ fluidSize:
84
+ s.narrow === s.wide
85
+ ? size
86
+ : `clamp(${size}, calc(${decimal(intercept)}rem + ${decimal(slope * 100)}cqi), ${decimal(s.wide / 16)}rem)`,
87
+ weight: s.weight,
88
+ lineHeight: decimal(s.lineHeight),
89
+ letterSpacing: `${decimal(s.tracking)}em`,
90
+ measure: s.measure ? `${decimal(s.measure)}ch` : 'none'
91
+ }
92
+ }
93
+ return {
94
+ roles,
95
+ flow: {
96
+ paragraph: `${decimal(flow)}em`,
97
+ headingBefore: `${decimal(flow * 1.6)}em`,
98
+ headingAfter: `${decimal(flow * 0.5)}em`
99
+ }
100
+ }
101
+ }
102
+
1
103
  /** The complete shared-token registry. CSS names are derived from these paths. */
2
104
  export interface SharedTokens {
3
105
  color: {
@@ -28,6 +130,8 @@ export interface SharedTokens {
28
130
  labelWeight: string | number
29
131
  headingWeight: string | number
30
132
  letterSpacing: string
133
+ roles: TypographyTokens['roles']
134
+ flow: TypographyTokens['flow']
31
135
  }
32
136
  control: {
33
137
  small: ControlMetrics
@@ -103,6 +207,7 @@ const light: SharedTokens = {
103
207
  dangerForeground: 'oklch(0.99 0 0)'
104
208
  },
105
209
  typography: {
210
+ ...baselineTypographyTokens(),
106
211
  family: 'system-ui, sans-serif',
107
212
  bodySize: '0.875rem',
108
213
  smallSize: '0.8125rem',
@@ -205,6 +310,38 @@ export function freezeTree<T extends object>(value: T): Readonly<T> {
205
310
  return Object.freeze(value)
206
311
  }
207
312
 
313
+ // Legacy/preset leaves remain a bridge until a recipe or explicit role owns them.
314
+ // UI measures stay layout-owned; controls retain their independent size metrics.
315
+ function baselineTypographyTokens(): TypographyTokens {
316
+ const tokens = typographyTokens(
317
+ typographyStyles(baselineProse, { size: 16, lineHeight: 1.5 }),
318
+ {
319
+ body: 'var(--rad-typography-family)',
320
+ headings: 'var(--rad-typography-family)',
321
+ ui: 'var(--rad-typography-family)',
322
+ code: 'ui-monospace, monospace'
323
+ },
324
+ baselineProse.paragraphSpacing
325
+ )
326
+ const roles = { ...tokens.roles }
327
+ for (const [role, size, weight] of [
328
+ ['ui-body', 'bodySize', 'bodyWeight'],
329
+ ['ui-label', 'bodySize', 'labelWeight'],
330
+ ['ui-title', 'headingSize', 'headingWeight'],
331
+ ['ui-supporting', 'smallSize', 'bodyWeight']
332
+ ] as const) {
333
+ const leaf = (name: string) => `var(--rad-typography-${kebabCase(name)})`
334
+ roles[role] = {
335
+ ...tokens.roles[role],
336
+ size: leaf(size),
337
+ fluidSize: leaf(size),
338
+ weight: leaf(weight),
339
+ letterSpacing: leaf('letterSpacing')
340
+ }
341
+ }
342
+ return { ...tokens, roles }
343
+ }
344
+
208
345
  export const tokenDefaults = freezeTree({ light, dark })
209
346
 
210
347
  export function kebabCase(value: string): string {