@pairdraw/design-jsx 0.19.1 → 0.20.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.
package/src/effects.ts CHANGED
@@ -1,6 +1,17 @@
1
- import type { BlendMode, Effect } from '@pairdraw/scene-graph'
1
+ import type {
2
+ BlendMode,
3
+ Effect,
4
+ NoiseEffectParams,
5
+ TextureEffectParams
6
+ } from '@pairdraw/scene-graph'
2
7
  import { parseColor } from '@pairdraw/scene-graph/color'
3
- import { TRANSPARENT } from '@pairdraw/scene-graph/constants'
8
+ import {
9
+ BLACK,
10
+ DEFAULT_NOISE,
11
+ DEFAULT_NOISE_COLOR,
12
+ DEFAULT_TEXTURE,
13
+ TRANSPARENT
14
+ } from '@pairdraw/scene-graph/constants'
4
15
  import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
5
16
 
6
17
  import { BLEND_MODE } from './enums'
@@ -86,3 +97,71 @@ export function backgroundBlur(radiusOrOptions?: number | BlurEffectOptions): Ef
86
97
  export function foregroundBlur(radiusOrOptions?: number | BlurEffectOptions): Effect {
87
98
  return blurEffect('FOREGROUND_BLUR', radiusOrOptions)
88
99
  }
100
+
101
+ /** A grain size as Figma's plugin API takes it, one number for both axes, or each axis apart. */
102
+ export type NoiseSize = number | Vector
103
+
104
+ /**
105
+ * A noise effect in Figma's terms: grains in `color`, a duotone's `secondaryColor` too, or a
106
+ * multitone's many colours at `opacity`. Left out, each value is what Figma's panel starts with.
107
+ */
108
+ export interface NoiseEffectOptions extends Partial<
109
+ Omit<NoiseEffectParams, 'noiseSize' | 'secondaryColor'>
110
+ > {
111
+ noiseSize?: NoiseSize
112
+ color?: EffectColor
113
+ secondaryColor?: EffectColor
114
+ visible?: boolean
115
+ }
116
+
117
+ /** A texture effect in Figma's terms, `radius` being how far its grain moves the edges. */
118
+ export interface TextureEffectOptions extends Partial<Omit<TextureEffectParams, 'noiseSize'>> {
119
+ noiseSize?: NoiseSize
120
+ radius?: number
121
+ visible?: boolean
122
+ }
123
+
124
+ /** Radius of a new texture effect, as Figma's effects panel starts one. */
125
+ const DEFAULT_TEXTURE_RADIUS = 4
126
+
127
+ function noiseSize(size: NoiseSize | undefined, fallback: Vector): Vector {
128
+ if (size === undefined) return { ...fallback }
129
+ return typeof size === 'number' ? { x: size, y: size } : { ...size }
130
+ }
131
+
132
+ /**
133
+ * A noise effect. A duotone's second colour starts white at the first colour's opacity and a
134
+ * multitone's opacity at that opacity, as Figma's panel switches them.
135
+ */
136
+ export function noise(options: NoiseEffectOptions = {}): Effect {
137
+ const color = options.color === undefined ? { ...DEFAULT_NOISE_COLOR } : toColor(options.color)
138
+ const params: NoiseEffectParams = {
139
+ noiseType: options.noiseType ?? DEFAULT_NOISE.noiseType,
140
+ noiseSize: noiseSize(options.noiseSize, DEFAULT_NOISE.noiseSize),
141
+ density: options.density ?? DEFAULT_NOISE.density
142
+ }
143
+ // A second colour or opacity given is kept whatever the type, so switching back finds it; a
144
+ // duotone or multitone that lacks one starts where Figma's panel does.
145
+ if (options.secondaryColor !== undefined) params.secondaryColor = toColor(options.secondaryColor)
146
+ else if (params.noiseType === 'DUOTONE') params.secondaryColor = { r: 1, g: 1, b: 1, a: color.a }
147
+ if (options.opacity !== undefined) params.opacity = options.opacity
148
+ else if (params.noiseType === 'MULTITONE') params.opacity = color.a
149
+ if (options.seed !== undefined) params.seed = options.seed
150
+ return { type: 'NOISE', color, visible: options.visible ?? true, noise: params }
151
+ }
152
+
153
+ /** A texture effect, which roughens the layer's edges by `radius`. */
154
+ export function texture(options: TextureEffectOptions = {}): Effect {
155
+ const params: TextureEffectParams = {
156
+ noiseSize: noiseSize(options.noiseSize, DEFAULT_TEXTURE.noiseSize),
157
+ clipToShape: options.clipToShape ?? DEFAULT_TEXTURE.clipToShape
158
+ }
159
+ if (options.seed !== undefined) params.seed = options.seed
160
+ return {
161
+ type: 'TEXTURE',
162
+ color: { ...BLACK },
163
+ radius: options.radius ?? DEFAULT_TEXTURE_RADIUS,
164
+ visible: options.visible ?? true,
165
+ texture: params
166
+ }
167
+ }
package/src/elements.ts CHANGED
@@ -140,7 +140,7 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [
140
140
  runtimeType: 'vector',
141
141
  description: 'A vector layer.',
142
142
  nodeType: 'VECTOR',
143
- writes: ['VECTOR']
143
+ writes: ['VECTOR', 'BOOLEAN_OPERATION']
144
144
  },
145
145
  {
146
146
  name: 'Group',
@@ -162,6 +162,8 @@ function nodeToJSX(
162
162
  for (let count = elementCount(content); count > 0; count--) layerIds?.push(null)
163
163
  return [jsx.element(tag, attributes, content, depth, inline)]
164
164
  }
165
+ // A boolean's result path draws it, so its operands are not written as children.
166
+ if (node.type === 'BOOLEAN_OPERATION') return [jsx.element(tag, attributes, [], depth)]
165
167
  return [jsx.element(tag, attributes, children(depth + 1), depth)]
166
168
  }
167
169
 
@@ -3,10 +3,11 @@ import type {
3
3
  Fill,
4
4
  GradientTransform,
5
5
  SceneNode,
6
- ShadowEffect,
6
+ ShaderEffect,
7
7
  Stroke
8
8
  } from '@pairdraw/scene-graph'
9
9
  import { gradientTransformRows, isIdentityGradientTransform } from '@pairdraw/scene-graph/gradient'
10
+ import type { Vector } from '@pairdraw/scene-graph/primitives'
10
11
  import { isShaderPresetPaint, shaderOfPaint } from '@pairdraw/scene-graph/shaders'
11
12
 
12
13
  import { STROKE_ALIGN, STROKE_CAP, STROKE_JOIN } from '../enums'
@@ -215,15 +216,22 @@ export function collectStrokeProps(node: SceneNode, props: JSXProp[]): void {
215
216
  }
216
217
  }
217
218
 
218
- const EFFECT_HELPERS: Record<ShadowEffect['type'], string> = {
219
+ const EFFECT_HELPERS: Record<Exclude<Effect['type'], 'SHADER'>, string> = {
219
220
  DROP_SHADOW: 'dropShadow',
220
221
  INNER_SHADOW: 'innerShadow',
221
222
  LAYER_BLUR: 'layerBlur',
222
223
  BACKGROUND_BLUR: 'backgroundBlur',
223
- FOREGROUND_BLUR: 'foregroundBlur'
224
+ FOREGROUND_BLUR: 'foregroundBlur',
225
+ NOISE: 'noise',
226
+ TEXTURE: 'texture'
224
227
  }
225
228
 
226
- function effectValue(effect: ShadowEffect): HelperCall {
229
+ /** A grain size as one number when both axes match, as Figma's plugin API writes it. */
230
+ function noiseSizeValue(size: Vector): JSXValue {
231
+ return size.x === size.y ? size.x : { x: size.x, y: size.y }
232
+ }
233
+
234
+ function effectValue(effect: Exclude<Effect, ShaderEffect>): HelperCall {
227
235
  const visible = effect.visible ? undefined : false
228
236
  if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {
229
237
  return helperCall(
@@ -240,6 +248,37 @@ function effectValue(effect: ShadowEffect): HelperCall {
240
248
  })
241
249
  )
242
250
  }
251
+ if (effect.type === 'NOISE') {
252
+ const grain = effect.noise
253
+ return helperCall(
254
+ EFFECT_HELPERS.NOISE,
255
+ options({
256
+ noiseType: grain.noiseType,
257
+ noiseSize: noiseSizeValue(grain.noiseSize),
258
+ density: grain.density,
259
+ color: formatColor(effect.color, effect.color.a),
260
+ secondaryColor: grain.secondaryColor
261
+ ? formatColor(grain.secondaryColor, grain.secondaryColor.a)
262
+ : undefined,
263
+ opacity: grain.opacity,
264
+ seed: grain.seed,
265
+ visible
266
+ })
267
+ )
268
+ }
269
+ if (effect.type === 'TEXTURE') {
270
+ const grain = effect.texture
271
+ return helperCall(
272
+ EFFECT_HELPERS.TEXTURE,
273
+ options({
274
+ noiseSize: noiseSizeValue(grain.noiseSize),
275
+ radius: effect.radius,
276
+ clipToShape: grain.clipToShape,
277
+ seed: grain.seed,
278
+ visible
279
+ })
280
+ )
281
+ }
243
282
  return helperCall(
244
283
  EFFECT_HELPERS[effect.type],
245
284
  visible === undefined ? effect.radius : { radius: effect.radius, visible }
@@ -259,20 +298,22 @@ function plainDropShadow(effect: Effect): string | null {
259
298
  * `shadow` and `blur` describe a plain drop shadow followed by a layer blur, each optional,
260
299
  * in the order the renderer appends them; anything else needs `effects`.
261
300
  */
262
- function effectShorthand(effects: ShadowEffect[]): JSXProp[] | null {
301
+ function effectShorthand(effects: Effect[]): JSXProp[] | null {
263
302
  if (effects.some((effect) => !effect.visible)) return null
264
303
  const shadow = effects.length > 0 ? plainDropShadow(effects[0]) : null
265
304
  const rest = shadow ? effects.slice(1) : effects
266
305
  if (rest.length > 1 || rest.some((effect) => effect.type !== 'LAYER_BLUR')) return null
267
306
  const props: JSXProp[] = []
268
307
  if (shadow) props.push(['shadow', shadow])
269
- for (const blur of rest) props.push(['blur', blur.radius])
308
+ for (const blur of rest) {
309
+ if (blur.type === 'LAYER_BLUR') props.push(['blur', blur.radius])
310
+ }
270
311
  return props
271
312
  }
272
313
 
273
- /** An effect JSX has a helper for; an imported one the modeller lacks, such as noise, has none. */
274
- function hasJSXHelper(effect: Effect): effect is ShadowEffect {
275
- return Object.hasOwn(EFFECT_HELPERS, effect.type)
314
+ /** An effect JSX has a helper for; a shader effect is not written back as JSX source. */
315
+ function hasJSXHelper(effect: Effect): effect is Exclude<Effect, ShaderEffect> {
316
+ return effect.type !== 'SHADER' && Object.hasOwn(EFFECT_HELPERS, effect.type)
276
317
  }
277
318
 
278
319
  export function collectEffectProps(node: SceneNode, props: JSXProp[]): void {
@@ -331,7 +331,7 @@ function collectShapeNodeProps(node: SceneNode, props: JSXProp[]): void {
331
331
  if (node.type === 'POLYGON' && node.pointCount !== 3) {
332
332
  props.push(['points', node.pointCount])
333
333
  }
334
- if (node.type === 'VECTOR' && node.vectorNetwork) {
334
+ if ((node.type === 'VECTOR' || node.type === 'BOOLEAN_OPERATION') && node.vectorNetwork) {
335
335
  // Figma's own form of a vector's geometry, which <Vector> reads back as written.
336
336
  const paths = vectorNetworkPaths(node.vectorNetwork)
337
337
  if (paths.length > 0) props.push(['paths', paths.map((path) => ({ ...path }))])
package/src/helpers.ts CHANGED
@@ -9,8 +9,12 @@ import {
9
9
  foregroundBlur,
10
10
  innerShadow,
11
11
  layerBlur,
12
+ noise,
13
+ texture,
12
14
  type BlurEffectOptions,
13
- type ShadowEffectOptions
15
+ type NoiseEffectOptions,
16
+ type ShadowEffectOptions,
17
+ type TextureEffectOptions
14
18
  } from './effects'
15
19
  import {
16
20
  angularGradient,
@@ -48,6 +52,25 @@ const BLUR_OPTIONS = {
48
52
  visible: true
49
53
  } satisfies OptionKeys<BlurEffectOptions>
50
54
 
55
+ const NOISE_OPTIONS = {
56
+ noiseType: true,
57
+ noiseSize: true,
58
+ density: true,
59
+ color: true,
60
+ secondaryColor: true,
61
+ opacity: true,
62
+ seed: true,
63
+ visible: true
64
+ } satisfies OptionKeys<NoiseEffectOptions>
65
+
66
+ const TEXTURE_OPTIONS = {
67
+ noiseSize: true,
68
+ radius: true,
69
+ clipToShape: true,
70
+ seed: true,
71
+ visible: true
72
+ } satisfies OptionKeys<TextureEffectOptions>
73
+
51
74
  const SOLID_OPTIONS = {
52
75
  opacity: true,
53
76
  visible: true,
@@ -119,6 +142,8 @@ export function designJSXHelpers(warnings: string[]) {
119
142
  layerBlur: checked(warnings, 'layerBlur', layerBlur, BLUR_OPTIONS, 0),
120
143
  backgroundBlur: checked(warnings, 'backgroundBlur', backgroundBlur, BLUR_OPTIONS, 0),
121
144
  foregroundBlur: checked(warnings, 'foregroundBlur', foregroundBlur, BLUR_OPTIONS, 0),
145
+ noise: checked(warnings, 'noise', noise, NOISE_OPTIONS, 0),
146
+ texture: checked(warnings, 'texture', texture, TEXTURE_OPTIONS, 0),
122
147
  defineVars,
123
148
  defineMode,
124
149
  designVar,
package/src/index.ts CHANGED
@@ -63,9 +63,14 @@ export {
63
63
  foregroundBlur,
64
64
  innerShadow,
65
65
  layerBlur,
66
+ noise,
67
+ texture,
66
68
  type BlurEffectOptions,
67
69
  type EffectColor,
68
- type ShadowEffectOptions
70
+ type NoiseEffectOptions,
71
+ type NoiseSize,
72
+ type ShadowEffectOptions,
73
+ type TextureEffectOptions
69
74
  } from './effects'
70
75
 
71
76
  export {
package/src/order.ts ADDED
@@ -0,0 +1,111 @@
1
+ import { compact, isPlainObject, isString, pull, range, uniq } from 'es-toolkit'
2
+
3
+ import { namesComponent, rekaRole } from './behaviours'
4
+ import { isComponentProperty } from './component-properties'
5
+ import { DESIGN_JSX_SUPPORTED_PROPERTIES } from './definitions'
6
+ import { elementNodeType } from './elements'
7
+ import { isLayerRef, type LayerRef } from './refs'
8
+ import { isTreeNode, type TreeNode } from './tree'
9
+
10
+ /** A component as an element names it: by name, or by the `ref()` that marks it. */
11
+ type ComponentKey = string | LayerRef
12
+
13
+ /**
14
+ * The components an element and its descendants define and name. `mayName` holds the text values
15
+ * property props give, an exposed nested instance's included: a swap takes one as a component's
16
+ * name, other properties as plain text, and which is which is known only once the component
17
+ * renders.
18
+ */
19
+ interface ComponentUse {
20
+ defines: ComponentKey[]
21
+ names: ComponentKey[]
22
+ mayName: string[]
23
+ }
24
+
25
+ /** Whether an element defines a component: a component, a set, or a Reka root naming none. */
26
+ function definesComponent(node: TreeNode): boolean {
27
+ const nodeType = elementNodeType(node.type)
28
+ if (nodeType === 'COMPONENT' || nodeType === 'COMPONENT_SET') return true
29
+ return rekaRole(node.type)?.role === 'root' && !namesComponent(node.props)
30
+ }
31
+
32
+ /** What the element itself defines or names, without its descendants. */
33
+ function ownUse(node: TreeNode): ComponentUse {
34
+ const { props } = node
35
+ if (definesComponent(node)) {
36
+ const name = isString(props.name) ? props.name : ''
37
+ return { defines: compact([name, isLayerRef(props.ref) && props.ref]), names: [], mayName: [] }
38
+ }
39
+ const of = props.component ?? props.componentId ?? props.of
40
+ const component = isComponentProperty(of) ? of.defaultValue : of
41
+ const assigned = [
42
+ ...Object.entries(props)
43
+ .filter(([key]) => !DESIGN_JSX_SUPPORTED_PROPERTIES.has(key))
44
+ .map(([, value]) => value),
45
+ ...(isPlainObject(props.properties) ? Object.values(props.properties) : [])
46
+ ]
47
+ // An exposed nested instance's values, as in `Action={{ Icon: 'Arrow' }}`.
48
+ const nested = assigned.filter(isPlainObject).flatMap((values) => Object.values(values))
49
+ return {
50
+ defines: [],
51
+ names: [
52
+ ...(isString(component) || isLayerRef(component) ? [component] : []),
53
+ ...assigned.filter(isLayerRef)
54
+ ],
55
+ mayName: [...assigned, ...nested].filter(isString)
56
+ }
57
+ }
58
+
59
+ /** Reads each element's components once, for every level an order is asked at. */
60
+ export class RenderOrder {
61
+ private readonly uses = new WeakMap<TreeNode, ComponentUse>()
62
+
63
+ private use(node: TreeNode): ComponentUse {
64
+ const known = this.uses.get(node)
65
+ if (known) return known
66
+ const parts = [
67
+ ownUse(node),
68
+ ...node.children.filter(isTreeNode).map((child) => this.use(child))
69
+ ]
70
+ const use = {
71
+ defines: uniq(parts.flatMap((part) => part.defines)),
72
+ names: uniq(parts.flatMap((part) => part.names)),
73
+ mayName: uniq(parts.flatMap((part) => part.mayName))
74
+ }
75
+ this.uses.set(node, use)
76
+ return use
77
+ }
78
+
79
+ /**
80
+ * The indices of `siblings` in render order: those that define a component before those that
81
+ * name it, otherwise as written. When none is ready, what text values may name gives way
82
+ * first, so a text that matches a component's name never holds back a real reference; only
83
+ * components that do name each other keep the written order.
84
+ */
85
+ of(siblings: readonly TreeNode[]): number[] {
86
+ const uses = siblings.map((sibling) => this.use(sibling))
87
+ if (uses.every((use) => use.defines.length === 0)) return range(siblings.length)
88
+
89
+ const owners = new Map<ComponentKey, number[]>()
90
+ uses.forEach((use, index) => {
91
+ for (const key of use.defines) owners.set(key, [...(owners.get(key) ?? []), index])
92
+ })
93
+ const siblingsDefining = (keys: ComponentKey[], index: number) =>
94
+ uniq(keys.flatMap((key) => owners.get(key) ?? [])).filter((owner) => owner !== index)
95
+ const needs = uses.map((use, index) => siblingsDefining(use.names, index))
96
+ const mayNeed = uses.map((use, index) => siblingsDefining(use.mayName, index))
97
+
98
+ const order: number[] = []
99
+ const pending = range(siblings.length)
100
+ const rendered = (indices: number[]) => indices.every((index) => order.includes(index))
101
+ while (pending.length > 0) {
102
+ const next =
103
+ pending.find((index) => rendered(needs[index]) && rendered(mayNeed[index])) ??
104
+ pending.find((index) => rendered(needs[index])) ??
105
+ pending[0]
106
+ order.push(next)
107
+ pull(pending, [next])
108
+ }
109
+ return order
110
+ }
111
+ }
package/src/reconcile.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+ import { remapCopiedReferences } from '@pairdraw/scene-graph/transfer'
2
3
 
3
4
  /**
4
5
  * Fields a layer keeps when its code is rendered again: its place in the tree and the identity
@@ -130,5 +131,6 @@ export function reconcileRenderedLayers(
130
131
  return [rendered.id]
131
132
  })
132
133
  for (const id of existingRootIds.slice(renderedRootIds.length)) graph.deleteNode(id)
134
+ remapCopiedReferences(graph, reconciler.ids)
133
135
  return { rootIds, ids: reconciler.ids }
134
136
  }
@@ -56,7 +56,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
56
56
 
57
57
  - A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Track`, `Progress.Indicator`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.
58
58
  - The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.
59
- - `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.
59
+ - `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A `Tabs.Root` in a component set can name the set's variant property in `modelValue`, so a trigger chooses that variant; the property's options must be the trigger words, and every variant draws the same triggers. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.
60
60
  - A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.
61
61
 
62
62
  ```tsx
package/src/render.ts CHANGED
@@ -281,7 +281,10 @@ export function createDesignJSXRenderer<Artwork>(services: DesignJSXServices<Art
281
281
  renderJSX(services, graph, jsxString, options),
282
282
  /** Render a tree built with the element functions into the graph. */
283
283
  renderTree: (graph: SceneGraph, tree: TreeNode, options?: RenderJSXOptions) =>
284
- renderTree(services, graph, tree, options)
284
+ renderTree(services, graph, tree, options),
285
+ /** Render every top-level element of a tree at once, one result per root. */
286
+ renderRoots: (graph: SceneGraph, tree: TreeNode, options?: RenderJSXOptions) =>
287
+ renderRoots(services, graph, tree, options)
285
288
  }
286
289
  }
287
290
 
package/src/renderer.ts CHANGED
@@ -17,9 +17,10 @@ import {
17
17
  } from './component-properties'
18
18
  import { CONNECTOR_ELEMENT, resolveConnectorEnds } from './connectors'
19
19
  import { elementNodeType, elementOwnLayer, type OwnLayerRenderer } from './elements'
20
+ import { RenderOrder } from './order'
20
21
  import { placeVectorPaths } from './overrides/vector'
21
22
  import { applySizeOverrides, propsToOverrides, shapeOverrides } from './props-overrides'
22
- import { LayerRefs } from './refs'
23
+ import { isLayerRef, LayerRefs } from './refs'
23
24
  import { prepareScalarBindings } from './scalar-bindings'
24
25
  import { readElementProps } from './schema'
25
26
  import type { DesignJSXServices } from './services'
@@ -63,6 +64,10 @@ export async function renderRoots<Artwork>(
63
64
  const parentId = options.parentId ?? graph.getPages()[0].id
64
65
  applyVariableDefinitions(graph, tree)
65
66
 
67
+ const originalChildCount = graph.getChildren(parentId).length
68
+ // Render roots that define a component before roots that name it, so an `<Instance of={card}>`
69
+ // written before its `<Component ref={card}>` still finds the component (RenderOrder).
70
+ const order = new RenderOrder()
66
71
  const nodes: SceneNode[] = []
67
72
  const connectors: Array<{ node: SceneNode; tree: TreeNode }> = []
68
73
  const refs = new LayerRefs()
@@ -71,12 +76,15 @@ export async function renderRoots<Artwork>(
71
76
  else refs.mark(element.props.ref, node)
72
77
  options.onNode?.(element, node)
73
78
  }
74
- for (const root of roots) {
75
- const node = await renderNode(services, graph, root, parentId, onNode)
76
- if (options.x !== undefined) graph.updateNode(node.id, { x: options.x })
77
- if (options.y !== undefined) graph.updateNode(node.id, { y: options.y })
78
- nodes.push(node)
79
+ for (const index of order.of(roots)) {
80
+ const node = await renderNode(services, graph, roots[index], parentId, onNode, undefined, refs)
81
+ const { x, y } = options.positions?.[index] ?? options
82
+ if (x !== undefined) graph.updateNode(node.id, { x })
83
+ if (y !== undefined) graph.updateNode(node.id, { y })
84
+ nodes[index] = node
79
85
  }
86
+ // Keep the written layer order even though components rendered first.
87
+ nodes.forEach((node, index) => graph.insertChildAt(node.id, parentId, originalChildCount + index))
80
88
 
81
89
  const rootIds = nodes.map((node) => node.id)
82
90
  const warnings = [...refs.warnings, ...resolveConnectorEnds(graph, rootIds, connectors, refs)]
@@ -312,8 +320,16 @@ function selectsVariant(set: SceneNode, props: Record<string, unknown>): boolean
312
320
  * the props select one of its variants, and the first otherwise; the warning from
313
321
  * `componentReferenceWarnings` says so and how to pick one by ID.
314
322
  */
315
- function namedComponent(graph: SceneGraph, props: Record<string, unknown>): SceneNode | undefined {
323
+ function namedComponent(
324
+ graph: SceneGraph,
325
+ props: Record<string, unknown>,
326
+ refs?: LayerRefs
327
+ ): SceneNode | undefined {
316
328
  const ref = props.component ?? props.componentId ?? props.of
329
+ if (isLayerRef(ref)) {
330
+ const marked = graph.getNode(refs?.layerOf(ref) ?? '')
331
+ return marked?.type === 'COMPONENT' || marked?.type === 'COMPONENT_SET' ? marked : undefined
332
+ }
317
333
  if (typeof ref !== 'string') return undefined
318
334
 
319
335
  const matches = componentsNamed(graph, ref)
@@ -369,9 +385,10 @@ function findVariantInSet(
369
385
 
370
386
  function resolveComponent(
371
387
  graph: SceneGraph,
372
- props: Record<string, unknown>
388
+ props: Record<string, unknown>,
389
+ refs?: LayerRefs
373
390
  ): SceneNode | undefined {
374
- const named = namedComponent(graph, props)
391
+ const named = namedComponent(graph, props, refs)
375
392
  return named?.type === 'COMPONENT_SET' ? findVariantInSet(graph, named, props) : named
376
393
  }
377
394
 
@@ -387,16 +404,24 @@ export function componentPropNames(graph: SceneGraph, props: Record<string, unkn
387
404
  async function renderInstanceNode(
388
405
  graph: SceneGraph,
389
406
  tree: TreeNode,
390
- parentId: string
407
+ parentId: string,
408
+ refs?: LayerRefs
391
409
  ): Promise<SceneNode> {
392
410
  const parent = graph.getNode(parentId)
393
411
  const parentLayout = parent?.layoutMode ?? 'NONE'
394
412
  const modes = variableModes(graph, tree.props.mode)
395
- const bound = bindProperties(graph, tree.props, 'INSTANCE', parentId, componentIdNamed(graph))
413
+ const bound = bindProperties(
414
+ graph,
415
+ tree.props,
416
+ 'INSTANCE',
417
+ parentId,
418
+ componentIdNamed(graph, refs)
419
+ )
396
420
  const { props, bindings } = preparePropsForRender(graph, bound.props, false, { parentId, modes })
397
- const component = resolveComponent(graph, props)
421
+ const component = resolveComponent(graph, props, refs)
398
422
  if (!component) {
399
423
  const ref = props.component ?? props.componentId ?? props.of
424
+ if (isLayerRef(ref)) throw new Error('<Instance> ref() marks no component rendered before it')
400
425
  const label = typeof ref === 'string' || typeof ref === 'number' ? String(ref) : ''
401
426
  throw new Error(`<Instance> component not found: ${label}`)
402
427
  }
@@ -430,8 +455,8 @@ async function renderInstanceNode(
430
455
  graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
431
456
  applyBindings(graph, instance.id, bindings)
432
457
  applyInstanceOverrides(graph, instance, tree.props.overrides)
433
- assignNamedProperties(graph, instance, props, componentIdNamed(graph))
434
- assignComponentProperties(graph, instance, props.properties, componentIdNamed(graph))
458
+ assignNamedProperties(graph, instance, props, componentIdNamed(graph, refs))
459
+ assignComponentProperties(graph, instance, props.properties, componentIdNamed(graph, refs))
435
460
  if (props.exposed === true) exposeInstance(graph, instance)
436
461
  return instance
437
462
  } catch (error) {
@@ -512,8 +537,8 @@ function layerMetadata(
512
537
  }
513
538
 
514
539
  /** The component a swap property's default names, by ID or name, as `<Instance of>` finds it. */
515
- function componentIdNamed(graph: SceneGraph) {
516
- return (name: string) => resolveComponent(graph, { of: name })?.id
540
+ function componentIdNamed(graph: SceneGraph, refs?: LayerRefs) {
541
+ return (name: string) => resolveComponent(graph, { of: name }, refs)?.id
517
542
  }
518
543
 
519
544
  export interface ElementOverrides {
@@ -560,9 +585,10 @@ async function renderNode<Artwork>(
560
585
  tree: TreeNode,
561
586
  parentId: string,
562
587
  onNode?: RenderOptions['onNode'],
563
- scope?: RekaScope
588
+ scope?: RekaScope,
589
+ refs?: LayerRefs
564
590
  ): Promise<SceneNode> {
565
- const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope)
591
+ const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope, refs)
566
592
  onNode?.(tree, node)
567
593
  return node
568
594
  }
@@ -575,14 +601,15 @@ function renderOwnElement<Artwork>(
575
601
  services: DesignJSXServices<Artwork>,
576
602
  graph: SceneGraph,
577
603
  tree: TreeNode,
578
- parentId: string
604
+ parentId: string,
605
+ refs?: LayerRefs
579
606
  ): Promise<SceneNode> | null {
580
607
  switch (tree.type) {
581
608
  case 'icon':
582
609
  case 'svg':
583
610
  return renderArtworkNode(services, graph, tree, parentId)
584
611
  case 'instance':
585
- return renderInstanceNode(graph, tree, parentId)
612
+ return renderInstanceNode(graph, tree, parentId, refs)
586
613
  default: {
587
614
  const element = elementOwnLayer(tree.type)
588
615
  return element ? Promise.resolve(renderOwnLayerElement(graph, tree, parentId, element)) : null
@@ -596,13 +623,14 @@ async function renderNodeContent<Artwork>(
596
623
  tree: TreeNode,
597
624
  parentId: string,
598
625
  onNode?: RenderOptions['onNode'],
599
- scope?: RekaScope
626
+ scope?: RekaScope,
627
+ refs?: LayerRefs
600
628
  ): Promise<SceneNode> {
601
- const own = renderOwnElement(services, graph, tree, parentId)
629
+ const own = renderOwnElement(services, graph, tree, parentId, refs)
602
630
  if (own) return own
603
631
  const reka = await renderRekaNode(graph, tree, parentId, scope, {
604
632
  render: (child, childParentId, childScope) =>
605
- renderNode(services, graph, child, childParentId, onNode, childScope),
633
+ renderNode(services, graph, child, childParentId, onNode, childScope, refs),
606
634
  create: (nodeType, element, elementParentId) => {
607
635
  const { overrides, bindings } = elementOverrides(graph, nodeType, element, elementParentId)
608
636
  const created = graph.createNode(nodeType, elementParentId, overrides)
@@ -610,7 +638,8 @@ async function renderNodeContent<Artwork>(
610
638
  placeVectorPaths(graph, created, element.props, (network) => services.vectorBounds(network))
611
639
  return created
612
640
  },
613
- instance: (element, elementParentId) => renderInstanceNode(graph, element, elementParentId),
641
+ instance: (element, elementParentId) =>
642
+ renderInstanceNode(graph, element, elementParentId, refs),
614
643
  finishSet: (setId) => inferComponentSetProperties(graph, setId)
615
644
  })
616
645
  if (reka) return reka
@@ -631,7 +660,7 @@ async function renderNodeContent<Artwork>(
631
660
  // Text holds characters and style runs, not layers: a child layer would exist in the graph but
632
661
  // not in the text's export, so it is refused rather than silently lost.
633
662
  if (node.type === 'TEXT') throw new Error(`<${child.type}> cannot be inside <Text>`)
634
- await renderNode(services, graph, child, node.id, onNode, scope)
663
+ await renderNode(services, graph, child, node.id, onNode, scope, refs)
635
664
  }
636
665
 
637
666
  if (node.type === 'COMPONENT_SET') inferComponentSetProperties(graph, node.id)
package/src/types.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import type { SceneNode } from '@pairdraw/scene-graph'
2
+ import type { Vector } from '@pairdraw/scene-graph/primitives'
2
3
 
3
4
  import type { TreeNode } from './tree'
4
5
 
5
6
  export interface RenderOptions {
6
7
  x?: number
7
8
  y?: number
9
+ /** Each root's position, in the order the roots are written; an entry replaces `x` and `y`. */
10
+ positions?: ReadonlyArray<Partial<Vector>>
8
11
  parentId?: string
9
12
  /** Called for every layer created from an element, so callers can map source to layers. */
10
13
  onNode?: (tree: TreeNode, node: SceneNode) => void