@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.
- package/LICENSE +21 -0
- package/README.md +219 -2
- package/dist/browser.d.ts +29 -0
- package/dist/browser.js +2 -0
- package/dist/chunks/behaviours/args.js +59 -0
- package/dist/chunks/behaviours/args.js.map +1 -0
- package/dist/chunks/behaviours/controls.js +109 -0
- package/dist/chunks/behaviours/controls.js.map +1 -0
- package/dist/chunks/behaviours/reset.js +40 -0
- package/dist/chunks/behaviours/reset.js.map +1 -0
- package/dist/chunks/behaviours/roles.js +51 -0
- package/dist/chunks/behaviours/roles.js.map +1 -0
- package/dist/chunks/behaviours/states/conditions.js +103 -0
- package/dist/chunks/behaviours/states/conditions.js.map +1 -0
- package/dist/chunks/behaviours/states/css.js +172 -0
- package/dist/chunks/behaviours/states/css.js.map +1 -0
- package/dist/chunks/behaviours/states/layers.js +1736 -0
- package/dist/chunks/behaviours/states/layers.js.map +1 -0
- package/dist/chunks/behaviours/states/model.js +144 -0
- package/dist/chunks/behaviours/states/model.js.map +1 -0
- package/dist/chunks/behaviours/states/tailwind.js +198 -0
- package/dist/chunks/behaviours/states/tailwind.js.map +1 -0
- package/dist/chunks/browser.js +1352 -0
- package/dist/chunks/browser.js.map +1 -0
- package/dist/chunks/export/bundle.js +337 -0
- package/dist/chunks/export/bundle.js.map +1 -0
- package/dist/chunks/export/components/drawn.js +60 -0
- package/dist/chunks/export/components/drawn.js.map +1 -0
- package/dist/chunks/export/components/fields.js +178 -0
- package/dist/chunks/export/components/fields.js.map +1 -0
- package/dist/chunks/export/components/groups.js +297 -0
- package/dist/chunks/export/components/groups.js.map +1 -0
- package/dist/chunks/export/components/icons.js +260 -0
- package/dist/chunks/export/components/icons.js.map +1 -0
- package/dist/chunks/export/components/layers.js +1599 -0
- package/dist/chunks/export/components/layers.js.map +1 -0
- package/dist/chunks/export/index.js +477 -0
- package/dist/chunks/export/index.js.map +1 -0
- package/dist/chunks/export/storybook/component.js +448 -0
- package/dist/chunks/export/storybook/component.js.map +1 -0
- package/dist/chunks/export/storybook/export.js +410 -0
- package/dist/chunks/export/storybook/export.js.map +1 -0
- package/dist/chunks/import/html.js +406 -0
- package/dist/chunks/import/html.js.map +1 -0
- package/dist/chunks/import/jsx/dev-runtime.js +37 -0
- package/dist/chunks/import/jsx/dev-runtime.js.map +1 -0
- package/dist/chunks/tokens/cssom-validator.js +10 -0
- package/dist/chunks/tokens/cssom-validator.js.map +1 -0
- package/dist/export.d.ts +594 -0
- package/dist/export.js +13 -0
- package/dist/index.d.ts +115 -0
- package/dist/index.js +7 -0
- package/dist/jsx-dev-runtime.d.ts +8 -0
- package/dist/jsx-dev-runtime.js +3 -0
- package/dist/jsx-runtime.d.ts +20 -0
- package/dist/jsx-runtime.js +3 -0
- package/dist/rolldown-runtime.js +13 -0
- package/dist/runtime.d.ts +10 -0
- package/dist/scene-graph.d.ts +2 -0
- package/dist/scene-graph.js +2 -0
- package/dist/scene-graph2.d.ts +10 -0
- package/dist/styling.d.ts +93 -0
- package/dist/tailwind.d.ts +39 -0
- package/dist/types.d.ts +89 -0
- package/package.json +88 -4
- package/src/behaviours/args.ts +85 -0
- package/src/behaviours/controls.ts +195 -0
- package/src/behaviours/index.ts +11 -0
- package/src/behaviours/reset.ts +37 -0
- package/src/behaviours/roles.ts +44 -0
- package/src/behaviours/states/conditions.ts +105 -0
- package/src/behaviours/states/css.ts +123 -0
- package/src/behaviours/states/index.ts +4 -0
- package/src/behaviours/states/layers.ts +205 -0
- package/src/behaviours/states/model.ts +175 -0
- package/src/behaviours/states/names.ts +39 -0
- package/src/behaviours/states/tailwind.ts +148 -0
- package/src/behaviours/states/types.ts +56 -0
- package/src/browser.ts +146 -0
- package/src/cssom.d.ts +38 -0
- package/src/export/bundle.ts +461 -0
- package/src/export/components/drawn.ts +73 -0
- package/src/export/components/fields.ts +178 -0
- package/src/export/components/groups.ts +78 -0
- package/src/export/components/icons.ts +230 -0
- package/src/export/components/layers.ts +121 -0
- package/src/export/components/model.ts +544 -0
- package/src/export/components/properties.ts +167 -0
- package/src/export/components/react/fields.ts +129 -0
- package/src/export/components/react/index.ts +412 -0
- package/src/export/components/react/props.ts +151 -0
- package/src/export/components/react/radix.ts +52 -0
- package/src/export/components/react/shared.ts +76 -0
- package/src/export/components/references.ts +212 -0
- package/src/export/components/repeats.ts +128 -0
- package/src/export/components/shaders.ts +125 -0
- package/src/export/components/styling.ts +31 -0
- package/src/export/components/tree.ts +72 -0
- package/src/export/components/vue.ts +517 -0
- package/src/export/css.ts +57 -0
- package/src/export/grid.ts +42 -0
- package/src/export/html.ts +163 -0
- package/src/export/index.ts +44 -0
- package/src/export/projection.ts +581 -0
- package/src/export/storybook/component.ts +334 -0
- package/src/export/storybook/export.ts +430 -0
- package/src/export/storybook/groups.ts +161 -0
- package/src/export/storybook/module.ts +319 -0
- package/src/export/storybook/names.ts +51 -0
- package/src/export/tailwind-jsx.ts +156 -0
- package/src/export/text.ts +415 -0
- package/src/import/css-text.ts +4 -0
- package/src/import/css-values.ts +31 -0
- package/src/import/flow.ts +248 -0
- package/src/import/html.ts +88 -0
- package/src/import/jsx/core.ts +130 -0
- package/src/import/jsx/dev-runtime.ts +8 -0
- package/src/import/jsx/runtime.ts +76 -0
- package/src/import/scene-graph.ts +582 -0
- package/src/import/style-attribute.ts +25 -0
- package/src/import/tailwind.ts +54 -0
- package/src/import/text.ts +518 -0
- package/src/index.ts +51 -0
- package/src/runtime/browser/runtime.ts +301 -0
- package/src/runtime/headless/runtime.ts +99 -0
- package/src/runtime/headless/styles.ts +330 -0
- package/src/runtime/index.ts +11 -0
- package/src/tokens/conditions.ts +66 -0
- package/src/tokens/cssom-validator.ts +8 -0
- package/src/tokens/custom-properties.ts +331 -0
- package/src/tokens/expression.ts +128 -0
- package/src/tokens/formula.ts +140 -0
- package/src/tokens/index.ts +43 -0
- package/src/tokens/names.ts +161 -0
- package/src/tokens/references.ts +201 -0
- package/src/tokens/stylesheet.ts +304 -0
- package/src/tokens/validate.ts +86 -0
- package/src/tokens/values.ts +44 -0
- package/src/types.ts +59 -0
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parse,
|
|
3
|
+
toPlainObject,
|
|
4
|
+
// eslint-disable-next-line pairdraw/no-mixed-case-acronym-identifiers -- Upstream export spelling.
|
|
5
|
+
type CssNodePlain as CSSNodePlain,
|
|
6
|
+
type SelectorPlain
|
|
7
|
+
} from 'css-tree'
|
|
8
|
+
|
|
9
|
+
import { featureConditionCSS, parseFeatureCondition } from './conditions'
|
|
10
|
+
import { tokenSlug } from './names'
|
|
11
|
+
|
|
12
|
+
/** One custom property a stylesheet declares: `--brand: #ff5b2e`. */
|
|
13
|
+
export interface CustomPropertyDeclaration {
|
|
14
|
+
/** The property without its leading `--`. */
|
|
15
|
+
name: string
|
|
16
|
+
/** The value as written, trimmed, without `!important`. */
|
|
17
|
+
value: string
|
|
18
|
+
/** Where the trimmed value sits in the source, so a write-back replaces only it. */
|
|
19
|
+
start: number
|
|
20
|
+
end: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A block of custom properties and the scope it applies in. The base set is `:root`, `html`,
|
|
25
|
+
* `:host`, or Tailwind's `@theme`; every other scope is a mode's condition, as the token
|
|
26
|
+
* stylesheet writes it: a selector such as `[data-theme="dark"]` or `.dark`, or an at-rule
|
|
27
|
+
* prelude such as `@media (prefers-color-scheme: dark)` around a `:root` block.
|
|
28
|
+
*/
|
|
29
|
+
export interface CustomPropertyScope {
|
|
30
|
+
/** Null for the base set. */
|
|
31
|
+
condition: string | null
|
|
32
|
+
/** The attribute and value a lone `[name="value"]` selector switches on. */
|
|
33
|
+
attribute?: { name: string; value: string }
|
|
34
|
+
/**
|
|
35
|
+
* `Collection: Mode` from a comment just above a mode's block, as the token stylesheet writes
|
|
36
|
+
* it. A comment is a label only where its mode is the one the condition names, such as `Dark`
|
|
37
|
+
* above `.dark`, or where the condition names none, such as `@media (min-width: 40rem)`.
|
|
38
|
+
*/
|
|
39
|
+
label?: { collection: string; mode: string }
|
|
40
|
+
declarations: CustomPropertyDeclaration[]
|
|
41
|
+
/** The offset of the block's closing brace, where new declarations go. */
|
|
42
|
+
insertAt: number
|
|
43
|
+
/** The indentation of the block's declarations. */
|
|
44
|
+
indent: string
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface CustomPropertySheet {
|
|
48
|
+
scopes: CustomPropertyScope[]
|
|
49
|
+
/** Selectors and at-rules that declare custom properties but name no mode, as written. */
|
|
50
|
+
skipped: string[]
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface Comment {
|
|
54
|
+
text: string
|
|
55
|
+
start: number
|
|
56
|
+
end: number
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface Reader {
|
|
60
|
+
css: string
|
|
61
|
+
comments: Comment[]
|
|
62
|
+
sheet: CustomPropertySheet
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Labels are one line, `Collection: Mode`, as `buildTokenStylesheet` writes above each mode. */
|
|
66
|
+
const LABEL = /^ ([^:\n]+?): ([^\n]+?) $/
|
|
67
|
+
|
|
68
|
+
const ROOT_PSEUDO_CLASSES = new Set(['root', 'host'])
|
|
69
|
+
const CONDITION_AT_RULES = new Set(['media', 'supports', 'container'])
|
|
70
|
+
|
|
71
|
+
function textOf(reader: Reader, node: CSSNodePlain): string {
|
|
72
|
+
const { loc } = node
|
|
73
|
+
return loc ? reader.css.slice(loc.start.offset, loc.end.offset) : ''
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `:root`, `html`, or `:host`, alone. */
|
|
77
|
+
function isRootSimple(node: CSSNodePlain | undefined): boolean {
|
|
78
|
+
if (node?.type === 'TypeSelector') return node.name.toLowerCase() === 'html'
|
|
79
|
+
return (
|
|
80
|
+
node?.type === 'PseudoClassSelector' &&
|
|
81
|
+
ROOT_PSEUDO_CLASSES.has(node.name.toLowerCase()) &&
|
|
82
|
+
!node.children
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function isRootSelector(selector: SelectorPlain): boolean {
|
|
87
|
+
return selector.children.length === 1 && isRootSimple(selector.children[0])
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A selector with the root it is written on taken off, `:root.dark` as `.dark`, or undefined for
|
|
92
|
+
* one with a combinator, which scopes part of a page rather than switching a mode.
|
|
93
|
+
*/
|
|
94
|
+
function modeSelector(reader: Reader, selector: SelectorPlain): string | undefined {
|
|
95
|
+
if (selector.children.some((node) => node.type === 'Combinator')) return undefined
|
|
96
|
+
const parts = isRootSimple(selector.children[0]) ? selector.children.slice(1) : selector.children
|
|
97
|
+
const first = parts.at(0)
|
|
98
|
+
const last = parts.at(-1)
|
|
99
|
+
if (!first?.loc || !last?.loc) return undefined
|
|
100
|
+
return reader.css.slice(first.loc.start.offset, last.loc.end.offset)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function attributeOf(selector: SelectorPlain): CustomPropertyScope['attribute'] {
|
|
104
|
+
const parts = isRootSimple(selector.children[0]) ? selector.children.slice(1) : selector.children
|
|
105
|
+
const only = parts.at(0)
|
|
106
|
+
if (parts.length !== 1 || only?.type !== 'AttributeSelector' || only.matcher !== '=') {
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
109
|
+
const value = only.value?.type === 'String' ? only.value.value : only.value?.name
|
|
110
|
+
return value === undefined ? undefined : { name: only.name.name, value }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The mode a condition names by itself: the value of `[data-theme="dark"]`, the class of `.dark`,
|
|
115
|
+
* or the scheme of `@media (prefers-color-scheme: dark)`. Undefined for other conditions.
|
|
116
|
+
*/
|
|
117
|
+
export function modeConditionName(
|
|
118
|
+
condition: string,
|
|
119
|
+
attribute?: CustomPropertyScope['attribute']
|
|
120
|
+
): string | undefined {
|
|
121
|
+
if (attribute) return attribute.value
|
|
122
|
+
const className = /^\.(-?[_a-z][\w-]*)$/i.exec(condition)?.[1]
|
|
123
|
+
if (className) return className
|
|
124
|
+
const feature = parseFeatureCondition(condition)
|
|
125
|
+
if (feature?.feature === 'prefers-color-scheme' && feature.value.type === 'keyword')
|
|
126
|
+
return feature.value.name
|
|
127
|
+
return undefined
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The comment just above a mode's block as its label. An ordinary comment such as
|
|
132
|
+
* `/* TODO: fix later *\/` above `.dark` is none: its mode is not the one `.dark` names.
|
|
133
|
+
*/
|
|
134
|
+
function labelBefore(
|
|
135
|
+
reader: Reader,
|
|
136
|
+
start: number,
|
|
137
|
+
scope: Pick<CustomPropertyScope, 'condition' | 'attribute'>
|
|
138
|
+
): CustomPropertyScope['label'] {
|
|
139
|
+
if (scope.condition === null) return undefined
|
|
140
|
+
const comment = reader.comments.findLast((candidate) => candidate.end <= start)
|
|
141
|
+
if (!comment || reader.css.slice(comment.end, start).trim() !== '') return undefined
|
|
142
|
+
const match = LABEL.exec(comment.text)
|
|
143
|
+
if (!match) return undefined
|
|
144
|
+
const [, collection, mode] = match
|
|
145
|
+
const named = modeConditionName(scope.condition, scope.attribute)
|
|
146
|
+
const fits =
|
|
147
|
+
named === undefined ||
|
|
148
|
+
tokenSlug(named) === tokenSlug(mode) ||
|
|
149
|
+
scope.attribute?.name === `data-${tokenSlug(collection)}`
|
|
150
|
+
return fits ? { collection, mode } : undefined
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The whitespace a line starts with. */
|
|
154
|
+
function indentAt(css: string, offset: number): string {
|
|
155
|
+
const lineStart = css.lastIndexOf('\n', offset - 1) + 1
|
|
156
|
+
return /^[ \t]*/.exec(css.slice(lineStart))?.[0] ?? ''
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function declarationsOf(reader: Reader, block: CSSNodePlain[]): CustomPropertyDeclaration[] {
|
|
160
|
+
const declarations: CustomPropertyDeclaration[] = []
|
|
161
|
+
for (const node of block) {
|
|
162
|
+
if (node.type !== 'Declaration' || !node.property.startsWith('--')) continue
|
|
163
|
+
const { loc } = node.value
|
|
164
|
+
// Tailwind's `--color-*: initial` resets a namespace; it declares no property.
|
|
165
|
+
if (!loc || node.property.length <= 2 || node.property.includes('*')) continue
|
|
166
|
+
const raw = reader.css.slice(loc.start.offset, loc.end.offset)
|
|
167
|
+
const value = raw.trim()
|
|
168
|
+
if (!value) continue
|
|
169
|
+
const start = loc.start.offset + (raw.length - raw.trimStart().length)
|
|
170
|
+
declarations.push({ name: node.property.slice(2), value, start, end: start + value.length })
|
|
171
|
+
}
|
|
172
|
+
return declarations
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function declaresCustomProperties(nodes: readonly CSSNodePlain[]): boolean {
|
|
176
|
+
return nodes.some((node) => {
|
|
177
|
+
if (node.type === 'Declaration') return node.property.startsWith('--')
|
|
178
|
+
if (node.type === 'Rule') return declaresCustomProperties(node.block.children)
|
|
179
|
+
if (node.type === 'Atrule') return declaresCustomProperties(node.block?.children ?? [])
|
|
180
|
+
return false
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A block's contents read as declarations. css-tree reads the block of an at-rule it does not
|
|
186
|
+
* know, such as Tailwind's `@theme`, as rules, which turns declarations before a nested
|
|
187
|
+
* `@keyframes` into one rule with a raw prelude.
|
|
188
|
+
*/
|
|
189
|
+
function declarationList(reader: Reader, block: CSSNodePlain): CSSNodePlain[] {
|
|
190
|
+
if (block.type !== 'Block' || !block.loc) return []
|
|
191
|
+
const start = block.loc.start.offset + 1
|
|
192
|
+
const list = toPlainObject(
|
|
193
|
+
parse(reader.css.slice(start, block.loc.end.offset - 1), {
|
|
194
|
+
context: 'declarationList',
|
|
195
|
+
positions: true,
|
|
196
|
+
offset: start
|
|
197
|
+
})
|
|
198
|
+
)
|
|
199
|
+
return list.type === 'DeclarationList' ? list.children : []
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function addScope(
|
|
203
|
+
reader: Reader,
|
|
204
|
+
block: CSSNodePlain,
|
|
205
|
+
scope: Pick<CustomPropertyScope, 'condition' | 'attribute'>,
|
|
206
|
+
labelAt: number,
|
|
207
|
+
children: CSSNodePlain[] = block.type === 'Block' ? block.children : []
|
|
208
|
+
) {
|
|
209
|
+
if (block.type !== 'Block' || !block.loc) return
|
|
210
|
+
const declarations = declarationsOf(reader, children)
|
|
211
|
+
const first = declarations.at(0)
|
|
212
|
+
if (!first) return
|
|
213
|
+
reader.sheet.scopes.push({
|
|
214
|
+
condition: scope.condition,
|
|
215
|
+
...(scope.attribute ? { attribute: scope.attribute } : {}),
|
|
216
|
+
label: labelBefore(reader, labelAt, scope),
|
|
217
|
+
declarations,
|
|
218
|
+
insertAt: block.loc.end.offset - 1,
|
|
219
|
+
indent: indentAt(reader.css, first.start)
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A rule at the top of the sheet or of a `@layer`: the base set, or a mode by its selector. */
|
|
224
|
+
function readRule(reader: Reader, rule: Extract<CSSNodePlain, { type: 'Rule' }>) {
|
|
225
|
+
if (!declaresCustomProperties(rule.block.children)) return
|
|
226
|
+
const start = rule.loc?.start.offset ?? 0
|
|
227
|
+
if (rule.prelude.type !== 'SelectorList') {
|
|
228
|
+
reader.sheet.skipped.push(textOf(reader, rule.prelude))
|
|
229
|
+
return
|
|
230
|
+
}
|
|
231
|
+
const selectors = rule.prelude.children.filter((node) => node.type === 'Selector')
|
|
232
|
+
if (selectors.some(isRootSelector)) {
|
|
233
|
+
addScope(reader, rule.block, { condition: null }, start)
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
const conditions = selectors.map((selector) => modeSelector(reader, selector))
|
|
237
|
+
if (conditions.length === 0 || conditions.some((condition) => condition === undefined)) {
|
|
238
|
+
reader.sheet.skipped.push(textOf(reader, rule.prelude))
|
|
239
|
+
return
|
|
240
|
+
}
|
|
241
|
+
const attribute = selectors.length === 1 ? attributeOf(selectors[0]) : undefined
|
|
242
|
+
const condition = attribute
|
|
243
|
+
? `[${attribute.name}="${attribute.value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"]`
|
|
244
|
+
: conditions.join(', ')
|
|
245
|
+
addScope(reader, rule.block, { condition, attribute }, start)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** `@media (prefers-color-scheme: dark)` written the way the token stylesheet writes it. */
|
|
249
|
+
function atRuleCondition(reader: Reader, rule: Extract<CSSNodePlain, { type: 'Atrule' }>) {
|
|
250
|
+
const prelude = rule.prelude ? textOf(reader, rule.prelude).replaceAll(/\s+/g, ' ').trim() : ''
|
|
251
|
+
const written = `@${rule.name.toLowerCase()} ${prelude}`
|
|
252
|
+
const feature = parseFeatureCondition(written)
|
|
253
|
+
return feature ? featureConditionCSS(feature) : written
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function readAtRule(reader: Reader, rule: Extract<CSSNodePlain, { type: 'Atrule' }>) {
|
|
257
|
+
const name = rule.name.toLowerCase()
|
|
258
|
+
const children = rule.block?.children ?? []
|
|
259
|
+
const start = rule.loc?.start.offset ?? 0
|
|
260
|
+
if (name === 'layer') {
|
|
261
|
+
readNodes(reader, children)
|
|
262
|
+
return
|
|
263
|
+
}
|
|
264
|
+
if (!rule.block) return
|
|
265
|
+
if (!CONDITION_AT_RULES.has(name)) {
|
|
266
|
+
const declared = declarationList(reader, rule.block)
|
|
267
|
+
if (!declaresCustomProperties(declared)) return
|
|
268
|
+
if (name === 'theme') addScope(reader, rule.block, { condition: null }, start, declared)
|
|
269
|
+
else reader.sheet.skipped.push(textOf(reader, rule).split('{')[0].trim())
|
|
270
|
+
return
|
|
271
|
+
}
|
|
272
|
+
if (!declaresCustomProperties(children)) return
|
|
273
|
+
const condition = atRuleCondition(reader, rule)
|
|
274
|
+
for (const child of children) {
|
|
275
|
+
if (child.type === 'Rule' && child.prelude.type === 'SelectorList') {
|
|
276
|
+
const selectors = child.prelude.children.filter((node) => node.type === 'Selector')
|
|
277
|
+
if (selectors.length > 0 && selectors.every(isRootSelector)) {
|
|
278
|
+
// A comment above the at-rule labels it, as the stylesheet writes one above each mode.
|
|
279
|
+
addScope(reader, child.block, { condition }, start)
|
|
280
|
+
continue
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (declaresCustomProperties([child]))
|
|
284
|
+
reader.sheet.skipped.push(`${condition} ${textOf(reader, child).split('{')[0].trim()}`)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function readNodes(reader: Reader, nodes: readonly CSSNodePlain[]) {
|
|
289
|
+
for (const node of nodes) {
|
|
290
|
+
if (node.type === 'Rule') readRule(reader, node)
|
|
291
|
+
else if (node.type === 'Atrule') readAtRule(reader, node)
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The custom properties a stylesheet declares, by the scope they apply in: the inverse of
|
|
297
|
+
* `buildTokenStylesheet`. It reads the base set, selector modes, and `:root` blocks inside
|
|
298
|
+
* `@media`, `@supports`, and `@container`, also inside `@layer`; a scope it cannot read as a mode,
|
|
299
|
+
* such as `.card .title` or a selector inside a media query, is listed in `skipped`.
|
|
300
|
+
*/
|
|
301
|
+
export function readCustomProperties(css: string): CustomPropertySheet {
|
|
302
|
+
const comments: Comment[] = []
|
|
303
|
+
const reader: Reader = { css, comments, sheet: { scopes: [], skipped: [] } }
|
|
304
|
+
// Plain objects from a full parse: with `list: false`, css-tree leaves rule preludes raw.
|
|
305
|
+
const sheet = toPlainObject(
|
|
306
|
+
parse(css, {
|
|
307
|
+
positions: true,
|
|
308
|
+
onComment: (text, loc) =>
|
|
309
|
+
comments.push({ text, start: loc.start.offset, end: loc.end.offset })
|
|
310
|
+
})
|
|
311
|
+
)
|
|
312
|
+
if (sheet.type === 'StyleSheet') readNodes(reader, sheet.children)
|
|
313
|
+
return reader.sheet
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* A mode's condition in the form `readCustomProperties` gives it, so conditions written
|
|
318
|
+
* differently compare equal: `:root[data-theme=dark]` and `[data-theme="dark"]`, or
|
|
319
|
+
* `@media (prefers-color-scheme:dark)` and `@media (prefers-color-scheme: dark)`.
|
|
320
|
+
*/
|
|
321
|
+
export function modeConditionKey(condition: string): string {
|
|
322
|
+
const trimmed = condition.trim()
|
|
323
|
+
const probe = trimmed.startsWith('@')
|
|
324
|
+
? `${trimmed} { :root { --probe: 0 } }`
|
|
325
|
+
: `${trimmed} { --probe: 0 }`
|
|
326
|
+
try {
|
|
327
|
+
return readCustomProperties(probe).scopes[0]?.condition ?? trimmed
|
|
328
|
+
} catch {
|
|
329
|
+
return trimmed
|
|
330
|
+
}
|
|
331
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import valueParser, { type Node } from 'postcss-value-parser'
|
|
2
|
+
|
|
3
|
+
import type { TokenUnit } from '@pairdraw/scene-graph'
|
|
4
|
+
|
|
5
|
+
import { parseCSSName } from './names'
|
|
6
|
+
import type { TokenValidator } from './validate'
|
|
7
|
+
import { TOKEN_UNIT_PROPERTY } from './values'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* What a piece of a CSS value is. A finished `var(--name)` is one `reference`; while it is typed
|
|
11
|
+
* it reads as a `function`, a `paren` and a `property`, the custom property name.
|
|
12
|
+
*/
|
|
13
|
+
export type CSSValueTokenKind =
|
|
14
|
+
| 'reference'
|
|
15
|
+
| 'property'
|
|
16
|
+
| 'function'
|
|
17
|
+
| 'paren'
|
|
18
|
+
| 'number'
|
|
19
|
+
| 'operator'
|
|
20
|
+
| 'separator'
|
|
21
|
+
| 'string'
|
|
22
|
+
| 'keyword'
|
|
23
|
+
|
|
24
|
+
export interface CSSValueToken {
|
|
25
|
+
kind: CSSValueTokenKind
|
|
26
|
+
text: string
|
|
27
|
+
from: number
|
|
28
|
+
to: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const OPERATORS = new Set(['+', '-', '*', '/'])
|
|
32
|
+
|
|
33
|
+
/** `var(--name)` with nothing else inside, which an editor can show as the variable it names. */
|
|
34
|
+
function isReference(node: valueParser.FunctionNode) {
|
|
35
|
+
if (node.value !== 'var' || node.unclosed || node.nodes.length !== 1) return false
|
|
36
|
+
const [argument] = node.nodes
|
|
37
|
+
return argument.type === 'word' && argument.value.startsWith('--')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function wordKind(word: string): CSSValueTokenKind {
|
|
41
|
+
if (word.startsWith('--')) return 'property'
|
|
42
|
+
if (OPERATORS.has(word)) return 'operator'
|
|
43
|
+
return valueParser.unit(word) ? 'number' : 'keyword'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The tokens of one CSS value, such as `clamp(1rem, 4vw, var(--space-md))`, in order and with
|
|
48
|
+
* their source ranges. Reading tolerates half-typed values: an unclosed function still gives
|
|
49
|
+
* its name and its `(`.
|
|
50
|
+
*/
|
|
51
|
+
export function cssValueTokens(source: string): CSSValueToken[] {
|
|
52
|
+
const tokens: CSSValueToken[] = []
|
|
53
|
+
const push = (kind: CSSValueTokenKind, from: number, to: number) =>
|
|
54
|
+
tokens.push({ kind, text: source.slice(from, to), from, to })
|
|
55
|
+
const walk = (nodes: Node[]) => {
|
|
56
|
+
for (const node of nodes) {
|
|
57
|
+
if (node.type === 'function') {
|
|
58
|
+
if (isReference(node)) {
|
|
59
|
+
push('reference', node.sourceIndex, node.sourceEndIndex)
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
const open = node.sourceIndex + node.value.length
|
|
63
|
+
if (node.value) push('function', node.sourceIndex, open)
|
|
64
|
+
push('paren', open, open + 1)
|
|
65
|
+
walk(node.nodes)
|
|
66
|
+
if (!node.unclosed) push('paren', node.sourceEndIndex - 1, node.sourceEndIndex)
|
|
67
|
+
} else if (node.type === 'word') {
|
|
68
|
+
push(wordKind(node.value), node.sourceIndex, node.sourceEndIndex)
|
|
69
|
+
} else if (node.type === 'div') {
|
|
70
|
+
push(node.value === '/' ? 'operator' : 'separator', node.sourceIndex, node.sourceEndIndex)
|
|
71
|
+
} else if (node.type === 'string') {
|
|
72
|
+
push('string', node.sourceIndex, node.sourceEndIndex)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
walk(valueParser(source).nodes)
|
|
77
|
+
return tokens
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The custom property a token names, in `var(--name)` or as a bare `--name`. */
|
|
81
|
+
export function cssTokenProperty(token: CSSValueToken): string | undefined {
|
|
82
|
+
if (token.kind !== 'reference' && token.kind !== 'property') return undefined
|
|
83
|
+
const name = parseCSSName(token.text)
|
|
84
|
+
return name ? `--${name}` : undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function hasUnclosedFunction(nodes: Node[]): boolean {
|
|
88
|
+
return nodes.some(
|
|
89
|
+
(node) => node.type === 'function' && (node.unclosed || hasUnclosedFunction(node.nodes))
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export type CSSExpressionProblem =
|
|
94
|
+
| { kind: 'unclosed' }
|
|
95
|
+
| { kind: 'syntax' }
|
|
96
|
+
| { kind: 'negated-reference'; property: string }
|
|
97
|
+
| { kind: 'unknown-token'; name: string }
|
|
98
|
+
| { kind: 'invalid'; property: string }
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Why a CSS expression cannot stand in for a token, if it cannot. The token validator checks it
|
|
102
|
+
* is one declaration; then it must name only tokens that exist and suit the token's unit, which
|
|
103
|
+
* `supports` checks where a browser can type values. A value holding `var()` passes that last
|
|
104
|
+
* check until it is used, so only its names are checked.
|
|
105
|
+
*/
|
|
106
|
+
export function cssExpressionProblem(
|
|
107
|
+
css: string,
|
|
108
|
+
unit: TokenUnit,
|
|
109
|
+
tokens: ReadonlySet<string>,
|
|
110
|
+
validator: TokenValidator,
|
|
111
|
+
supports?: (property: string, value: string) => boolean
|
|
112
|
+
): CSSExpressionProblem | undefined {
|
|
113
|
+
if (!validator.declaration('token', css))
|
|
114
|
+
return hasUnclosedFunction(valueParser(css).nodes) ? { kind: 'unclosed' } : { kind: 'syntax' }
|
|
115
|
+
const parsed = cssValueTokens(css)
|
|
116
|
+
// `-var(--x)` reads as a function named `-var`: CSS negates a value only inside calc().
|
|
117
|
+
const negated = parsed.findIndex((token) => token.kind === 'function' && token.text === '-var')
|
|
118
|
+
if (negated !== -1) {
|
|
119
|
+
const property = parsed.slice(negated).map(cssTokenProperty).find(Boolean)
|
|
120
|
+
if (property) return { kind: 'negated-reference', property }
|
|
121
|
+
}
|
|
122
|
+
for (const token of parsed) {
|
|
123
|
+
const name = cssTokenProperty(token)
|
|
124
|
+
if (name && !tokens.has(name)) return { kind: 'unknown-token', name }
|
|
125
|
+
}
|
|
126
|
+
const property = TOKEN_UNIT_PROPERTY[unit]
|
|
127
|
+
return !supports || supports(property, css) ? undefined : { kind: 'invalid', property }
|
|
128
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { Variable, VariableFormulaNode } from '@pairdraw/scene-graph'
|
|
2
|
+
import { foldFormula } from '@pairdraw/scene-graph/variables'
|
|
3
|
+
|
|
4
|
+
import { tokenNumberToCSS, variableUnit } from './values'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A number formula as `calc()`, with each reference a `var()`. CSS adds only like with like and
|
|
8
|
+
* multiplies a length only by a plain number, so a literal takes the unit of what it is added
|
|
9
|
+
* to, and a formula CSS cannot type, such as a length times a length, has no CSS form.
|
|
10
|
+
*/
|
|
11
|
+
type Term =
|
|
12
|
+
| { kind: 'literal'; value: number }
|
|
13
|
+
| { kind: 'css'; text: string; precedence: number; dimension: boolean }
|
|
14
|
+
|
|
15
|
+
const OPERATORS = {
|
|
16
|
+
add: { symbol: '+', precedence: 1 },
|
|
17
|
+
subtract: { symbol: '-', precedence: 1 },
|
|
18
|
+
multiply: { symbol: '*', precedence: 2 },
|
|
19
|
+
divide: { symbol: '/', precedence: 2 }
|
|
20
|
+
} as const
|
|
21
|
+
type Arithmetic = keyof typeof OPERATORS
|
|
22
|
+
const ATOM = 3
|
|
23
|
+
|
|
24
|
+
class UnsupportedFormulaError extends Error {
|
|
25
|
+
override name = 'UnsupportedFormulaError'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface FormulaContext {
|
|
29
|
+
variables: ReadonlyMap<string, Variable>
|
|
30
|
+
names: ReadonlyMap<string, string>
|
|
31
|
+
/** A literal written as a length, in the exported token's unit. */
|
|
32
|
+
length: (value: number) => string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function formulaToCSS(
|
|
36
|
+
node: VariableFormulaNode,
|
|
37
|
+
variable: Variable,
|
|
38
|
+
variables: ReadonlyMap<string, Variable>,
|
|
39
|
+
names: ReadonlyMap<string, string>
|
|
40
|
+
): string | { issue: string } {
|
|
41
|
+
const unit = variableUnit(variable)
|
|
42
|
+
const context = { variables, names, length: (value: number) => tokenNumberToCSS(value, unit) }
|
|
43
|
+
try {
|
|
44
|
+
const result = convert(node, context)
|
|
45
|
+
const dimension = unit !== 'none'
|
|
46
|
+
if (result.kind === 'literal') return write(result, dimension, context)
|
|
47
|
+
if (result.dimension !== dimension)
|
|
48
|
+
return { issue: dimension ? 'has a formula without a unit' : 'has a formula with a unit' }
|
|
49
|
+
return `calc(${result.text})`
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error instanceof UnsupportedFormulaError) return { issue: error.message }
|
|
52
|
+
throw error
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function convert(node: VariableFormulaNode, context: FormulaContext): Term {
|
|
57
|
+
return foldFormula<Term>(node, {
|
|
58
|
+
literal: (value) => {
|
|
59
|
+
if (typeof value === 'number') return { kind: 'literal', value }
|
|
60
|
+
if (typeof value === 'boolean')
|
|
61
|
+
throw new UnsupportedFormulaError('mixes true/false into a number')
|
|
62
|
+
throw new UnsupportedFormulaError('mixes text or a color into a number')
|
|
63
|
+
},
|
|
64
|
+
reference: (id) => reference(id, context),
|
|
65
|
+
operation: ({ operator }, operands) => {
|
|
66
|
+
const [a, b] = operands
|
|
67
|
+
if (operator === 'negate' && operands.length === 1) return negate(a, context)
|
|
68
|
+
if (operands.length !== 2 || !isArithmetic(operator))
|
|
69
|
+
throw new UnsupportedFormulaError('uses logic that CSS has no form for')
|
|
70
|
+
if (a.kind === 'literal' && b.kind === 'literal')
|
|
71
|
+
return { kind: 'literal', value: fold(operator, a.value, b.value) }
|
|
72
|
+
return binary(operator, a, b, context)
|
|
73
|
+
}
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function reference(id: string, { variables, names }: FormulaContext): Term {
|
|
78
|
+
const target = variables.get(id)
|
|
79
|
+
const name = names.get(id)
|
|
80
|
+
if (!target || !name)
|
|
81
|
+
throw new UnsupportedFormulaError('refers to a variable that does not exist')
|
|
82
|
+
if (target.type !== 'FLOAT')
|
|
83
|
+
throw new UnsupportedFormulaError('uses a variable that is not a number')
|
|
84
|
+
const dimension = variableUnit(target) !== 'none'
|
|
85
|
+
return { kind: 'css', text: `var(--${name})`, precedence: ATOM, dimension }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function negate(term: Term, context: FormulaContext): Term {
|
|
89
|
+
if (term.kind === 'literal') return { kind: 'literal', value: -term.value }
|
|
90
|
+
const text = `-1 * ${grouped(term, false, OPERATORS.multiply.precedence, context)}`
|
|
91
|
+
return { kind: 'css', text, precedence: OPERATORS.multiply.precedence, dimension: term.dimension }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function binary(operator: Arithmetic, a: Term, b: Term, context: FormulaContext): Term {
|
|
95
|
+
const { symbol, precedence } = OPERATORS[operator]
|
|
96
|
+
// The right side of - and / keeps its parentheses even at equal precedence.
|
|
97
|
+
const rightBelow = operator === 'subtract' || operator === 'divide' ? precedence + 1 : precedence
|
|
98
|
+
const aDimension = a.kind === 'css' && a.dimension
|
|
99
|
+
const bDimension = b.kind === 'css' && b.dimension
|
|
100
|
+
if (precedence === 1) {
|
|
101
|
+
if (a.kind === 'css' && b.kind === 'css' && aDimension !== bDimension)
|
|
102
|
+
throw new UnsupportedFormulaError('adds a length to a plain number')
|
|
103
|
+
const dimension = aDimension || bDimension
|
|
104
|
+
const left = grouped(a, dimension, precedence, context)
|
|
105
|
+
const right = grouped(b, dimension, rightBelow, context)
|
|
106
|
+
return { kind: 'css', text: `${left} ${symbol} ${right}`, precedence, dimension }
|
|
107
|
+
}
|
|
108
|
+
if (bDimension && operator === 'divide') throw new UnsupportedFormulaError('divides by a length')
|
|
109
|
+
if (aDimension && bDimension) throw new UnsupportedFormulaError('multiplies two lengths')
|
|
110
|
+
const left = grouped(a, false, precedence, context)
|
|
111
|
+
const right = grouped(b, false, rightBelow, context)
|
|
112
|
+
return {
|
|
113
|
+
kind: 'css',
|
|
114
|
+
text: `${left} ${symbol} ${right}`,
|
|
115
|
+
precedence,
|
|
116
|
+
dimension: aDimension || bDimension
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function write(term: Term, dimension: boolean, context: FormulaContext) {
|
|
121
|
+
if (term.kind === 'css') return term.text
|
|
122
|
+
return dimension ? context.length(term.value) : String(Number(term.value.toFixed(6)))
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function grouped(term: Term, dimension: boolean, below: number, context: FormulaContext) {
|
|
126
|
+
return term.kind === 'css' && term.precedence < below
|
|
127
|
+
? `(${term.text})`
|
|
128
|
+
: write(term, dimension, context)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function isArithmetic(operator: string): operator is Arithmetic {
|
|
132
|
+
return Object.hasOwn(OPERATORS, operator)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function fold(operator: Arithmetic, a: number, b: number) {
|
|
136
|
+
if (operator === 'add') return a + b
|
|
137
|
+
if (operator === 'subtract') return a - b
|
|
138
|
+
if (operator === 'multiply') return a * b
|
|
139
|
+
return a / b
|
|
140
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Design tokens as CSS custom properties: names, namespaces, units, and the stylesheet.
|
|
2
|
+
export { featureConditionCSS, parseFeatureCondition, type FeatureCondition } from './conditions'
|
|
3
|
+
export {
|
|
4
|
+
modeConditionKey,
|
|
5
|
+
modeConditionName,
|
|
6
|
+
readCustomProperties,
|
|
7
|
+
type CustomPropertyDeclaration,
|
|
8
|
+
type CustomPropertyScope,
|
|
9
|
+
type CustomPropertySheet
|
|
10
|
+
} from './custom-properties'
|
|
11
|
+
export {
|
|
12
|
+
cssExpressionProblem,
|
|
13
|
+
cssTokenProperty,
|
|
14
|
+
cssValueTokens,
|
|
15
|
+
type CSSExpressionProblem,
|
|
16
|
+
type CSSValueToken,
|
|
17
|
+
type CSSValueTokenKind
|
|
18
|
+
} from './expression'
|
|
19
|
+
export {
|
|
20
|
+
collectionVariables,
|
|
21
|
+
cssNameCodeSyntax,
|
|
22
|
+
cssNameVariableName,
|
|
23
|
+
deriveCSSName,
|
|
24
|
+
explicitCSSName,
|
|
25
|
+
parseCSSName,
|
|
26
|
+
tokenSlug,
|
|
27
|
+
variableCSSNames,
|
|
28
|
+
variableNamespace
|
|
29
|
+
} from './names'
|
|
30
|
+
export {
|
|
31
|
+
buildTokenStylesheet,
|
|
32
|
+
defaultModeAttributeName,
|
|
33
|
+
defaultModeCondition,
|
|
34
|
+
loadTokenValidator,
|
|
35
|
+
modeAttribute,
|
|
36
|
+
tokenStylesheet,
|
|
37
|
+
type TokenStylesheet,
|
|
38
|
+
type TokenStylesheetFormat,
|
|
39
|
+
type TokenStylesheetIssue,
|
|
40
|
+
type TokenStylesheetOptions
|
|
41
|
+
} from './stylesheet'
|
|
42
|
+
export { createTokenValidator, type TokenValidator } from './validate'
|
|
43
|
+
export { TOKEN_UNIT_PROPERTY, tokenNumberToCSS, variableUnit } from './values'
|