@pairdraw/design-jsx 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +54 -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,144 @@
1
+ import type { NodeType, SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ import { designJSXProp } from '../definitions'
4
+ import type { TreeNode } from '../tree'
5
+ import {
6
+ BEHAVIOUR_PROPS,
7
+ bindInput,
8
+ bindPart,
9
+ containerPart,
10
+ createScope,
11
+ finishRoot,
12
+ namesComponent,
13
+ rekaRole,
14
+ wrapRepeatedParts,
15
+ type RekaScope
16
+ } from './index'
17
+
18
+ export type RenderChild = (
19
+ tree: TreeNode,
20
+ parentId: string,
21
+ scope?: RekaScope
22
+ ) => Promise<SceneNode>
23
+ export type CreateElement = (nodeType: NodeType, tree: TreeNode, parentId: string) => SceneNode
24
+ export type RenderInstance = (tree: TreeNode, parentId: string) => Promise<SceneNode>
25
+
26
+ function withoutBehaviourProps(tree: TreeNode): TreeNode {
27
+ const props = Object.fromEntries(
28
+ Object.entries(tree.props).filter(
29
+ ([key]) => !(BEHAVIOUR_PROPS as readonly string[]).includes(key)
30
+ )
31
+ )
32
+ return { ...tree, props }
33
+ }
34
+
35
+ async function renderChildren(
36
+ render: RenderChild,
37
+ children: TreeNode['children'],
38
+ parentId: string,
39
+ scope: RekaScope | undefined
40
+ ): Promise<void> {
41
+ for (const child of children) if (typeof child !== 'string') await render(child, parentId, scope)
42
+ }
43
+
44
+ /** A name for a part that JSX leaves unnamed: the Reka part it is, such as Thumb. */
45
+ function named(tree: TreeNode, fallback: string): TreeNode {
46
+ return tree.props.name === undefined
47
+ ? { ...tree, props: { ...tree.props, name: fallback } }
48
+ : tree
49
+ }
50
+
51
+ /** The props that give a frame a layout or size of its own, under any of their names. */
52
+ const LAYOUT_PROPS = ['flex', 'display', 'w', 'h']
53
+
54
+ /**
55
+ * A part that holds content, such as a panel or a trigger, with no layout of its own stacks
56
+ * its children in a column that hugs them, rather than pinning them in a fixed box.
57
+ */
58
+ function laidOut(tree: TreeNode): TreeNode {
59
+ const content = tree.children.some((child) => typeof child !== 'string')
60
+ if (!content || LAYOUT_PROPS.some((prop) => designJSXProp(tree.props, prop) !== undefined))
61
+ return tree
62
+ return { ...tree, props: { ...tree.props, flex: 'col' } }
63
+ }
64
+
65
+ /**
66
+ * Render a Reka UI element: a root as a main component (or a component set, when it has
67
+ * variants) that behaves as its control, a part as the slot that draws it, and an input as the
68
+ * text layer of the field's text property. Returns undefined for other elements.
69
+ */
70
+ export async function renderRekaNode(
71
+ graph: SceneGraph,
72
+ tree: TreeNode,
73
+ parentId: string,
74
+ scope: RekaScope | undefined,
75
+ hooks: {
76
+ render: RenderChild
77
+ create: CreateElement
78
+ instance: RenderInstance
79
+ /** Derive a component set's variant properties from its variants' names. */
80
+ finishSet: (setId: string) => void
81
+ }
82
+ ): Promise<SceneNode | undefined> {
83
+ const container = containerPart(tree.type)
84
+ const role = container ? { role: 'part' as const, part: container } : rekaRole(tree.type)
85
+ if (!role) return undefined
86
+ const partName = tree.type.slice(tree.type.indexOf('.') + 1)
87
+ switch (role.role) {
88
+ case 'root': {
89
+ // A group's item that names a component is an item, drawn as an instance of it.
90
+ if (namesComponent(tree.props)) return hooks.instance(tree, parentId)
91
+ const variants = tree.children.some(
92
+ (child) => typeof child !== 'string' && child.type === 'component'
93
+ )
94
+ const root = hooks.create(
95
+ variants ? 'COMPONENT_SET' : 'COMPONENT',
96
+ withoutBehaviourProps(tree),
97
+ parentId
98
+ )
99
+ const own = createScope(role.kind, root.id)
100
+ await renderChildren(hooks.render, wrapRepeatedParts(tree, role.kind), root.id, own)
101
+ if (variants) hooks.finishSet(root.id)
102
+ finishRoot(graph, own, tree.props)
103
+ return root
104
+ }
105
+ case 'part': {
106
+ if (!scope) throw new Error(`<${tree.type}> must be inside its Root`)
107
+ const frame = hooks.create('FRAME', laidOut(named(tree, partName)), parentId)
108
+ await renderChildren(hooks.render, tree.children, frame.id, scope)
109
+ bindPart(graph, scope, frame, role.part)
110
+ return frame
111
+ }
112
+ case 'repeat': {
113
+ const frame = hooks.create('FRAME', laidOut(named(tree, partName)), parentId)
114
+ await renderChildren(hooks.render, tree.children, frame.id, scope)
115
+ // Only the first tab's panel shows as designed; preview shows the others as chosen.
116
+ const siblings = graph.getChildren(parentId)
117
+ if (
118
+ role.container === 'panels' &&
119
+ siblings[0]?.id !== frame.id &&
120
+ tree.props.visible === undefined
121
+ )
122
+ graph.updateNode(frame.id, { visible: false })
123
+ return frame
124
+ }
125
+ case 'input': {
126
+ if (!scope) throw new Error(`<${tree.type}> must be inside its Root`)
127
+ const text = hooks.create('TEXT', named(tree, 'Text'), parentId)
128
+ bindInput(
129
+ graph,
130
+ scope,
131
+ text,
132
+ role.valueId,
133
+ typeof tree.props.name === 'string' ? tree.props.name : 'Text'
134
+ )
135
+ return text
136
+ }
137
+ case 'frame': {
138
+ const frame = hooks.create('FRAME', laidOut(named(tree, partName)), parentId)
139
+ await renderChildren(hooks.render, tree.children, frame.id, scope)
140
+ return frame
141
+ }
142
+ }
143
+ return undefined
144
+ }
@@ -0,0 +1,428 @@
1
+ import { compact } from 'es-toolkit/array'
2
+ import { isPlainObject } from 'es-toolkit/predicate'
3
+ import * as v from 'valibot'
4
+
5
+ import type {
6
+ ComponentPropertyDefinition,
7
+ ComponentPropertyReference,
8
+ SceneGraph,
9
+ SceneNode
10
+ } from '@pairdraw/scene-graph'
11
+ import {
12
+ applyComponentPropertyValue,
13
+ componentPropertyDefinitions,
14
+ createComponentPropertyId,
15
+ exposableInstances,
16
+ exposedInstances,
17
+ instanceExposureIssue
18
+ } from '@pairdraw/scene-graph/components'
19
+ import { instanceMainComponent } from '@pairdraw/scene-graph/instances'
20
+
21
+ import { DESIGN_JSX_SUPPORTED_PROPERTIES } from './definitions'
22
+ import { parseScriptInput } from './schema'
23
+
24
+ const PROPERTY_SYMBOL = Symbol.for('pairdraw.component-property')
25
+
26
+ /**
27
+ * A component property, by its name in the component that holds it. Where it is placed picks
28
+ * its type: `text` on a text layer makes a TEXT property, `visible` a BOOLEAN one, and `of` on an
29
+ * instance an INSTANCE_SWAP one, whose default is the component that `of` names.
30
+ */
31
+ export interface ComponentProperty<T extends string | boolean = string | boolean> {
32
+ readonly [PROPERTY_SYMBOL]: true
33
+ readonly name: string
34
+ readonly defaultValue: T
35
+ }
36
+
37
+ export function isComponentProperty(value: unknown): value is ComponentProperty {
38
+ return typeof value === 'object' && value !== null && PROPERTY_SYMBOL in value
39
+ }
40
+
41
+ /**
42
+ * Bind a field to a property of the component it is drawn in, created on first use: on the
43
+ * component set, for a variant, as Figma keeps them, or else on the component.
44
+ */
45
+ export function property<T extends string | boolean>(
46
+ name: string,
47
+ defaultValue: T
48
+ ): ComponentProperty<T> {
49
+ return Object.freeze({ [PROPERTY_SYMBOL]: true as const, name, defaultValue })
50
+ }
51
+
52
+ /** The prop each property type binds, and the field it binds there. */
53
+ const BOUND_PROPS = {
54
+ text: { type: 'TEXT', field: 'TEXT', node: 'TEXT' },
55
+ visible: { type: 'BOOLEAN', field: 'VISIBLE', node: undefined },
56
+ of: { type: 'INSTANCE_SWAP', field: 'INSTANCE_SWAP', node: 'INSTANCE' }
57
+ } as const satisfies Record<
58
+ string,
59
+ {
60
+ type: ComponentPropertyDefinition['type']
61
+ field: ComponentPropertyReference['field']
62
+ node: SceneNode['type'] | undefined
63
+ }
64
+ >
65
+
66
+ /** The component, or the set it is a variant of, that holds properties for layers under `parentId`. */
67
+ function propertyOwner(graph: SceneGraph, parentId: string): SceneNode {
68
+ let node = graph.getNode(parentId)
69
+ while (node) {
70
+ if (node.type === 'INSTANCE') throw new Error('property() cannot be used inside an instance')
71
+ if (node.type === 'COMPONENT_SET') return node
72
+ if (node.type === 'COMPONENT') {
73
+ const set = node.parentId ? graph.getNode(node.parentId) : undefined
74
+ return set?.type === 'COMPONENT_SET' ? set : node
75
+ }
76
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
77
+ }
78
+ throw new Error('property() must be inside a <Component> or <ComponentSet>')
79
+ }
80
+
81
+ /** The ID of the property with this name on `owner`, added if it has none. */
82
+ function ensureDefinition(
83
+ graph: SceneGraph,
84
+ owner: SceneNode,
85
+ name: string,
86
+ type: ComponentPropertyDefinition['type'],
87
+ defaultValue: string
88
+ ): string {
89
+ const existing = owner.componentPropertyDefinitions.find((item) => item.name === name)
90
+ if (existing) {
91
+ if (existing.type !== type)
92
+ throw new Error(`Component property ${name} is ${existing.type}, not ${type}`)
93
+ if (existing.defaultValue !== defaultValue)
94
+ throw new Error(
95
+ `Component property ${name} has two defaults: ${existing.defaultValue} and ${defaultValue}`
96
+ )
97
+ return existing.id
98
+ }
99
+ const id = createComponentPropertyId()
100
+ graph.updateNode(owner.id, {
101
+ componentPropertyDefinitions: [
102
+ ...owner.componentPropertyDefinitions,
103
+ { id, name, type, defaultValue }
104
+ ]
105
+ })
106
+ return id
107
+ }
108
+
109
+ export interface BoundProperties {
110
+ /** The props, with each property in place of its default. */
111
+ props: Record<string, unknown>
112
+ references: ComponentPropertyReference[]
113
+ }
114
+
115
+ /**
116
+ * Bind the fields a layer's props place a `property()` in, creating the properties on its
117
+ * component; `componentId` gives the ID a swap's default component has.
118
+ */
119
+ export function bindProperties(
120
+ graph: SceneGraph,
121
+ source: Record<string, unknown>,
122
+ type: SceneNode['type'],
123
+ parentId: string,
124
+ componentId: ComponentLookup
125
+ ): BoundProperties {
126
+ if (source.properties !== undefined && type !== 'INSTANCE')
127
+ throw new Error('Only instances accept properties; bind a field to property() instead')
128
+ const props = { ...source }
129
+ const references: ComponentPropertyReference[] = []
130
+ for (const [key, value] of Object.entries(source)) {
131
+ if (!isComponentProperty(value)) continue
132
+ if (!Object.hasOwn(BOUND_PROPS, key))
133
+ throw new Error(`property() binds text, visible, or of, not ${key}`)
134
+ const bound = BOUND_PROPS[key as keyof typeof BOUND_PROPS]
135
+ if (bound.node && bound.node !== type)
136
+ throw new Error(
137
+ `property() in ${key} needs ${bound.node === 'TEXT' ? '<Text>' : '<Instance>'}`
138
+ )
139
+ const expected = bound.type === 'BOOLEAN' ? 'boolean' : 'string'
140
+ if (typeof value.defaultValue !== expected)
141
+ throw new Error(`Component property ${value.name} in ${key} takes a ${expected} default`)
142
+ let defaultValue = String(value.defaultValue)
143
+ if (bound.type === 'INSTANCE_SWAP') {
144
+ const id = componentId(defaultValue)
145
+ if (!id) throw new Error(`<Instance> component not found: ${defaultValue}`)
146
+ defaultValue = id
147
+ }
148
+ const owner = propertyOwner(graph, parentId)
149
+ const propertyId = ensureDefinition(graph, owner, value.name, bound.type, defaultValue)
150
+ references.push({ propertyId, field: bound.field })
151
+ props[key] = value.defaultValue
152
+ }
153
+ return { props, references }
154
+ }
155
+
156
+ /** Match the nearest component scope, including definitions inherited from its set. */
157
+ function componentPropertyScope(
158
+ graph: SceneGraph,
159
+ parentId: string
160
+ ): readonly ComponentPropertyDefinition[] | undefined {
161
+ let parent = graph.getNode(parentId)
162
+ while (parent) {
163
+ if (parent.type === 'INSTANCE') return componentPropertyDefinitions(graph, parent)
164
+ if (parent.type === 'COMPONENT_SET') return parent.componentPropertyDefinitions
165
+ if (parent.type === 'COMPONENT') {
166
+ const set = parent.parentId ? graph.getNode(parent.parentId) : undefined
167
+ return set?.type === 'COMPONENT_SET'
168
+ ? [...set.componentPropertyDefinitions, ...parent.componentPropertyDefinitions]
169
+ : parent.componentPropertyDefinitions
170
+ }
171
+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
172
+ }
173
+ return undefined
174
+ }
175
+
176
+ /** The one property with this name; a name several properties share is an error. */
177
+ function namedDefinition(
178
+ definitions: readonly ComponentPropertyDefinition[],
179
+ name: string
180
+ ): ComponentPropertyDefinition | undefined {
181
+ const matches = definitions.filter((item) => item.name === name)
182
+ if (matches.length > 1)
183
+ throw new Error(
184
+ `Component property name ${name} is ambiguous; use one of the IDs: ${matches.map((item) => item.id).join(', ')}`
185
+ )
186
+ return matches[0]
187
+ }
188
+
189
+ /** The ID of the component a name or ID names, as `<Instance of>` finds it. */
190
+ export type ComponentLookup = (nameOrId: string) => string | undefined
191
+
192
+ function assignValue(
193
+ graph: SceneGraph,
194
+ instance: SceneNode,
195
+ definition: ComponentPropertyDefinition,
196
+ key: string,
197
+ value: string,
198
+ componentId: ComponentLookup
199
+ ): void {
200
+ if (definition.type === 'VARIANT')
201
+ throw new Error('Select a component-set variant when creating the instance')
202
+ if (definition.type === 'BOOLEAN' && value !== 'true' && value !== 'false')
203
+ throw new Error(`Expected true or false for component property: ${key}`)
204
+ // A swap names its component as `of` does: by ID or by name.
205
+ const assigned = definition.type === 'INSTANCE_SWAP' ? (componentId(value) ?? value) : value
206
+ if (!applyComponentPropertyValue(graph, instance.id, definition, assigned))
207
+ throw new Error(`Cannot assign component property: ${key}`)
208
+ }
209
+
210
+ /** A value an instance gives a property, or an exposed nested instance's values by name. */
211
+ const assignedValueSchema = v.union([v.string(), v.boolean(), v.number()])
212
+ const exposedValuesSchema = v.record(v.string(), assignedValueSchema)
213
+
214
+ /** The one exposed nested instance with this name; a name several share is an error. */
215
+ function exposedInstanceNamed(
216
+ graph: SceneGraph,
217
+ instance: SceneNode,
218
+ name: string
219
+ ): SceneNode | undefined {
220
+ const matches = exposedInstances(graph, instance).filter((node) => node.name === name)
221
+ if (matches.length > 1)
222
+ throw new Error(`Exposed instance name ${name} is shared by ${matches.length} layers`)
223
+ return matches[0]
224
+ }
225
+
226
+ /**
227
+ * Pick the variant of an exposed instance's set that has the values it names, keeping its own
228
+ * for the rest, as its panel group does.
229
+ */
230
+ function selectNestedVariant(
231
+ graph: SceneGraph,
232
+ nested: SceneNode,
233
+ name: string,
234
+ values: Record<string, string>
235
+ ): void {
236
+ if (Object.keys(values).length === 0) return
237
+ const component = instanceMainComponent(graph, nested)
238
+ const set = component?.parentId ? graph.getNode(component.parentId) : undefined
239
+ if (!component || set?.type !== 'COMPONENT_SET') return
240
+ const wanted = { ...component.componentPropertyValues, ...values }
241
+ const variant = graph
242
+ .getChildren(set.id)
243
+ .find(
244
+ (node) =>
245
+ node.type === 'COMPONENT' &&
246
+ Object.entries(wanted).every(([key, value]) => node.componentPropertyValues[key] === value)
247
+ )
248
+ if (!variant)
249
+ throw new Error(
250
+ `${name} has no variant ${Object.entries(values)
251
+ .map(([key, value]) => `${key}=${value}`)
252
+ .join(', ')}`
253
+ )
254
+ if (variant.id !== component.id) graph.swapInstanceComponent(nested.id, variant.id)
255
+ }
256
+
257
+ /**
258
+ * Give the exposed nested instance named `name` its values: variants and properties by name,
259
+ * the way the instance itself takes them.
260
+ */
261
+ function assignExposedInstance(
262
+ graph: SceneGraph,
263
+ instance: SceneNode,
264
+ name: string,
265
+ input: unknown,
266
+ componentId: ComponentLookup
267
+ ): void {
268
+ const nested = exposedInstanceNamed(graph, instance, name)
269
+ if (!nested) throw new Error(`Unknown component property or exposed instance: ${name}`)
270
+ const values = parseScriptInput(`Invalid values for ${name}`, exposedValuesSchema, input)
271
+ const variantNames = new Set(
272
+ componentPropertyDefinitions(graph, nested)
273
+ .filter((definition) => definition.type === 'VARIANT')
274
+ .map((definition) => definition.name)
275
+ )
276
+ const variants = Object.fromEntries(
277
+ Object.entries(values)
278
+ .filter(([key]) => variantNames.has(key))
279
+ .map(([key, value]) => [key, String(value)])
280
+ )
281
+ selectNestedVariant(graph, nested, name, variants)
282
+ const definitions = componentPropertyDefinitions(graph, nested)
283
+ for (const [key, value] of Object.entries(values)) {
284
+ if (variantNames.has(key)) continue
285
+ const definition = namedDefinition(definitions, key)
286
+ if (!definition) throw new Error(`Unknown component property on ${name}: ${key}`)
287
+ assignValue(graph, nested, definition, key, String(value), componentId)
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Set text, boolean, and swap properties an instance names as props, as in `Title="Hello"`, the
293
+ * way it picks a variant, and an exposed nested instance's values, as in `Action={{ Label: 'Save' }}`;
294
+ * design JSX props keep their meaning.
295
+ */
296
+ export function assignNamedProperties(
297
+ graph: SceneGraph,
298
+ instance: SceneNode,
299
+ props: Record<string, unknown>,
300
+ componentId: ComponentLookup
301
+ ): void {
302
+ const definitions = componentPropertyDefinitions(graph, instance).filter(
303
+ (definition) => definition.type !== 'VARIANT'
304
+ )
305
+ for (const [key, value] of Object.entries(props)) {
306
+ if (DESIGN_JSX_SUPPORTED_PROPERTIES.has(key)) continue
307
+ if (isPlainObject(value) && exposedInstanceNamed(graph, instance, key)) {
308
+ assignExposedInstance(graph, instance, key, value, componentId)
309
+ continue
310
+ }
311
+ const definition = namedDefinition(definitions, key)
312
+ if (!definition) continue
313
+ if (typeof value !== 'string' && typeof value !== 'boolean' && typeof value !== 'number')
314
+ throw new Error(`Expected a string or boolean for component property: ${key}`)
315
+ assignValue(graph, instance, definition, key, String(value), componentId)
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Keys are property IDs or, because saving to `.fig` replaces authored IDs
321
+ * with GUIDs, names, which survive a reload; an object gives an exposed nested instance its values.
322
+ */
323
+ export function assignComponentProperties(
324
+ graph: SceneGraph,
325
+ instance: SceneNode,
326
+ input: unknown,
327
+ componentId: ComponentLookup
328
+ ): void {
329
+ if (input === undefined) return
330
+ const assignments = parseScriptInput(
331
+ 'Invalid properties on <Instance>',
332
+ v.record(v.string(), v.union([assignedValueSchema, exposedValuesSchema])),
333
+ input
334
+ )
335
+ const definitions = componentPropertyDefinitions(graph, instance)
336
+ for (const [key, value] of Object.entries(assignments)) {
337
+ if (isPlainObject(value)) {
338
+ assignExposedInstance(graph, instance, key, value, componentId)
339
+ continue
340
+ }
341
+ const definition =
342
+ definitions.find((item) => item.id === key) ?? namedDefinition(definitions, key)
343
+ if (!definition) throw new Error(`Unknown component property: ${key}`)
344
+ assignValue(graph, instance, definition, key, String(value), componentId)
345
+ }
346
+ }
347
+
348
+ /** Mark an instance in a component's layers as exposed, under Figma's rules for exposing one. */
349
+ export function exposeInstance(graph: SceneGraph, instance: SceneNode): void {
350
+ const issue = instanceExposureIssue(graph, instance)
351
+ if (issue === 'not-in-component') throw new Error('exposed needs an <Instance> in a component')
352
+ if (issue === 'not-primary')
353
+ throw new Error('exposed needs an <Instance> in a component, not inside another instance')
354
+ if (issue === 'nothing-to-expose')
355
+ throw new Error(`${instance.name} has no properties or exposed instances to expose`)
356
+ graph.updateNode(instance.id, { isExposedInstance: true })
357
+ }
358
+
359
+ /** The names an instance of `component` takes: its properties' and its exposed instances'. */
360
+ export function componentPropNames(graph: SceneGraph, component: SceneNode): string[] {
361
+ return [
362
+ ...(componentPropertyScope(graph, component.id) ?? []).map((definition) => definition.name),
363
+ ...exposableInstances(graph, component.id)
364
+ .filter((node) => node.isExposedInstance)
365
+ .map((node) => node.name)
366
+ ]
367
+ }
368
+
369
+ function parseVariantValues(name: string): Record<string, string> {
370
+ const entries = compact(name.split(',').map((part) => part.trim()))
371
+ const values: Record<string, string> = {}
372
+ for (const entry of entries) {
373
+ const [key = '', ...rest] = entry.split('=')
374
+ const property = key.trim()
375
+ const value = rest.join('=').trim()
376
+ if (property && value) values[property] = value
377
+ }
378
+ return values
379
+ }
380
+
381
+ /** Variant properties a component set takes from its variants' names, such as `State=On`. */
382
+ export function inferComponentSetProperties(graph: SceneGraph, componentSetId: string): void {
383
+ const componentSet = graph.getNode(componentSetId)
384
+ if (componentSet?.type !== 'COMPONENT_SET') return
385
+ const existingDefinitions = componentSet.componentPropertyDefinitions
386
+
387
+ const variants = graph.getChildren(componentSetId).filter((node) => node.type === 'COMPONENT')
388
+ const options = new Map<string, Set<string>>()
389
+ const valuesById = new Map<string, Record<string, string>>()
390
+
391
+ for (const variant of variants) {
392
+ const values = parseVariantValues(variant.name)
393
+ valuesById.set(variant.id, values)
394
+ for (const [property, value] of Object.entries(values)) {
395
+ let set = options.get(property)
396
+ if (!set) {
397
+ set = new Set()
398
+ options.set(property, set)
399
+ }
400
+ set.add(value)
401
+ }
402
+ }
403
+
404
+ const definitions: ComponentPropertyDefinition[] = [...options.entries()]
405
+ .filter(
406
+ ([name]) =>
407
+ !existingDefinitions.some(
408
+ (definition) => definition.type === 'VARIANT' && definition.name === name
409
+ )
410
+ )
411
+ .map(([name, values]) => {
412
+ const variantOptions = [...values]
413
+ return {
414
+ id: createComponentPropertyId(),
415
+ name,
416
+ type: 'VARIANT',
417
+ defaultValue: variantOptions[0] ?? '',
418
+ variantOptions
419
+ }
420
+ })
421
+
422
+ for (const [id, values] of valuesById) {
423
+ graph.updateNode(id, { componentPropertyValues: values })
424
+ }
425
+ graph.updateNode(componentSetId, {
426
+ componentPropertyDefinitions: [...existingDefinitions, ...definitions]
427
+ })
428
+ }
@@ -0,0 +1,109 @@
1
+ import {
2
+ node,
3
+ type BaseProps,
4
+ type EllipseProps,
5
+ type VectorProps,
6
+ type ComponentProps,
7
+ type InstanceProps,
8
+ type ParagraphProps,
9
+ type SpanProps,
10
+ type TextProps,
11
+ type TreeNode
12
+ } from './tree'
13
+
14
+ type Child = TreeNode | string
15
+
16
+ function withChildren(type: string, props: Record<string, unknown>, children: Child[]): TreeNode {
17
+ if (children.length > 0) {
18
+ return node(type, { ...props, children })
19
+ }
20
+ return node(type, props)
21
+ }
22
+
23
+ export function Frame(props: BaseProps, ...children: Child[]): TreeNode {
24
+ return withChildren('frame', props, children)
25
+ }
26
+
27
+ export function Text(props: TextProps, ...children: Child[]): TreeNode {
28
+ return withChildren('text', props, children)
29
+ }
30
+
31
+ export function Span(props: SpanProps, ...children: Child[]): TreeNode {
32
+ return withChildren('text-span', props, children)
33
+ }
34
+
35
+ export function Paragraph(props: ParagraphProps, ...children: Child[]): TreeNode {
36
+ return withChildren('text-paragraph', props, children)
37
+ }
38
+
39
+ export function Rectangle(props: BaseProps, ...children: Child[]): TreeNode {
40
+ return withChildren('rectangle', props, children)
41
+ }
42
+
43
+ export function Ellipse(props: BaseProps & EllipseProps, ...children: Child[]): TreeNode {
44
+ return withChildren('ellipse', props, children)
45
+ }
46
+
47
+ export function Line(props: BaseProps, ...children: Child[]): TreeNode {
48
+ return withChildren('line', props, children)
49
+ }
50
+
51
+ export function Star(
52
+ props: BaseProps & { points?: number; innerRadius?: number },
53
+ ...children: Child[]
54
+ ): TreeNode {
55
+ return withChildren('star', props, children)
56
+ }
57
+
58
+ export function Polygon(
59
+ props: BaseProps & { pointCount?: number },
60
+ ...children: Child[]
61
+ ): TreeNode {
62
+ return withChildren('polygon', props, children)
63
+ }
64
+
65
+ export function Vector(props: BaseProps & VectorProps, ...children: Child[]): TreeNode {
66
+ return withChildren('vector', props, children)
67
+ }
68
+
69
+ export function Group(props: BaseProps, ...children: Child[]): TreeNode {
70
+ return withChildren('group', props, children)
71
+ }
72
+
73
+ export function Section(props: BaseProps, ...children: Child[]): TreeNode {
74
+ return withChildren('section', props, children)
75
+ }
76
+
77
+ export function Component(props: ComponentProps, ...children: Child[]): TreeNode {
78
+ return withChildren('component', props, children)
79
+ }
80
+
81
+ export function ComponentSet(props: ComponentProps, ...children: Child[]): TreeNode {
82
+ return withChildren('component-set', props, children)
83
+ }
84
+
85
+ export function Instance(props: InstanceProps, ...children: Child[]): TreeNode {
86
+ return withChildren('instance', props, children)
87
+ }
88
+
89
+ export const View = Frame
90
+ export const Rect = Rectangle
91
+ export const Page = Frame
92
+
93
+ export const INTRINSIC_ELEMENTS = [
94
+ 'frame',
95
+ 'text',
96
+ 'text-span',
97
+ 'text-paragraph',
98
+ 'rectangle',
99
+ 'ellipse',
100
+ 'line',
101
+ 'star',
102
+ 'polygon',
103
+ 'vector',
104
+ 'group',
105
+ 'section',
106
+ 'component',
107
+ 'component-set',
108
+ 'instance'
109
+ ] as const