@pairdraw/dom-css 0.16.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,8 @@ interface HeadlessCSSRule {
18
18
  selector: string
19
19
  specificity: number
20
20
  order: number
21
- style: DesignStyleDeclaration
21
+ /** Declared values with `var()` unresolved, so each element resolves them in its own scope. */
22
+ declarations: DesignStyleDeclaration
22
23
  }
23
24
 
24
25
  interface ParsedHeadlessCSS {
@@ -39,16 +40,38 @@ const INHERITED_PROPERTIES = new Set([
39
40
  'line-height'
40
41
  ])
41
42
 
42
- function styleToRecord(
43
- style: CSSStyleDeclarationLike,
44
- customProperties: DesignStyleDeclaration = {}
45
- ): DesignStyleDeclaration {
43
+ /** Declared values as written, before custom properties and shorthands are resolved. */
44
+ function declarationsOf(style: CSSStyleDeclarationLike): DesignStyleDeclaration {
46
45
  const result: DesignStyleDeclaration = {}
47
46
  for (const property of Array.from({ length: style.length }, (_, index) => style[index])) {
48
- const value = resolveCSSValue(style.getPropertyValue(property), customProperties)
47
+ const value = style.getPropertyValue(property).trim()
49
48
  if (property && value) result[property] = value
50
49
  }
51
- return expandStyleShorthands(result)
50
+ return result
51
+ }
52
+
53
+ function resolveDeclarations(
54
+ declarations: DesignStyleDeclaration,
55
+ customProperties: DesignStyleDeclaration
56
+ ): DesignStyleDeclaration {
57
+ const resolved: DesignStyleDeclaration = {}
58
+ for (const [property, value] of Object.entries(declarations)) {
59
+ const resolvedValue = resolveCSSValue(value, customProperties)
60
+ if (resolvedValue) resolved[property] = resolvedValue
61
+ }
62
+ return expandStyleShorthands(resolved)
63
+ }
64
+
65
+ /** Adds the custom properties a declaration block sets, resolved against those already in scope. */
66
+ function declareCustomProperties(
67
+ scope: DesignStyleDeclaration,
68
+ declarations: DesignStyleDeclaration
69
+ ): void {
70
+ for (const [name, value] of Object.entries(declarations)) {
71
+ if (!name.startsWith('--')) continue
72
+ const resolved = resolveCSSValue(value, scope)
73
+ if (resolved) scope[name] = resolved
74
+ }
52
75
  }
53
76
 
54
77
  function isStyleRule(rule: unknown): rule is CSSStyleRuleLike {
@@ -81,7 +104,7 @@ function parseRules(cssText: string): ParsedHeadlessCSS {
81
104
  const styleRules = collectStyleRules(sheet.cssRules)
82
105
  const customProperties = collectCustomProperties(styleRules)
83
106
  const rules = styleRules.flatMap((rule) => {
84
- const style = styleToRecord(rule.style, customProperties)
107
+ const declarations = declarationsOf(rule.style)
85
108
  return rule.selectorText
86
109
  .split(',')
87
110
  .map((selector) => selector.trim())
@@ -90,7 +113,7 @@ function parseRules(cssText: string): ParsedHeadlessCSS {
90
113
  selector,
91
114
  specificity: selectorSpecificity(selector),
92
115
  order: order++,
93
- style
116
+ declarations
94
117
  }))
95
118
  })
96
119
  return { rules, customProperties }
@@ -100,27 +123,61 @@ function collectCustomProperties(rules: CSSStyleRuleLike[]): DesignStyleDeclarat
100
123
  const customProperties: DesignStyleDeclaration = {}
101
124
  for (const rule of rules) {
102
125
  if (!rule.selectorText.split(',').some((selector) => selector.trim() === ':root')) continue
103
- Object.assign(customProperties, styleToRecord(rule.style))
126
+ declareCustomProperties(customProperties, declarationsOf(rule.style))
104
127
  }
105
128
  return customProperties
106
129
  }
107
130
 
108
131
  function resolveCSSValue(value: string, customProperties: DesignStyleDeclaration): string {
109
- const withVariables = value.replaceAll(/var\((--[\w-]+)(?:,[^)]+)?\)/g, (_, name: string) => {
110
- return customProperties[name] ?? ''
111
- })
112
- return resolveSimpleCalc(withVariables)
132
+ return resolveSimpleCalc(resolveVariables(value, customProperties))
113
133
  }
114
134
 
115
- function resolveSimpleCalc(value: string): string {
116
- const calc = value.match(/^calc\(([-\d.]+)(rem|px)?\s*\*\s*([-\d.]+)\)$/)
117
- if (!calc?.[1] || !calc[3]) return value
135
+ const CUSTOM_PROPERTY_NAME = /^--[\w-]+$/
136
+
137
+ /** `var()` references as their values; a fallback can hold parentheses and other `var()`s. */
138
+ function resolveVariables(value: string, customProperties: DesignStyleDeclaration): string {
139
+ let result = ''
140
+ let index = 0
141
+ for (;;) {
142
+ const start = value.indexOf('var(', index)
143
+ const end = start === -1 ? -1 : closingParenthesis(value, start + 3)
144
+ if (end === -1) return result + value.slice(index)
145
+ const inner = value.slice(start + 4, end)
146
+ const comma = inner.indexOf(',')
147
+ const name = (comma === -1 ? inner : inner.slice(0, comma)).trim()
148
+ const declared: string | undefined = Object.hasOwn(customProperties, name)
149
+ ? customProperties[name]
150
+ : undefined
151
+ const fallback = comma === -1 ? '' : inner.slice(comma + 1).trim()
152
+ result += value.slice(index, start)
153
+ result += CUSTOM_PROPERTY_NAME.test(name)
154
+ ? (declared ?? resolveVariables(fallback, customProperties))
155
+ : value.slice(start, end + 1)
156
+ index = end + 1
157
+ }
158
+ }
118
159
 
119
- const base = Number.parseFloat(calc[1])
120
- const multiplier = Number.parseFloat(calc[3])
121
- const unit = calc.at(2) ?? 'px'
122
- if (!Number.isFinite(base) || !Number.isFinite(multiplier)) return value
123
- return `${unit === 'rem' ? base * multiplier * 16 : base * multiplier}px`
160
+ /** The index of the `)` closing the `(` at `open`, or -1 when it is never closed. */
161
+ function closingParenthesis(value: string, open: number): number {
162
+ let depth = 0
163
+ for (let index = open; index < value.length; index++) {
164
+ if (value[index] === '(') depth++
165
+ else if (value[index] === ')' && --depth === 0) return index
166
+ }
167
+ return -1
168
+ }
169
+
170
+ /** `calc()` of a product, with the length on either side, as pixels. */
171
+ function resolveSimpleCalc(value: string): string {
172
+ const calc = /^calc\(\s*([-\d.]+)(rem|px)?\s*\*\s*([-\d.]+)(rem|px)?\s*\)$/.exec(value)
173
+ if (!calc?.[1] || !calc[3] || (calc[2] && calc[4])) return value
174
+
175
+ const left = Number.parseFloat(calc[1])
176
+ const right = Number.parseFloat(calc[3])
177
+ // An unmatched group is undefined at run time, though the match array types it as a string.
178
+ const unit = calc[2] || calc[4] || 'px'
179
+ if (!Number.isFinite(left) || !Number.isFinite(right)) return value
180
+ return `${unit === 'rem' ? left * right * 16 : left * right}px`
124
181
  }
125
182
 
126
183
  const BORDER_STYLES = new Set([
@@ -230,63 +287,70 @@ function matchesSimpleSelector(element: DesignElement, selector: string): boolea
230
287
  return tag.length === 0 || tag === '*' || element.tagName.toLowerCase() === tag.toLowerCase()
231
288
  }
232
289
 
233
- function matchesSelector(
234
- element: DesignElement,
235
- selector: string,
236
- parent: AncestorContext | null
237
- ): boolean {
238
- const childParts = selector.split('>').map((part) => part.trim())
239
- if (childParts.length > 1) return matchesChildSelector(element, childParts, parent)
240
-
241
- const descendantParts = selector.split(/\s+/).filter((part) => part.length > 0)
242
- if (descendantParts.length > 1) return matchesDescendantSelector(element, descendantParts, parent)
243
-
244
- return matchesSimpleSelector(element, selector)
290
+ interface SelectorStep {
291
+ compound: string
292
+ /** How this compound relates to the one after it: `>` for a parent, ` ` for any ancestor. */
293
+ combinator: '>' | ' '
245
294
  }
246
295
 
247
- function matchesSelectorParts(
248
- element: DesignElement,
249
- parts: string[],
250
- parent: AncestorContext | null,
251
- directParentOnly: boolean
252
- ): boolean {
253
- const current = parts.at(-1)
254
- if (!current || !matchesSimpleSelector(element, current)) return false
255
-
256
- let ancestor = parent
257
- for (const selector of parts.slice(0, -1).reverse()) {
258
- if (!directParentOnly) {
259
- while (ancestor && !matchesSimpleSelector(ancestor.element, selector)) {
260
- ancestor = ancestor.parent
261
- }
296
+ /** A complex selector as its compounds, rightmost last; `null` when a combinator lacks a side. */
297
+ function selectorSteps(selector: string): SelectorStep[] | null {
298
+ const tokens = selector
299
+ .replaceAll('>', ' > ')
300
+ .split(/\s+/)
301
+ .filter((token) => token.length > 0)
302
+ const steps: SelectorStep[] = []
303
+ let pending: '>' | null = null
304
+ for (const token of tokens) {
305
+ if (token === '>') {
306
+ if (pending || steps.length === 0) return null
307
+ pending = '>'
308
+ continue
262
309
  }
263
- if (!ancestor || !matchesSimpleSelector(ancestor.element, selector)) return false
264
- ancestor = ancestor.parent
310
+ const previous = steps.at(-1)
311
+ if (previous) previous.combinator = pending ?? ' '
312
+ steps.push({ compound: token, combinator: ' ' })
313
+ pending = null
265
314
  }
266
- return true
315
+ return pending ? null : steps
267
316
  }
268
317
 
269
- function matchesChildSelector(
318
+ function matchesSelector(
270
319
  element: DesignElement,
271
- parts: string[],
320
+ selector: string,
272
321
  parent: AncestorContext | null
273
322
  ): boolean {
274
- return matchesSelectorParts(element, parts, parent, true)
323
+ const steps = selectorSteps(selector)
324
+ return steps !== null && matchesSteps(element, steps, steps.length - 1, parent)
275
325
  }
276
326
 
277
- function matchesDescendantSelector(
327
+ /** Whether the element matches the compound at `index` and some ancestors match those before. */
328
+ function matchesSteps(
278
329
  element: DesignElement,
279
- parts: string[],
330
+ steps: SelectorStep[],
331
+ index: number,
280
332
  parent: AncestorContext | null
281
333
  ): boolean {
282
- return matchesSelectorParts(element, parts, parent, false)
334
+ const step = steps.at(index)
335
+ if (!step || !matchesSimpleSelector(element, step.compound)) return false
336
+ if (index === 0) return true
337
+ const previous = steps.at(index - 1)
338
+ if (!previous) return false
339
+ if (previous.combinator === '>') {
340
+ return parent !== null && matchesSteps(parent.element, steps, index - 1, parent.parent)
341
+ }
342
+ for (let ancestor = parent; ancestor; ancestor = ancestor.parent) {
343
+ if (matchesSteps(ancestor.element, steps, index - 1, ancestor.parent)) return true
344
+ }
345
+ return false
283
346
  }
284
347
 
285
348
  function applyComputedStyles(
286
349
  node: DesignNode,
287
350
  rules: HeadlessCSSRule[],
288
351
  parent: AncestorContext | null,
289
- inheritedStyle: DesignStyleDeclaration
352
+ inheritedStyle: DesignStyleDeclaration,
353
+ inheritedCustomProperties: DesignStyleDeclaration
290
354
  ): DesignNode {
291
355
  if (node.type === 'text') return node
292
356
 
@@ -295,15 +359,22 @@ function applyComputedStyles(
295
359
  .filter((rule) => matchesSelector(node, rule.selector, parent))
296
360
  .sort((left, right) => left.specificity - right.specificity || left.order - right.order)
297
361
 
298
- for (const rule of matchingRules) Object.assign(computedStyle, rule.style)
299
- Object.assign(computedStyle, expandStyleShorthands(node.inlineStyle ?? {}))
362
+ // Custom properties cascade and inherit like any property, so `var()` resolves per element.
363
+ const customProperties = { ...inheritedCustomProperties }
364
+ for (const rule of matchingRules) declareCustomProperties(customProperties, rule.declarations)
365
+ declareCustomProperties(customProperties, node.inlineStyle ?? {})
366
+
367
+ for (const rule of matchingRules) {
368
+ Object.assign(computedStyle, resolveDeclarations(rule.declarations, customProperties))
369
+ }
370
+ Object.assign(computedStyle, resolveDeclarations(node.inlineStyle ?? {}, customProperties))
300
371
 
301
372
  const context = { element: node, parent }
302
373
  return {
303
374
  ...node,
304
375
  computedStyle: Object.keys(computedStyle).length > 0 ? computedStyle : undefined,
305
376
  children: node.children.map((child) =>
306
- applyComputedStyles(child, rules, context, computedStyle)
377
+ applyComputedStyles(child, rules, context, computedStyle, customProperties)
307
378
  )
308
379
  }
309
380
  }
@@ -321,10 +392,17 @@ export function computeHeadlessStyles(document: DesignDocument, cssText = ''): D
321
392
  const stylesheetText = [document.stylesheets?.map((sheet) => sheet.cssText).join('\n'), cssText]
322
393
  .filter((text): text is string => !!text)
323
394
  .join('\n')
324
- const { rules } = parseRules(stylesheetText)
395
+ const { rules, customProperties } = parseRules(stylesheetText)
396
+ // A fragment has no document element, so `:root` reaches its elements through inheritance only.
397
+ const rootStyle: DesignStyleDeclaration = {}
398
+ for (const rule of rules.filter(({ selector }) => selector === ':root')) {
399
+ Object.assign(rootStyle, resolveDeclarations(rule.declarations, customProperties))
400
+ }
325
401
 
326
402
  return {
327
403
  ...document,
328
- children: document.children.map((child) => applyComputedStyles(child, rules, null, {}))
404
+ children: document.children.map((child) =>
405
+ applyComputedStyles(child, rules, null, rootStyle, customProperties)
406
+ )
329
407
  }
330
408
  }
@@ -9,7 +9,14 @@ import { variableValueReferences } from '@pairdraw/scene-graph/variables'
9
9
 
10
10
  import { cssColor } from '../export/css'
11
11
  import { formulaToCSS } from './formula'
12
- import { collectionVariables, tokenSlug, variableCSSNames, variableNamespace } from './names'
12
+ import {
13
+ collectionVariables,
14
+ deriveCSSName,
15
+ explicitCSSName,
16
+ tokenSlug,
17
+ variableCSSNames,
18
+ variableNamespace
19
+ } from './names'
13
20
  import { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'
14
21
  import { tokenNumberToCSS, variableUnit } from './values'
15
22
 
@@ -132,8 +139,16 @@ function block(selector: string, declarations: Declaration[], indent = ''): stri
132
139
  return `${indent}${selector} {\n${body}\n${indent}}`
133
140
  }
134
141
 
142
+ /**
143
+ * A comment naming `text`. Collection and mode names are the person's own text, so a `*` before
144
+ * a `/` in them is spaced apart, which keeps a name from ending the comment and writing rules.
145
+ */
146
+ function cssComment(text: string): string {
147
+ return `/* ${text.replaceAll('*/', '* /')} */`
148
+ }
149
+
135
150
  function modeBlock(scope: ModeScope): string {
136
- const comment = `/* ${scope.collection.name}: ${scope.mode.name} */`
151
+ const comment = cssComment(`${scope.collection.name}: ${scope.mode.name}`)
137
152
  if (!isAtRuleCondition(scope.condition))
138
153
  return `${comment}\n${block(scope.condition, scope.declarations)}`
139
154
  return `${comment}\n${scope.condition} {\n${block(':root', scope.declarations, ' ')}\n}`
@@ -162,6 +177,29 @@ function variantNames(scopes: ModeScope[]): string[] {
162
177
  * references, and number formulas `calc()` over them; both are declared again in each mode that
163
178
  * changes what they point to.
164
179
  */
180
+ /**
181
+ * A name that took a numeric suffix is an alias nobody can read back from the stylesheet, so it
182
+ * is reported rather than left as a silent second spelling of another token.
183
+ */
184
+ function numberedNameIssues(
185
+ variables: readonly Variable[],
186
+ names: Map<string, string>,
187
+ modeOf: (variable: Variable) => string
188
+ ): TokenStylesheetIssue[] {
189
+ const issues: TokenStylesheetIssue[] = []
190
+ for (const variable of variables) {
191
+ const name = names.get(variable.id)
192
+ const base = deriveCSSName(variable)
193
+ if (!name || explicitCSSName(variable) || name === base) continue
194
+ issues.push({
195
+ message: `"${variable.name}" is written --${name}: --${base} is taken`,
196
+ variableId: variable.id,
197
+ modeId: modeOf(variable)
198
+ })
199
+ }
200
+ return issues
201
+ }
202
+
165
203
  export function buildTokenStylesheet(
166
204
  source: TokenSource,
167
205
  { format, include = () => true }: TokenStylesheetOptions,
@@ -197,6 +235,8 @@ export function buildTokenStylesheet(
197
235
  return { name, value: css }
198
236
  }
199
237
 
238
+ issues.push(...numberedNameIssues(variables, names, defaultModeOf))
239
+
200
240
  const defaults = new Map<string, Declaration>()
201
241
  const theme: Declaration[] = []
202
242
  const root: Declaration[] = []