@pairdraw/dom-css 0.21.1 → 0.22.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 (37) hide show
  1. package/dist/chunks/behaviours/states/layers.js +78 -12
  2. package/dist/chunks/behaviours/states/layers.js.map +1 -1
  3. package/dist/chunks/browser.js +373 -37
  4. package/dist/chunks/browser.js.map +1 -1
  5. package/dist/chunks/import/html.js +66 -11
  6. package/dist/chunks/import/html.js.map +1 -1
  7. package/dist/chunks/import/jsx/source/ast.js +207 -0
  8. package/dist/chunks/import/jsx/source/ast.js.map +1 -0
  9. package/dist/chunks/import/jsx/source/candidates.js +74 -0
  10. package/dist/chunks/import/jsx/source/candidates.js.map +1 -0
  11. package/dist/chunks/import/jsx/source/evaluate.js +213 -0
  12. package/dist/chunks/import/jsx/source/evaluate.js.map +1 -0
  13. package/dist/chunks/import/jsx/source/index.js +448 -0
  14. package/dist/chunks/import/jsx/source/index.js.map +1 -0
  15. package/dist/export.d.ts +15 -2
  16. package/dist/export.js +2 -2
  17. package/dist/index.d.ts +66 -1
  18. package/dist/index.js +5 -2
  19. package/package.json +5 -3
  20. package/src/cssom/browser.ts +63 -0
  21. package/src/export/css.ts +28 -1
  22. package/src/export/index.ts +1 -0
  23. package/src/export/projection.ts +69 -10
  24. package/src/import/flow.ts +127 -6
  25. package/src/import/jsx/source/ast.ts +267 -0
  26. package/src/import/jsx/source/candidates.ts +72 -0
  27. package/src/import/jsx/source/evaluate.ts +300 -0
  28. package/src/import/jsx/source/index.ts +36 -0
  29. package/src/import/jsx/source/render.ts +543 -0
  30. package/src/import/jsx/source/report.ts +49 -0
  31. package/src/import/scene-graph.ts +19 -7
  32. package/src/index.ts +10 -0
  33. package/src/runtime/browser/runtime.ts +13 -5
  34. package/src/runtime/browser/sandbox.ts +176 -27
  35. package/src/runtime/css/scan.ts +45 -0
  36. package/src/runtime/css/url.ts +92 -0
  37. package/src/runtime/headless/styles.ts +71 -15
@@ -0,0 +1,543 @@
1
+ import type { DesignNode, DesignStyleDeclaration } from '#dom-css/types'
2
+ import type {
3
+ ArrayExpression,
4
+ CallExpression,
5
+ ConditionalExpression,
6
+ ExportNamedDeclaration,
7
+ ExpressionStatement,
8
+ FunctionDeclaration,
9
+ IfStatement,
10
+ Identifier,
11
+ LogicalExpression,
12
+ ModuleDeclaration,
13
+ Node,
14
+ ObjectExpression,
15
+ Program,
16
+ Statement,
17
+ VariableDeclaration
18
+ } from 'acorn'
19
+
20
+ import {
21
+ calleeName,
22
+ declarationOf,
23
+ drawsElements,
24
+ isLiteralFunction,
25
+ expressionText,
26
+ functionNode,
27
+ isElementCall,
28
+ memberName,
29
+ pascalCase,
30
+ propertyKey,
31
+ UNKNOWN,
32
+ type Env,
33
+ type LiteralFunction,
34
+ type LiteralValue
35
+ } from './ast'
36
+ import { CLASS_HELPERS, bindParams, evaluate, mergeClasses, truthy } from './evaluate'
37
+ import { CodeTooLargeError, MAX_CODE_ELEMENTS, type CodeReport } from './report'
38
+
39
+ /** Attributes a layer has a place for; the rest of an element's props are counted as dropped. */
40
+ const KEPT_ATTRIBUTES = new Set([
41
+ 'id',
42
+ 'href',
43
+ 'src',
44
+ 'alt',
45
+ 'srcset',
46
+ 'title',
47
+ 'type',
48
+ 'value',
49
+ 'placeholder',
50
+ 'name',
51
+ 'role',
52
+ 'for',
53
+ 'lang',
54
+ 'rows',
55
+ 'cols'
56
+ ])
57
+
58
+ /** A declaration's name. Acorn types it as required; a pasted `export default function () {}` has none. */
59
+ interface IdHolder extends Node {
60
+ id?: Identifier | null
61
+ }
62
+
63
+ const MAX_EXPANDED_ITEMS = 100
64
+ const MAX_COMPONENT_DEPTH = 16
65
+
66
+ export interface RenderState {
67
+ report: CodeReport
68
+ /** Top-level functions of the pasted module, by name. */
69
+ components: Map<string, LiteralFunction>
70
+ depth: number
71
+ /** Elements drawn so far, bounded by `MAX_CODE_ELEMENTS`. */
72
+ elements: number
73
+ }
74
+
75
+ /** The trees the paste stands for: its default export, its last exported component, or all of them. */
76
+ export function renderRoots(program: Program, env: Env, state: RenderState): DesignNode[] {
77
+ const defaultExport = program.body.find(
78
+ (statement) => statement.type === 'ExportDefaultDeclaration'
79
+ )
80
+ if (defaultExport) return renderExported(defaultExport.declaration, env, state)
81
+ const exported = program.body.filter(
82
+ (statement) => statement.type === 'ExportNamedDeclaration' && statement.declaration !== null
83
+ )
84
+ const lastExport = exported.at(-1)
85
+ if (lastExport) {
86
+ const declaration = (lastExport as ExportNamedDeclaration).declaration
87
+ if (declaration) {
88
+ const rendered = renderExported(declaration, env, state)
89
+ if (rendered.length > 0) return rendered
90
+ }
91
+ }
92
+ const expressions = program.body.filter(
93
+ (statement) => statement.type === 'ExpressionStatement' && isElementCall(statement.expression)
94
+ )
95
+ const lastExpression = expressions.at(-1)
96
+ if (lastExpression) {
97
+ return renderExpression((lastExpression as ExpressionStatement).expression, env, state)
98
+ }
99
+ // A pasted component library defines several components and exports none as its default.
100
+ const rendered: DesignNode[] = []
101
+ for (const component of state.components.values()) {
102
+ if (rendered.length >= MAX_EXPANDED_ITEMS) break
103
+ rendered.push(...nameAfterComponent(component.name, renderFunction(component, [], state)))
104
+ }
105
+ return rendered
106
+ }
107
+
108
+ /** Every top-level function that builds an element, so a component the source defines expands. */
109
+ export function collectComponents(program: Program, env: Env): Map<string, LiteralFunction> {
110
+ const components = new Map<string, LiteralFunction>()
111
+ for (const statement of program.body) {
112
+ const target = declarationOf(statement)
113
+ if (target?.type === 'FunctionDeclaration') {
114
+ addFunction(components, target as FunctionDeclaration, env)
115
+ continue
116
+ }
117
+ if (target?.type !== 'VariableDeclaration') continue
118
+ for (const declarator of (target as VariableDeclaration).declarations) {
119
+ if (declarator.id.type !== 'Identifier') continue
120
+ const init = declarator.init
121
+ if (!init) continue
122
+ const fn = functionNode(init)
123
+ if (!fn) continue
124
+ addNamedFunction(components, declarator.id.name, fn, env)
125
+ }
126
+ }
127
+ return components
128
+ }
129
+
130
+ function addFunction(
131
+ components: Map<string, LiteralFunction>,
132
+ node: FunctionDeclaration,
133
+ env: Env
134
+ ): void {
135
+ const id = (node as IdHolder).id
136
+ if (id) addNamedFunction(components, id.name, node, env)
137
+ }
138
+
139
+ function addNamedFunction(
140
+ components: Map<string, LiteralFunction>,
141
+ name: string,
142
+ node: LiteralFunction['node'],
143
+ env: Env
144
+ ): void {
145
+ if (!drawsElements(node)) return
146
+ components.set(name, { kind: 'function', node, env, name })
147
+ }
148
+
149
+ /** Module-scope `const` values, read as literals; anything else stays unknown. */
150
+ export function collectBindings(statement: Statement | ModuleDeclaration, env: Env): void {
151
+ if (statement.type !== 'VariableDeclaration') return
152
+ for (const declarator of statement.declarations) {
153
+ if (declarator.id.type !== 'Identifier') continue
154
+ const init = declarator.init
155
+ if (!init) continue
156
+ const name = declarator.id.name
157
+ const callable = functionNode(init)
158
+ if (callable) {
159
+ env.set(name, { kind: 'function', node: callable, env, name })
160
+ continue
161
+ }
162
+ const value = evaluate(init, env)
163
+ if (value !== null) env.set(name, value)
164
+ }
165
+ }
166
+
167
+ function renderExported(declaration: Node, env: Env, state: RenderState): DesignNode[] {
168
+ if (!drawsElements(declaration)) return []
169
+ const component = functionNode(declaration)
170
+ if (component) {
171
+ const id = component.type === 'FunctionDeclaration' ? (component as IdHolder).id : null
172
+ const name = id?.name ?? ''
173
+ const known = name ? state.components.get(name) : undefined
174
+ return renderFunction(known ?? { kind: 'function', node: component, env, name }, [], state)
175
+ }
176
+ const value = evaluate(declaration, env)
177
+ if (isLiteralFunction(value)) return renderFunction(value, [], state)
178
+ return renderExpression(declaration, env, state)
179
+ }
180
+
181
+ /** A component's rendered tree, with its parameters bound to the values a call passes. */
182
+ export function renderFunction(
183
+ component: LiteralFunction,
184
+ args: (LiteralValue | null)[],
185
+ state: RenderState
186
+ ): DesignNode[] {
187
+ if (state.depth >= MAX_COMPONENT_DEPTH) {
188
+ state.report.approximations += 1
189
+ return [{ type: 'text', text: `{${component.name ?? 'component'}}` }]
190
+ }
191
+ const env: Env = new Map(component.env)
192
+ bindParams(component.node, args, env)
193
+ const depth = state.depth
194
+ state.depth = depth + 1
195
+ try {
196
+ return renderBody(component.node, env, state)
197
+ } finally {
198
+ state.depth = depth
199
+ }
200
+ }
201
+
202
+ function renderBody(node: LiteralFunction['node'], env: Env, state: RenderState): DesignNode[] {
203
+ if (node.body.type !== 'BlockStatement') return renderExpression(node.body, env, state)
204
+ return runStatements(node.body.body, env, state) ?? []
205
+ }
206
+
207
+ /** The tree a block's statements end with, reading only what JavaScript would collect. */
208
+ function runStatements(statements: Statement[], env: Env, state: RenderState): DesignNode[] | null {
209
+ for (const statement of statements) {
210
+ if (statement.type === 'VariableDeclaration') {
211
+ collectBindings(statement, env)
212
+ continue
213
+ }
214
+ if (statement.type === 'ReturnStatement') {
215
+ const argument = statement.argument
216
+ return argument ? renderExpression(argument, env, state) : []
217
+ }
218
+ if (statement.type !== 'IfStatement') continue
219
+ const nested = renderBranch(statement, env, state)
220
+ if (nested) return nested
221
+ }
222
+ return null
223
+ }
224
+
225
+ function renderBranch(statement: IfStatement, env: Env, state: RenderState): DesignNode[] | null {
226
+ const test = evaluate(statement.test, env)
227
+ if (test === null) {
228
+ state.report.approximations += 1
229
+ return null
230
+ }
231
+ const branch = truthy(test) ? statement.consequent : statement.alternate
232
+ if (!branch) return null
233
+ return branch.type === 'BlockStatement'
234
+ ? runStatements(branch.body, env, state)
235
+ : runStatements([branch], env, state)
236
+ }
237
+
238
+ /** The nodes an expression draws: elements, an array of them, or text. */
239
+ export function renderExpression(node: Node, env: Env, state: RenderState): DesignNode[] {
240
+ if (isElementCall(node)) return renderElement(node as CallExpression, env, state)
241
+ const drawn = renderComposite(node, env, state)
242
+ if (drawn) return drawn
243
+ const value = evaluate(node, env)
244
+ return value === null ? placeholder(node, state) : literalNodes(value)
245
+ }
246
+
247
+ /** Expressions that stand for other expressions rather than for one value. */
248
+ function renderComposite(node: Node, env: Env, state: RenderState): DesignNode[] | null {
249
+ if (node.type === 'ArrayExpression') {
250
+ return (node as ArrayExpression).elements.flatMap((element) =>
251
+ element && element.type !== 'SpreadElement' ? renderExpression(element, env, state) : []
252
+ )
253
+ }
254
+ if (node.type === 'ConditionalExpression')
255
+ return renderChoice(node as ConditionalExpression, env, state)
256
+ if (node.type === 'LogicalExpression') return renderLogical(node as LogicalExpression, env, state)
257
+ if (node.type === 'CallExpression') return renderMapped(node as CallExpression, env, state)
258
+ if (node.type !== 'Identifier') return null
259
+ const value = env.get((node as Identifier).name)
260
+ if (value === undefined || value === UNKNOWN) return placeholder(node, state)
261
+ return literalNodes(value)
262
+ }
263
+
264
+ function renderChoice(node: ConditionalExpression, env: Env, state: RenderState): DesignNode[] {
265
+ const test = evaluate(node.test, env)
266
+ if (test === null) state.report.approximations += 1
267
+ const chosen = test === null || truthy(test) ? node.consequent : node.alternate
268
+ return renderExpression(chosen, env, state)
269
+ }
270
+
271
+ function renderLogical(node: LogicalExpression, env: Env, state: RenderState): DesignNode[] {
272
+ const left = evaluate(node.left, env)
273
+ if (node.operator === '&&') {
274
+ if (left === null) state.report.approximations += 1
275
+ return truthy(left) ? renderExpression(node.right, env, state) : []
276
+ }
277
+ return left !== null && truthy(left)
278
+ ? renderExpression(node.left, env, state)
279
+ : renderExpression(node.right, env, state)
280
+ }
281
+
282
+ /** `items.map((item) => <li>{item.label}</li>)` over a literal array, one element per item. */
283
+ function renderMapped(node: CallExpression, env: Env, state: RenderState): DesignNode[] | null {
284
+ if (node.callee.type !== 'MemberExpression') return null
285
+ const member = node.callee
286
+ const isMap =
287
+ !member.computed && member.property.type === 'Identifier' && member.property.name === 'map'
288
+ if (!isMap) return null
289
+ const items = evaluate(member.object, env)
290
+ if (!Array.isArray(items)) return null
291
+ const callback = node.arguments.at(0)
292
+ if (!callback) return null
293
+ const fn = functionNode(callback)
294
+ if (!fn) return null
295
+
296
+ if (items.length > MAX_EXPANDED_ITEMS) state.report.approximations += 1
297
+ const rendered: DesignNode[] = []
298
+ for (const item of items.slice(0, MAX_EXPANDED_ITEMS)) {
299
+ const callbackEnv: Env = new Map(env)
300
+ const first = fn.params.at(0)
301
+ if (first?.type === 'Identifier') callbackEnv.set(first.name, item)
302
+ const nodes =
303
+ fn.body.type === 'BlockStatement'
304
+ ? (runStatements(fn.body.body, callbackEnv, state) ?? [])
305
+ : renderExpression(fn.body, callbackEnv, state)
306
+ rendered.push(...nodes)
307
+ }
308
+ return rendered
309
+ }
310
+
311
+ /** One `__h(tag, props, …children)` call as a layer. */
312
+ function renderElement(call: CallExpression, env: Env, state: RenderState): DesignNode[] {
313
+ state.elements += 1
314
+ if (state.elements > MAX_CODE_ELEMENTS) {
315
+ throw new CodeTooLargeError(
316
+ `The paste draws more than ${MAX_CODE_ELEMENTS} layers; paste a smaller part of it.`
317
+ )
318
+ }
319
+ const tag = call.arguments.at(0)
320
+ const propsNode = call.arguments.at(1) ?? null
321
+ const props = propsNode ? readProps(propsNode, env, state) : { attrs: {} }
322
+ const children = call.arguments
323
+ .slice(2)
324
+ .flatMap((child) => (child.type === 'SpreadElement' ? [] : renderExpression(child, env, state)))
325
+ if (!tag || tag.type === 'SpreadElement') return children
326
+
327
+ if (tag.type === 'Identifier') {
328
+ const name = tag.name
329
+ if (name === '__fragment') return children
330
+ const component = state.components.get(name) ?? env.get(name)
331
+ if (isLiteralFunction(component)) {
332
+ const passed = propsNode ? evaluate(propsNode, env) : {}
333
+ const first =
334
+ passed !== null && typeof passed === 'object' && !Array.isArray(passed) ? passed : null
335
+ return renderFunction(component, [first], state)
336
+ }
337
+ return [componentFrame(name, componentProps(props, state), children, state)]
338
+ }
339
+ const name = tag.type === 'MemberExpression' ? memberName(tag) : undefined
340
+ const value = name ? undefined : evaluate(tag, env)
341
+ if (typeof value !== 'string') {
342
+ const frameName = name ?? expressionText(tag)
343
+ return [componentFrame(frameName, componentProps(props, state), children, state)]
344
+ }
345
+
346
+ const element = elementNode(value, props, children)
347
+ if (value.toLowerCase() === 'img') state.report.imagesAsPlaceholders += 1
348
+ return [element]
349
+ }
350
+
351
+ /** Props an element keeps, with what it has no place for counted. */
352
+ interface ReadProps {
353
+ class?: string
354
+ style?: DesignStyleDeclaration
355
+ attrs: Record<string, string>
356
+ }
357
+
358
+ function readProps(node: Node, env: Env, state: RenderState): ReadProps {
359
+ if (node.type !== 'ObjectExpression') {
360
+ state.report.droppedProps += 1
361
+ return { attrs: {} }
362
+ }
363
+ const props: ReadProps = { attrs: {} }
364
+ for (const property of (node as ObjectExpression).properties) {
365
+ if (property.type === 'SpreadElement') {
366
+ // `{...props}` names whatever a caller passes, which a paste does not have.
367
+ state.report.droppedProps += 1
368
+ continue
369
+ }
370
+ const name = propertyKey(property)
371
+ if (!name || name === 'key' || name.startsWith('on')) continue
372
+ readProperty(name, property.value, props, env, state)
373
+ }
374
+ return props
375
+ }
376
+
377
+ function readProperty(
378
+ name: string,
379
+ value: Node,
380
+ props: ReadProps,
381
+ env: Env,
382
+ state: RenderState
383
+ ): void {
384
+ if (name === 'className' || name === 'class') {
385
+ const classes = readClasses(value, env, state)
386
+ if (classes) props.class = classes
387
+ return
388
+ }
389
+ if (name === 'style') {
390
+ const style = readStyle(value, env)
391
+ if (style) props.style = style
392
+ return
393
+ }
394
+ const kept = attributeValue(value, env)
395
+ if (kept !== null) {
396
+ if (isKeptAttribute(name)) props.attrs[name] = kept
397
+ else state.report.droppedProps += 1
398
+ return
399
+ }
400
+ if (isKeptAttribute(name)) {
401
+ // A value only the paste's own code could know, on an attribute a layer keeps.
402
+ props.attrs[name] = `{${expressionText(value)}}`
403
+ state.report.placeholders += 1
404
+ return
405
+ }
406
+ state.report.droppedProps += 1
407
+ }
408
+
409
+ function isKeptAttribute(name: string): boolean {
410
+ return name.startsWith('data-') || name.startsWith('aria-') || KEPT_ATTRIBUTES.has(name)
411
+ }
412
+
413
+ /** `cn("flex", cond && "gap-2")` read as one class list, leaving out arguments it cannot know. */
414
+ function readClasses(node: Node, env: Env, state: RenderState): string | undefined {
415
+ const value = evaluate(node, env)
416
+ const text = classesOf(value)
417
+ if (text !== undefined) return text
418
+ if (
419
+ node.type === 'CallExpression' &&
420
+ CLASS_HELPERS.has(calleeName(node as CallExpression) ?? '')
421
+ ) {
422
+ return mergeClasses(node as CallExpression, env) || undefined
423
+ }
424
+ if (node.type === 'ConditionalExpression')
425
+ return readClassChoice(node as ConditionalExpression, env, state)
426
+ if (node.type === 'LogicalExpression')
427
+ return readClassLogical(node as LogicalExpression, env, state)
428
+ if (value === null) state.report.approximations += 1
429
+ return undefined
430
+ }
431
+
432
+ function classesOf(value: LiteralValue | null): string | undefined {
433
+ if (typeof value === 'string') return value || undefined
434
+ if (!Array.isArray(value)) return undefined
435
+ const names = value.filter((entry): entry is string => typeof entry === 'string')
436
+ return names.length > 0 ? names.join(' ') : undefined
437
+ }
438
+
439
+ function readClassChoice(
440
+ node: ConditionalExpression,
441
+ env: Env,
442
+ state: RenderState
443
+ ): string | undefined {
444
+ const test = evaluate(node.test, env)
445
+ if (test === null) state.report.approximations += 1
446
+ return readClasses(test === null || truthy(test) ? node.consequent : node.alternate, env, state)
447
+ }
448
+
449
+ function readClassLogical(
450
+ node: LogicalExpression,
451
+ env: Env,
452
+ state: RenderState
453
+ ): string | undefined {
454
+ const left = evaluate(node.left, env)
455
+ if (node.operator === '&&') {
456
+ if (left === null) state.report.approximations += 1
457
+ return truthy(left) ? readClasses(node.right, env, state) : undefined
458
+ }
459
+ return readClasses(node.right, env, state)
460
+ }
461
+
462
+ function readStyle(node: Node, env: Env): DesignStyleDeclaration | undefined {
463
+ const value = evaluate(node, env)
464
+ if (typeof value === 'string') return styleFromText(value)
465
+ if (value === null || typeof value !== 'object' || Array.isArray(value) || 'kind' in value) {
466
+ return undefined
467
+ }
468
+ const declaration: DesignStyleDeclaration = {}
469
+ for (const [property, entry] of Object.entries(value)) {
470
+ if (typeof entry === 'object') continue
471
+ declaration[cssProperty(property)] = String(entry)
472
+ }
473
+ return Object.keys(declaration).length > 0 ? declaration : undefined
474
+ }
475
+
476
+ function styleFromText(value: string): DesignStyleDeclaration | undefined {
477
+ const declaration: DesignStyleDeclaration = {}
478
+ for (const part of value.split(';')) {
479
+ const colon = part.indexOf(':')
480
+ if (colon === -1) continue
481
+ const property = cssProperty(part.slice(0, colon).trim())
482
+ const entry = part.slice(colon + 1).trim()
483
+ if (property && entry) declaration[property] = entry
484
+ }
485
+ return Object.keys(declaration).length > 0 ? declaration : undefined
486
+ }
487
+
488
+ function cssProperty(name: string): string {
489
+ if (name.startsWith('--')) return name
490
+ return name.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`)
491
+ }
492
+
493
+ function attributeValue(node: Node, env: Env): string | null {
494
+ const value = evaluate(node, env)
495
+ if (value === null || typeof value === 'object') return null
496
+ return String(value)
497
+ }
498
+
499
+ function elementNode(tag: string, props: ReadProps, children: DesignNode[]): DesignNode {
500
+ const attrs: Record<string, string> = { 'data-name': pascalCase(tag), ...props.attrs }
501
+ if (props.class) attrs.class = props.class
502
+ return { type: 'element', tagName: tag.toLowerCase(), attrs, inlineStyle: props.style, children }
503
+ }
504
+
505
+ function componentFrame(
506
+ name: string,
507
+ props: ReadProps,
508
+ children: DesignNode[],
509
+ state: RenderState
510
+ ): DesignNode {
511
+ state.report.componentsAsFrames += 1
512
+ const attrs: Record<string, string> = { 'data-name': name, ...props.attrs }
513
+ if (props.class) attrs.class = props.class
514
+ return { type: 'element', tagName: 'div', attrs, inlineStyle: props.style, children }
515
+ }
516
+
517
+ /** A component's props an element would hold have no place on a frame; only classes carry over. */
518
+ function componentProps(props: ReadProps, state: RenderState): ReadProps {
519
+ state.report.droppedProps += Object.keys(props.attrs).length
520
+ return { class: props.class, style: props.style, attrs: {} }
521
+ }
522
+
523
+ /** A component's rendered roots take its name, so the layer tree says which component drew them. */
524
+ function nameAfterComponent(name: string | undefined, nodes: DesignNode[]): DesignNode[] {
525
+ if (!name) return nodes
526
+ const first = nodes.at(0)
527
+ if (first?.type !== 'element') return nodes
528
+ const rest = nodes.slice(1)
529
+ return [{ ...first, attrs: { ...first.attrs, 'data-name': name } }, ...rest]
530
+ }
531
+
532
+ function placeholder(node: Node, state: RenderState): DesignNode[] {
533
+ state.report.placeholders += 1
534
+ return [{ type: 'text', text: `{${expressionText(node)}}` }]
535
+ }
536
+
537
+ function literalNodes(value: LiteralValue): DesignNode[] {
538
+ if (typeof value === 'string') return value.trim() ? [{ type: 'text', text: value }] : []
539
+ if (typeof value === 'number' || typeof value === 'boolean') {
540
+ return [{ type: 'text', text: String(value) }]
541
+ }
542
+ return []
543
+ }
@@ -0,0 +1,49 @@
1
+ import type { DesignNode } from '#dom-css/types'
2
+
3
+ /** Pasted source that a reader cannot turn into layers. */
4
+ export class CodeSourceError extends Error {
5
+ constructor(message: string) {
6
+ super(message)
7
+ this.name = 'CodeSourceError'
8
+ }
9
+ }
10
+
11
+ /** The most layers one paste may draw, so a pathological source cannot stall a document. */
12
+ export const MAX_CODE_ELEMENTS = 2_000
13
+
14
+ /** Pasted source that draws more than a document should take, which a paste refuses by size. */
15
+ export class CodeTooLargeError extends CodeSourceError {
16
+ constructor(message: string) {
17
+ super(message)
18
+ this.name = 'CodeTooLargeError'
19
+ }
20
+ }
21
+
22
+ /** What a paste could not keep, so the caller can tell the user in one toast. */
23
+ export interface CodeReport {
24
+ /** Expressions rendered as their own source text. */
25
+ placeholders: number
26
+ /** Components with no definition in the paste, drawn as frames under their name. */
27
+ componentsAsFrames: number
28
+ /** Attributes an element has no layer property for, and props no component could take. */
29
+ droppedProps: number
30
+ /** Branches and values read from one possibility rather than known exactly. */
31
+ approximations: number
32
+ /** Images whose source a paste cannot load, drawn at their box size. */
33
+ imagesAsPlaceholders: number
34
+ }
35
+
36
+ export interface CodeTree {
37
+ children: DesignNode[]
38
+ report: CodeReport
39
+ }
40
+
41
+ export function emptyReport(): CodeReport {
42
+ return {
43
+ placeholders: 0,
44
+ componentsAsFrames: 0,
45
+ droppedProps: 0,
46
+ approximations: 0,
47
+ imagesAsPlaceholders: 0
48
+ }
49
+ }
@@ -1,5 +1,5 @@
1
1
  import { pick } from 'es-toolkit'
2
- import { isValid, toUint8Array } from 'js-base64'
2
+ import { decode, isValid, toUint8Array } from 'js-base64'
3
3
 
4
4
  import {
5
5
  SceneGraph,
@@ -22,6 +22,7 @@ import { colorToStrokeFromCSS, mergedStyle, pickStyle } from './css-values'
22
22
  import {
23
23
  applyContainerLayout,
24
24
  applyFlowSizing,
25
+ applyGridPlacement,
25
26
  elementDisplay,
26
27
  flowOf,
27
28
  inheritedTextStyle,
@@ -262,10 +263,15 @@ function applyCornerRadii(node: SceneNode, style: DesignStyleDeclaration): void
262
263
  ].some((radius) => radius !== fallback)
263
264
  }
264
265
 
265
- function applyFlexGap(node: SceneNode, style: DesignStyleDeclaration): void {
266
+ function applyAutoLayoutGap(node: SceneNode, style: DesignStyleDeclaration): void {
266
267
  const gap = firstCSSNumber(style, 'gap')
267
268
  const rowGap = firstCSSNumber(style, 'row-gap')
268
269
  const columnGap = firstCSSNumber(style, 'column-gap')
270
+ if (node.layoutMode === 'GRID') {
271
+ node.gridColumnGap = columnGap ?? gap ?? 0
272
+ node.gridRowGap = rowGap ?? gap ?? 0
273
+ return
274
+ }
269
275
  const isHorizontal = node.layoutMode === 'HORIZONTAL'
270
276
  const isWrapped = node.layoutWrap === 'WRAP'
271
277
 
@@ -351,7 +357,10 @@ function applyImageFill(
351
357
  style: DesignStyleDeclaration
352
358
  ): void {
353
359
  if (element.tagName.toLowerCase() !== 'img') return
354
- const source = element.attrs.src
360
+ // The styling pass keeps an address it must not load as a data attribute; it is still the node's
361
+ // image source, so a paste keeps the picture even when it cannot be fetched.
362
+ const kept = element.attrs['data-image-source-b64']
363
+ const source = element.attrs.src || (kept && isValid(kept) ? decode(kept) : undefined)
355
364
  const bytes = bytesFromDataURL(source)
356
365
  if (!bytes) {
357
366
  if (source) {
@@ -387,6 +396,7 @@ function applyElementStyle(
387
396
  applyBoxSizing(node, style)
388
397
  applyPositioning(node, style)
389
398
  applyPadding(node, style)
399
+ applyGridPlacement(node, style)
390
400
 
391
401
  const background = backgroundPaint(graph, style, node)
392
402
  if (background.fills.length > 0) node.fills = background.fills
@@ -627,8 +637,9 @@ function holdsInlineBoxes(element: DesignElement): boolean {
627
637
  /** The flow a box lays its children out in, and whether they are one text instead. */
628
638
  function containerFlow(element: DesignElement, display: string) {
629
639
  // A box without content keeps its own size, as an image does, unless it declares a layout.
630
- const own = hasContent(element) || flowOf(display) === 'flex' ? flowOf(display) : null
631
- const richText = own !== 'flex' && holdsRichText(element)
640
+ const flowKind = flowOf(display)
641
+ const own = hasContent(element) || flowKind === 'flex' || flowKind === 'grid' ? flowKind : null
642
+ const richText = own !== 'flex' && own !== 'grid' && holdsRichText(element)
632
643
  // Inline content that cannot be one text runs in lines that wrap at the block's width.
633
644
  const lines = own === 'block' && !richText && holdsInlineBoxes(element)
634
645
  const flow: FlowKind | null = lines ? 'inline' : own
@@ -643,7 +654,8 @@ function paintChildren(
643
654
  style: DesignStyleDeclaration,
644
655
  flow: ParentFlow
645
656
  ): void {
646
- const children = flow === 'flex' ? element.children.toSorted(byFlexOrder) : element.children
657
+ const children =
658
+ flow === 'flex' || flow === 'grid' ? element.children.toSorted(byFlexOrder) : element.children
647
659
  const painted: PaintedChild[] = []
648
660
  for (const child of children) {
649
661
  const layer = createDesignNode(graph, node.id, child, flow, inheritedTextStyle(element, style))
@@ -684,7 +696,7 @@ function createElementNode(
684
696
  const { flow, richText, lines } = containerFlow(element, display)
685
697
  if (flow) {
686
698
  applyContainerLayout(node, element, style, flow)
687
- if (flow === 'flex') applyFlexGap(node, style)
699
+ if (flow === 'flex' || flow === 'grid') applyAutoLayoutGap(node, style)
688
700
  if (lines) node.layoutWrap = 'WRAP'
689
701
  }
690
702
  applyFlowSizing(graph, node, style, display, parentFlow)
package/src/index.ts CHANGED
@@ -10,6 +10,16 @@ export {
10
10
  tailwindHTMLToSceneGraph
11
11
  } from './import/html'
12
12
  export { compileTailwindCSS } from './import/tailwind'
13
+ export { decodedCSS, mentionsResource, mentionsURL, withoutResourceRules } from './runtime/css/url'
14
+ export {
15
+ CodeSourceError,
16
+ CodeTooLargeError,
17
+ MAX_CODE_ELEMENTS,
18
+ jsxSourceToTree,
19
+ tailwindCandidates,
20
+ tailwindUtilities
21
+ } from './import/jsx/source'
22
+ export type { CodeReport, CodeTree } from './import/jsx/source'
13
23
  export {
14
24
  jsxToDesignDocument,
15
25
  jsxToSceneGraph,