@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
package/src/tree.ts ADDED
@@ -0,0 +1,285 @@
1
+ import type { Effect, Fill } from '@pairdraw/scene-graph'
2
+ import type { Color } from '@pairdraw/scene-graph/primitives'
3
+
4
+ import type { ComponentProperty } from './component-properties'
5
+ import type { DesignMode, DesignVariable } from './variables'
6
+
7
+ export interface TreeNode {
8
+ type: string
9
+ props: Record<string, unknown>
10
+ children: (TreeNode | string)[]
11
+ /** Where the element was written, when the source is known. */
12
+ source?: { line: number }
13
+ }
14
+
15
+ /** A fragment (`<>…</>`) groups siblings without creating a node of its own. */
16
+ export const FRAGMENT = ''
17
+
18
+ function inlineFragments(children: (TreeNode | string)[]): (TreeNode | string)[] {
19
+ return children.flatMap((child) =>
20
+ typeof child !== 'string' && child.type === FRAGMENT ? child.children : [child]
21
+ )
22
+ }
23
+
24
+ /**
25
+ * The text an element holds as children, such as a sticky note's body or a connector's label.
26
+ * Elements among its children are not text and are skipped.
27
+ */
28
+ export function plainTextOf(tree: TreeNode): string {
29
+ return tree.children.filter((child): child is string => typeof child === 'string').join('')
30
+ }
31
+
32
+ export function isTreeNode(x: unknown): x is TreeNode {
33
+ if (x === null || typeof x !== 'object') return false
34
+ return (
35
+ 'type' in x &&
36
+ typeof x.type === 'string' &&
37
+ 'props' in x &&
38
+ 'children' in x &&
39
+ Array.isArray(x.children)
40
+ )
41
+ }
42
+
43
+ type FunctionComponent = (props: Record<string, unknown>) => unknown
44
+
45
+ interface ReactElement {
46
+ type: unknown
47
+ props: Record<string, unknown>
48
+ }
49
+
50
+ function isReactElement(x: unknown): x is ReactElement {
51
+ return x !== null && typeof x === 'object' && 'type' in x && 'props' in x
52
+ }
53
+
54
+ /**
55
+ * Resolve any element-like value (ReactElement, TreeNode, function component)
56
+ * into a TreeNode. Handles recursive function components up to depth 100.
57
+ */
58
+ export function resolveToTree(element: unknown, depth = 0): TreeNode | null {
59
+ if (depth > 100) throw new Error('Component resolution depth exceeded')
60
+ if (element == null) return null
61
+ if (isTreeNode(element)) return element
62
+ if (!isReactElement(element)) return null
63
+
64
+ if (typeof element.type === 'function') {
65
+ const component = element.type as FunctionComponent
66
+ return resolveToTree(component(element.props), depth + 1)
67
+ }
68
+
69
+ if (typeof element.type === 'string') {
70
+ const children: (TreeNode | string)[] = []
71
+ const elChildren = element.props.children
72
+ if (elChildren != null) {
73
+ const childArray = Array.isArray(elChildren) ? elChildren : [elChildren]
74
+ for (const child of childArray.flat()) {
75
+ if (child == null) continue
76
+ if (typeof child === 'string' || typeof child === 'number') {
77
+ children.push(String(child))
78
+ } else {
79
+ const resolved = resolveToTree(child, depth + 1)
80
+ if (resolved) children.push(resolved)
81
+ }
82
+ }
83
+ }
84
+ const { children: _, ...props } = element.props
85
+ return { type: element.type, props, children: inlineFragments(children) }
86
+ }
87
+
88
+ return null
89
+ }
90
+
91
+ function resolveChild(child: unknown): TreeNode | string | null {
92
+ if (child == null) return null
93
+ if (typeof child === 'string' || typeof child === 'number') return String(child)
94
+ return resolveToTree(child)
95
+ }
96
+
97
+ export function node(
98
+ type: string,
99
+ props: { children?: unknown; [key: string]: unknown }
100
+ ): TreeNode {
101
+ const { children, ...rest } = props
102
+ const processed = [children]
103
+ .flat(Infinity)
104
+ .map(resolveChild)
105
+ .filter((c): c is TreeNode | string => c !== null)
106
+ return { type, props: rest, children: inlineFragments(processed) }
107
+ }
108
+
109
+ export type PaintProp = string | Color | Fill | DesignVariable
110
+
111
+ export type StyleProps = {
112
+ flex?: 'row' | 'col' | 'column'
113
+ flow?: 'auto' | 'ltr' | 'rtl'
114
+ dir?: 'auto' | 'ltr' | 'rtl'
115
+ gap?: number | DesignVariable
116
+ wrap?: boolean
117
+ rowGap?: number | DesignVariable
118
+ columnGap?: number | DesignVariable
119
+ justify?: 'start' | 'end' | 'center' | 'between' | 'around'
120
+ justifyContent?: 'start' | 'end' | 'center' | 'between' | 'around'
121
+ items?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'
122
+ align?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'
123
+ alignItems?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'
124
+ grow?: number
125
+
126
+ w?: number | 'fill' | 'hug' | DesignVariable
127
+ h?: number | 'fill' | 'hug' | DesignVariable
128
+ minW?: number
129
+ maxW?: number
130
+ minH?: number
131
+ maxH?: number
132
+
133
+ x?: number
134
+ y?: number
135
+
136
+ p?: number | DesignVariable
137
+ px?: number | DesignVariable
138
+ py?: number | DesignVariable
139
+ pt?: number | DesignVariable
140
+ pr?: number | DesignVariable
141
+ pb?: number | DesignVariable
142
+ pl?: number | DesignVariable
143
+
144
+ bg?: PaintProp
145
+ fill?: PaintProp
146
+ fills?: PaintProp[]
147
+ stroke?: PaintProp
148
+ strokeWidth?: number | DesignVariable
149
+ strokeAlign?: 'inside' | 'outside' | 'center'
150
+ strokeDash?: number[] | boolean
151
+ dashPattern?: number[]
152
+ rounded?: number | DesignVariable
153
+ roundedTL?: number | DesignVariable
154
+ roundedTR?: number | DesignVariable
155
+ roundedBL?: number | DesignVariable
156
+ roundedBR?: number | DesignVariable
157
+ cornerSmoothing?: number
158
+ opacity?: number | DesignVariable
159
+ blendMode?: string
160
+ mask?: boolean | 'alpha' | 'luminance' | 'vector'
161
+ rotate?: number
162
+ rotation?: number
163
+ /** Reflects the layer across its vertical centre line, before it turns. */
164
+ flipX?: boolean
165
+ /** Reflects the layer across its horizontal centre line, before it turns. */
166
+ flipY?: boolean
167
+ overflow?: 'hidden' | 'visible'
168
+ shadow?: string
169
+ blur?: number
170
+ effects?: Effect[]
171
+
172
+ size?: number | DesignVariable
173
+ fontSize?: number | DesignVariable
174
+ /** Pixels, or a percent of the font size such as `'150%'`. */
175
+ lineHeight?: number | `${number}%` | 'auto' | DesignVariable
176
+ /** Pixels, or a percent of the font size such as `'5%'`. */
177
+ letterSpacing?: number | `${number}%` | DesignVariable
178
+ /** OpenType features on or off by tag, as CSS's `font-feature-settings`: `{ tnum: true }`. */
179
+ fontFeatures?: Record<string, boolean>
180
+ /** Variable-font axis values by tag, as CSS's `font-variation-settings`: `{ wght: 650 }`. */
181
+ fontVariations?: Record<string, number>
182
+ /** The language the text is in, as a BCP 47 tag such as `de` or `sr-Latn`. */
183
+ lang?: string | null
184
+ /**
185
+ * Whether a variable font's optical size follows the font size (`auto`, the default) or takes
186
+ * the `opsz` in `fontVariations` (`none`), as CSS's `font-optical-sizing`.
187
+ */
188
+ fontOpticalSizing?: 'auto' | 'none'
189
+ font?: string
190
+ fontFamily?: string
191
+ weight?: number | 'bold' | 'medium' | 'normal'
192
+ fontWeight?: number | 'bold' | 'medium' | 'normal'
193
+ color?: PaintProp
194
+ text?: string | ComponentProperty<string>
195
+ characters?: string
196
+ textAlign?: 'left' | 'center' | 'right' | 'justified'
197
+ textAlignHorizontal?: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'
198
+ textHorizontalAlignment?: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'
199
+ textAlignVertical?: 'TOP' | 'CENTER' | 'BOTTOM'
200
+ textVerticalAlignment?: 'TOP' | 'CENTER' | 'BOTTOM'
201
+ textAutoResize?: 'none' | 'width' | 'height'
202
+ }
203
+
204
+ type NodeProps = StyleProps & {
205
+ name?: string
206
+ key?: string | number
207
+ children?: unknown
208
+ bind?: Record<string, unknown>
209
+ visible?: boolean | ComponentProperty<boolean>
210
+ /** The modes the layer shows collections in, as the Appearance panel sets them. */
211
+ mode?: DesignMode | DesignMode[]
212
+ [key: string]: unknown
213
+ }
214
+
215
+ export type BaseProps = NodeProps & { properties?: never }
216
+
217
+ /** An `<Ellipse>`'s arc: angles in degrees, clockwise from three o'clock, and its hole. */
218
+ export type EllipseProps = {
219
+ startAngle?: number
220
+ endAngle?: number
221
+ /** The hole as a share of the ellipse, from 0 (none) to 1. */
222
+ innerRadius?: number
223
+ }
224
+ /** A `<Vector>`'s path, in SVG's syntax as `d` or as Figma's `vectorPaths`. */
225
+ export type VectorProps = {
226
+ /** Path data as SVG writes it, filled under `fillRule`; an open subpath fills only without a stroke. */
227
+ d?: string
228
+ fillRule?: 'nonzero' | 'evenodd'
229
+ /** Paths with their own winding rules, as export writes them; `NONE` draws an open path. */
230
+ paths?: Array<{ windingRule: 'NONZERO' | 'EVENODD' | 'NONE'; data: string }>
231
+ }
232
+ export type TextProps = BaseProps
233
+
234
+ /** A `<Span>`'s props: the character styles of `<Text>`, under the same names. */
235
+ export type SpanProps = Pick<
236
+ StyleProps,
237
+ | 'size'
238
+ | 'fontSize'
239
+ | 'font'
240
+ | 'fontFamily'
241
+ | 'weight'
242
+ | 'fontWeight'
243
+ | 'color'
244
+ | 'fill'
245
+ | 'fills'
246
+ | 'lineHeight'
247
+ | 'letterSpacing'
248
+ | 'fontFeatures'
249
+ | 'fontVariations'
250
+ | 'lang'
251
+ > & {
252
+ key?: string | number
253
+ style?: Record<string, unknown>
254
+ italic?: boolean
255
+ textDecoration?: 'none' | 'underline' | 'strikethrough'
256
+ textDecorationStyle?: 'solid' | 'dotted' | 'wavy'
257
+ textDecorationColor?: string | Color | Fill
258
+ textDecorationThickness?: number | 'auto'
259
+ textUnderlineOffset?: number | 'auto'
260
+ textDecorationSkipInk?: boolean
261
+ children?: unknown
262
+ }
263
+
264
+ /** A `<Paragraph>`'s props: a list item at `level` 1–5, or a plain paragraph, and its spacing. */
265
+ export type ParagraphProps = {
266
+ key?: string | number
267
+ list?: 'ordered' | 'unordered'
268
+ level?: number
269
+ spacing?: number
270
+ listSpacing?: number
271
+ indent?: number
272
+ children?: unknown
273
+ }
274
+
275
+ export type ComponentProps = BaseProps
276
+
277
+ export type InstanceProps = NodeProps & {
278
+ component?: string
279
+ componentId?: string
280
+ of?: string | ComponentProperty<string>
281
+ /** Show the instance's own properties on instances of the component it is in, as Figma does. */
282
+ exposed?: boolean
283
+ /** Values by property ID or name, or an exposed nested instance's values by its name. */
284
+ properties?: Record<string, string | boolean | number | Record<string, string | boolean | number>>
285
+ }
package/src/types.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ import type { TreeNode } from './tree'
4
+
5
+ export interface RenderOptions {
6
+ x?: number
7
+ y?: number
8
+ parentId?: string
9
+ /** Called for every layer created from an element, so callers can map source to layers. */
10
+ onNode?: (tree: TreeNode, node: SceneNode) => void
11
+ /** Leave layout to the caller, which lays out once after moving the roots into place. */
12
+ deferLayout?: boolean
13
+ }
@@ -0,0 +1,265 @@
1
+ import { isEqual } from 'es-toolkit'
2
+ import { isPlainObject } from 'es-toolkit/predicate'
3
+
4
+ import type {
5
+ SceneGraph,
6
+ Variable,
7
+ VariableCollection,
8
+ VariableLiteral,
9
+ VariableModeMap,
10
+ VariableType,
11
+ VariableValue
12
+ } from '@pairdraw/scene-graph'
13
+ import { tryParseColor } from '@pairdraw/scene-graph/color'
14
+ import { getNodeVariableModeId, resolveVariableInModes } from '@pairdraw/scene-graph/variables'
15
+
16
+ import { isTreeNode, type TreeNode } from '../tree'
17
+ import {
18
+ isMode,
19
+ isVariable,
20
+ type CollectionDefinition,
21
+ type DesignVariable,
22
+ type VariableInput
23
+ } from './index'
24
+
25
+ /**
26
+ * Every collection a value declares, through the variables and modes in it and their aliases;
27
+ * a collection comes after the ones it aliases, as it would be written.
28
+ */
29
+ function collectDefinitions(
30
+ value: unknown,
31
+ found: Map<string, CollectionDefinition>,
32
+ visiting = new Set<CollectionDefinition>()
33
+ ): void {
34
+ const definition = isVariable(value) || isMode(value) ? value.collection : undefined
35
+ if (definition && typeof definition !== 'string') {
36
+ const known = found.get(definition.name)
37
+ if (known === definition || visiting.has(definition)) return
38
+ if (known && !isEqual(known, definition))
39
+ throw new Error(`Collection ${definition.name} is defined twice with different variables`)
40
+ visiting.add(definition)
41
+ for (const mode of definition.modes) collectDefinitions(mode.values, found, visiting)
42
+ found.set(definition.name, definition)
43
+ return
44
+ }
45
+ if (isTreeNode(value)) {
46
+ collectDefinitions(value.props, found, visiting)
47
+ for (const child of value.children) collectDefinitions(child, found, visiting)
48
+ } else if (Array.isArray(value)) {
49
+ for (const item of value) collectDefinitions(item, found, visiting)
50
+ } else if (isPlainObject(value)) {
51
+ for (const item of Object.values(value)) collectDefinitions(item, found, visiting)
52
+ }
53
+ }
54
+
55
+ /** The one collection with this name; a name several collections share is an error. */
56
+ export function collectionNamed(graph: SceneGraph, name: string): VariableCollection | undefined {
57
+ const matches = [...graph.variableCollections.values()].filter((item) => item.name === name)
58
+ if (matches.length > 1)
59
+ throw new Error(`More than one variable collection is named ${name}; rename one to use it`)
60
+ return matches[0]
61
+ }
62
+
63
+ function variableNamed(
64
+ graph: SceneGraph,
65
+ collection: VariableCollection,
66
+ name: string
67
+ ): Variable | undefined {
68
+ for (const id of collection.variableIds) {
69
+ const variable = graph.variables.get(id)
70
+ if (variable?.name === name) return variable
71
+ }
72
+ return undefined
73
+ }
74
+
75
+ /** The collection, with its modes in place, by the definition's names. */
76
+ function ensureCollection(graph: SceneGraph, definition: CollectionDefinition): VariableCollection {
77
+ let collection = collectionNamed(graph, definition.name)
78
+ if (!collection) {
79
+ collection = graph.createCollection(definition.name)
80
+ graph.renameMode(collection.id, collection.defaultModeId, definition.modes[0].name)
81
+ }
82
+ for (const mode of definition.modes) {
83
+ if (!collection.modes.some((existing) => existing.name === mode.name))
84
+ graph.createMode(collection.id, mode.name)
85
+ }
86
+ const first = collection.modes.find((mode) => mode.name === definition.modes[0].name)
87
+ if (first && collection.defaultModeId !== first.modeId)
88
+ graph.setDefaultMode(collection.id, first.modeId)
89
+ return collection
90
+ }
91
+
92
+ function literalType(value: Exclude<VariableInput, DesignVariable>): VariableType {
93
+ if (typeof value === 'number') return 'FLOAT'
94
+ if (typeof value === 'boolean') return 'BOOLEAN'
95
+ return 'COLOR'
96
+ }
97
+
98
+ /** The type a defined variable holds: its first value's, or for an alias, its target's. */
99
+ function definedType(
100
+ graph: SceneGraph,
101
+ definition: CollectionDefinition,
102
+ name: string,
103
+ visiting = new Set<string>()
104
+ ): VariableType {
105
+ const key = `${definition.name}\u0000${name}`
106
+ if (visiting.has(key)) throw new Error(`Variable ${name} aliases itself`)
107
+ visiting.add(key)
108
+ const value = definition.modes[0].values[name]
109
+ if (!isVariable(value)) return literalType(value)
110
+ if (typeof value.collection === 'object')
111
+ return definedType(graph, value.collection, value.name, visiting)
112
+ const target = graph.variables.get(requireVariableId(graph, value))
113
+ if (!target) throw new Error(`Unknown variable: ${value.name}`)
114
+ return target.type
115
+ }
116
+
117
+ function storedValue(
118
+ graph: SceneGraph,
119
+ type: VariableType,
120
+ name: string,
121
+ value: VariableInput
122
+ ): VariableValue {
123
+ if (isVariable(value)) return { aliasId: requireVariableId(graph, value) }
124
+ if (literalType(value) !== type)
125
+ throw new Error(`Variable ${name} mixes ${type} with ${literalType(value)} values`)
126
+ if (typeof value !== 'string') return value
127
+ const color = tryParseColor(value)
128
+ if (!color) throw new Error(`Variable ${name} has "${value}", which is not a color`)
129
+ return color
130
+ }
131
+
132
+ /**
133
+ * Create or update the collections a tree defines, by name: their modes, their variables, and
134
+ * each variable's value in each mode, a mode's missing values taken from the first mode.
135
+ */
136
+ export function applyVariableDefinitions(graph: SceneGraph, tree: TreeNode): void {
137
+ const found = new Map<string, CollectionDefinition>()
138
+ collectDefinitions(tree, found)
139
+ const definitions = [...found.values()]
140
+ const collections = definitions.map((definition) => ensureCollection(graph, definition))
141
+
142
+ const variables = definitions.map((definition, index) => {
143
+ const collection = collections[index]
144
+ return Object.keys(definition.modes[0].values).map((name) => {
145
+ const type = definedType(graph, definition, name)
146
+ const existing = variableNamed(graph, collection, name)
147
+ if (existing && existing.type !== type)
148
+ throw new Error(`Variable ${name} in ${definition.name} is ${existing.type}, not ${type}`)
149
+ return existing ?? graph.createVariable(name, type, collection.id)
150
+ })
151
+ })
152
+
153
+ definitions.forEach((definition, index) => {
154
+ const collection = collections[index]
155
+ const [first] = definition.modes
156
+ for (const variable of variables[index]) {
157
+ for (const mode of definition.modes) {
158
+ const modeId = collection.modes.find((existing) => existing.name === mode.name)?.modeId
159
+ if (!modeId) continue
160
+ const value = mode.values[variable.name] ?? first.values[variable.name]
161
+ variable.valuesByMode[modeId] = storedValue(graph, variable.type, variable.name, value)
162
+ }
163
+ }
164
+ })
165
+ }
166
+
167
+ /** The ID of the variable a handle refers to: by collection and name, or by ID or name. */
168
+ export function resolveVariableId(graph: SceneGraph, variable: DesignVariable): string | undefined {
169
+ if (variable.collection) {
170
+ const name =
171
+ typeof variable.collection === 'string' ? variable.collection : variable.collection.name
172
+ const collection = collectionNamed(graph, name)
173
+ return collection && variableNamed(graph, collection, variable.name)?.id
174
+ }
175
+ if (graph.variables.has(variable.name)) return variable.name
176
+ const matches = [...graph.variables.values()].filter((item) => item.name === variable.name)
177
+ if (matches.length > 1) {
178
+ const [first] = matches
179
+ const collection = graph.variableCollections.get(first.collectionId)?.name ?? ''
180
+ throw new Error(
181
+ `Variable name ${variable.name} is in more than one collection; name one, as in designVar('${collection}', '${variable.name}')`
182
+ )
183
+ }
184
+ return matches[0]?.id
185
+ }
186
+
187
+ export function requireVariableId(graph: SceneGraph, variable: DesignVariable): string {
188
+ const id = resolveVariableId(graph, variable)
189
+ if (id) return id
190
+ const collection =
191
+ typeof variable.collection === 'object' ? variable.collection.name : variable.collection
192
+ throw new Error(
193
+ collection
194
+ ? `Unknown variable ${variable.name} in ${collection}`
195
+ : `Unknown variable: ${variable.name}`
196
+ )
197
+ }
198
+
199
+ /** The collection and mode IDs a layer's `mode` prop pins, by their names. */
200
+ export function variableModes(graph: SceneGraph, value: unknown): VariableModeMap | undefined {
201
+ if (value === undefined) return undefined
202
+ const modes: unknown[] = Array.isArray(value) ? value : [value]
203
+ const result: VariableModeMap = {}
204
+ for (const mode of modes) {
205
+ if (!isMode(mode)) throw new Error('mode takes defineMode() or designMode() modes')
206
+ const name = typeof mode.collection === 'string' ? mode.collection : mode.collection.name
207
+ const collection =
208
+ (typeof mode.collection === 'string' && graph.variableCollections.get(name)) ||
209
+ collectionNamed(graph, name)
210
+ if (!collection)
211
+ throw new Error(
212
+ `Unknown variable collection: ${name}. A defineVars() collection is added once a layer binds one of its variables`
213
+ )
214
+ const modeId = collection.modes.find((item) => item.name === mode.name)?.modeId
215
+ if (!modeId) throw new Error(`Collection ${name} has no mode named ${mode.name}`)
216
+ result[collection.id] = modeId
217
+ }
218
+ return result
219
+ }
220
+
221
+ /**
222
+ * A variable's value for a layer created under `parentId`, in the modes the layer pins or else
223
+ * the ones it inherits.
224
+ */
225
+ export function resolveForLayer(
226
+ graph: SceneGraph,
227
+ variableId: string,
228
+ parentId: string,
229
+ modes: VariableModeMap | undefined
230
+ ): VariableLiteral | undefined {
231
+ try {
232
+ return resolveVariableInModes(
233
+ graph,
234
+ variableId,
235
+ (collectionId) =>
236
+ modes?.[collectionId] ?? getNodeVariableModeId(graph, parentId, collectionId)
237
+ )
238
+ } catch {
239
+ return undefined
240
+ }
241
+ }
242
+
243
+ /** Where a layer is created, and the modes it pins, which give a variable its value there. */
244
+ export interface LayerContext {
245
+ parentId: string
246
+ modes: VariableModeMap | undefined
247
+ }
248
+
249
+ /** Bind the variable in `target[key]`, if it holds one, and put its value for the layer there. */
250
+ export function bindVariableProp(
251
+ graph: SceneGraph,
252
+ target: Record<string, unknown>,
253
+ bindings: Record<string, string>,
254
+ key: string,
255
+ field: string,
256
+ layer: LayerContext
257
+ ): void {
258
+ const value = target[key]
259
+ if (!isVariable(value)) return
260
+ const variableId = requireVariableId(graph, value)
261
+ bindings[field] = variableId
262
+ const resolved = resolveForLayer(graph, variableId, layer.parentId, layer.modes)
263
+ if (resolved === undefined) throw new Error(`Cannot resolve variable ${value.name} for ${key}`)
264
+ target[key] = resolved
265
+ }
@@ -0,0 +1,124 @@
1
+ import { isPlainObject } from 'es-toolkit/predicate'
2
+
3
+ import type { Color } from '@pairdraw/scene-graph/primitives'
4
+
5
+ const VAR_SYMBOL = Symbol.for('pairdraw.variable')
6
+ const MODE_SYMBOL = Symbol.for('pairdraw.variable-mode')
7
+
8
+ /** The name a collection's first mode has when `defineVars` names none, as Figma names it. */
9
+ export const DEFAULT_MODE_NAME = 'Mode 1'
10
+
11
+ /**
12
+ * A value a variable holds in one mode: a color as a string or a `Color`, a number, a boolean,
13
+ * or another variable, which makes it an alias.
14
+ */
15
+ export type VariableInput = string | Color | number | boolean | DesignVariable
16
+
17
+ /** A collection as `defineVars` and `defineMode` declare it; the first mode is the default. */
18
+ export interface CollectionDefinition {
19
+ name: string
20
+ modes: Array<{ name: string; values: Record<string, VariableInput> }>
21
+ }
22
+
23
+ /**
24
+ * A variable a field binds to. `defineVars` gives one its collection, which a render creates or
25
+ * updates; `designVar` names a variable the document already has, and may name its collection.
26
+ */
27
+ export interface DesignVariable {
28
+ readonly [VAR_SYMBOL]: true
29
+ /** The variable's name, or for `designVar` without a collection, its name or ID. */
30
+ readonly name: string
31
+ readonly collection?: CollectionDefinition | string
32
+ }
33
+
34
+ /**
35
+ * A mode a layer shows a collection in. `defineMode` gives it the collection it declares;
36
+ * `designMode` names a collection the document already has.
37
+ */
38
+ export interface DesignMode {
39
+ readonly [MODE_SYMBOL]: true
40
+ readonly name: string
41
+ readonly collection: CollectionDefinition | string
42
+ }
43
+
44
+ export function isVariable(value: unknown): value is DesignVariable {
45
+ return typeof value === 'object' && value !== null && VAR_SYMBOL in value
46
+ }
47
+
48
+ export function isMode(value: unknown): value is DesignMode {
49
+ return typeof value === 'object' && value !== null && MODE_SYMBOL in value
50
+ }
51
+
52
+ /** Whether a value can be a variable's value: a color, a number, a boolean, or a variable. */
53
+ export function isVariableInput(value: unknown): value is VariableInput {
54
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
55
+ return true
56
+ if (isVariable(value)) return true
57
+ return isPlainObject(value) && ['r', 'g', 'b', 'a'].every((key) => typeof value[key] === 'number')
58
+ }
59
+
60
+ /**
61
+ * A variable the document already has: by its name or ID, or by the names of its collection and
62
+ * itself, as `designMode` names a mode, for a name more than one collection has.
63
+ */
64
+ export function designVar(idOrName: string): DesignVariable
65
+ export function designVar(collection: string, name: string): DesignVariable
66
+ export function designVar(first: string, second?: string): DesignVariable {
67
+ return Object.freeze(
68
+ second === undefined
69
+ ? { [VAR_SYMBOL]: true as const, name: first }
70
+ : { [VAR_SYMBOL]: true as const, name: second, collection: first }
71
+ )
72
+ }
73
+
74
+ /**
75
+ * Define a variable collection: its variables, by name, with their values in its first mode,
76
+ * named `mode` (Figma's `Mode 1` by default). A render that binds any of them creates the
77
+ * collection, or updates the one with that name, so running the JSX again changes nothing twice.
78
+ */
79
+ export function defineVars<T extends Record<string, VariableInput>>(
80
+ collection: string,
81
+ values: T,
82
+ options: { mode?: string } = {}
83
+ ): { [K in keyof T]: DesignVariable } {
84
+ const definition: CollectionDefinition = {
85
+ name: collection,
86
+ modes: [{ name: options.mode ?? DEFAULT_MODE_NAME, values }]
87
+ }
88
+ const handles = {} as { [K in keyof T]: DesignVariable }
89
+ for (const name of Object.keys(values) as Array<keyof T & string>) {
90
+ handles[name] = Object.freeze({ [VAR_SYMBOL]: true as const, name, collection: definition })
91
+ }
92
+ return handles
93
+ }
94
+
95
+ /**
96
+ * Add a mode to a collection `defineVars` defined, with the values that differ from its first
97
+ * mode; the rest keep the first mode's values, as a mode Figma adds copies them.
98
+ */
99
+ export function defineMode(
100
+ vars: Record<string, DesignVariable>,
101
+ name: string,
102
+ values: Record<string, VariableInput>
103
+ ): DesignMode {
104
+ const definition = Object.values(vars)[0]?.collection
105
+ if (!definition || typeof definition === 'string')
106
+ throw new Error('defineMode() takes the variables defineVars() returned')
107
+ if (definition.modes.some((mode) => mode.name === name))
108
+ throw new Error(`Collection ${definition.name} already has a mode named ${name}`)
109
+ const known = definition.modes[0].values
110
+ for (const key of Object.keys(values)) {
111
+ if (!Object.hasOwn(known, key))
112
+ throw new Error(`Collection ${definition.name} has no variable named ${key}`)
113
+ }
114
+ definition.modes.push({ name, values })
115
+ return Object.freeze({ [MODE_SYMBOL]: true as const, name, collection: definition })
116
+ }
117
+
118
+ /**
119
+ * A mode of a collection the document already has, by their names, or by the collection's ID
120
+ * when several collections share its name.
121
+ */
122
+ export function designMode(collection: string, mode: string): DesignMode {
123
+ return Object.freeze({ [MODE_SYMBOL]: true as const, name: mode, collection })
124
+ }