@pairdraw/dom-css 0.0.0-stage → 0.16.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.
Files changed (137) 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 +1594 -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 +73 -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 +606 -0
  91. package/src/export/components/react/shared.ts +76 -0
  92. package/src/export/components/references.ts +212 -0
  93. package/src/export/components/repeats.ts +128 -0
  94. package/src/export/components/shaders.ts +125 -0
  95. package/src/export/components/styling.ts +31 -0
  96. package/src/export/components/tree.ts +72 -0
  97. package/src/export/components/vue.ts +517 -0
  98. package/src/export/css.ts +57 -0
  99. package/src/export/grid.ts +42 -0
  100. package/src/export/html.ts +163 -0
  101. package/src/export/index.ts +44 -0
  102. package/src/export/projection.ts +581 -0
  103. package/src/export/storybook/component.ts +334 -0
  104. package/src/export/storybook/export.ts +430 -0
  105. package/src/export/storybook/groups.ts +161 -0
  106. package/src/export/storybook/module.ts +319 -0
  107. package/src/export/storybook/names.ts +51 -0
  108. package/src/export/tailwind-jsx.ts +156 -0
  109. package/src/export/text.ts +415 -0
  110. package/src/import/css-text.ts +4 -0
  111. package/src/import/css-values.ts +31 -0
  112. package/src/import/flow.ts +248 -0
  113. package/src/import/html.ts +88 -0
  114. package/src/import/jsx/core.ts +130 -0
  115. package/src/import/jsx/dev-runtime.ts +8 -0
  116. package/src/import/jsx/runtime.ts +76 -0
  117. package/src/import/scene-graph.ts +582 -0
  118. package/src/import/style-attribute.ts +25 -0
  119. package/src/import/tailwind.ts +54 -0
  120. package/src/import/text.ts +518 -0
  121. package/src/index.ts +51 -0
  122. package/src/runtime/browser/runtime.ts +301 -0
  123. package/src/runtime/headless/runtime.ts +99 -0
  124. package/src/runtime/headless/styles.ts +330 -0
  125. package/src/runtime/index.ts +11 -0
  126. package/src/tokens/conditions.ts +66 -0
  127. package/src/tokens/cssom-validator.ts +8 -0
  128. package/src/tokens/custom-properties.ts +331 -0
  129. package/src/tokens/expression.ts +128 -0
  130. package/src/tokens/formula.ts +140 -0
  131. package/src/tokens/index.ts +43 -0
  132. package/src/tokens/names.ts +161 -0
  133. package/src/tokens/references.ts +201 -0
  134. package/src/tokens/stylesheet.ts +304 -0
  135. package/src/tokens/validate.ts +86 -0
  136. package/src/tokens/values.ts +44 -0
  137. package/src/types.ts +59 -0
@@ -0,0 +1,415 @@
1
+ import { isEqual } from 'es-toolkit/predicate'
2
+
3
+ import type { CharacterStyleOverride, HyperlinkTarget, SceneNode } from '@pairdraw/scene-graph'
4
+ import {
5
+ hasTextList,
6
+ listNumberFormat,
7
+ paragraphSpacingAt,
8
+ paragraphStyleAt,
9
+ textListItems,
10
+ textParagraphRanges,
11
+ type TextListItem,
12
+ type TextParagraphRange
13
+ } from '@pairdraw/scene-graph/text'
14
+
15
+ import type { DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
16
+ import { fillToCSS, letterSpacingToCSS, lineHeightToCSS } from './css'
17
+
18
+ /** The character styles CSS writes, as a text layer and its runs hold them. */
19
+ type CharacterStyle = Pick<
20
+ SceneNode,
21
+ | 'fontFamily'
22
+ | 'fontSize'
23
+ | 'fontWeight'
24
+ | 'italic'
25
+ | 'letterSpacing'
26
+ | 'lineHeight'
27
+ | 'fills'
28
+ | 'textDecoration'
29
+ | 'textDecorationStyle'
30
+ | 'textDecorationThickness'
31
+ | 'textDecorationFills'
32
+ | 'textDecorationSkipInk'
33
+ | 'textUnderlineOffset'
34
+ | 'textCase'
35
+ >
36
+
37
+ type CharacterStyleKey = keyof CharacterStyle
38
+
39
+ const CHARACTER_STYLE_KEYS: readonly CharacterStyleKey[] = [
40
+ 'fontFamily',
41
+ 'fontSize',
42
+ 'fontWeight',
43
+ 'italic',
44
+ 'letterSpacing',
45
+ 'lineHeight',
46
+ 'fills',
47
+ 'textDecoration',
48
+ 'textDecorationStyle',
49
+ 'textDecorationThickness',
50
+ 'textDecorationFills',
51
+ 'textDecorationSkipInk',
52
+ 'textUnderlineOffset',
53
+ 'textCase'
54
+ ]
55
+
56
+ /** A list's indent per level, in ems of its first character, as the canvas lays lists out. */
57
+ const LIST_INDENT_EMS = 1.5
58
+
59
+ const DECORATION_PROPERTIES = new Set([
60
+ 'text-decoration-line',
61
+ 'text-decoration-style',
62
+ 'text-decoration-color',
63
+ 'text-decoration-thickness',
64
+ 'text-underline-offset',
65
+ 'text-decoration-skip-ink'
66
+ ])
67
+
68
+ const px = (value: number) => `${value}px`
69
+
70
+ /** Characters `[start, end)`, the run style over them, and where they link to. */
71
+ interface StyledRange {
72
+ start: number
73
+ end: number
74
+ style: CharacterStyle
75
+ href: string | null
76
+ }
77
+
78
+ /** Links a page can follow: to the web, to mail, or to a phone; others are left out. */
79
+ const LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:'])
80
+
81
+ /** A link as an `href`, for a link to a URL a page can follow. */
82
+ function linkHref(link: HyperlinkTarget | null | undefined): string | null {
83
+ if (link?.type !== 'URL') return null
84
+ try {
85
+ return LINK_PROTOCOLS.has(new URL(link.value).protocol) ? link.value : null
86
+ } catch {
87
+ // Not an absolute URL, which a page could not follow from anywhere it is placed.
88
+ return null
89
+ }
90
+ }
91
+
92
+ export function textCaseToCSS(value: SceneNode['textCase']): string | undefined {
93
+ if (value === 'UPPER') return 'uppercase'
94
+ if (value === 'LOWER') return 'lowercase'
95
+ if (value === 'TITLE') return 'capitalize'
96
+ return undefined
97
+ }
98
+
99
+ function characterStyle(node: SceneNode, override: CharacterStyleOverride = {}): CharacterStyle {
100
+ const style = Object.fromEntries(CHARACTER_STYLE_KEYS.map((key) => [key, node[key]]))
101
+ for (const key of CHARACTER_STYLE_KEYS) {
102
+ const value = override[key]
103
+ if (value !== undefined) style[key] = value
104
+ }
105
+ return style as CharacterStyle
106
+ }
107
+
108
+ /** The text in ranges of one style each: the runs, and the layer's own style between them. */
109
+ function styledRanges(node: SceneNode): StyledRange[] {
110
+ const ranges: StyledRange[] = []
111
+ const base = characterStyle(node)
112
+ let at = 0
113
+ for (const run of node.styleRuns.toSorted((a, b) => a.start - b.start)) {
114
+ const start = Math.max(at, run.start)
115
+ const end = Math.min(node.text.length, run.start + run.length)
116
+ if (start > at) ranges.push({ start: at, end: start, style: base, href: null })
117
+ if (end > start) {
118
+ const href = linkHref(run.style.hyperlink)
119
+ ranges.push({ start, end, style: characterStyle(node, run.style), href })
120
+ }
121
+ at = Math.max(at, end)
122
+ }
123
+ if (at < node.text.length) {
124
+ ranges.push({ start: at, end: node.text.length, style: base, href: null })
125
+ }
126
+ return ranges
127
+ }
128
+
129
+ /** Underline or strikethrough as CSS writes it: Figma's offset is CSS's, from the baseline. */
130
+ function decorationCSS(style: CharacterStyle): DesignStyleDeclaration {
131
+ if (style.textDecoration === 'NONE') return {}
132
+ const underline = style.textDecoration === 'UNDERLINE'
133
+ const css: DesignStyleDeclaration = {
134
+ 'text-decoration-line': underline ? 'underline' : 'line-through'
135
+ }
136
+ if (style.textDecorationStyle !== 'SOLID') {
137
+ css['text-decoration-style'] = style.textDecorationStyle.toLowerCase()
138
+ }
139
+ const color = fillToCSS(style.textDecorationFills.find((fill) => fill.visible))
140
+ if (color) css['text-decoration-color'] = color
141
+ if (style.textDecorationThickness !== null) {
142
+ css['text-decoration-thickness'] = px(style.textDecorationThickness)
143
+ }
144
+ if (underline && style.textUnderlineOffset !== null) {
145
+ css['text-underline-offset'] = px(style.textUnderlineOffset)
146
+ }
147
+ if (underline && !style.textDecorationSkipInk) css['text-decoration-skip-ink'] = 'none'
148
+ return css
149
+ }
150
+
151
+ function characterCSS(style: CharacterStyle, decorated: boolean): DesignStyleDeclaration {
152
+ return {
153
+ color: fillToCSS(style.fills.at(0)) ?? '',
154
+ 'font-family': style.fontFamily,
155
+ 'font-size': px(style.fontSize),
156
+ 'font-weight': String(style.fontWeight),
157
+ 'font-style': style.italic ? 'italic' : 'normal',
158
+ 'letter-spacing': letterSpacingToCSS(style.letterSpacing),
159
+ 'line-height': style.lineHeight === null ? 'normal' : lineHeightToCSS(style.lineHeight),
160
+ 'text-transform': textCaseToCSS(style.textCase) ?? 'none',
161
+ ...(decorated ? decorationCSS(style) : {})
162
+ }
163
+ }
164
+
165
+ /** What `css` sets differently from `base`. */
166
+ function differing(
167
+ css: DesignStyleDeclaration,
168
+ base: DesignStyleDeclaration
169
+ ): DesignStyleDeclaration {
170
+ return Object.fromEntries(
171
+ Object.entries(css).filter(([property, value]) => value !== '' && base[property] !== value)
172
+ )
173
+ }
174
+
175
+ /**
176
+ * Whether the text decorates every character alike. CSS draws an element's decoration through
177
+ * its descendants, which cannot take it off, so mixed decorations go on the spans instead.
178
+ */
179
+ function uniformDecoration(node: SceneNode, ranges: readonly StyledRange[]): boolean {
180
+ const decorations = ranges
181
+ .filter((range) => node.text.slice(range.start, range.end).replaceAll('\n', '') !== '')
182
+ .map((range) => decorationCSS(range.style))
183
+ return decorations.every((decoration) => isEqual(decoration, decorations[0]))
184
+ }
185
+
186
+ interface TextProjection {
187
+ node: SceneNode
188
+ ranges: StyledRange[]
189
+ base: DesignStyleDeclaration
190
+ decorated: boolean
191
+ }
192
+
193
+ function textNode(text: string): DesignNode {
194
+ return { type: 'text', text }
195
+ }
196
+
197
+ function element(
198
+ tagName: string,
199
+ inlineStyle: DesignStyleDeclaration,
200
+ children: DesignNode[]
201
+ ): DesignElement {
202
+ return { type: 'element', tagName, attrs: {}, inlineStyle, children }
203
+ }
204
+
205
+ /**
206
+ * A link styled as the text around it: a link draws in the text's colour and with only the
207
+ * decoration its characters have, as in Figma, not in a browser's link style.
208
+ */
209
+ function linkElement(href: string, css: DesignStyleDeclaration, text: string): DesignElement {
210
+ const style = { color: 'inherit', 'text-decoration-line': 'none', ...css }
211
+ return { ...element('a', style, [textNode(text)]), attrs: { href } }
212
+ }
213
+
214
+ /**
215
+ * `text[start, end)` as text and spans, each span setting only what differs from the layer;
216
+ * linked characters are a link instead.
217
+ */
218
+ function inlineContent(projection: TextProjection, start: number, end: number): DesignNode[] {
219
+ const { node, ranges, base, decorated } = projection
220
+ const pieces: { css: DesignStyleDeclaration; text: string; href: string | null }[] = []
221
+ for (const range of ranges) {
222
+ const from = Math.max(start, range.start)
223
+ const to = Math.min(end, range.end)
224
+ if (to <= from) continue
225
+ const css = differing(characterCSS(range.style, !decorated), base)
226
+ const text = node.text.slice(from, to)
227
+ const previous = pieces.at(-1)
228
+ if (previous && previous.href === range.href && isEqual(previous.css, css)) {
229
+ previous.text += text
230
+ } else pieces.push({ css, text, href: range.href })
231
+ }
232
+ return pieces.map(({ css, text, href }) => {
233
+ if (href) return linkElement(href, css, text)
234
+ return Object.keys(css).length === 0 ? textNode(text) : element('span', css, [textNode(text)])
235
+ })
236
+ }
237
+
238
+ /** A paragraph's content; an empty one holds a line break, which gives it a line's height. */
239
+ function paragraphContent(projection: TextProjection, range: TextParagraphRange): DesignNode[] {
240
+ if (range.end === range.start) return [element('br', {}, [])]
241
+ return inlineContent(projection, range.start, range.end)
242
+ }
243
+
244
+ /** Text that CSS lays out in one element: no lists, and no spacing or indent between lines. */
245
+ function needsBlocks(node: SceneNode): boolean {
246
+ if (hasTextList(node)) return true
247
+ const paragraphs = textParagraphRanges(node.text)
248
+ return paragraphs.some(
249
+ (_, index) =>
250
+ paragraphSpacingAt(node, index, 'paragraphIndent') > 0 ||
251
+ (index < paragraphs.length - 1 && paragraphSpacingAt(node, index, 'paragraphSpacing') > 0)
252
+ )
253
+ }
254
+
255
+ /** The space after paragraph `index`: list spacing between two items, paragraph spacing else. */
256
+ function spaceAfter(node: SceneNode, index: number, count: number): number {
257
+ if (index >= count - 1) return 0
258
+ const betweenItems =
259
+ paragraphStyleAt(node.textParagraphs, index).listType !== 'NONE' &&
260
+ paragraphStyleAt(node.textParagraphs, index + 1).listType !== 'NONE'
261
+ return paragraphSpacingAt(node, index, betweenItems ? 'listSpacing' : 'paragraphSpacing')
262
+ }
263
+
264
+ function listStyleType(item: TextListItem): string {
265
+ if (item.listType === 'UNORDERED') return 'disc'
266
+ const format = listNumberFormat(item.level)
267
+ if (format === 'LOWER_ALPHA') return 'lower-alpha'
268
+ if (format === 'LOWER_ROMAN') return 'lower-roman'
269
+ return 'decimal'
270
+ }
271
+
272
+ /** A list in the text, open at one level, with the item that nested lists go into. */
273
+ interface OpenList {
274
+ level: number
275
+ listType: TextListItem['listType']
276
+ element: DesignElement
277
+ item: DesignElement | undefined
278
+ }
279
+
280
+ /** Where the next list item goes: closes lists deeper than it, or of another kind at its level. */
281
+ function closeListsFor(open: OpenList[], item: TextListItem): void {
282
+ while ((open.at(-1)?.level ?? 0) > item.level) open.pop()
283
+ const top = open.at(-1)
284
+ if (top?.level === item.level && (top.listType !== item.listType || item.startsList)) open.pop()
285
+ }
286
+
287
+ /**
288
+ * Opens a list one level below the innermost open one, inside its last item; a level an item
289
+ * skips gets an item without a marker to hold it.
290
+ */
291
+ function openList(
292
+ open: OpenList[],
293
+ blocks: DesignNode[],
294
+ item: TextListItem,
295
+ indent: number
296
+ ): void {
297
+ const parent = open.at(-1)
298
+ const level = (parent?.level ?? 0) + 1
299
+ const list = element(
300
+ item.listType === 'ORDERED' ? 'ol' : 'ul',
301
+ {
302
+ ...blockMargins(0, 0),
303
+ 'padding-inline-start': px(indent),
304
+ 'list-style-type': level === item.level ? listStyleType(item) : 'none'
305
+ },
306
+ []
307
+ )
308
+ if (parent) {
309
+ parent.item ??= appendTo(parent.element, element('li', { 'list-style-type': 'none' }, []))
310
+ // The space after the item the list nests in stands above the list.
311
+ const spacing = parent.item.inlineStyle?.['margin-bottom']
312
+ if (spacing && parent.item.inlineStyle && list.inlineStyle) {
313
+ delete parent.item.inlineStyle['margin-bottom']
314
+ list.inlineStyle['margin-top'] = spacing
315
+ }
316
+ parent.item.children.push(list)
317
+ } else blocks.push(list)
318
+ open.push({ level, listType: item.listType, element: list, item: undefined })
319
+ }
320
+
321
+ function plainParagraph(
322
+ projection: TextProjection,
323
+ index: number,
324
+ range: TextParagraphRange,
325
+ after: number
326
+ ): DesignElement {
327
+ const style = blockMargins(0, after)
328
+ const indent = paragraphSpacingAt(projection.node, index, 'paragraphIndent')
329
+ if (indent > 0) style['text-indent'] = px(indent)
330
+ return element('p', style, paragraphContent(projection, range))
331
+ }
332
+
333
+ /**
334
+ * The text as blocks, as Figma lays it out: a paragraph per plain one, lists nested by level
335
+ * with Figma's markers (bullets at every level, numbers counting 1, a, i as they nest), and the
336
+ * space after each paragraph as a margin on what ends it.
337
+ */
338
+ function blockContent(projection: TextProjection): DesignNode[] {
339
+ const { node } = projection
340
+ const paragraphs = textParagraphRanges(node.text)
341
+ const items = new Map(
342
+ textListItems(node.text, node.textParagraphs).map((item) => [item.paragraph, item])
343
+ )
344
+ const blocks: DesignNode[] = []
345
+ const open: OpenList[] = []
346
+ for (const [index, range] of paragraphs.entries()) {
347
+ const after = spaceAfter(node, index, paragraphs.length)
348
+ const item = items.get(index)
349
+ if (!item) {
350
+ open.length = 0
351
+ blocks.push(plainParagraph(projection, index, range, after))
352
+ continue
353
+ }
354
+ const unit = groupEm(projection, paragraphs, item) * LIST_INDENT_EMS
355
+ closeListsFor(open, item)
356
+ while ((open.at(-1)?.level ?? 0) < item.level) {
357
+ // A hanging list's markers stand outside the text, so its first level has no indent.
358
+ const first = open.length === 0
359
+ openList(open, blocks, item, first && node.hangingList ? 0 : unit)
360
+ }
361
+ const list = open.at(-1)
362
+ if (!list) continue
363
+ const style: DesignStyleDeclaration = after > 0 ? { 'margin-bottom': px(after) } : {}
364
+ list.item = appendTo(list.element, element('li', style, paragraphContent(projection, range)))
365
+ }
366
+ return blocks
367
+ }
368
+
369
+ /** Margins above and below a block, written out: paragraphs and lists have their own in CSS. */
370
+ function blockMargins(top: number, bottom: number): DesignStyleDeclaration {
371
+ return { 'margin-top': px(top), 'margin-bottom': px(bottom) }
372
+ }
373
+
374
+ function appendTo(parent: DesignElement, child: DesignElement): DesignElement {
375
+ parent.children.push(child)
376
+ return child
377
+ }
378
+
379
+ /** The size of a list's first character, which its indents are measured in. */
380
+ function groupEm(
381
+ projection: TextProjection,
382
+ paragraphs: readonly TextParagraphRange[],
383
+ item: TextListItem
384
+ ): number {
385
+ const at = paragraphs[item.groupStart]?.start ?? item.start
386
+ const range = projection.ranges.find((candidate) => at >= candidate.start && at < candidate.end)
387
+ return range?.style.fontSize ?? projection.node.fontSize
388
+ }
389
+
390
+ /**
391
+ * A text layer's element: its tag, its style with the decoration the whole text shares, and
392
+ * its content. Runs of characters styled apart become spans; text with lists, paragraph
393
+ * spacing, or a first-line indent becomes blocks, which a `<div>` holds.
394
+ */
395
+ export function textElementContent(
396
+ node: SceneNode,
397
+ layerStyle: DesignStyleDeclaration
398
+ ): { tagName: string; style: DesignStyleDeclaration; children: DesignNode[] } {
399
+ const ranges = styledRanges(node)
400
+ const decorated = uniformDecoration(node, ranges)
401
+ const style = Object.fromEntries(
402
+ Object.entries(layerStyle).filter(([property]) => !DECORATION_PROPERTIES.has(property))
403
+ )
404
+ if (decorated) Object.assign(style, decorationCSS(characterStyle(node)))
405
+ const projection: TextProjection = {
406
+ node,
407
+ ranges,
408
+ base: characterCSS(characterStyle(node), decorated),
409
+ decorated
410
+ }
411
+ if (!needsBlocks(node)) {
412
+ return { tagName: 'span', style, children: inlineContent(projection, 0, node.text.length) }
413
+ }
414
+ return { tagName: 'div', style, children: blockContent(projection) }
415
+ }
@@ -0,0 +1,4 @@
1
+ export function mergeCSSText(...parts: Array<string | undefined>): string | undefined {
2
+ const text = parts.map((part) => part?.trim()).filter((part): part is string => !!part)
3
+ return text.length > 0 ? text.join('\n') : undefined
4
+ }
@@ -0,0 +1,31 @@
1
+ import type { Fill, Stroke } from '@pairdraw/scene-graph'
2
+ import { parseCSSColor, parseCSSNumber } from '@pairdraw/scene-graph/css'
3
+
4
+ import type { DesignStyleDeclaration } from '../types'
5
+
6
+ export function colorToFillFromCSS(value: string | undefined): Fill[] {
7
+ const color = parseCSSColor(value)
8
+ if (!color) return []
9
+ return [{ type: 'SOLID', color, opacity: color.a, visible: true }]
10
+ }
11
+
12
+ export function colorToStrokeFromCSS(
13
+ colorValue: string | undefined,
14
+ weightValue: string | undefined
15
+ ): Stroke[] {
16
+ const color = parseCSSColor(colorValue)
17
+ const weight = parseCSSNumber(weightValue)
18
+ if (!color || weight === null || weight <= 0) return []
19
+ return [{ type: 'SOLID', color, weight, opacity: color.a, visible: true, align: 'INSIDE' }]
20
+ }
21
+
22
+ export function pickStyle(elementStyle: DesignStyleDeclaration | undefined, property: string) {
23
+ return elementStyle?.[property]
24
+ }
25
+
26
+ export function mergedStyle(node: {
27
+ inlineStyle?: DesignStyleDeclaration
28
+ computedStyle?: DesignStyleDeclaration
29
+ }) {
30
+ return { ...node.inlineStyle, ...node.computedStyle }
31
+ }
@@ -0,0 +1,248 @@
1
+ import { pick } from 'es-toolkit'
2
+
3
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
4
+ import {
5
+ parseCSSAlignItems,
6
+ parseCSSFlexDirection,
7
+ parseCSSJustifyContent,
8
+ parseCSSNumber
9
+ } from '@pairdraw/scene-graph/css'
10
+ import {
11
+ autoLayoutSizingFields,
12
+ fillSizingFields,
13
+ layoutSizing,
14
+ textAutoResizeFor
15
+ } from '@pairdraw/scene-graph/layout'
16
+
17
+ import type { DesignElement, DesignStyleDeclaration } from '../types'
18
+ import { pickStyle } from './css-values'
19
+
20
+ /**
21
+ * How CSS lays an element and its children out, mapped onto auto layout: block flow stacks
22
+ * children vertically and stretches block-level ones across, a flex container is a stack in its
23
+ * direction that stretches items across by default, and inline-level content hugs.
24
+ */
25
+ export type FlowKind = 'block' | 'flex' | 'inline'
26
+
27
+ /** The layout a child is placed in: its parent's flow, or none at the top of the page. */
28
+ export type ParentFlow = FlowKind | 'none'
29
+
30
+ /** Tags browsers lay out in a line by default. */
31
+ export const INLINE_TAGS = new Set([
32
+ 'a',
33
+ 'abbr',
34
+ 'b',
35
+ 'code',
36
+ 'del',
37
+ 'em',
38
+ 'i',
39
+ 'ins',
40
+ 'kbd',
41
+ 'label',
42
+ 'mark',
43
+ 's',
44
+ 'small',
45
+ 'span',
46
+ 'strong',
47
+ 'sub',
48
+ 'sup',
49
+ 'u'
50
+ ])
51
+ const INLINE_BLOCK_TAGS = new Set(['button', 'img', 'input', 'select', 'textarea'])
52
+ /** Elements browsers center their text in by default. */
53
+ const CENTERED_TAGS = new Set(['button'])
54
+
55
+ /** What a run of text takes from its element: the properties CSS inherits, and decoration. */
56
+ const TEXT_PROPERTIES = [
57
+ 'color',
58
+ 'font-family',
59
+ 'font-size',
60
+ 'font-style',
61
+ 'font-weight',
62
+ 'letter-spacing',
63
+ 'line-height',
64
+ 'text-align',
65
+ 'text-decoration-line',
66
+ 'text-shadow',
67
+ 'text-transform',
68
+ 'white-space'
69
+ ]
70
+
71
+ /**
72
+ * The style a run of text directly inside an element takes from it. The element's own box,
73
+ * position, and opacity stay on the element, so the text is neither placed nor faded twice.
74
+ */
75
+ export function inheritedTextStyle(
76
+ element: DesignElement,
77
+ style: DesignStyleDeclaration
78
+ ): DesignStyleDeclaration {
79
+ const inherited = pick(style, TEXT_PROPERTIES)
80
+ if (!inherited['text-align'] && CENTERED_TAGS.has(element.tagName.toLowerCase())) {
81
+ inherited['text-align'] = 'center'
82
+ }
83
+ return inherited
84
+ }
85
+
86
+ /** The element's `display`, or the one browsers give its tag by default. */
87
+ export function elementDisplay(element: DesignElement, style: DesignStyleDeclaration): string {
88
+ const display = pickStyle(style, 'display')?.trim().toLowerCase()
89
+ if (display) return display
90
+ const tag = element.tagName.toLowerCase()
91
+ if (INLINE_TAGS.has(tag)) return 'inline'
92
+ return INLINE_BLOCK_TAGS.has(tag) ? 'inline-block' : 'block'
93
+ }
94
+
95
+ /**
96
+ * The flow an element lays its own children out in. An `inline-block` sits in a line but holds
97
+ * a block of its own, so only a plain `inline` element lays its children out in a line.
98
+ */
99
+ export function flowOf(display: string): FlowKind {
100
+ if (display === 'flex' || display === 'inline-flex') return 'flex'
101
+ return display === 'inline' ? 'inline' : 'block'
102
+ }
103
+
104
+ /** Whether the element sits in a line rather than on its own row, so it hugs its content. */
105
+ function isInlineLevel(display: string): boolean {
106
+ return display.startsWith('inline')
107
+ }
108
+
109
+ function textAlignAxis(element: DesignElement, style: DesignStyleDeclaration) {
110
+ const align = pickStyle(style, 'text-align')?.trim().toLowerCase()
111
+ if (align === 'center') return 'CENTER'
112
+ if (align === 'right' || align === 'end') return 'MAX'
113
+ if (align) return 'MIN'
114
+ return CENTERED_TAGS.has(element.tagName.toLowerCase()) ? 'CENTER' : 'MIN'
115
+ }
116
+
117
+ /** The auto layout an element's own flow gives its children. */
118
+ export function applyContainerLayout(
119
+ node: SceneNode,
120
+ element: DesignElement,
121
+ style: DesignStyleDeclaration,
122
+ flow: FlowKind
123
+ ): void {
124
+ if (flow === 'flex') {
125
+ node.layoutMode = parseCSSFlexDirection(pickStyle(style, 'flex-direction')) ?? 'HORIZONTAL'
126
+ node.primaryAxisAlign = parseCSSJustifyContent(pickStyle(style, 'justify-content')) ?? 'MIN'
127
+ // Flex items stretch across the container unless `align-items` says otherwise.
128
+ node.counterAxisAlign = parseCSSAlignItems(pickStyle(style, 'align-items')) ?? 'STRETCH'
129
+ node.layoutWrap = pickStyle(style, 'flex-wrap') === 'wrap' ? 'WRAP' : 'NO_WRAP'
130
+ return
131
+ }
132
+ if (flow === 'block') {
133
+ node.layoutMode = 'VERTICAL'
134
+ // Browsers center a button's content both ways.
135
+ if (CENTERED_TAGS.has(element.tagName.toLowerCase())) {
136
+ node.primaryAxisAlign = 'CENTER'
137
+ node.counterAxisAlign = 'CENTER'
138
+ }
139
+ return
140
+ }
141
+ // Inline content runs in a line, aligned by `text-align`.
142
+ node.layoutMode = 'HORIZONTAL'
143
+ node.primaryAxisAlign = textAlignAxis(element, style)
144
+ node.counterAxisAlign = 'CENTER'
145
+ }
146
+
147
+ function grows(style: DesignStyleDeclaration): boolean {
148
+ const grow = parseCSSNumber(pickStyle(style, 'flex-grow'))
149
+ if (grow !== null) return grow > 0
150
+ const flex = pickStyle(style, 'flex')?.trim().split(/\s+/)[0]
151
+ if (flex === 'auto') return true
152
+ const shorthand = parseCSSNumber(flex)
153
+ return shorthand !== null && shorthand > 0
154
+ }
155
+
156
+ function isFullSize(style: DesignStyleDeclaration, property: 'width' | 'height'): boolean {
157
+ return pickStyle(style, property)?.trim() === '100%'
158
+ }
159
+
160
+ interface BoxSize {
161
+ fixedWidth: boolean
162
+ fixedHeight: boolean
163
+ }
164
+
165
+ /** Fill from the parent's flow: block children across, growing items along, `100%` either way. */
166
+ function applyParentFill(
167
+ graph: SceneGraph,
168
+ node: SceneNode,
169
+ style: DesignStyleDeclaration,
170
+ display: string,
171
+ parentFlow: ParentFlow,
172
+ { fixedWidth, fixedHeight }: BoxSize
173
+ ): void {
174
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
175
+ const parentLayout = parent?.layoutMode ?? 'NONE'
176
+ if (!parent || parentLayout === 'NONE' || node.layoutPositioning === 'ABSOLUTE') return
177
+ const fill = (axis: 'HORIZONTAL' | 'VERTICAL') =>
178
+ Object.assign(node, fillSizingFields(parentLayout, axis))
179
+ const mainAxis = parentLayout === 'VERTICAL' ? 'VERTICAL' : 'HORIZONTAL'
180
+ // A box sized to its content, as an inline-block, a flex item, or an absolute box is, has no
181
+ // width of its own for block children to fill; they size it instead.
182
+ const block = parentFlow === 'block' && !isInlineLevel(display) && !fixedWidth
183
+ if (block && hasDefiniteWidth(graph, parent)) fill('HORIZONTAL')
184
+ if (parentFlow === 'flex' && grows(style)) fill(mainAxis)
185
+ if (isFullSize(style, 'width')) fill('HORIZONTAL')
186
+ if (isFullSize(style, 'height')) fill('VERTICAL')
187
+ if (parentFlow === 'flex') keepFixedCrossSize(node, parent, mainAxis, { fixedWidth, fixedHeight })
188
+ }
189
+
190
+ /** An item with its own cross size keeps it in a stretching flex container, as in CSS. */
191
+ function keepFixedCrossSize(
192
+ node: SceneNode,
193
+ parent: SceneNode,
194
+ mainAxis: 'HORIZONTAL' | 'VERTICAL',
195
+ { fixedWidth, fixedHeight }: BoxSize
196
+ ): void {
197
+ const crossFixed = mainAxis === 'VERTICAL' ? fixedWidth : fixedHeight
198
+ const inheritsStretch = node.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH'
199
+ if (crossFixed && inheritsStretch) node.layoutAlignSelf = 'MIN'
200
+ }
201
+
202
+ function hasDefiniteWidth(graph: SceneGraph, node: SceneNode): boolean {
203
+ return layoutSizing(graph, node, 'HORIZONTAL') !== 'HUG'
204
+ }
205
+
206
+ /**
207
+ * Text wraps where its width is fixed or fills a parent with a width of its own, and hugs its
208
+ * content otherwise. It is measured when the document is laid out.
209
+ */
210
+ function applyTextSizing(graph: SceneGraph, node: SceneNode, size: BoxSize): void {
211
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
212
+ const fillsWidth =
213
+ parent !== undefined &&
214
+ hasDefiniteWidth(graph, parent) &&
215
+ layoutSizing(graph, node, 'HORIZONTAL') === 'FILL'
216
+ const wraps = size.fixedWidth || fillsWidth
217
+ node.textAutoResize = wraps ? textAutoResizeFor(false, !size.fixedHeight) : 'WIDTH_AND_HEIGHT'
218
+ // Wrapping text starts at its content's width.
219
+ if (!size.fixedWidth) node.width = 0
220
+ if (!size.fixedHeight) node.height = 0
221
+ }
222
+
223
+ /**
224
+ * How a child sizes in its parent's flow, as CSS sizes it: an explicit size is fixed, block-level
225
+ * children of block flow and items of a stretching flex container fill across, a growing flex
226
+ * item fills along, `100%` fills, and everything else hugs. Text that fills its width wraps.
227
+ */
228
+ export function applyFlowSizing(
229
+ graph: SceneGraph,
230
+ node: SceneNode,
231
+ style: DesignStyleDeclaration,
232
+ display: string,
233
+ parentFlow: ParentFlow
234
+ ): void {
235
+ const size: BoxSize = {
236
+ fixedWidth: parseCSSNumber(pickStyle(style, 'width')) !== null,
237
+ fixedHeight: parseCSSNumber(pickStyle(style, 'height')) !== null
238
+ }
239
+ if (node.layoutMode !== 'NONE' && node.layoutMode !== 'GRID') {
240
+ const own = (fixed: boolean) => (fixed ? 'FIXED' : 'HUG')
241
+ Object.assign(
242
+ node,
243
+ autoLayoutSizingFields(node.layoutMode, own(size.fixedWidth), own(size.fixedHeight))
244
+ )
245
+ }
246
+ applyParentFill(graph, node, style, display, parentFlow, size)
247
+ if (node.type === 'TEXT') applyTextSizing(graph, node, size)
248
+ }