@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,582 @@
1
+ import { pick } from 'es-toolkit'
2
+ import { isValid, toUint8Array } from 'js-base64'
3
+
4
+ import {
5
+ SceneGraph,
6
+ type Fill,
7
+ type ImageScaleMode,
8
+ type SceneNode,
9
+ type Stroke
10
+ } from '@pairdraw/scene-graph'
11
+ import { TRANSPARENT } from '@pairdraw/scene-graph/constants'
12
+ import { parseCSSAlignSelf, parseCSSNumber, parseCSSShadows } from '@pairdraw/scene-graph/css'
13
+ import { computeImageHash } from '@pairdraw/scene-graph/images'
14
+
15
+ import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
16
+ import { colorToFillFromCSS, colorToStrokeFromCSS, mergedStyle, pickStyle } from './css-values'
17
+ import {
18
+ applyContainerLayout,
19
+ applyFlowSizing,
20
+ elementDisplay,
21
+ flowOf,
22
+ inheritedTextStyle,
23
+ type ParentFlow
24
+ } from './flow'
25
+ import {
26
+ blockRichText,
27
+ characterStyleFromCSS,
28
+ elementLink,
29
+ holdsTextBlocks,
30
+ inlineRichText,
31
+ isInlineContent,
32
+ applyParagraphs,
33
+ type CSSCharacterStyle
34
+ } from './text'
35
+
36
+ const DOM_CSS_PLUGIN_ID = 'pairdraw-dom-css'
37
+ const IMAGE_SOURCE_URL_KEY = 'image-source-url'
38
+
39
+ export interface DesignDocumentToSceneGraphOptions {
40
+ pageName?: string
41
+ }
42
+
43
+ function textContent(node: DesignNode): string {
44
+ if (node.type === 'text') return node.text
45
+ return node.children.map(textContent).join('')
46
+ }
47
+
48
+ function isTextLikeElement(node: DesignElement): boolean {
49
+ return [
50
+ 'span',
51
+ 'p',
52
+ 'label',
53
+ 'strong',
54
+ 'em',
55
+ 'button',
56
+ 'a',
57
+ 'h1',
58
+ 'h2',
59
+ 'h3',
60
+ 'h4',
61
+ 'h5',
62
+ 'h6'
63
+ ].includes(node.tagName.toLowerCase())
64
+ }
65
+
66
+ function firstCSSNumber(style: DesignStyleDeclaration, ...properties: string[]): number | null {
67
+ for (const property of properties) {
68
+ const parsed = parseCSSNumber(pickStyle(style, property))
69
+ if (parsed !== null) return parsed
70
+ }
71
+ return null
72
+ }
73
+
74
+ function fillsFromStyle(style: DesignStyleDeclaration, property: string): Fill[] {
75
+ return colorToFillFromCSS(pickStyle(style, property))
76
+ }
77
+
78
+ function aspectRatioFromCSS(value: string | undefined): number | null {
79
+ if (!value || value === 'auto') return null
80
+ const parts = value
81
+ .split('/')
82
+ .map((part) => Number.parseFloat(part.trim()))
83
+ .filter(Number.isFinite)
84
+ if (parts.length === 1 && parts[0] > 0) return parts[0]
85
+ if (parts.length === 2 && parts[0] > 0 && parts[1] > 0) return parts[0] / parts[1]
86
+ return null
87
+ }
88
+
89
+ function setNodeBox(node: SceneNode, style: DesignStyleDeclaration): void {
90
+ const width = firstCSSNumber(style, 'width')
91
+ const height = firstCSSNumber(style, 'height')
92
+ const minWidth = firstCSSNumber(style, 'min-width')
93
+ const maxWidth = firstCSSNumber(style, 'max-width')
94
+ const minHeight = firstCSSNumber(style, 'min-height')
95
+ const maxHeight = firstCSSNumber(style, 'max-height')
96
+ const aspectRatio = aspectRatioFromCSS(pickStyle(style, 'aspect-ratio'))
97
+ if (width !== null) node.width = width
98
+ if (height !== null) node.height = height
99
+ if (height === null && width !== null && aspectRatio !== null) node.height = width / aspectRatio
100
+ if (width === null && height !== null && aspectRatio !== null) node.width = height * aspectRatio
101
+ if (minWidth !== null) node.minWidth = minWidth
102
+ if (maxWidth !== null) node.maxWidth = maxWidth
103
+ if (minHeight !== null) node.minHeight = minHeight
104
+ if (maxHeight !== null) node.maxHeight = maxHeight
105
+ }
106
+
107
+ function firstStrokeColor(style: DesignStyleDeclaration) {
108
+ return (
109
+ pickStyle(style, 'border-color') ??
110
+ pickStyle(style, 'border-top-color') ??
111
+ pickStyle(style, 'border-right-color') ??
112
+ pickStyle(style, 'border-bottom-color') ??
113
+ pickStyle(style, 'border-left-color')
114
+ )
115
+ }
116
+
117
+ function strokeWeightFromStyle(style: DesignStyleDeclaration) {
118
+ const borderWidth = firstCSSNumber(style, 'border-width')
119
+ if (borderWidth !== null) return borderWidth
120
+
121
+ const sideWeights = [
122
+ firstCSSNumber(style, 'border-top-width'),
123
+ firstCSSNumber(style, 'border-right-width'),
124
+ firstCSSNumber(style, 'border-bottom-width'),
125
+ firstCSSNumber(style, 'border-left-width')
126
+ ].filter((weight): weight is number => weight !== null)
127
+ if (sideWeights.length === 0) return null
128
+ return Math.max(...sideWeights)
129
+ }
130
+
131
+ function borderStyleFromCSS(style: DesignStyleDeclaration): string | undefined {
132
+ return (
133
+ pickStyle(style, 'border-style') ??
134
+ pickStyle(style, 'border-top-style') ??
135
+ pickStyle(style, 'border-right-style') ??
136
+ pickStyle(style, 'border-bottom-style') ??
137
+ pickStyle(style, 'border-left-style')
138
+ )
139
+ }
140
+
141
+ function dashPatternFromCSS(style: DesignStyleDeclaration, strokeWeight: number): number[] {
142
+ const borderStyle = borderStyleFromCSS(style)
143
+ if (borderStyle === 'dashed') return [strokeWeight * 3, strokeWeight * 2]
144
+ if (borderStyle === 'dotted') return [strokeWeight, strokeWeight]
145
+ return []
146
+ }
147
+
148
+ function setBorderWeights(node: SceneNode, style: DesignStyleDeclaration, stroke: Stroke): void {
149
+ const top = firstCSSNumber(style, 'border-top-width') ?? stroke.weight
150
+ const right = firstCSSNumber(style, 'border-right-width') ?? stroke.weight
151
+ const bottom = firstCSSNumber(style, 'border-bottom-width') ?? stroke.weight
152
+ const left = firstCSSNumber(style, 'border-left-width') ?? stroke.weight
153
+ node.borderTopWeight = top
154
+ node.borderRightWeight = right
155
+ node.borderBottomWeight = bottom
156
+ node.borderLeftWeight = left
157
+ node.independentStrokeWeights = [top, right, bottom, left].some(
158
+ (weight) => weight !== stroke.weight
159
+ )
160
+ }
161
+
162
+ function applyCornerRadii(node: SceneNode, style: DesignStyleDeclaration): void {
163
+ const cornerRadius = firstCSSNumber(style, 'border-radius')
164
+ const topLeft = firstCSSNumber(style, 'border-top-left-radius')
165
+ const topRight = firstCSSNumber(style, 'border-top-right-radius')
166
+ const bottomRight = firstCSSNumber(style, 'border-bottom-right-radius')
167
+ const bottomLeft = firstCSSNumber(style, 'border-bottom-left-radius')
168
+
169
+ if (cornerRadius !== null) node.cornerRadius = cornerRadius
170
+ if (topLeft === null && topRight === null && bottomRight === null && bottomLeft === null) return
171
+
172
+ const fallback = cornerRadius ?? 0
173
+ node.topLeftRadius = topLeft ?? fallback
174
+ node.topRightRadius = topRight ?? fallback
175
+ node.bottomRightRadius = bottomRight ?? fallback
176
+ node.bottomLeftRadius = bottomLeft ?? fallback
177
+ node.independentCorners = [
178
+ node.topLeftRadius,
179
+ node.topRightRadius,
180
+ node.bottomRightRadius,
181
+ node.bottomLeftRadius
182
+ ].some((radius) => radius !== fallback)
183
+ }
184
+
185
+ function applyFlexGap(node: SceneNode, style: DesignStyleDeclaration): void {
186
+ const gap = firstCSSNumber(style, 'gap')
187
+ const rowGap = firstCSSNumber(style, 'row-gap')
188
+ const columnGap = firstCSSNumber(style, 'column-gap')
189
+ const isHorizontal = node.layoutMode === 'HORIZONTAL'
190
+ const isWrapped = node.layoutWrap === 'WRAP'
191
+
192
+ node.itemSpacing = (isHorizontal ? columnGap : rowGap) ?? gap ?? 0
193
+ node.counterAxisSpacing = (isHorizontal ? rowGap : columnGap) ?? (isWrapped ? (gap ?? 0) : 0)
194
+ }
195
+
196
+ function applyPositioning(node: SceneNode, style: DesignStyleDeclaration): void {
197
+ const position = pickStyle(style, 'position')
198
+ if (position === 'absolute' || position === 'fixed') node.layoutPositioning = 'ABSOLUTE'
199
+
200
+ const left = firstCSSNumber(style, 'left')
201
+ const top = firstCSSNumber(style, 'top')
202
+ if (left !== null) node.x = left
203
+ if (top !== null) node.y = top
204
+ }
205
+
206
+ /**
207
+ * What CSS adds outside an explicit size: padding and borders, unless `box-sizing: border-box`
208
+ * puts them inside it as auto layout does.
209
+ */
210
+ function contentBoxExtras(style: DesignStyleDeclaration): { width: number; height: number } {
211
+ if (pickStyle(style, 'box-sizing')?.trim() === 'border-box') return { width: 0, height: 0 }
212
+ // A border takes room once it has a style other than none, its CSS default, whatever its color.
213
+ const borderStyle = borderStyleFromCSS(style)
214
+ const bordered = borderStyle !== undefined && borderStyle !== 'none' && borderStyle !== 'hidden'
215
+ const side = (name: 'top' | 'right' | 'bottom' | 'left', axis: 'block' | 'inline') =>
216
+ (firstCSSNumber(style, `padding-${name}`, `padding-${axis}`, 'padding') ?? 0) +
217
+ (bordered ? (firstCSSNumber(style, `border-${name}-width`, 'border-width') ?? 0) : 0)
218
+ return {
219
+ width: side('left', 'inline') + side('right', 'inline'),
220
+ height: side('top', 'block') + side('bottom', 'block')
221
+ }
222
+ }
223
+
224
+ /** Explicit sizes count the padding and borders CSS places outside them. */
225
+ function applyBoxSizing(node: SceneNode, style: DesignStyleDeclaration): void {
226
+ const extras = contentBoxExtras(style)
227
+ const width = firstCSSNumber(style, 'width')
228
+ const height = firstCSSNumber(style, 'height')
229
+ // A size `aspect-ratio` derives from the other is a content size too.
230
+ const ratio = aspectRatioFromCSS(pickStyle(style, 'aspect-ratio')) !== null
231
+ if (extras.width > 0) {
232
+ if (width !== null || (ratio && height !== null)) node.width += extras.width
233
+ if (node.minWidth !== null) node.minWidth += extras.width
234
+ if (node.maxWidth !== null) node.maxWidth += extras.width
235
+ }
236
+ if (extras.height > 0) {
237
+ if (height !== null || (ratio && width !== null)) node.height += extras.height
238
+ if (node.minHeight !== null) node.minHeight += extras.height
239
+ if (node.maxHeight !== null) node.maxHeight += extras.height
240
+ }
241
+ }
242
+
243
+ function applyPadding(node: SceneNode, style: DesignStyleDeclaration): void {
244
+ node.paddingTop = firstCSSNumber(style, 'padding-top', 'padding-block', 'padding') ?? 0
245
+ node.paddingRight = firstCSSNumber(style, 'padding-right', 'padding-inline', 'padding') ?? 0
246
+ node.paddingBottom = firstCSSNumber(style, 'padding-bottom', 'padding-block', 'padding') ?? 0
247
+ node.paddingLeft = firstCSSNumber(style, 'padding-left', 'padding-inline', 'padding') ?? 0
248
+ }
249
+
250
+ function imageScaleModeFromObjectFit(value: string | undefined): ImageScaleMode | null {
251
+ if (value === 'contain' || value === 'scale-down') return 'FIT'
252
+ if (value === 'cover') return 'FILL'
253
+ return null
254
+ }
255
+
256
+ function bytesFromDataURL(value: string | undefined): Uint8Array | null {
257
+ if (!value?.startsWith('data:')) return null
258
+ const commaIndex = value.indexOf(',')
259
+ if (commaIndex === -1) return null
260
+ const metadata = value.slice(0, commaIndex)
261
+ const body = value.slice(commaIndex + 1)
262
+ // Invalid Base64 in imported HTML drops that image instead of the whole import.
263
+ if (!metadata.endsWith(';base64') || !isValid(body)) return null
264
+ return toUint8Array(body)
265
+ }
266
+
267
+ function applyImageFill(
268
+ graph: SceneGraph,
269
+ node: SceneNode,
270
+ element: DesignElement,
271
+ style: DesignStyleDeclaration
272
+ ): void {
273
+ if (element.tagName.toLowerCase() !== 'img') return
274
+ const source = element.attrs.src
275
+ const bytes = bytesFromDataURL(source)
276
+ if (!bytes) {
277
+ if (source) {
278
+ node.pluginData.push({
279
+ pluginId: DOM_CSS_PLUGIN_ID,
280
+ key: IMAGE_SOURCE_URL_KEY,
281
+ value: source
282
+ })
283
+ }
284
+ return
285
+ }
286
+
287
+ const imageHash = computeImageHash(bytes)
288
+ graph.images.set(imageHash, bytes)
289
+ node.fills = [
290
+ {
291
+ type: 'IMAGE',
292
+ imageHash,
293
+ imageScaleMode: imageScaleModeFromObjectFit(pickStyle(style, 'object-fit')) ?? 'FILL',
294
+ color: TRANSPARENT,
295
+ opacity: 1,
296
+ visible: true
297
+ }
298
+ ]
299
+ }
300
+
301
+ function applyElementStyle(
302
+ graph: SceneGraph,
303
+ node: SceneNode,
304
+ element: DesignElement,
305
+ style: DesignStyleDeclaration
306
+ ): void {
307
+ setNodeBox(node, style)
308
+ applyBoxSizing(node, style)
309
+ applyPositioning(node, style)
310
+ applyPadding(node, style)
311
+
312
+ const fills = fillsFromStyle(style, 'background-color')
313
+ if (fills.length > 0) node.fills = fills
314
+ applyImageFill(graph, node, element, style)
315
+
316
+ const strokes = colorToStrokeFromCSS(
317
+ firstStrokeColor(style),
318
+ strokeWeightFromStyle(style)?.toString()
319
+ )
320
+ if (strokes.length > 0) {
321
+ const dashPattern = dashPatternFromCSS(style, strokes[0].weight)
322
+ if (dashPattern.length > 0) {
323
+ strokes[0].dashPattern = dashPattern
324
+ node.dashPattern = dashPattern
325
+ }
326
+ node.strokes = strokes
327
+ setBorderWeights(node, style, strokes[0])
328
+ }
329
+
330
+ const effects = parseCSSShadows(pickStyle(style, 'box-shadow'))
331
+ if (effects.length > 0) node.effects = effects
332
+
333
+ const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
334
+ if (opacity !== null) node.opacity = opacity
335
+
336
+ applyCornerRadii(node, style)
337
+
338
+ const overflow = pickStyle(style, 'overflow')
339
+ if (overflow === 'hidden' || overflow === 'clip') node.clipsContent = true
340
+
341
+ const alignSelf = parseCSSAlignSelf(pickStyle(style, 'align-self')) ?? 'AUTO'
342
+ if (alignSelf !== 'AUTO') node.layoutAlignSelf = alignSelf
343
+ }
344
+
345
+ const CHARACTER_FIELDS = [
346
+ 'fontFamily',
347
+ 'fontSize',
348
+ 'fontWeight',
349
+ 'italic',
350
+ 'letterSpacing',
351
+ 'lineHeight',
352
+ 'fills',
353
+ 'textDecoration',
354
+ 'textDecorationStyle',
355
+ 'textDecorationThickness',
356
+ 'textDecorationFills',
357
+ 'textDecorationSkipInk',
358
+ 'textUnderlineOffset',
359
+ 'textCase'
360
+ ] as const satisfies readonly (keyof CSSCharacterStyle)[]
361
+
362
+ function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {
363
+ setNodeBox(node, style)
364
+ applyPositioning(node, style)
365
+ Object.assign(node, characterStyleFromCSS(style, pick(node, CHARACTER_FIELDS)))
366
+
367
+ const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
368
+ if (opacity !== null) node.opacity = opacity
369
+
370
+ const effects = parseCSSShadows(pickStyle(style, 'text-shadow'))
371
+ if (effects.length > 0) node.effects = effects
372
+
373
+ const textAlign = pickStyle(style, 'text-align')?.toUpperCase()
374
+ if (textAlign === 'CENTER' || textAlign === 'RIGHT' || textAlign === 'JUSTIFIED') {
375
+ node.textAlignHorizontal = textAlign
376
+ }
377
+
378
+ if (pickStyle(style, 'white-space') === 'nowrap') node.maxLines = 1
379
+ }
380
+
381
+ /**
382
+ * Text and inline elements, or blocks of text, as one text layer: spans become runs, blocks
383
+ * paragraphs, and lists list paragraphs, as Figma holds rich text.
384
+ */
385
+ function createRichTextNode(
386
+ graph: SceneGraph,
387
+ parentId: string,
388
+ element: DesignElement,
389
+ style: DesignStyleDeclaration,
390
+ display: string,
391
+ parentFlow: ParentFlow
392
+ ): SceneNode {
393
+ const node = graph.createNode('TEXT', parentId, { name: 'Text' })
394
+ applyTextStyle(node, style)
395
+ const blocks = holdsTextBlocks(element, isPlainElement, isInlineElement)
396
+ const base = pick(node, CHARACTER_FIELDS)
397
+ const rich = blocks ? blockRichText(element, style, base) : inlineRichText(element, style, base)
398
+ node.text = rich.text
399
+ node.name = rich.text.slice(0, 32) || 'Text'
400
+ node.styleRuns = rich.styleRuns
401
+ if (blocks) applyParagraphs(node, rich)
402
+ applyFlowSizing(graph, node, style, display, parentFlow)
403
+ return node
404
+ }
405
+
406
+ /** Whether an element draws nothing of its own, so its text can join the text around it. */
407
+ function isPlainElement(element: DesignElement): boolean {
408
+ return !hasBoxStyle(mergedStyle(element))
409
+ }
410
+
411
+ function isInlineElement(element: DesignElement): boolean {
412
+ const style = mergedStyle(element)
413
+ return elementDisplay(element, style) === 'inline' && !hasBoxStyle(style)
414
+ }
415
+
416
+ /** Whether the element's children are text in one layer: inline content, or text blocks. */
417
+ function holdsRichText(element: DesignElement): boolean {
418
+ if (!element.children.some((child) => child.type === 'element')) return false
419
+ if (holdsTextBlocks(element, isPlainElement, isInlineElement)) return true
420
+ return isInlineContent(element, isInlineElement)
421
+ }
422
+
423
+ function createTextNode(
424
+ graph: SceneGraph,
425
+ parentId: string,
426
+ text: string,
427
+ style: DesignStyleDeclaration,
428
+ display: string,
429
+ parentFlow: ParentFlow
430
+ ) {
431
+ const node = graph.createNode('TEXT', parentId, { name: text.slice(0, 32) || 'Text', text })
432
+ applyTextStyle(node, style)
433
+ applyFlowSizing(graph, node, style, display, parentFlow)
434
+ return node
435
+ }
436
+
437
+ /** A link of text alone links all of it. */
438
+ function linkText(node: SceneNode, element: DesignElement): void {
439
+ const hyperlink = elementLink(element)
440
+ if (hyperlink && node.text.length > 0) {
441
+ node.styleRuns = [{ start: 0, length: node.text.length, style: { hyperlink } }]
442
+ }
443
+ }
444
+
445
+ function hasBoxStyle(style: DesignStyleDeclaration): boolean {
446
+ return [
447
+ 'aspect-ratio',
448
+ 'background-color',
449
+ 'border-color',
450
+ 'border-style',
451
+ 'border-width',
452
+ 'border-top-style',
453
+ 'border-top-width',
454
+ 'border-right-style',
455
+ 'border-right-width',
456
+ 'border-bottom-style',
457
+ 'border-bottom-width',
458
+ 'border-left-style',
459
+ 'border-left-width',
460
+ 'border-radius',
461
+ 'box-shadow',
462
+ 'display',
463
+ 'height',
464
+ 'padding',
465
+ 'padding-top',
466
+ 'padding-right',
467
+ 'padding-bottom',
468
+ 'padding-left',
469
+ 'padding-block',
470
+ 'padding-inline',
471
+ 'width',
472
+ 'min-width',
473
+ 'max-width',
474
+ 'min-height',
475
+ 'max-height',
476
+ 'object-fit',
477
+ 'overflow',
478
+ 'position',
479
+ 'top',
480
+ 'right',
481
+ 'bottom',
482
+ 'left',
483
+ 'flex-wrap',
484
+ 'align-self'
485
+ ].some((property) => pickStyle(style, property) !== undefined)
486
+ }
487
+
488
+ function hasContent(element: DesignElement): boolean {
489
+ return element.children.some((child) => child.type !== 'text' || child.text.trim().length > 0)
490
+ }
491
+
492
+ function createElementNode(
493
+ graph: SceneGraph,
494
+ parentId: string,
495
+ element: DesignElement,
496
+ parentFlow: ParentFlow
497
+ ): SceneNode | null {
498
+ const style = mergedStyle(element)
499
+ const display = elementDisplay(element, style)
500
+ if (display === 'none') return null
501
+ if (
502
+ isTextLikeElement(element) &&
503
+ !hasBoxStyle(style) &&
504
+ element.children.every((child) => child.type === 'text')
505
+ ) {
506
+ const text = createTextNode(graph, parentId, textContent(element), style, display, parentFlow)
507
+ linkText(text, element)
508
+ return text
509
+ }
510
+ if (!hasBoxStyle(style) && holdsRichText(element)) {
511
+ return createRichTextNode(graph, parentId, element, style, display, parentFlow)
512
+ }
513
+
514
+ const node = graph.createNode('FRAME', parentId, {
515
+ name: element.attrs.id || element.attrs.class || element.tagName,
516
+ clipsContent: false
517
+ })
518
+ applyElementStyle(graph, node, element, style)
519
+ // A box without content keeps its own size, as an image does, unless it declares a layout.
520
+ const flow = hasContent(element) || flowOf(display) === 'flex' ? flowOf(display) : null
521
+ if (flow) {
522
+ applyContainerLayout(node, element, style, flow)
523
+ if (flow === 'flex') applyFlexGap(node, style)
524
+ }
525
+ applyFlowSizing(graph, node, style, display, parentFlow)
526
+
527
+ // Blocks of text in a box's own flow are one text; a flex box's children are items.
528
+ if (flow !== 'flex' && holdsRichText(element)) {
529
+ const textStyle = inheritedTextStyle(element, style)
530
+ const textDisplay = flow === 'inline' ? 'inline' : 'block'
531
+ createRichTextNode(graph, node.id, element, textStyle, textDisplay, flow ?? 'none')
532
+ return node
533
+ }
534
+ for (const child of element.children) {
535
+ createDesignNode(graph, node.id, child, flow ?? 'none', inheritedTextStyle(element, style))
536
+ }
537
+
538
+ return node
539
+ }
540
+
541
+ function createDesignNode(
542
+ graph: SceneGraph,
543
+ parentId: string,
544
+ node: DesignNode,
545
+ parentFlow: ParentFlow,
546
+ inheritedStyle: DesignStyleDeclaration = {}
547
+ ): SceneNode | null {
548
+ if (node.type === 'text') {
549
+ if (node.text.trim().length === 0) return null
550
+ // Text runs in block flow and flex containers are blocks of their own, as CSS boxes them.
551
+ const display = parentFlow === 'inline' ? 'inline' : 'block'
552
+ return createTextNode(graph, parentId, node.text, inheritedStyle, display, parentFlow)
553
+ }
554
+
555
+ return createElementNode(graph, parentId, node, parentFlow)
556
+ }
557
+
558
+ function fitPageToChildren(page: SceneNode, graph: SceneGraph): void {
559
+ const children = graph.getChildren(page.id)
560
+ if (children.length === 0) return
561
+ page.width = Math.max(...children.map((child) => child.x + child.width))
562
+ page.height = Math.max(...children.map((child) => child.y + child.height))
563
+ }
564
+
565
+ export function designDocumentToSceneGraph(
566
+ document: DesignDocument,
567
+ options: DesignDocumentToSceneGraphOptions = {}
568
+ ): SceneGraph {
569
+ const graph = new SceneGraph()
570
+ const page = graph.getPages().find((node) => node.type === 'CANVAS') ?? graph.addPage('DesignDOM')
571
+
572
+ page.name = options.pageName ?? 'DesignDOM'
573
+
574
+ for (const child of document.children) {
575
+ createDesignNode(graph, page.id, child, 'none')
576
+ }
577
+
578
+ fitPageToChildren(page, graph)
579
+ return graph
580
+ }
581
+
582
+ export type { DesignDocumentToSceneGraphOptions as ToSceneGraphOptions }
@@ -0,0 +1,25 @@
1
+ import { parse } from '@acemir/cssom'
2
+ import type { CSSStyleRuleLike } from '@acemir/cssom'
3
+
4
+ import type { DesignStyleDeclaration } from '../types'
5
+
6
+ function firstStyleRule(cssText: string): CSSStyleRuleLike | null {
7
+ const [rule] = parse(cssText).cssRules
8
+ if (!rule || typeof rule !== 'object' || !('style' in rule)) return null
9
+ return rule as CSSStyleRuleLike
10
+ }
11
+
12
+ export function parseStyleAttribute(value: string | undefined): DesignStyleDeclaration | undefined {
13
+ if (!value) return undefined
14
+
15
+ const rule = firstStyleRule(`*{${value}}`)
16
+ if (!rule) return undefined
17
+
18
+ const style: DesignStyleDeclaration = {}
19
+ for (const property of Array.from(rule.style)) {
20
+ const propertyValue = rule.style.getPropertyValue(property)
21
+ if (propertyValue) style[property] = propertyValue
22
+ }
23
+
24
+ return Object.keys(style).length > 0 ? style : undefined
25
+ }
@@ -0,0 +1,54 @@
1
+ import { compile } from 'tailwindcss'
2
+
3
+ export interface CompileTailwindCSSOptions {
4
+ css?: string
5
+ base?: string
6
+ loadStylesheet?: (id: string, base: string) => Promise<string>
7
+ }
8
+
9
+ const DEFAULT_TAILWIND_CSS = '@import "tailwindcss";'
10
+
11
+ export async function compileTailwindCSS(
12
+ classes: string | Iterable<string>,
13
+ options: CompileTailwindCSSOptions = {}
14
+ ): Promise<string> {
15
+ const compiler = await compile(tailwindCompilerCSS(options.css), {
16
+ base: options.base,
17
+ loadStylesheet: async (id, base) => {
18
+ const content = options.loadStylesheet
19
+ ? await options.loadStylesheet(id, base)
20
+ : await loadTailwindStylesheet(id)
21
+ return { path: id, base, content }
22
+ }
23
+ })
24
+ return compiler.build(normalizeClasses(classes))
25
+ }
26
+
27
+ function tailwindCompilerCSS(css: string | undefined): string {
28
+ const trimmed = css?.trim()
29
+ if (!trimmed) return DEFAULT_TAILWIND_CSS
30
+ if (containsTailwindImport(trimmed)) return trimmed
31
+ return `${DEFAULT_TAILWIND_CSS}\n${trimmed}`
32
+ }
33
+
34
+ function containsTailwindImport(css: string): boolean {
35
+ const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, '')
36
+ return /^\s*@import\s+(?:"tailwindcss(?:\/[^"]*)?"|'tailwindcss(?:\/[^']*)?')/m.test(
37
+ withoutComments
38
+ )
39
+ }
40
+
41
+ function normalizeClasses(classes: string | Iterable<string>): string[] {
42
+ const classNames = typeof classes === 'string' ? [classes] : Array.from(classes)
43
+ return classNames
44
+ .flatMap((className) => className.split(/\s+/))
45
+ .map((className) => className.trim())
46
+ .filter((className) => className.length > 0)
47
+ }
48
+
49
+ async function loadTailwindStylesheet(id: string): Promise<string> {
50
+ const stylesheet = id === 'tailwindcss' ? 'tailwindcss/index.css' : id
51
+ const url = new URL(import.meta.resolve(stylesheet))
52
+ const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')
53
+ return readFile(url, 'utf8')
54
+ }