@pairdraw/dom-css 0.0.0-stage → 0.16.1

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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/dist/browser.d.ts +29 -0
  4. package/dist/browser.js +2 -0
  5. package/dist/chunks/behaviours/args.js +59 -0
  6. package/dist/chunks/behaviours/args.js.map +1 -0
  7. package/dist/chunks/behaviours/controls.js +109 -0
  8. package/dist/chunks/behaviours/controls.js.map +1 -0
  9. package/dist/chunks/behaviours/reset.js +40 -0
  10. package/dist/chunks/behaviours/reset.js.map +1 -0
  11. package/dist/chunks/behaviours/roles.js +51 -0
  12. package/dist/chunks/behaviours/roles.js.map +1 -0
  13. package/dist/chunks/behaviours/states/conditions.js +103 -0
  14. package/dist/chunks/behaviours/states/conditions.js.map +1 -0
  15. package/dist/chunks/behaviours/states/css.js +172 -0
  16. package/dist/chunks/behaviours/states/css.js.map +1 -0
  17. package/dist/chunks/behaviours/states/layers.js +1736 -0
  18. package/dist/chunks/behaviours/states/layers.js.map +1 -0
  19. package/dist/chunks/behaviours/states/model.js +144 -0
  20. package/dist/chunks/behaviours/states/model.js.map +1 -0
  21. package/dist/chunks/behaviours/states/tailwind.js +198 -0
  22. package/dist/chunks/behaviours/states/tailwind.js.map +1 -0
  23. package/dist/chunks/browser.js +1352 -0
  24. package/dist/chunks/browser.js.map +1 -0
  25. package/dist/chunks/export/bundle.js +337 -0
  26. package/dist/chunks/export/bundle.js.map +1 -0
  27. package/dist/chunks/export/components/drawn.js +60 -0
  28. package/dist/chunks/export/components/drawn.js.map +1 -0
  29. package/dist/chunks/export/components/fields.js +178 -0
  30. package/dist/chunks/export/components/fields.js.map +1 -0
  31. package/dist/chunks/export/components/groups.js +297 -0
  32. package/dist/chunks/export/components/groups.js.map +1 -0
  33. package/dist/chunks/export/components/icons.js +260 -0
  34. package/dist/chunks/export/components/icons.js.map +1 -0
  35. package/dist/chunks/export/components/layers.js +1599 -0
  36. package/dist/chunks/export/components/layers.js.map +1 -0
  37. package/dist/chunks/export/index.js +477 -0
  38. package/dist/chunks/export/index.js.map +1 -0
  39. package/dist/chunks/export/storybook/component.js +448 -0
  40. package/dist/chunks/export/storybook/component.js.map +1 -0
  41. package/dist/chunks/export/storybook/export.js +410 -0
  42. package/dist/chunks/export/storybook/export.js.map +1 -0
  43. package/dist/chunks/import/html.js +406 -0
  44. package/dist/chunks/import/html.js.map +1 -0
  45. package/dist/chunks/import/jsx/dev-runtime.js +37 -0
  46. package/dist/chunks/import/jsx/dev-runtime.js.map +1 -0
  47. package/dist/chunks/tokens/cssom-validator.js +10 -0
  48. package/dist/chunks/tokens/cssom-validator.js.map +1 -0
  49. package/dist/export.d.ts +594 -0
  50. package/dist/export.js +13 -0
  51. package/dist/index.d.ts +115 -0
  52. package/dist/index.js +7 -0
  53. package/dist/jsx-dev-runtime.d.ts +8 -0
  54. package/dist/jsx-dev-runtime.js +3 -0
  55. package/dist/jsx-runtime.d.ts +20 -0
  56. package/dist/jsx-runtime.js +3 -0
  57. package/dist/rolldown-runtime.js +13 -0
  58. package/dist/runtime.d.ts +10 -0
  59. package/dist/scene-graph.d.ts +2 -0
  60. package/dist/scene-graph.js +2 -0
  61. package/dist/scene-graph2.d.ts +10 -0
  62. package/dist/styling.d.ts +93 -0
  63. package/dist/tailwind.d.ts +39 -0
  64. package/dist/types.d.ts +89 -0
  65. package/package.json +88 -4
  66. package/src/behaviours/args.ts +85 -0
  67. package/src/behaviours/controls.ts +195 -0
  68. package/src/behaviours/index.ts +11 -0
  69. package/src/behaviours/reset.ts +37 -0
  70. package/src/behaviours/roles.ts +44 -0
  71. package/src/behaviours/states/conditions.ts +105 -0
  72. package/src/behaviours/states/css.ts +123 -0
  73. package/src/behaviours/states/index.ts +4 -0
  74. package/src/behaviours/states/layers.ts +205 -0
  75. package/src/behaviours/states/model.ts +175 -0
  76. package/src/behaviours/states/names.ts +39 -0
  77. package/src/behaviours/states/tailwind.ts +148 -0
  78. package/src/behaviours/states/types.ts +56 -0
  79. package/src/browser.ts +146 -0
  80. package/src/cssom.d.ts +38 -0
  81. package/src/export/bundle.ts +461 -0
  82. package/src/export/components/drawn.ts +73 -0
  83. package/src/export/components/fields.ts +178 -0
  84. package/src/export/components/groups.ts +78 -0
  85. package/src/export/components/icons.ts +230 -0
  86. package/src/export/components/layers.ts +121 -0
  87. package/src/export/components/model.ts +544 -0
  88. package/src/export/components/properties.ts +167 -0
  89. package/src/export/components/react/fields.ts +129 -0
  90. package/src/export/components/react/index.ts +412 -0
  91. package/src/export/components/react/props.ts +151 -0
  92. package/src/export/components/react/radix.ts +52 -0
  93. package/src/export/components/react/shared.ts +76 -0
  94. package/src/export/components/references.ts +212 -0
  95. package/src/export/components/repeats.ts +128 -0
  96. package/src/export/components/shaders.ts +125 -0
  97. package/src/export/components/styling.ts +31 -0
  98. package/src/export/components/tree.ts +72 -0
  99. package/src/export/components/vue.ts +517 -0
  100. package/src/export/css.ts +57 -0
  101. package/src/export/grid.ts +42 -0
  102. package/src/export/html.ts +163 -0
  103. package/src/export/index.ts +44 -0
  104. package/src/export/projection.ts +581 -0
  105. package/src/export/storybook/component.ts +334 -0
  106. package/src/export/storybook/export.ts +430 -0
  107. package/src/export/storybook/groups.ts +161 -0
  108. package/src/export/storybook/module.ts +319 -0
  109. package/src/export/storybook/names.ts +51 -0
  110. package/src/export/tailwind-jsx.ts +156 -0
  111. package/src/export/text.ts +415 -0
  112. package/src/import/css-text.ts +4 -0
  113. package/src/import/css-values.ts +31 -0
  114. package/src/import/flow.ts +248 -0
  115. package/src/import/html.ts +88 -0
  116. package/src/import/jsx/core.ts +130 -0
  117. package/src/import/jsx/dev-runtime.ts +8 -0
  118. package/src/import/jsx/runtime.ts +76 -0
  119. package/src/import/scene-graph.ts +582 -0
  120. package/src/import/style-attribute.ts +25 -0
  121. package/src/import/tailwind.ts +54 -0
  122. package/src/import/text.ts +518 -0
  123. package/src/index.ts +51 -0
  124. package/src/runtime/browser/runtime.ts +301 -0
  125. package/src/runtime/headless/runtime.ts +99 -0
  126. package/src/runtime/headless/styles.ts +330 -0
  127. package/src/runtime/index.ts +11 -0
  128. package/src/tokens/conditions.ts +66 -0
  129. package/src/tokens/cssom-validator.ts +8 -0
  130. package/src/tokens/custom-properties.ts +331 -0
  131. package/src/tokens/expression.ts +128 -0
  132. package/src/tokens/formula.ts +140 -0
  133. package/src/tokens/index.ts +43 -0
  134. package/src/tokens/names.ts +161 -0
  135. package/src/tokens/references.ts +201 -0
  136. package/src/tokens/stylesheet.ts +304 -0
  137. package/src/tokens/validate.ts +86 -0
  138. package/src/tokens/values.ts +44 -0
  139. package/src/types.ts +59 -0
@@ -0,0 +1,161 @@
1
+ import { compact } from 'es-toolkit/array'
2
+ import valueParser from 'postcss-value-parser'
3
+ import { themeNamespaces, type ThemeNamespace } from 'twirlwind'
4
+
5
+ import type { SceneGraph, Variable, VariableScope } from '@pairdraw/scene-graph'
6
+
7
+ /** Every variable, collection by collection, in each collection's own order. */
8
+ export function collectionVariables(
9
+ source: Pick<SceneGraph, 'variables' | 'variableCollections'>
10
+ ): Variable[] {
11
+ return compact(
12
+ [...source.variableCollections.values()].flatMap((collection) =>
13
+ collection.variableIds.map((id) => source.variables.get(id))
14
+ )
15
+ )
16
+ }
17
+
18
+ const SCOPE_NAMESPACES: Partial<Record<VariableScope, ThemeNamespace>> = {
19
+ CORNER_RADIUS: 'radius',
20
+ GAP: 'spacing',
21
+ WIDTH_HEIGHT: 'spacing',
22
+ FONT_SIZE: 'text',
23
+ LINE_HEIGHT: 'leading',
24
+ LETTER_SPACING: 'tracking',
25
+ FONT_FAMILY: 'font',
26
+ FONT_STYLE: 'font-weight',
27
+ EFFECT_FLOAT: 'blur'
28
+ }
29
+
30
+ /** Leading name segments that already say the namespace, so `Color/primary` is not `--color-color-primary`. */
31
+ const NAMESPACE_WORDS: Record<string, ThemeNamespace> = {
32
+ ...Object.fromEntries(themeNamespaces.map((namespace) => [namespace, namespace])),
33
+ colors: 'color',
34
+ colour: 'color',
35
+ colours: 'color',
36
+ space: 'spacing',
37
+ radii: 'radius',
38
+ rounded: 'radius',
39
+ corner: 'radius',
40
+ corners: 'radius',
41
+ 'font-size': 'text',
42
+ 'line-height': 'leading',
43
+ 'letter-spacing': 'tracking',
44
+ fonts: 'font',
45
+ 'font-family': 'font',
46
+ weight: 'font-weight',
47
+ shadows: 'shadow'
48
+ }
49
+
50
+ /**
51
+ * Lowercase words joined by `-`, keeping digits on their word, as Tailwind keys do: `Text/2xl`
52
+ * is `text-2xl`, `Heading/H1` is `heading-h1`, `brandPrimary` is `brand-primary`. es-toolkit's
53
+ * `kebabCase` splits digits off (`text-2-xl`), which no design system writes.
54
+ */
55
+ export function tokenSlug(text: string): string {
56
+ const words = text
57
+ .normalize('NFKC')
58
+ .replaceAll(/(\p{Ll})(\p{Lu})/gu, '$1 $2')
59
+ .toLowerCase()
60
+ .split(/[^\p{L}\p{N}]+/u)
61
+ return compact(words).join('-')
62
+ }
63
+
64
+ /** The Tailwind namespace a token belongs to, from its type, its scopes, then its leading name segment. */
65
+ export function variableNamespace(variable: Variable): ThemeNamespace | undefined {
66
+ if (variable.type === 'COLOR') return 'color'
67
+ const fromScopes = new Set((variable.scopes ?? []).map((scope) => SCOPE_NAMESPACES[scope]))
68
+ const [only] = fromScopes
69
+ if (fromScopes.size === 1 && only) return only
70
+ return NAMESPACE_WORDS[tokenSlug(variable.name.split('/')[0] ?? '')]
71
+ }
72
+
73
+ /**
74
+ * The custom property a code snippet names, without `--`: `var(--brand)`, `var(--brand, red)`
75
+ * and `--brand` all name `brand`. A snippet that is anything else, such as a Tailwind class,
76
+ * names none.
77
+ */
78
+ export function parseCSSName(snippet: string | undefined): string | undefined {
79
+ const nodes = valueParser(snippet ?? '').nodes.filter((node) => node.type !== 'space')
80
+ const [node] = nodes
81
+ if (nodes.length !== 1) return undefined
82
+ const word =
83
+ node.type === 'function' && node.value === 'var' && 'nodes' in node
84
+ ? node.nodes.find((child) => child.type !== 'space')
85
+ : node
86
+ return word?.type === 'word' && word.value.startsWith('--') && word.value.length > 2
87
+ ? word.value.slice(2)
88
+ : undefined
89
+ }
90
+
91
+ /** The name `codeSyntax.WEB` gives the token, if it gives one. */
92
+ export function explicitCSSName(variable: Variable): string | undefined {
93
+ return parseCSSName(variable.codeSyntax?.WEB)
94
+ }
95
+
96
+ /**
97
+ * `Gray/50` as COLOR is `color-gray-50`; `Space/small` is `spacing-small`. A group the next segment
98
+ * repeats is said once, so `Gap/gap-1` is `gap-1`, as kits that mirror Tailwind classes name them. Two tokens can derive
99
+ * the same name, so stylesheet output takes names from `variableCSSNames`, which makes them unique.
100
+ */
101
+ export function deriveCSSName(variable: Variable): string {
102
+ const namespace = variableNamespace(variable)
103
+ const segments = compact(variable.name.split('/').map(tokenSlug))
104
+ if (segments.length > 1 && namespace && NAMESPACE_WORDS[segments[0] ?? ''] === namespace) {
105
+ segments.shift()
106
+ }
107
+ const body =
108
+ segments
109
+ .filter((segment, index) => {
110
+ const next = segments.at(index + 1)
111
+ return next === undefined || (next !== segment && !next.startsWith(`${segment}-`))
112
+ })
113
+ .join('-') || 'token'
114
+ if (!namespace || body === namespace || body.startsWith(`${namespace}-`)) return body
115
+ return `${namespace}-${body}`
116
+ }
117
+
118
+ /**
119
+ * Document-wide custom property names, without `--`. The first token whose `WEB` snippet claims
120
+ * a name keeps it; later claimants, which Figma files do contain, and derived names that collide
121
+ * take a derived name with a numeric suffix, in iteration order.
122
+ */
123
+ export function variableCSSNames(variables: Iterable<Variable>): Map<string, string> {
124
+ const list = [...variables]
125
+ const names = new Map<string, string>()
126
+ const taken = new Set<string>()
127
+ for (const variable of list) {
128
+ const name = explicitCSSName(variable)
129
+ if (!name || taken.has(name)) continue
130
+ names.set(variable.id, name)
131
+ taken.add(name)
132
+ }
133
+ for (const variable of list) {
134
+ if (names.has(variable.id)) continue
135
+ const base = deriveCSSName(variable)
136
+ let name = base
137
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`
138
+ names.set(variable.id, name)
139
+ taken.add(name)
140
+ }
141
+ return names
142
+ }
143
+
144
+ /** The `WEB` snippet that names a token in Figma's Dev Mode and here. */
145
+ export function cssNameCodeSyntax(name: string): string {
146
+ return `var(--${name})`
147
+ }
148
+
149
+ /** Namespaces longest first, so `font-weight-bold` reads as `font-weight`, not `font`. */
150
+ const NAMESPACES_BY_LENGTH = [...themeNamespaces].sort((a, b) => b.length - a.length)
151
+
152
+ /**
153
+ * The variable name a custom property reads as: a Tailwind namespace becomes the group, so
154
+ * `color-gray-50` is `color/gray-50` and `radius-md` is `radius/md`; any other name stays as it
155
+ * is. Variables made this way keep the property in their `WEB` code syntax, so the stylesheet
156
+ * writes the same name back.
157
+ */
158
+ export function cssNameVariableName(name: string): string {
159
+ const namespace = NAMESPACES_BY_LENGTH.find((candidate) => name.startsWith(`${candidate}-`))
160
+ return namespace ? `${namespace}/${name.slice(namespace.length + 1)}` : name
161
+ }
@@ -0,0 +1,201 @@
1
+ import type { SceneGraph, SceneNode, Variable } from '@pairdraw/scene-graph'
2
+ import type { Color } from '@pairdraw/scene-graph/primitives'
3
+
4
+ import { collectionVariables, variableCSSNames, variableNamespace } from './names'
5
+ import { modeAttribute } from './stylesheet'
6
+ import { variableUnit } from './values'
7
+
8
+ /** The mode CSS applies for each collection, by collection id. */
9
+ export type CSSModes = ReadonlyMap<string, string>
10
+
11
+ /** Bound fields drawn as a length; any other numeric binding is unitless or not exported. */
12
+ const LENGTH_FIELDS = new Set([
13
+ 'width',
14
+ 'height',
15
+ 'minWidth',
16
+ 'maxWidth',
17
+ 'minHeight',
18
+ 'maxHeight',
19
+ 'cornerRadius',
20
+ 'topLeftRadius',
21
+ 'topRightRadius',
22
+ 'bottomLeftRadius',
23
+ 'bottomRightRadius',
24
+ 'strokeWeight',
25
+ 'borderTopWeight',
26
+ 'borderBottomWeight',
27
+ 'borderLeftWeight',
28
+ 'borderRightWeight',
29
+ 'fontSize',
30
+ 'letterSpacing',
31
+ 'lineHeight',
32
+ 'paddingLeft',
33
+ 'paddingRight',
34
+ 'paddingTop',
35
+ 'paddingBottom',
36
+ 'itemSpacing',
37
+ 'counterAxisSpacing',
38
+ 'gridRowGap',
39
+ 'gridColumnGap'
40
+ ])
41
+
42
+ const LENGTH_UNITS = new Set(['px', 'rem'])
43
+
44
+ /** Color channels are stored as floats; a bound paint copies them, so this only absorbs rounding. */
45
+ const CHANNEL_TOLERANCE = 1 / 512
46
+
47
+ const CHANNELS = ['r', 'g', 'b', 'a'] as const
48
+
49
+ function sameColor(a: Color, b: Color): boolean {
50
+ return CHANNELS.every((channel) => Math.abs(a[channel] - b[channel]) <= CHANNEL_TOLERANCE)
51
+ }
52
+
53
+ function isColor(value: unknown): value is Color {
54
+ return typeof value === 'object' && value !== null && 'r' in value && 'a' in value
55
+ }
56
+
57
+ /** Where an alias chain ends in the modes the canvas draws: a value, or a CSS expression. */
58
+ type TokenChain = {
59
+ ids: string[]
60
+ value: Variable['valuesByMode'][string] | undefined
61
+ end: Variable
62
+ expression: boolean
63
+ }
64
+
65
+ /** The paint a `fills/0/color` or `strokes/1/color` binding names. */
66
+ function boundPaint(node: SceneNode, field: string) {
67
+ const [list, index] = field.split('/')
68
+ if (list === 'fills') return node.fills[Number(index)]
69
+ if (list === 'strokes') return node.strokes[Number(index)]
70
+ return undefined
71
+ }
72
+
73
+ /**
74
+ * Variable references for design-to-code. A bound field becomes `var(--name)` only when the
75
+ * stylesheet resolves it to what the canvas draws: the element sits in the same modes, and the
76
+ * token's CSS value is a length for a length, a bare number for opacity, or the paint's color.
77
+ * Anything else keeps its literal value.
78
+ */
79
+ export class DesignTokens {
80
+ readonly names: ReadonlyMap<string, string>
81
+ /** Tokens the output references, with every variable their aliases reach. */
82
+ readonly used = new Set<string>()
83
+ readonly #graph: SceneGraph
84
+
85
+ constructor(graph: SceneGraph) {
86
+ this.#graph = graph
87
+ this.names = variableCSSNames(collectionVariables(graph))
88
+ }
89
+
90
+ /** The modes CSS applies outside the exported nodes: every collection's default. */
91
+ defaultModes(): CSSModes {
92
+ return new Map(
93
+ [...this.#graph.variableCollections.values()].map((collection) => [
94
+ collection.id,
95
+ collection.defaultModeId
96
+ ])
97
+ )
98
+ }
99
+
100
+ /**
101
+ * Attributes that put an element in the modes the canvas draws it in, and the modes CSS then
102
+ * applies to it. An exported root takes the editor's active modes; below it, a node changes
103
+ * modes only where it sets one. Only a mode without its own condition can be set this way.
104
+ */
105
+ enter(
106
+ node: SceneNode,
107
+ inherited: CSSModes,
108
+ root: boolean
109
+ ): { attrs: Record<string, string>; modes: CSSModes } {
110
+ const attrs: Record<string, string> = {}
111
+ const modes = new Map(inherited)
112
+ for (const collection of this.#graph.variableCollections.values()) {
113
+ if (!root && !node.variableModes[collection.id]) continue
114
+ const modeId = this.#graph.getNodeVariableModeId(node.id, collection.id)
115
+ const mode = collection.modes.find((candidate) => candidate.modeId === modeId)
116
+ if (!mode || modeId === inherited.get(collection.id)) continue
117
+ if (modeId === collection.defaultModeId || mode.condition) continue
118
+ const { name, value } = modeAttribute(collection, mode)
119
+ attrs[name] = value
120
+ modes.set(collection.id, modeId)
121
+ }
122
+ return { attrs, modes }
123
+ }
124
+
125
+ /** `var(--name)` for a bound field, or `undefined` where the literal value must stay. */
126
+ reference(node: SceneNode, field: string, modes: CSSModes): string | undefined {
127
+ const variableId = node.boundVariables[field]
128
+ const variable = variableId ? this.#graph.variables.get(variableId) : undefined
129
+ const name = variable && this.names.get(variable.id)
130
+ if (!variable || !name) return undefined
131
+ const chain = this.#chain(node, variable, modes)
132
+ if (!chain || !this.#drawsResolved(node, field, chain)) return undefined
133
+ for (const id of chain.ids) this.used.add(id)
134
+ return `var(--${name})`
135
+ }
136
+
137
+ /**
138
+ * Follow aliases in the modes the canvas draws the node in, stopping at a value or at a CSS
139
+ * expression, which is what the stylesheet writes for that mode. Fails where CSS would resolve
140
+ * any link in another mode.
141
+ */
142
+ #chain(node: SceneNode, start: Variable, modes: CSSModes): TokenChain | undefined {
143
+ const ids: string[] = []
144
+ let variable: Variable | undefined = start
145
+ while (variable && !ids.includes(variable.id)) {
146
+ ids.push(variable.id)
147
+ const modeId = this.#graph.getNodeVariableModeId(node.id, variable.collectionId)
148
+ const collection = this.#graph.variableCollections.get(variable.collectionId)
149
+ const cssModeId = modes.get(variable.collectionId) ?? collection?.defaultModeId
150
+ if (modeId !== cssModeId) return undefined
151
+ const value =
152
+ variable.valuesByMode[modeId] ??
153
+ (collection ? variable.valuesByMode[collection.defaultModeId] : undefined)
154
+ if (variable.expressions?.[modeId]) return { ids, value, end: variable, expression: true }
155
+ if (typeof value === 'object' && 'aliasId' in value) {
156
+ variable = this.#graph.variables.get(value.aliasId)
157
+ continue
158
+ }
159
+ return { ids, value, end: variable, expression: false }
160
+ }
161
+ return undefined
162
+ }
163
+
164
+ #drawsResolved(node: SceneNode, field: string, { value, end, expression }: TokenChain): boolean {
165
+ if (field.endsWith('/color')) {
166
+ const paint = boundPaint(node, field)
167
+ if (!paint?.visible || paint.type !== 'SOLID' || !isColor(value)) return false
168
+ return sameColor({ ...paint.color, a: paint.opacity }, value)
169
+ }
170
+ const drawn: unknown = Reflect.get(node, field)
171
+ if (typeof drawn !== 'number' || typeof value !== 'number') return false
172
+ if (Math.fround(drawn) !== Math.fround(value)) return false
173
+ // An expression is the author's CSS for the value, whatever unit the token stores.
174
+ if (field === 'opacity') return expression || variableUnit(end) === 'none'
175
+ return LENGTH_FIELDS.has(field) && (expression || LENGTH_UNITS.has(variableUnit(end)))
176
+ }
177
+
178
+ /**
179
+ * The variables a stylesheet for this output declares: the referenced ones and every variable
180
+ * their aliases reach in any mode, since each mode's scope declares its own alias targets.
181
+ */
182
+ stylesheetVariables(): Set<string> {
183
+ const ids = new Set<string>()
184
+ const pending = [...this.used]
185
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
186
+ if (ids.has(id)) continue
187
+ ids.add(id)
188
+ for (const value of Object.values(this.#graph.variables.get(id)?.valuesByMode ?? {}))
189
+ if (typeof value === 'object' && 'aliasId' in value) pending.push(value.aliasId)
190
+ }
191
+ return ids
192
+ }
193
+
194
+ /** Custom properties the Tailwind stylesheet declares in `@theme`, which name utilities. */
195
+ themeVariables(): string[] {
196
+ return [...this.names].flatMap(([id, name]) => {
197
+ const variable = this.#graph.variables.get(id)
198
+ return variable && variableNamespace(variable) !== undefined ? [`--${name}`] : []
199
+ })
200
+ }
201
+ }
@@ -0,0 +1,304 @@
1
+ import type {
2
+ SceneGraph,
3
+ Variable,
4
+ VariableCollection,
5
+ VariableCollectionMode,
6
+ VariableValue
7
+ } from '@pairdraw/scene-graph'
8
+ import { variableValueReferences } from '@pairdraw/scene-graph/variables'
9
+
10
+ import { cssColor } from '../export/css'
11
+ import { formulaToCSS } from './formula'
12
+ import { collectionVariables, tokenSlug, variableCSSNames, variableNamespace } from './names'
13
+ import { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'
14
+ import { tokenNumberToCSS, variableUnit } from './values'
15
+
16
+ export type TokenStylesheetFormat = 'css' | 'tailwind'
17
+
18
+ export type TokenStylesheetIssue = {
19
+ message: string
20
+ variableId?: string
21
+ collectionId?: string
22
+ modeId?: string
23
+ }
24
+
25
+ export type TokenStylesheetOptions = {
26
+ format: TokenStylesheetFormat
27
+ /** Write only these tokens. Names still come from every token, so aliases outside resolve. */
28
+ include?: (variable: Variable) => boolean
29
+ }
30
+
31
+ export type TokenStylesheet = {
32
+ css: string
33
+ issues: TokenStylesheetIssue[]
34
+ }
35
+
36
+ type Declaration = { name: string; value: string }
37
+
38
+ type ModeScope = {
39
+ collection: VariableCollection
40
+ mode: VariableCollectionMode
41
+ condition: string
42
+ declarations: Declaration[]
43
+ }
44
+
45
+ type TokenSource = Pick<SceneGraph, 'variables' | 'variableCollections'>
46
+
47
+ function isAtRuleCondition(condition: string): boolean {
48
+ return condition.trim().startsWith('@')
49
+ }
50
+
51
+ /**
52
+ * A mode's name as an identifier. A name with no letters or digits falls back to its id, slugged
53
+ * too: Figma ids such as `1:2` are not valid in a selector value or a variant name as they are.
54
+ * Names that slug alike in one collection, such as `Dark` and `dark!`, are numbered in mode
55
+ * order, so each mode keeps its own selector and variant.
56
+ */
57
+ function modeSlug(collection: VariableCollection, mode: VariableCollectionMode): string {
58
+ const plainSlug = ({ name, modeId }: VariableCollectionMode) =>
59
+ tokenSlug(name) || `mode-${tokenSlug(modeId) || 'unnamed'}`
60
+ const taken = new Set<string>()
61
+ for (const candidate of collection.modes) {
62
+ const base = plainSlug(candidate)
63
+ let slug = base
64
+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`
65
+ if (candidate.modeId === mode.modeId) return slug
66
+ taken.add(slug)
67
+ }
68
+ return plainSlug(mode)
69
+ }
70
+
71
+ /** The attribute a collection's manual modes are switched by, unless it names its own. */
72
+ export function defaultModeAttributeName(collection: VariableCollection): string {
73
+ return `data-${tokenSlug(collection.name) || 'mode'}`
74
+ }
75
+
76
+ /** The attribute that puts an element in a mode with no condition of its own: `data-theme`. */
77
+ export function modeAttribute(
78
+ collection: VariableCollection,
79
+ mode: VariableCollectionMode
80
+ ): { name: string; value: string } {
81
+ return {
82
+ name: collection.modeAttribute ?? defaultModeAttributeName(collection),
83
+ value: modeSlug(collection, mode)
84
+ }
85
+ }
86
+
87
+ /** The scope a mode applies in when it names none: `[data-theme="dark"]` for Theme / Dark. */
88
+ export function defaultModeCondition(
89
+ collection: VariableCollection,
90
+ mode: VariableCollectionMode
91
+ ): string {
92
+ const { name, value } = modeAttribute(collection, mode)
93
+ return `[${name}="${value}"]`
94
+ }
95
+
96
+ function quoteString(value: string): string {
97
+ return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\a ')}"`
98
+ }
99
+
100
+ /** One mode's value as CSS, or why it has none. */
101
+ function modeValue(
102
+ variable: Variable,
103
+ value: VariableValue | undefined,
104
+ modeId: string,
105
+ names: ReadonlyMap<string, string>,
106
+ variables: ReadonlyMap<string, Variable>
107
+ ): string | { issue: string } {
108
+ const expression = variable.expressions?.[modeId]
109
+ if (expression) return expression.css
110
+ if (value === undefined) return { issue: 'has no value in this mode' }
111
+ if (typeof value === 'object' && 'expression' in value) {
112
+ if (value.expression === 'FORMULA' && variable.type === 'FLOAT')
113
+ return formulaToCSS(value.value, variable, variables, names)
114
+ if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }
115
+ return { issue: 'uses an expression that CSS token export does not support' }
116
+ }
117
+ if (typeof value === 'object' && 'aliasId' in value) {
118
+ const target = names.get(value.aliasId)
119
+ return target ? `var(--${target})` : { issue: 'aliases a variable that does not exist' }
120
+ }
121
+ if (variable.type === 'COLOR' && typeof value === 'object') return cssColor(value)
122
+ if (variable.type === 'FLOAT' && typeof value === 'number')
123
+ return tokenNumberToCSS(value, variableUnit(variable))
124
+ if (variable.type === 'STRING' && typeof value === 'string')
125
+ return variableNamespace(variable) === 'font' ? value : quoteString(value)
126
+ if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }
127
+ return { issue: 'has a value that does not match its type' }
128
+ }
129
+
130
+ function block(selector: string, declarations: Declaration[], indent = ''): string {
131
+ const body = declarations.map(({ name, value }) => `${indent} --${name}: ${value};`).join('\n')
132
+ return `${indent}${selector} {\n${body}\n${indent}}`
133
+ }
134
+
135
+ function modeBlock(scope: ModeScope): string {
136
+ const comment = `/* ${scope.collection.name}: ${scope.mode.name} */`
137
+ if (!isAtRuleCondition(scope.condition))
138
+ return `${comment}\n${block(scope.condition, scope.declarations)}`
139
+ return `${comment}\n${scope.condition} {\n${block(':root', scope.declarations, ' ')}\n}`
140
+ }
141
+
142
+ /** `@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));` */
143
+ function customVariant(name: string, condition: string): string {
144
+ const body = isAtRuleCondition(condition) ? condition : `&:where(${condition}, ${condition} *)`
145
+ return `@custom-variant ${name} (${body});`
146
+ }
147
+
148
+ /** Variants are named after their mode, prefixed with the collection where two modes share a name. */
149
+ function variantNames(scopes: ModeScope[]): string[] {
150
+ const plain = scopes.map(({ collection, mode }) => modeSlug(collection, mode))
151
+ return plain.map((name, index) => {
152
+ const shared = plain.filter((other) => other === name).length > 1
153
+ const collection = scopes[index]?.collection.name ?? ''
154
+ return shared ? `${tokenSlug(collection)}-${name}` : name
155
+ })
156
+ }
157
+
158
+ /**
159
+ * Variables as a stylesheet of custom properties. The default mode of every collection is the
160
+ * base set, in `:root` or, for Tailwind, in `@theme` when the token has a Tailwind namespace;
161
+ * every other mode overrides the values that differ, under its condition. Aliases stay `var()`
162
+ * references, and number formulas `calc()` over them; both are declared again in each mode that
163
+ * changes what they point to.
164
+ */
165
+ export function buildTokenStylesheet(
166
+ source: TokenSource,
167
+ { format, include = () => true }: TokenStylesheetOptions,
168
+ validate: TokenValidator
169
+ ): TokenStylesheet {
170
+ const issues: TokenStylesheetIssue[] = []
171
+ const collections = [...source.variableCollections.values()]
172
+ const all = collectionVariables(source)
173
+ const names = variableCSSNames(all)
174
+ const variables = all.filter(include)
175
+ const defaultModeOf = (variable: Variable) =>
176
+ source.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''
177
+
178
+ function declare(
179
+ variable: Variable,
180
+ modeId: string,
181
+ value: VariableValue | undefined
182
+ ): Declaration | undefined {
183
+ const name = names.get(variable.id) ?? variable.id
184
+ const css = modeValue(variable, value, modeId, names, source.variables)
185
+ if (typeof css !== 'string') {
186
+ issues.push({ message: `${variable.name} ${css.issue}`, variableId: variable.id, modeId })
187
+ return undefined
188
+ }
189
+ if (!validate.declaration(name, css)) {
190
+ issues.push({
191
+ message: `${variable.name} is not a valid CSS declaration: --${name}: ${css}`,
192
+ variableId: variable.id,
193
+ modeId
194
+ })
195
+ return undefined
196
+ }
197
+ return { name, value: css }
198
+ }
199
+
200
+ const defaults = new Map<string, Declaration>()
201
+ const theme: Declaration[] = []
202
+ const root: Declaration[] = []
203
+ for (const variable of variables) {
204
+ const modeId = defaultModeOf(variable)
205
+ const declaration = declare(variable, modeId, variable.valuesByMode[modeId])
206
+ if (!declaration) continue
207
+ defaults.set(variable.id, declaration)
208
+ if (format === 'tailwind' && variableNamespace(variable) !== undefined) theme.push(declaration)
209
+ else root.push(declaration)
210
+ }
211
+
212
+ /**
213
+ * What a mode's scope declares: the collection's values that differ from its default, and every
214
+ * alias or formula, in any collection, whose chain reaches one of them. Custom properties inherit as
215
+ * computed values, so `--primary: var(--blue)` resolved at `:root` would keep the old blue
216
+ * unless it is declared again where `--blue` changes.
217
+ */
218
+ function modeDeclarations(
219
+ collection: VariableCollection,
220
+ mode: VariableCollectionMode
221
+ ): Declaration[] {
222
+ const own = (variable: Variable) => variable.collectionId === collection.id
223
+ const valueIn = (variable: Variable) =>
224
+ own(variable)
225
+ ? (variable.valuesByMode[mode.modeId] ?? variable.valuesByMode[collection.defaultModeId])
226
+ : variable.valuesByMode[defaultModeOf(variable)]
227
+ const inMode = new Map<string, Declaration>()
228
+ const scoped = new Map<string, Declaration>()
229
+ for (const variable of variables.filter(own)) {
230
+ const declaration = declare(variable, mode.modeId, valueIn(variable))
231
+ if (!declaration) continue
232
+ inMode.set(variable.id, declaration)
233
+ if (declaration.value !== defaults.get(variable.id)?.value)
234
+ scoped.set(variable.id, declaration)
235
+ }
236
+ for (let grew = true; grew;) {
237
+ grew = false
238
+ for (const variable of variables) {
239
+ const references = variableValueReferences(valueIn(variable))
240
+ if (scoped.has(variable.id) || !references.some((target) => scoped.has(target))) continue
241
+ const declaration = inMode.get(variable.id) ?? defaults.get(variable.id)
242
+ if (!declaration) continue
243
+ scoped.set(variable.id, declaration)
244
+ grew = true
245
+ }
246
+ }
247
+ return variables.flatMap((variable) => {
248
+ const declaration = scoped.get(variable.id)
249
+ return declaration ? [declaration] : []
250
+ })
251
+ }
252
+
253
+ const scopes: ModeScope[] = []
254
+ for (const collection of collections) {
255
+ for (const mode of collection.modes) {
256
+ if (mode.modeId === collection.defaultModeId) continue
257
+ const condition = mode.condition ?? defaultModeCondition(collection, mode)
258
+ if (!validate.condition(condition)) {
259
+ issues.push({
260
+ message: `${collection.name}: ${mode.name} has a condition that is not a selector or a @media, @supports or @container query: ${condition}`,
261
+ collectionId: collection.id,
262
+ modeId: mode.modeId
263
+ })
264
+ continue
265
+ }
266
+ const declarations = modeDeclarations(collection, mode)
267
+ if (declarations.length > 0) scopes.push({ collection, mode, condition, declarations })
268
+ }
269
+ }
270
+
271
+ const sections: string[] = []
272
+ if (theme.length > 0) sections.push(block('@theme', theme))
273
+ if (root.length > 0) sections.push(block(':root', root))
274
+ sections.push(...scopes.map(modeBlock))
275
+ if (format === 'tailwind' && scopes.length > 0) {
276
+ const variants = variantNames(scopes)
277
+ sections.push(
278
+ scopes
279
+ .map((scope, index) =>
280
+ customVariant(variants[index] ?? modeSlug(scope.collection, scope.mode), scope.condition)
281
+ )
282
+ .join('\n')
283
+ )
284
+ }
285
+ return { css: sections.length > 0 ? `${sections.join('\n\n')}\n` : '', issues }
286
+ }
287
+
288
+ /**
289
+ * Browsers check token strings with their own CSS parser. Elsewhere, in the CLI and MCP, the CSS
290
+ * object model package loads on first use; its browser build exports nothing, so it is never
291
+ * the browser path.
292
+ */
293
+ export async function loadTokenValidator(): Promise<TokenValidator> {
294
+ if (typeof CSSStyleSheet === 'function') return createTokenValidator(parseWithBrowser)
295
+ const headless = await import('./cssom-validator')
296
+ return headless.tokenValidator
297
+ }
298
+
299
+ export async function tokenStylesheet(
300
+ source: TokenSource,
301
+ options: TokenStylesheetOptions
302
+ ): Promise<TokenStylesheet> {
303
+ return buildTokenStylesheet(source, options, await loadTokenValidator())
304
+ }