@pairdraw/design-jsx 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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -2
  3. package/dist/chunks/attributes.js +32 -0
  4. package/dist/chunks/attributes.js.map +1 -0
  5. package/dist/chunks/behaviours/elements.js +321 -0
  6. package/dist/chunks/behaviours/elements.js.map +1 -0
  7. package/dist/chunks/behaviours/render.js +368 -0
  8. package/dist/chunks/behaviours/render.js.map +1 -0
  9. package/dist/chunks/component-properties.js +809 -0
  10. package/dist/chunks/component-properties.js.map +1 -0
  11. package/dist/chunks/components.js +78 -0
  12. package/dist/chunks/components.js.map +1 -0
  13. package/dist/chunks/connectors.js +290 -0
  14. package/dist/chunks/connectors.js.map +1 -0
  15. package/dist/chunks/effects.js +57 -0
  16. package/dist/chunks/effects.js.map +1 -0
  17. package/dist/chunks/elements.js +618 -0
  18. package/dist/chunks/elements.js.map +1 -0
  19. package/dist/chunks/export/behaviours.js +113 -0
  20. package/dist/chunks/export/behaviours.js.map +1 -0
  21. package/dist/chunks/export/bindings.js +273 -0
  22. package/dist/chunks/export/bindings.js.map +1 -0
  23. package/dist/chunks/export/decoration.js +96 -0
  24. package/dist/chunks/export/decoration.js.map +1 -0
  25. package/dist/chunks/export/font.js +17 -0
  26. package/dist/chunks/export/font.js.map +1 -0
  27. package/dist/chunks/export/icons.js +34 -0
  28. package/dist/chunks/export/icons.js.map +1 -0
  29. package/dist/chunks/export/index.js +1390 -0
  30. package/dist/chunks/export/index.js.map +1 -0
  31. package/dist/chunks/fields.js +1065 -0
  32. package/dist/chunks/fields.js.map +1 -0
  33. package/dist/chunks/index.js +438 -0
  34. package/dist/chunks/index.js.map +1 -0
  35. package/dist/chunks/jsx-dev-runtime.js +16 -0
  36. package/dist/chunks/jsx-dev-runtime.js.map +1 -0
  37. package/dist/index.d.ts +543 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +11 -0
  40. package/dist/jsx-dev-runtime.d.ts +2 -0
  41. package/dist/jsx-dev-runtime.js +2 -0
  42. package/dist/jsx-runtime.d.ts +44 -0
  43. package/dist/jsx-runtime.d.ts.map +1 -0
  44. package/dist/jsx-runtime.js +2 -0
  45. package/dist/tree.d.ts +261 -0
  46. package/dist/tree.d.ts.map +1 -0
  47. package/package.json +66 -4
  48. package/src/attributes.ts +30 -0
  49. package/src/behaviours/elements.ts +47 -0
  50. package/src/behaviours/index.ts +253 -0
  51. package/src/behaviours/render.ts +144 -0
  52. package/src/component-properties.ts +428 -0
  53. package/src/components.ts +109 -0
  54. package/src/connectors.ts +316 -0
  55. package/src/definitions.ts +277 -0
  56. package/src/effects.ts +80 -0
  57. package/src/elements.ts +321 -0
  58. package/src/enums.ts +182 -0
  59. package/src/export/behaviours.ts +143 -0
  60. package/src/export/bindings.ts +155 -0
  61. package/src/export/decoration.ts +39 -0
  62. package/src/export/font.ts +25 -0
  63. package/src/export/helpers.ts +75 -0
  64. package/src/export/icons.ts +42 -0
  65. package/src/export/index.ts +297 -0
  66. package/src/export/paint.ts +276 -0
  67. package/src/export/props.ts +369 -0
  68. package/src/export/state.ts +52 -0
  69. package/src/export/text.ts +155 -0
  70. package/src/export/value.ts +99 -0
  71. package/src/export/variables.ts +393 -0
  72. package/src/fields.ts +39 -0
  73. package/src/figjam-text.ts +37 -0
  74. package/src/global.d.ts +4 -0
  75. package/src/helpers.ts +135 -0
  76. package/src/index.ts +155 -0
  77. package/src/jsx-dev-runtime.ts +1 -0
  78. package/src/jsx-runtime.ts +51 -0
  79. package/src/mini-react.ts +23 -0
  80. package/src/overrides/effects.ts +39 -0
  81. package/src/overrides/fills.ts +56 -0
  82. package/src/overrides/state.ts +55 -0
  83. package/src/overrides/strokes.ts +109 -0
  84. package/src/overrides/text.ts +116 -0
  85. package/src/overrides/vector.ts +122 -0
  86. package/src/paints.ts +230 -0
  87. package/src/props-overrides.ts +481 -0
  88. package/src/reconcile.ts +134 -0
  89. package/src/reference/authoring.md +76 -0
  90. package/src/reference/examples.ts +49 -0
  91. package/src/reference.ts +19 -0
  92. package/src/refs.ts +48 -0
  93. package/src/render.ts +147 -0
  94. package/src/renderer.ts +598 -0
  95. package/src/scalar-bindings.ts +36 -0
  96. package/src/schema.ts +213 -0
  97. package/src/services.ts +36 -0
  98. package/src/shapes-with-text.ts +73 -0
  99. package/src/stickies.ts +72 -0
  100. package/src/streaming/index.ts +47 -0
  101. package/src/streaming/literals.ts +82 -0
  102. package/src/streaming/projection.ts +189 -0
  103. package/src/text-content.ts +233 -0
  104. package/src/transform.ts +78 -0
  105. package/src/tree.ts +285 -0
  106. package/src/types.ts +13 -0
  107. package/src/variables/graph.ts +265 -0
  108. package/src/variables/index.ts +124 -0
  109. package/src/variables/props.ts +77 -0
@@ -0,0 +1,598 @@
1
+ import { omitBy } from 'es-toolkit/object'
2
+
3
+ import type { NodeType, SceneGraph, SceneNode, VariableModeMap } from '@pairdraw/scene-graph'
4
+ import { parseColor } from '@pairdraw/scene-graph/color'
5
+ import { setInstanceOverride } from '@pairdraw/scene-graph/instances/overrides'
6
+
7
+ import type { RekaScope } from './behaviours'
8
+ import { renderRekaNode } from './behaviours/render'
9
+ import {
10
+ assignComponentProperties,
11
+ assignNamedProperties,
12
+ bindProperties,
13
+ componentPropNames as namesOnInstance,
14
+ exposeInstance,
15
+ inferComponentSetProperties
16
+ } from './component-properties'
17
+ import { CONNECTOR_ELEMENT, resolveConnectorEnds } from './connectors'
18
+ import { elementNodeType, elementOwnLayer, type OwnLayerRenderer } from './elements'
19
+ import { placeVectorPaths } from './overrides/vector'
20
+ import { applySizeOverrides, propsToOverrides, shapeOverrides } from './props-overrides'
21
+ import { LayerRefs } from './refs'
22
+ import { prepareScalarBindings } from './scalar-bindings'
23
+ import { readElementProps } from './schema'
24
+ import type { DesignJSXServices } from './services'
25
+ import { isTextContent, TEXT_CONTENT_NAMES, textContentFields } from './text-content'
26
+ import { FRAGMENT, isTreeNode } from './tree'
27
+ import type { TreeNode } from './tree'
28
+ import type { RenderOptions } from './types'
29
+ import { isVariable } from './variables'
30
+ import {
31
+ applyVariableDefinitions,
32
+ bindVariableProp,
33
+ requireVariableId,
34
+ resolveForLayer,
35
+ variableModes,
36
+ type LayerContext
37
+ } from './variables/graph'
38
+ import { paintProps } from './variables/props'
39
+
40
+ export interface RenderResult {
41
+ id: string
42
+ name: string
43
+ type: NodeType
44
+ childIds: string[]
45
+ warnings?: string[]
46
+ }
47
+
48
+ /** The nodes a tree renders as: a fragment's children, or the tree itself. */
49
+ function treeRoots(tree: TreeNode): TreeNode[] {
50
+ return tree.type === FRAGMENT ? tree.children.filter(isTreeNode) : [tree]
51
+ }
52
+
53
+ /** Render every root of `tree` into the parent and lay out once. */
54
+ export async function renderRoots<Artwork>(
55
+ services: DesignJSXServices<Artwork>,
56
+ graph: SceneGraph,
57
+ tree: TreeNode,
58
+ options: RenderOptions = {}
59
+ ): Promise<RenderResult[]> {
60
+ const roots = treeRoots(tree)
61
+ if (roots.length === 0) throw new Error('JSX must return a Figma element (Frame, Text, etc)')
62
+ const parentId = options.parentId ?? graph.getPages()[0].id
63
+ applyVariableDefinitions(graph, tree)
64
+
65
+ const nodes: SceneNode[] = []
66
+ const connectors: Array<{ node: SceneNode; tree: TreeNode }> = []
67
+ const refs = new LayerRefs()
68
+ const onNode = (element: TreeNode, node: SceneNode) => {
69
+ if (element.type === CONNECTOR_ELEMENT) connectors.push({ node, tree: element })
70
+ else refs.mark(element.props.ref, node)
71
+ options.onNode?.(element, node)
72
+ }
73
+ for (const root of roots) {
74
+ const node = await renderNode(services, graph, root, parentId, onNode)
75
+ if (options.x !== undefined) graph.updateNode(node.id, { x: options.x })
76
+ if (options.y !== undefined) graph.updateNode(node.id, { y: options.y })
77
+ nodes.push(node)
78
+ }
79
+
80
+ const rootIds = nodes.map((node) => node.id)
81
+ const warnings = [...refs.warnings, ...resolveConnectorEnds(graph, rootIds, connectors, refs)]
82
+ if (!options.deferLayout) services.layout(graph, rootIds)
83
+
84
+ return nodes.map((node) => ({
85
+ id: node.id,
86
+ name: node.name,
87
+ type: node.type,
88
+ childIds: node.childIds,
89
+ ...(warnings.length > 0 && { warnings })
90
+ }))
91
+ }
92
+
93
+ /** Render `tree` and return its first root; a fragment's other roots are rendered too. */
94
+ export async function renderTree<Artwork>(
95
+ services: DesignJSXServices<Artwork>,
96
+ graph: SceneGraph,
97
+ tree: TreeNode,
98
+ options: RenderOptions = {}
99
+ ): Promise<RenderResult> {
100
+ const [first] = await renderRoots(services, graph, tree, options)
101
+ return first
102
+ }
103
+
104
+ interface PreparedProps {
105
+ props: Record<string, unknown>
106
+ bindings: Record<string, string>
107
+ }
108
+
109
+ function isObjectRecord(value: unknown): value is Record<string, unknown> {
110
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
111
+ }
112
+
113
+ function preparePropsForRender(
114
+ graph: SceneGraph,
115
+ source: Record<string, unknown>,
116
+ isText: boolean,
117
+ layer: LayerContext
118
+ ): PreparedProps {
119
+ const props = { ...source }
120
+ const bindings: Record<string, string> = {}
121
+
122
+ if (Array.isArray(props.fills)) {
123
+ props.fills = props.fills.map((value: unknown, index) => {
124
+ const fill = { value }
125
+ bindVariableProp(graph, fill, bindings, 'value', `fills/${index}/color`, layer)
126
+ return fill.value
127
+ })
128
+ }
129
+
130
+ for (const { prop, fields } of paintProps({ text: isText })) {
131
+ bindVariableProp(graph, props, bindings, prop, fields[0], layer)
132
+ }
133
+
134
+ if (isObjectRecord(props.style)) {
135
+ const style = { ...props.style }
136
+ for (const key of ['background', 'backgroundColor']) {
137
+ bindVariableProp(graph, style, bindings, key, 'fills/0/color', layer)
138
+ }
139
+ if (isText) bindVariableProp(graph, style, bindings, 'color', 'fills/0/color', layer)
140
+ bindVariableProp(graph, style, bindings, 'borderColor', 'strokes/0/color', layer)
141
+ props.style = style
142
+ }
143
+
144
+ prepareScalarBindings(graph, props, bindings, isText, (variableId) =>
145
+ resolveForLayer(graph, variableId, layer.parentId, layer.modes)
146
+ )
147
+
148
+ if (isObjectRecord(props.bind)) {
149
+ for (const [field, value] of Object.entries(props.bind)) {
150
+ if (isVariable(value)) {
151
+ bindings[field] = requireVariableId(graph, value)
152
+ } else if (typeof value === 'string') {
153
+ bindings[field] = value
154
+ }
155
+ }
156
+ }
157
+
158
+ return { props, bindings }
159
+ }
160
+
161
+ /**
162
+ * An element that draws its own layer. Its props are resolved as any layer's are, so a
163
+ * `designVar()` binds, and its layer props become fields as any layer's do; the element reads the
164
+ * rest itself.
165
+ */
166
+ function renderOwnLayerElement(
167
+ graph: SceneGraph,
168
+ tree: TreeNode,
169
+ parentId: string,
170
+ element: OwnLayerRenderer
171
+ ): SceneNode {
172
+ const modes = variableModes(graph, tree.props.mode)
173
+ const { props, bindings } = preparePropsForRender(graph, tree.props, false, { parentId, modes })
174
+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'
175
+ const layer = omitBy(
176
+ {
177
+ ...propsToOverrides(readElementProps(element.layer, props), false, parentLayout),
178
+ ...(modes && { variableModes: modes })
179
+ },
180
+ (value) => value === undefined
181
+ )
182
+ const node = element.render(graph, { ...tree, props }, parentId, layer)
183
+ for (const [field, variableId] of Object.entries(bindings)) {
184
+ graph.bindVariable(element.bindingTarget?.(graph, node, field) ?? node.id, field, variableId)
185
+ }
186
+ return node
187
+ }
188
+
189
+ function applyBindings(graph: SceneGraph, nodeId: string, bindings: Record<string, string>): void {
190
+ for (const [field, variableId] of Object.entries(bindings)) {
191
+ graph.bindVariable(nodeId, field, variableId)
192
+ }
193
+ }
194
+
195
+ function applyIconSize(
196
+ props: Record<string, unknown>,
197
+ overrides: Partial<SceneNode>,
198
+ parentLayout: SceneNode['layoutMode'],
199
+ size: number
200
+ ): void {
201
+ const { w, h } = applySizeOverrides(props, overrides, parentLayout)
202
+ if (typeof w !== 'number') overrides.width = size
203
+ if (typeof h !== 'number') overrides.height = size
204
+ }
205
+
206
+ async function renderIconNode<Artwork>(
207
+ services: DesignJSXServices<Artwork>,
208
+ graph: SceneGraph,
209
+ tree: TreeNode,
210
+ parentId: string
211
+ ): Promise<SceneNode> {
212
+ const props = tree.props
213
+ const iconName = props.name as string | undefined
214
+ if (!iconName) throw new Error('<Icon> requires a name prop (e.g. name="lucide:heart")')
215
+
216
+ const size = (props.size as number | undefined) ?? 24
217
+ const artwork = await services.icon(iconName, size)
218
+ if (!artwork) throw new Error(`Icon "${iconName}" not found`)
219
+ return placeArtwork(services, graph, artwork, props, size, parentId)
220
+ }
221
+
222
+ function placeArtwork<Artwork>(
223
+ services: DesignJSXServices<Artwork>,
224
+ graph: SceneGraph,
225
+ artwork: Artwork,
226
+ props: Record<string, unknown>,
227
+ size: number,
228
+ parentId: string
229
+ ): SceneNode {
230
+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'
231
+ const overrides: Partial<SceneNode> = {}
232
+ if (props.label) overrides.name = props.label as string
233
+ applyIconSize(props, overrides, parentLayout, size)
234
+ const modes = variableModes(graph, props.mode)
235
+ if (modes) overrides.variableModes = modes
236
+ const variableId = isVariable(props.color) ? requireVariableId(graph, props.color) : undefined
237
+ const resolved = variableId && resolveForLayer(graph, variableId, parentId, modes)
238
+ if (isVariable(props.color) && typeof resolved !== 'object')
239
+ throw new Error(`Cannot resolve color variable ${props.color.name} for color`)
240
+ const color =
241
+ typeof resolved === 'object'
242
+ ? resolved
243
+ : parseColor(typeof props.color === 'string' ? props.color : '#000000')
244
+ const node = services.createArtwork(graph, artwork, { parentId, size, color, overrides })
245
+ if (variableId) bindSolidPaints(graph, node, variableId)
246
+ return node
247
+ }
248
+
249
+ /** Bind every solid paint of an artwork's paths, so it follows the variable it was drawn in. */
250
+ function bindSolidPaints(graph: SceneGraph, node: SceneNode, variableId: string): void {
251
+ for (const field of ['fills', 'strokes'] as const) {
252
+ node[field].forEach((paint, index) => {
253
+ if (paint.type === 'SOLID') graph.bindVariable(node.id, `${field}/${index}/color`, variableId)
254
+ })
255
+ }
256
+ for (const child of graph.getChildren(node.id)) bindSolidPaints(graph, child, variableId)
257
+ }
258
+
259
+ /**
260
+ * Render an inline <svg> element into vector nodes through the same artwork path as
261
+ * icons. The body may be string children or a `body` prop; parsed shape children work too.
262
+ */
263
+ function renderSVGNode<Artwork>(
264
+ services: DesignJSXServices<Artwork>,
265
+ graph: SceneGraph,
266
+ tree: TreeNode,
267
+ parentId: string
268
+ ): SceneNode {
269
+ const props = tree.props
270
+ const explicitW = typeof props.w === 'number' ? props.w : 0
271
+ const explicitH = typeof props.h === 'number' ? props.h : 0
272
+ const size =
273
+ explicitW > 0 || explicitH > 0
274
+ ? Math.max(explicitW, explicitH)
275
+ : ((props.size as number | undefined) ?? 24)
276
+ const body =
277
+ (typeof props.body === 'string' && props.body) ||
278
+ tree.children.filter((c): c is string => typeof c === 'string').join('')
279
+ const artwork = services.svg({ body, elements: tree.children.filter(isTreeNode), props }, size)
280
+ if (!artwork) {
281
+ throw new Error('<svg> requires SVG markup, a body prop, or supported SVG shape children')
282
+ }
283
+ return placeArtwork(services, graph, artwork, props, size, parentId)
284
+ }
285
+
286
+ function findComponentByName(graph: SceneGraph, name: string): SceneNode | undefined {
287
+ for (const node of graph.getAllNodes()) {
288
+ if (node.type === 'COMPONENT' && node.name === name) return node
289
+ }
290
+ return undefined
291
+ }
292
+
293
+ function findVariantInSet(
294
+ graph: SceneGraph,
295
+ componentSet: SceneNode,
296
+ props: Record<string, unknown>
297
+ ) {
298
+ const requested = Object.fromEntries(
299
+ Object.entries(props)
300
+ .filter(([key]) =>
301
+ componentSet.componentPropertyDefinitions.some(
302
+ (definition) => definition.type === 'VARIANT' && definition.name === key
303
+ )
304
+ )
305
+ .map(([key, value]) => [key, String(value)])
306
+ )
307
+ const variants = graph.getChildren(componentSet.id).filter((node) => node.type === 'COMPONENT')
308
+ return (
309
+ variants.find((variant) =>
310
+ Object.entries(requested).every(
311
+ ([key, value]) => variant.componentPropertyValues[key] === value
312
+ )
313
+ ) ?? variants[0]
314
+ )
315
+ }
316
+
317
+ /** The component or component set an element names by id or name. */
318
+ function namedComponent(graph: SceneGraph, props: Record<string, unknown>): SceneNode | undefined {
319
+ const ref = props.component ?? props.componentId ?? props.of
320
+ if (typeof ref !== 'string') return undefined
321
+
322
+ const byId = graph.getNode(ref)
323
+ if (byId?.type === 'COMPONENT' || byId?.type === 'COMPONENT_SET') return byId
324
+
325
+ const byName = findComponentByName(graph, ref)
326
+ if (byName) return byName
327
+
328
+ for (const node of graph.getAllNodes()) {
329
+ if (node.type === 'COMPONENT_SET' && node.name === ref) return node
330
+ }
331
+ return undefined
332
+ }
333
+
334
+ function resolveComponent(
335
+ graph: SceneGraph,
336
+ props: Record<string, unknown>
337
+ ): SceneNode | undefined {
338
+ const named = namedComponent(graph, props)
339
+ return named?.type === 'COMPONENT_SET' ? findVariantInSet(graph, named, props) : named
340
+ }
341
+
342
+ /**
343
+ * The names an element sets on its component by prop: properties such as `State` or `Title`, and
344
+ * exposed instances.
345
+ */
346
+ export function componentPropNames(graph: SceneGraph, props: Record<string, unknown>): string[] {
347
+ const component = resolveComponent(graph, props)
348
+ return component ? namesOnInstance(graph, component) : []
349
+ }
350
+
351
+ async function renderInstanceNode(
352
+ graph: SceneGraph,
353
+ tree: TreeNode,
354
+ parentId: string
355
+ ): Promise<SceneNode> {
356
+ const parent = graph.getNode(parentId)
357
+ const parentLayout = parent?.layoutMode ?? 'NONE'
358
+ const modes = variableModes(graph, tree.props.mode)
359
+ const bound = bindProperties(graph, tree.props, 'INSTANCE', parentId, componentIdNamed(graph))
360
+ const { props, bindings } = preparePropsForRender(graph, bound.props, false, { parentId, modes })
361
+ const component = resolveComponent(graph, props)
362
+ if (!component) {
363
+ const ref = props.component ?? props.componentId ?? props.of
364
+ const label = typeof ref === 'string' || typeof ref === 'number' ? String(ref) : ''
365
+ throw new Error(`<Instance> component not found: ${label}`)
366
+ }
367
+ const overrides: Partial<SceneNode> = {
368
+ ...propsToOverrides(props, false, parentLayout),
369
+ ...layerMetadata(modes, bound.references)
370
+ }
371
+ // Instances inherit their container layout, but explicitly authored dimensions
372
+ // must also replace the inherited sizing mode on that axis.
373
+ const layout = overrides.layoutMode ?? component.layoutMode
374
+ if (layout !== 'NONE') {
375
+ const axes =
376
+ layout === 'HORIZONTAL'
377
+ ? (['primaryAxisSizing', 'counterAxisSizing'] as const)
378
+ : (['counterAxisSizing', 'primaryAxisSizing'] as const)
379
+ for (const [dimension, field] of [
380
+ ['w', axes[0]],
381
+ ['h', axes[1]]
382
+ ] as const) {
383
+ const value = props[dimension]
384
+ if (typeof value === 'number') overrides[field] = 'FIXED'
385
+ else if (value === 'hug' || value === 'fill') overrides[field] = 'HUG'
386
+ }
387
+ }
388
+ const instance =
389
+ graph.createInstance(component.id, parentId, overrides) ?? graph.createNode('FRAME', parentId)
390
+ try {
391
+ for (const [field, value] of Object.entries(overrides)) {
392
+ setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, field, value)
393
+ }
394
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
395
+ applyBindings(graph, instance.id, bindings)
396
+ applyInstanceOverrides(graph, instance, tree.props.overrides)
397
+ assignNamedProperties(graph, instance, props, componentIdNamed(graph))
398
+ assignComponentProperties(graph, instance, props.properties, componentIdNamed(graph))
399
+ if (props.exposed === true) exposeInstance(graph, instance)
400
+ return instance
401
+ } catch (error) {
402
+ graph.deleteNode(instance.id)
403
+ throw error
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Apply child overrides to a freshly created instance. Keys are
409
+ * `childName:prop` (e.g. 'label:text', 'icon:fills'); the child is resolved by
410
+ * name among the instance's descendants, and the value is applied to both the
411
+ * child node and the instance's overrides record so component sync keeps it.
412
+ */
413
+ function applyInstanceOverrides(
414
+ graph: SceneGraph,
415
+ instance: SceneNode,
416
+ overridesProp: unknown
417
+ ): void {
418
+ if (!overridesProp || typeof overridesProp !== 'object') return
419
+ if (Array.isArray(overridesProp)) return
420
+ const entries = Object.entries(overridesProp)
421
+ if (entries.length === 0) return
422
+
423
+ const descendants: SceneNode[] = []
424
+ const walk = (id: string) => {
425
+ const node = graph.getNode(id)
426
+ if (!node) return
427
+ descendants.push(node)
428
+ for (const cid of node.childIds) walk(cid)
429
+ }
430
+ walk(instance.id)
431
+
432
+ let mutated = false
433
+ for (const [key, value] of entries) {
434
+ const sep = key.indexOf(':')
435
+ if (sep === -1) continue
436
+ const childName = key.slice(0, sep)
437
+ const prop = key.slice(sep + 1)
438
+ const child = descendants.find((n) => n.name === childName)
439
+ if (!child || !(prop in child)) continue
440
+ graph.updateNode(child.id, { [prop]: value })
441
+ setInstanceOverride(instance.instanceOverrides, instance.id, child.id, prop, value)
442
+ mutated = true
443
+ }
444
+ if (mutated) {
445
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
446
+ }
447
+ }
448
+
449
+ async function renderArtworkNode<Artwork>(
450
+ services: DesignJSXServices<Artwork>,
451
+ graph: SceneGraph,
452
+ tree: TreeNode,
453
+ parentId: string
454
+ ): Promise<SceneNode> {
455
+ const bound = bindProperties(graph, tree.props, 'VECTOR', parentId, componentIdNamed(graph))
456
+ const artwork = { ...tree, props: bound.props }
457
+ const node =
458
+ tree.type === 'icon'
459
+ ? await renderIconNode(services, graph, artwork, parentId)
460
+ : renderSVGNode(services, graph, artwork, parentId)
461
+ const metadata: Partial<SceneNode> = layerMetadata(undefined, bound.references)
462
+ if (typeof bound.props.visible === 'boolean') metadata.visible = bound.props.visible
463
+ if (Object.keys(metadata).length > 0) graph.updateNode(node.id, metadata)
464
+ return node
465
+ }
466
+
467
+ /** The modes a layer pins and the component properties its fields are bound to. */
468
+ function layerMetadata(
469
+ modes: VariableModeMap | undefined,
470
+ references: SceneNode['componentPropertyReferences']
471
+ ): Partial<SceneNode> {
472
+ return {
473
+ ...(modes && { variableModes: modes }),
474
+ ...(references.length > 0 && { componentPropertyReferences: references })
475
+ }
476
+ }
477
+
478
+ /** The component a swap property's default names, by ID or name, as `<Instance of>` finds it. */
479
+ function componentIdNamed(graph: SceneGraph) {
480
+ return (name: string) => resolveComponent(graph, { of: name })?.id
481
+ }
482
+
483
+ export interface ElementOverrides {
484
+ overrides: Partial<SceneNode>
485
+ /** Variable IDs by bound field, such as `fills/0/color`. */
486
+ bindings: Record<string, string>
487
+ }
488
+
489
+ /** The fields and variable bindings an element's props set on a `nodeType` node under `parentId`. */
490
+ export function elementOverrides(
491
+ graph: SceneGraph,
492
+ nodeType: NodeType,
493
+ tree: TreeNode,
494
+ parentId: string
495
+ ): ElementOverrides {
496
+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'
497
+ const isText = nodeType === 'TEXT'
498
+ const modes = variableModes(graph, tree.props.mode)
499
+ const bound = bindProperties(graph, tree.props, nodeType, parentId, componentIdNamed(graph))
500
+ const layer = { parentId, modes }
501
+ const { props, bindings } = preparePropsForRender(graph, bound.props, isText, layer)
502
+ const overrides = {
503
+ ...propsToOverrides(props, isText, parentLayout),
504
+ ...shapeOverrides(nodeType, props),
505
+ ...layerMetadata(modes, bound.references)
506
+ }
507
+
508
+ if (isText) {
509
+ // A span's variables give their values; characters keep no bindings of their own.
510
+ const spanOverrides = (spanProps: Record<string, unknown>) =>
511
+ propsToOverrides(preparePropsForRender(graph, spanProps, true, layer).props, true, 'NONE')
512
+ Object.assign(overrides, textContentFields(tree, props, overrides, spanOverrides))
513
+ }
514
+ return { overrides, bindings }
515
+ }
516
+
517
+ async function renderNode<Artwork>(
518
+ services: DesignJSXServices<Artwork>,
519
+ graph: SceneGraph,
520
+ tree: TreeNode,
521
+ parentId: string,
522
+ onNode?: RenderOptions['onNode'],
523
+ scope?: RekaScope
524
+ ): Promise<SceneNode> {
525
+ const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope)
526
+ onNode?.(tree, node)
527
+ return node
528
+ }
529
+
530
+ /**
531
+ * The elements rendered their own way rather than as the layer their definition names, or null
532
+ * for any other element.
533
+ */
534
+ function renderOwnElement<Artwork>(
535
+ services: DesignJSXServices<Artwork>,
536
+ graph: SceneGraph,
537
+ tree: TreeNode,
538
+ parentId: string
539
+ ): Promise<SceneNode> | null {
540
+ switch (tree.type) {
541
+ case 'icon':
542
+ case 'svg':
543
+ return renderArtworkNode(services, graph, tree, parentId)
544
+ case 'instance':
545
+ return renderInstanceNode(graph, tree, parentId)
546
+ default: {
547
+ const element = elementOwnLayer(tree.type)
548
+ return element ? Promise.resolve(renderOwnLayerElement(graph, tree, parentId, element)) : null
549
+ }
550
+ }
551
+ }
552
+
553
+ async function renderNodeContent<Artwork>(
554
+ services: DesignJSXServices<Artwork>,
555
+ graph: SceneGraph,
556
+ tree: TreeNode,
557
+ parentId: string,
558
+ onNode?: RenderOptions['onNode'],
559
+ scope?: RekaScope
560
+ ): Promise<SceneNode> {
561
+ const own = renderOwnElement(services, graph, tree, parentId)
562
+ if (own) return own
563
+ const reka = await renderRekaNode(graph, tree, parentId, scope, {
564
+ render: (child, childParentId, childScope) =>
565
+ renderNode(services, graph, child, childParentId, onNode, childScope),
566
+ create: (nodeType, element, elementParentId) => {
567
+ const { overrides, bindings } = elementOverrides(graph, nodeType, element, elementParentId)
568
+ const created = graph.createNode(nodeType, elementParentId, overrides)
569
+ applyBindings(graph, created.id, bindings)
570
+ placeVectorPaths(graph, created, element.props, (network) => services.vectorBounds(network))
571
+ return created
572
+ },
573
+ instance: (element, elementParentId) => renderInstanceNode(graph, element, elementParentId),
574
+ finishSet: (setId) => inferComponentSetProperties(graph, setId)
575
+ })
576
+ if (reka) return reka
577
+
578
+ if (isTextContent(tree))
579
+ throw new Error(`<${TEXT_CONTENT_NAMES[tree.type]}> must be inside <Text>`)
580
+ const nodeType = elementNodeType(tree.type)
581
+ if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)
582
+
583
+ const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId)
584
+ const node = graph.createNode(nodeType, parentId, overrides)
585
+ applyBindings(graph, node.id, bindings)
586
+ placeVectorPaths(graph, node, tree.props, (network) => services.vectorBounds(network))
587
+
588
+ for (const child of tree.children) {
589
+ if (typeof child === 'string' || (node.type === 'TEXT' && isTextContent(child))) continue
590
+ if (isTreeNode(child)) {
591
+ await renderNode(services, graph, child, node.id, onNode, scope)
592
+ }
593
+ }
594
+
595
+ if (node.type === 'COMPONENT_SET') inferComponentSetProperties(graph, node.id)
596
+
597
+ return node
598
+ }
@@ -0,0 +1,36 @@
1
+ import type { SceneGraph, VariableLiteral } from '@pairdraw/scene-graph'
2
+
3
+ import { isVariable } from './variables'
4
+ import { requireVariableId } from './variables/graph'
5
+ import { scalarProps } from './variables/props'
6
+
7
+ /** Resolve numeric props before sizing inference; retain real graph bindings afterward. */
8
+ export function prepareScalarBindings(
9
+ graph: SceneGraph,
10
+ props: Record<string, unknown>,
11
+ bindings: Record<string, string>,
12
+ isText: boolean,
13
+ resolve: (variableId: string) => VariableLiteral | undefined
14
+ ): void {
15
+ const entries = scalarProps({ text: isText, grid: !!props.grid, wrap: !!props.wrap })
16
+ const scalarBindings = new Map<string, string>()
17
+ for (const { prop: key, fields } of entries) {
18
+ const value = props[key]
19
+ if (value === undefined) continue
20
+ // A literal longhand must also override a bound shorthand on that edge.
21
+ for (const field of fields) scalarBindings.delete(field)
22
+ if (!isVariable(value)) continue
23
+
24
+ const variable = graph.variables.get(requireVariableId(graph, value))
25
+ if (variable?.type !== 'FLOAT') {
26
+ throw new Error(`Expected a FLOAT variable for ${key}: ${value.name}`)
27
+ }
28
+ const resolved = resolve(variable.id)
29
+ if (typeof resolved !== 'number' || !Number.isFinite(resolved)) {
30
+ throw new TypeError(`Cannot resolve numeric variable for ${key}: ${value.name}`)
31
+ }
32
+ props[key] = resolved
33
+ for (const field of fields) scalarBindings.set(field, variable.id)
34
+ }
35
+ Object.assign(bindings, Object.fromEntries(scalarBindings))
36
+ }