@open-pencil/scene-graph 0.15.1 → 0.16.0-beta.2

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 (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +607 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +577 -522
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2291 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/group-bounds.js +104 -0
  34. package/dist/chunks/group-bounds.js.map +1 -0
  35. package/dist/chunks/icons/glyph.js +147 -0
  36. package/dist/chunks/icons/glyph.js.map +1 -0
  37. package/dist/chunks/index.js +1724 -663
  38. package/dist/chunks/index.js.map +1 -1
  39. package/dist/color.d.ts +72 -0
  40. package/dist/color.d.ts.map +1 -0
  41. package/dist/color.js +3 -0
  42. package/dist/constants.d.ts +2 -2
  43. package/dist/constants.js +2 -2
  44. package/dist/constants2.d.ts +3 -1
  45. package/dist/constants2.d.ts.map +1 -1
  46. package/dist/coordinate.d.ts +2 -448
  47. package/dist/coordinate.js +2 -2
  48. package/dist/copy.d.ts +1 -1
  49. package/dist/copy.js +1 -1
  50. package/dist/css.d.ts +39 -0
  51. package/dist/css.d.ts.map +1 -0
  52. package/dist/css.js +3 -0
  53. package/dist/geometry.d.ts +1 -1
  54. package/dist/geometry.js +1 -1
  55. package/dist/gradient.d.ts +51 -0
  56. package/dist/gradient.d.ts.map +1 -0
  57. package/dist/gradient.js +132 -0
  58. package/dist/gradient.js.map +1 -0
  59. package/dist/guides.d.ts +2 -2
  60. package/dist/guides.js +39 -0
  61. package/dist/guides.js.map +1 -0
  62. package/dist/hit-test.d.ts +2 -9
  63. package/dist/hit-test.js +176 -34
  64. package/dist/hit-test.js.map +1 -1
  65. package/dist/index.d.ts +4 -8
  66. package/dist/index.js +19 -5
  67. package/dist/instances.d.ts +2 -2
  68. package/dist/instances.js +2 -2
  69. package/dist/layout.d.ts +2 -0
  70. package/dist/layout.js +4 -0
  71. package/dist/node-defaults.d.ts +2 -8
  72. package/dist/node-defaults.js +2 -2
  73. package/dist/order-keys.d.ts +39 -0
  74. package/dist/order-keys.d.ts.map +1 -0
  75. package/dist/order-keys.js +136 -0
  76. package/dist/order-keys.js.map +1 -0
  77. package/dist/parse-path.d.ts +7 -1
  78. package/dist/parse-path.d.ts.map +1 -1
  79. package/dist/parse-path.js +6 -2
  80. package/dist/parse-path.js.map +1 -1
  81. package/dist/polygon.d.ts +53 -0
  82. package/dist/polygon.d.ts.map +1 -0
  83. package/dist/polygon.js +205 -0
  84. package/dist/polygon.js.map +1 -0
  85. package/dist/preview.d.ts +1 -1
  86. package/dist/random.d.ts +7 -0
  87. package/dist/random.d.ts.map +1 -0
  88. package/dist/random.js +2 -0
  89. package/dist/resize.d.ts +11 -2
  90. package/dist/resize.d.ts.map +1 -1
  91. package/dist/resize.js +2 -184
  92. package/dist/snap.d.ts +1 -1
  93. package/dist/text-direction.d.ts +13 -0
  94. package/dist/text-direction.d.ts.map +1 -0
  95. package/dist/text-direction.js +31 -0
  96. package/dist/text-direction.js.map +1 -0
  97. package/dist/text-picture.d.ts +1 -1
  98. package/dist/text-picture.d.ts.map +1 -1
  99. package/dist/text.d.ts +2 -0
  100. package/dist/text.js +3 -0
  101. package/dist/types.d.ts +2121 -15
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -1
  104. package/dist/types2.d.ts +2 -2
  105. package/dist/undo.d.ts +2 -2
  106. package/dist/undo.js +2 -2
  107. package/dist/undo2.d.ts +29 -1
  108. package/dist/undo2.d.ts.map +1 -1
  109. package/dist/variables.d.ts +2 -29
  110. package/dist/variables.js +2 -2
  111. package/dist/variant-properties.d.ts +9 -1
  112. package/dist/variant-properties.d.ts.map +1 -1
  113. package/dist/variant-properties.js +36 -1
  114. package/dist/variant-properties.js.map +1 -1
  115. package/dist/vector-network.d.ts +1 -1
  116. package/dist/vector-network.js +1 -1
  117. package/package.json +60 -9
  118. package/src/behaviours/kinds.ts +185 -0
  119. package/src/behaviours/layers.ts +51 -0
  120. package/src/behaviours/model.ts +192 -0
  121. package/src/behaviours/schema.ts +58 -0
  122. package/src/behaviours/spec.ts +223 -0
  123. package/src/buffered-events.ts +64 -0
  124. package/src/color/contrast.ts +31 -0
  125. package/src/color/index.ts +88 -0
  126. package/src/color/management.ts +210 -0
  127. package/src/color/normalize.ts +7 -0
  128. package/src/color/okhcl.ts +201 -0
  129. package/src/comments/document.ts +51 -0
  130. package/src/comments/list.ts +52 -0
  131. package/src/comments/merge.ts +63 -0
  132. package/src/comments/threads.ts +156 -0
  133. package/src/components/exposure.ts +61 -0
  134. package/src/components/properties.ts +18 -15
  135. package/src/components/variants.ts +53 -0
  136. package/src/constants.ts +2 -0
  137. package/src/coordinate.ts +100 -43
  138. package/src/copy.ts +17 -6
  139. package/src/css/grid.ts +70 -0
  140. package/src/css/index.ts +9 -0
  141. package/src/css/layout.ts +53 -0
  142. package/src/css/shadows.ts +68 -0
  143. package/src/css/values.ts +42 -0
  144. package/src/export-format.ts +12 -0
  145. package/src/fields/geometry.ts +11 -0
  146. package/src/fields/text.ts +35 -0
  147. package/src/gradient.ts +166 -0
  148. package/src/group-bounds.ts +131 -0
  149. package/src/guides.ts +39 -0
  150. package/src/hit-test.ts +262 -46
  151. package/src/icons/glyph.ts +128 -0
  152. package/src/icons/model.ts +54 -0
  153. package/src/icons/schema.ts +18 -0
  154. package/src/index.ts +347 -57
  155. package/src/instance-overrides.ts +27 -0
  156. package/src/instances/content-size.ts +58 -0
  157. package/src/instances/copies.ts +239 -0
  158. package/src/instances/cycles.ts +73 -0
  159. package/src/instances/fields.ts +143 -0
  160. package/src/instances/main-component.ts +19 -0
  161. package/src/instances/placement.ts +29 -0
  162. package/src/instances/source-walk.ts +41 -0
  163. package/src/instances/sync.ts +600 -0
  164. package/src/instances/vector-geometry.ts +81 -0
  165. package/src/instances.ts +125 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +41 -12
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/shared-styles.ts +5 -2
  187. package/src/slots/authoring.ts +101 -0
  188. package/src/slots/content.ts +124 -0
  189. package/src/slots/frames.ts +160 -0
  190. package/src/slots/limits.ts +49 -0
  191. package/src/text/direction.ts +55 -0
  192. package/src/text/index.ts +3 -0
  193. package/src/text/lists.ts +138 -0
  194. package/src/text/paragraphs.ts +241 -0
  195. package/src/{text-picture.ts → text/picture.ts} +21 -29
  196. package/src/text/references.ts +50 -0
  197. package/src/transfer/apply.ts +84 -0
  198. package/src/transfer/history.ts +49 -0
  199. package/src/transfer/identity.ts +16 -0
  200. package/src/transfer/index.ts +6 -0
  201. package/src/transfer/nodes.ts +120 -0
  202. package/src/transfer/plan.ts +130 -0
  203. package/src/transfer/references.ts +9 -0
  204. package/src/transfer/remove.ts +39 -0
  205. package/src/transfer/validation.ts +59 -0
  206. package/src/transfer/variables.ts +82 -0
  207. package/src/types.ts +257 -13
  208. package/src/undo.ts +54 -2
  209. package/src/variables/bindings.ts +224 -0
  210. package/src/variables/fields.ts +43 -0
  211. package/src/variables/token.ts +14 -0
  212. package/src/variables/units.ts +15 -0
  213. package/src/variables.ts +118 -69
  214. package/src/variant-properties.ts +50 -0
  215. package/dist/chunks/components/properties.js.map +0 -1
  216. package/dist/chunks/export-scale.js +0 -19
  217. package/dist/chunks/export-scale.js.map +0 -1
  218. package/dist/coordinate.d.ts.map +0 -1
  219. package/dist/coordinate2.d.ts +0 -2
  220. package/dist/guides2.d.ts +0 -11
  221. package/dist/guides2.d.ts.map +0 -1
  222. package/dist/hit-test.d.ts.map +0 -1
  223. package/dist/layout-guides.d.ts +0 -2
  224. package/dist/layout-guides.js +0 -2
  225. package/dist/layout-guides2.d.ts +0 -16
  226. package/dist/layout-guides2.d.ts.map +0 -1
  227. package/dist/node-defaults.d.ts.map +0 -1
  228. package/dist/preview2.d.ts +0 -12
  229. package/dist/preview2.d.ts.map +0 -1
  230. package/dist/resize.js.map +0 -1
  231. package/dist/variables.d.ts.map +0 -1
  232. package/dist/vector-network2.d.ts +0 -32
  233. package/dist/vector-network2.d.ts.map +0 -1
  234. package/src/instance-overrides.test.ts +0 -67
@@ -0,0 +1,224 @@
1
+ import { copyFills, copyStrokes } from '../copy'
2
+ import type { SceneGraph } from '../index'
3
+ import { hasInstanceOverride } from '../instances'
4
+ import type { Color } from '../primitives'
5
+ import type { Fill, SceneNode, Stroke, StyleRun } from '../types'
6
+ import type { VariableModeFallback } from '../variables'
7
+ import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
8
+ export { isNumericVariableBindingField } from './fields'
9
+
10
+ /** New declarations belong to the outermost occurrence, bounded by a component definition. */
11
+ export function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {
12
+ let owner = node
13
+ let current: SceneNode | undefined = node
14
+ while (current) {
15
+ if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break
16
+ if (current.type === 'INSTANCE') owner = current
17
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
18
+ }
19
+ return owner
20
+ }
21
+
22
+ export function assignVariableBindingUnits(
23
+ graph: SceneGraph,
24
+ node: SceneNode,
25
+ field: string
26
+ ): void {
27
+ if (!isNumericVariableBindingField(field)) return
28
+ const owner = variableBindingOwner(graph, node)
29
+ node.variableBindingScales = {
30
+ ...node.variableBindingScales,
31
+ [field]: owner.variableAssignmentScales[field] ?? 1
32
+ }
33
+ }
34
+
35
+ /**
36
+ * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields
37
+ * whose stored value differs. A width or height an instance overrides keeps its own value.
38
+ */
39
+ export function resolvedNumericBindings(
40
+ graph: SceneGraph,
41
+ node: SceneNode,
42
+ fallback: VariableModeFallback = 'active'
43
+ ): Partial<SceneNode> {
44
+ const updates: Partial<SceneNode> = {}
45
+ for (const [field, variableId] of Object.entries(node.boundVariables)) {
46
+ if (!NUMERIC_FIELDS.has(field)) continue
47
+ if ((field === 'width' || field === 'height') && hasInstanceOverride(graph, node.id, field))
48
+ continue
49
+ const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)
50
+ if (value === undefined || !Number.isFinite(value)) continue
51
+ const scale = node.variableBindingScales[field] ?? 1
52
+ const effective = value * scale
53
+ if (!Number.isFinite(effective)) continue
54
+ const next = field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective
55
+ if (node[field as keyof SceneNode] !== next) Object.assign(updates, { [field]: next })
56
+ }
57
+ return updates
58
+ }
59
+
60
+ /**
61
+ * The text and visibility a node's string and boolean bindings resolve to in its mode, for the
62
+ * fields whose stored value differs. Text or visibility an instance overrides, which typing in a
63
+ * layer or toggling its eye records, keeps its own value, as an overridden width or height does.
64
+ * A bound font family is left as stored: changing it needs the font loaded, which resolving a
65
+ * binding cannot do.
66
+ */
67
+ export function resolvedValueBindings(
68
+ graph: SceneGraph,
69
+ node: SceneNode,
70
+ fallback: VariableModeFallback = 'active'
71
+ ): Partial<SceneNode> {
72
+ const updates: Partial<SceneNode> = {}
73
+ const resolve = (field: 'text' | 'visible') => {
74
+ const variableId = node.boundVariables[field]
75
+ if (!variableId || hasInstanceOverride(graph, node.id, field)) return undefined
76
+ return graph.resolveVariableForNode(node.id, variableId, fallback)
77
+ }
78
+ const text = node.type === 'TEXT' ? resolve('text') : undefined
79
+ if (typeof text === 'string' && text !== node.text) updates.text = text
80
+ const visible = resolve('visible')
81
+ if (typeof visible === 'boolean' && visible !== node.visible) updates.visible = visible
82
+ return updates
83
+ }
84
+
85
+ /** Fields of a range of characters a bound number gives its value; the rest need fonts loaded. */
86
+ const NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const
87
+
88
+ /**
89
+ * The runs a text's character bindings resolve to in its mode, when a bound number differs from
90
+ * what its characters hold. Bound font families and styles are left as stored, as the text's own.
91
+ */
92
+ export function resolvedRunBindings(
93
+ graph: SceneGraph,
94
+ node: SceneNode,
95
+ fallback: VariableModeFallback = 'active'
96
+ ): Pick<Partial<SceneNode>, 'styleRuns'> {
97
+ const styleRuns = node.styleRuns.map((run): StyleRun => {
98
+ const bound = run.style.boundVariables
99
+ if (!bound) return run
100
+ let style = run.style
101
+ for (const field of NUMERIC_RUN_FIELDS) {
102
+ const variableId = bound[field]
103
+ if (!variableId) continue
104
+ const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)
105
+ if (value === undefined || !Number.isFinite(value) || style[field] === value) continue
106
+ style = { ...style, [field]: value }
107
+ }
108
+ return style === run.style ? run : { ...run, style }
109
+ })
110
+ const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])
111
+ return changed ? { styleRuns } : {}
112
+ }
113
+
114
+ /** The variables a node binds, its own and its characters'. */
115
+ function boundVariableIds(node: SceneNode): string[] {
116
+ return [
117
+ ...Object.values(node.boundVariables),
118
+ ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))
119
+ ].filter((id): id is string => typeof id === 'string')
120
+ }
121
+
122
+ /**
123
+ * A bound paint takes its whole color from the variable, alpha included, the way Figma stores
124
+ * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
125
+ */
126
+ function applyBoundColor(paint: Fill | Stroke, color: Color): void {
127
+ paint.color = { ...color, a: 1 }
128
+ paint.opacity = color.a
129
+ }
130
+
131
+ /** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */
132
+ export function resolvedPaintBindings(
133
+ graph: SceneGraph,
134
+ node: SceneNode,
135
+ fallback: VariableModeFallback = 'active'
136
+ ): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {
137
+ // Most nodes bind nothing, so no copy is made until a paint binding is actually found.
138
+ const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}
139
+ for (const field in node.boundVariables) {
140
+ if (!field.endsWith('/color')) continue
141
+ const match = /^(fills|strokes)\/(\d+)\/color$/.exec(field)
142
+ if (!match) continue
143
+ const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback)
144
+ const index = Number(match[2])
145
+ if (!color) continue
146
+ if (match[1] === 'fills') {
147
+ if (!node.fills[index]) continue
148
+ changes.fills ??= copyFills(node.fills)
149
+ applyBoundColor(changes.fills[index], color)
150
+ } else {
151
+ if (!node.strokes[index]) continue
152
+ changes.strokes ??= copyStrokes(node.strokes)
153
+ applyBoundColor(changes.strokes[index], color)
154
+ }
155
+ }
156
+ return changes
157
+ }
158
+
159
+ /**
160
+ * The layers a reconcile looks at: those bound to these variables, directly or through a variable
161
+ * aliasing them, or the layers in these subtrees. Without a scope, every layer.
162
+ */
163
+ export type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }
164
+
165
+ /** These variables and every variable that aliases one of them, at any depth and in any mode. */
166
+ export function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {
167
+ const found = new Set(ids)
168
+ let grew = true
169
+ while (grew) {
170
+ grew = false
171
+ for (const variable of graph.variables.values()) {
172
+ if (found.has(variable.id)) continue
173
+ const aliases = Object.values(variable.valuesByMode).some(
174
+ (value) => typeof value === 'object' && 'aliasId' in value && found.has(value.aliasId)
175
+ )
176
+ if (aliases) {
177
+ found.add(variable.id)
178
+ grew = true
179
+ }
180
+ }
181
+ }
182
+ return found
183
+ }
184
+
185
+ function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {
186
+ const nodes: SceneNode[] = []
187
+ const pending = [...roots]
188
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
189
+ const node = graph.getNode(id)
190
+ if (!node) continue
191
+ nodes.push(node)
192
+ pending.push(...node.childIds)
193
+ }
194
+ return nodes
195
+ }
196
+
197
+ function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {
198
+ if (!scope) return graph.getAllNodes()
199
+ if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)
200
+ const variables = variablesResolvingThrough(graph, scope.variables)
201
+ return [...graph.getAllNodes()].filter((node) =>
202
+ boundVariableIds(node).some((id) => variables.has(id))
203
+ )
204
+ }
205
+
206
+ /**
207
+ * Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
208
+ * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved
209
+ * values differ from their bindings elsewhere in the document are left as saved.
210
+ */
211
+ export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {
212
+ const changed: string[] = []
213
+ for (const node of scopedNodes(graph, scope)) {
214
+ const updates = {
215
+ ...resolvedNumericBindings(graph, node),
216
+ ...resolvedValueBindings(graph, node),
217
+ ...resolvedRunBindings(graph, node)
218
+ }
219
+ if (Object.keys(updates).length === 0) continue
220
+ graph.updateNode(node.id, updates)
221
+ changed.push(node.id)
222
+ }
223
+ return changed
224
+ }
@@ -0,0 +1,43 @@
1
+ export const NUMERIC_FIELDS = new Set([
2
+ 'opacity',
3
+ 'width',
4
+ 'height',
5
+ 'minWidth',
6
+ 'maxWidth',
7
+ 'minHeight',
8
+ 'maxHeight',
9
+ 'x',
10
+ 'y',
11
+ 'rotation',
12
+ 'cornerRadius',
13
+ 'topLeftRadius',
14
+ 'topRightRadius',
15
+ 'bottomLeftRadius',
16
+ 'bottomRightRadius',
17
+ 'strokeWeight',
18
+ 'borderTopWeight',
19
+ 'borderBottomWeight',
20
+ 'borderLeftWeight',
21
+ 'borderRightWeight',
22
+ 'fontSize',
23
+ 'letterSpacing',
24
+ 'lineHeight',
25
+ 'paddingLeft',
26
+ 'paddingRight',
27
+ 'paddingTop',
28
+ 'paddingBottom',
29
+ 'itemSpacing',
30
+ 'counterAxisSpacing',
31
+ 'gridRowGap',
32
+ 'gridColumnGap'
33
+ ])
34
+
35
+ export function isNumericVariableBindingField(field: string): boolean {
36
+ return NUMERIC_FIELDS.has(field)
37
+ }
38
+
39
+ /** Text content and font family are the string-valued bindings a node accepts. */
40
+ export const STRING_BINDING_FIELDS: ReadonlySet<string> = new Set(['text', 'fontFamily'])
41
+
42
+ /** Visibility is the only boolean-valued binding a node accepts. */
43
+ export const BOOLEAN_BINDING_FIELDS: ReadonlySet<string> = new Set(['visible'])
@@ -0,0 +1,14 @@
1
+ import type { TokenUnit } from '../types'
2
+
3
+ /** `rem` tokens are stored in canvas pixels and shown against this root font size. */
4
+ export const ROOT_FONT_SIZE_PX = 16
5
+
6
+ /** The stored number for a value typed in a unit: `1.5` in `rem` is 24 canvas pixels. */
7
+ export function tokenNumberFromUnit(value: number, unit: TokenUnit): number {
8
+ return unit === 'rem' ? value * ROOT_FONT_SIZE_PX : value
9
+ }
10
+
11
+ /** A stored number as it reads in its unit: 24 canvas pixels in `rem` is `1.5`. */
12
+ export function tokenNumberInUnit(value: number, unit: TokenUnit): number {
13
+ return unit === 'rem' ? value / ROOT_FONT_SIZE_PX : value
14
+ }
@@ -0,0 +1,15 @@
1
+ import type { SceneNode } from '../types'
2
+ import { NUMERIC_FIELDS } from './fields'
3
+
4
+ export function scaleVariableBindingUnits(node: SceneNode, factor: number): Partial<SceneNode> {
5
+ const variableBindingScales = { ...node.variableBindingScales }
6
+ const variableAssignmentScales = { ...node.variableAssignmentScales }
7
+ for (const field of NUMERIC_FIELDS) {
8
+ if (field === 'opacity' || field === 'rotation') continue
9
+ if (field in node.boundVariables)
10
+ variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor
11
+ if (node.type === 'INSTANCE')
12
+ variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor
13
+ }
14
+ return { variableBindingScales, variableAssignmentScales }
15
+ }
package/src/variables.ts CHANGED
@@ -1,10 +1,24 @@
1
+ import { partition } from 'es-toolkit/array'
1
2
  import { omit, omitBy } from 'es-toolkit/object'
2
3
 
3
4
  import { BLACK } from './constants'
4
5
  import type { SceneGraph } from './index'
5
6
  import { setInstanceOverride } from './instance-overrides'
7
+ import { findInstanceAncestor } from './instances'
6
8
  import type { Color } from './primitives'
7
- import type { Variable, VariableCollection, VariableType, VariableValue } from './types'
9
+ import type {
10
+ Variable,
11
+ VariableCollection,
12
+ VariableCollectionMode,
13
+ VariableType,
14
+ VariableValue
15
+ } from './types'
16
+ import {
17
+ isNumericVariableBindingField,
18
+ variableBindingOwner,
19
+ assignVariableBindingUnits
20
+ } from './variables/bindings'
21
+ import { BOOLEAN_BINDING_FIELDS, STRING_BINDING_FIELDS } from './variables/fields'
8
22
 
9
23
  export function addVariable(graph: SceneGraph, variable: Variable): void {
10
24
  graph.variables.set(variable.id, variable)
@@ -25,11 +39,19 @@ export function removeVariable(graph: SceneGraph, id: string): void {
25
39
  for (const node of graph.nodes.values()) {
26
40
  const hadBinding = Object.values(node.boundVariables).includes(id)
27
41
  if (!hadBinding) continue
42
+ graph.willChangeNode(node)
28
43
  node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<
29
44
  string,
30
45
  string
31
46
  >
32
- graph.emitter.emit('node:updated', node.id, { boundVariables: { ...node.boundVariables } })
47
+ node.variableBindingScales = omitBy(
48
+ node.variableBindingScales,
49
+ (_, field) => !(field in node.boundVariables)
50
+ )
51
+ graph.emitter.emit('node:updated', node.id, {
52
+ boundVariables: { ...node.boundVariables },
53
+ variableBindingScales: { ...node.variableBindingScales }
54
+ })
33
55
  markBoundVariablesOverrideOnInstance(graph, node.id)
34
56
  }
35
57
  }
@@ -114,10 +136,17 @@ export function getActiveModeId(graph: SceneGraph, collectionId: string): string
114
136
  return collection?.defaultModeId ?? ''
115
137
  }
116
138
 
139
+ /**
140
+ * What a node without an explicit mode falls back to: the mode the editor shows (`active`), or
141
+ * the collection's default (`default`), which is what a saved document means to other tools.
142
+ */
143
+ export type VariableModeFallback = 'active' | 'default'
144
+
117
145
  export function getNodeVariableModeId(
118
146
  graph: SceneGraph,
119
147
  nodeId: string,
120
- collectionId: string
148
+ collectionId: string,
149
+ fallback: VariableModeFallback = 'active'
121
150
  ): string {
122
151
  let node = graph.nodes.get(nodeId)
123
152
  while (node) {
@@ -125,6 +154,8 @@ export function getNodeVariableModeId(
125
154
  if (modeId) return modeId
126
155
  node = node.parentId ? graph.nodes.get(node.parentId) : undefined
127
156
  }
157
+ if (fallback === 'default')
158
+ return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''
128
159
  return getActiveModeId(graph, collectionId)
129
160
  }
130
161
 
@@ -152,6 +183,20 @@ export function addMode(
152
183
  }
153
184
  }
154
185
 
186
+ /** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */
187
+ export function createMode(
188
+ graph: SceneGraph,
189
+ generateId: () => string,
190
+ collectionId: string,
191
+ name: string,
192
+ sourceMode?: string
193
+ ): string | undefined {
194
+ if (!graph.variableCollections.has(collectionId)) return undefined
195
+ const modeId = generateId()
196
+ addMode(graph, collectionId, modeId, name, sourceMode)
197
+ return modeId
198
+ }
199
+
155
200
  export function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {
156
201
  const collection = graph.variableCollections.get(collectionId)
157
202
  if (!collection || collection.modes.length <= 1) return
@@ -185,6 +230,13 @@ export function setDefaultMode(graph: SceneGraph, collectionId: string, modeId:
185
230
  if (!collection) return
186
231
  if (!collection.modes.some((m) => m.modeId === modeId)) return
187
232
  collection.defaultModeId = modeId
233
+ collection.modes = modesDefaultFirst(collection)
234
+ }
235
+
236
+ /** Figma has no default-mode field: the first mode is the default. */
237
+ export function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {
238
+ const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)
239
+ return [...defaults, ...rest]
188
240
  }
189
241
 
190
242
  export function resolveVariable(
@@ -232,11 +284,12 @@ export function resolveNumberVariable(graph: SceneGraph, variableId: string): nu
232
284
  export function resolveColorVariableForNode(
233
285
  graph: SceneGraph,
234
286
  nodeId: string,
235
- variableId: string
287
+ variableId: string,
288
+ fallback: VariableModeFallback = 'active'
236
289
  ): Color | undefined {
237
290
  const variable = graph.variables.get(variableId)
238
291
  if (!variable) return undefined
239
- const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId)
292
+ const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback)
240
293
  const value = resolveVariable(graph, variableId, modeId)
241
294
  if (value && typeof value === 'object' && 'r' in value) return value
242
295
  return undefined
@@ -245,15 +298,39 @@ export function resolveColorVariableForNode(
245
298
  export function resolveNumberVariableForNode(
246
299
  graph: SceneGraph,
247
300
  nodeId: string,
248
- variableId: string
301
+ variableId: string,
302
+ fallback: VariableModeFallback = 'active'
249
303
  ): number | undefined {
250
304
  const variable = graph.variables.get(variableId)
251
305
  if (!variable) return undefined
252
- const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId)
306
+ const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback)
253
307
  const value = resolveVariable(graph, variableId, modeId)
254
308
  return typeof value === 'number' ? value : undefined
255
309
  }
256
310
 
311
+ /** A variable's value in the mode a node is in, aliases followed. */
312
+ export function resolveVariableForNode(
313
+ graph: SceneGraph,
314
+ nodeId: string,
315
+ variableId: string,
316
+ fallback: VariableModeFallback = 'active'
317
+ ): VariableValue | undefined {
318
+ const variable = graph.variables.get(variableId)
319
+ if (!variable) return undefined
320
+ const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback)
321
+ return resolveVariable(graph, variableId, modeId)
322
+ }
323
+
324
+ export function resolveStringVariableForNode(
325
+ graph: SceneGraph,
326
+ nodeId: string,
327
+ variableId: string,
328
+ fallback: VariableModeFallback = 'active'
329
+ ): string | undefined {
330
+ const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
331
+ return typeof value === 'string' ? value : undefined
332
+ }
333
+
257
334
  export function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {
258
335
  const collection = graph.variableCollections.get(collectionId)
259
336
  if (!collection) return []
@@ -266,44 +343,6 @@ export function getVariablesByType(graph: SceneGraph, type: VariableType): Varia
266
343
  return [...graph.variables.values()].filter((v) => v.type === type)
267
344
  }
268
345
 
269
- const SCALAR_BINDING_FIELDS: ReadonlySet<string> = new Set([
270
- 'opacity',
271
- 'width',
272
- 'height',
273
- 'cornerRadius',
274
- 'fontSize',
275
- 'letterSpacing',
276
- 'lineHeight',
277
- 'itemSpacing',
278
- 'strokeWeight',
279
- 'paddingLeft',
280
- 'paddingRight',
281
- 'paddingTop',
282
- 'paddingBottom',
283
- 'counterAxisSpacing',
284
- 'topLeftRadius',
285
- 'topRightRadius',
286
- 'bottomLeftRadius',
287
- 'bottomRightRadius',
288
- 'rotation',
289
- 'x',
290
- 'y',
291
- 'minWidth',
292
- 'maxWidth',
293
- 'minHeight',
294
- 'maxHeight',
295
- 'borderTopWeight',
296
- 'borderBottomWeight',
297
- 'borderLeftWeight',
298
- 'borderRightWeight',
299
- 'gridRowGap',
300
- 'gridColumnGap'
301
- ])
302
-
303
- const STRING_BINDING_FIELDS: ReadonlySet<string> = new Set(['fontFamily'])
304
-
305
- const BOOLEAN_BINDING_FIELDS: ReadonlySet<string> = new Set(['visible'])
306
-
307
346
  export function bindVariable(
308
347
  graph: SceneGraph,
309
348
  nodeId: string,
@@ -339,7 +378,7 @@ export function bindVariable(
339
378
  }
340
379
  }
341
380
 
342
- if (SCALAR_BINDING_FIELDS.has(field) && variable.type !== 'FLOAT') {
381
+ if (isNumericVariableBindingField(field) && variable.type !== 'FLOAT') {
343
382
  throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`)
344
383
  }
345
384
 
@@ -352,7 +391,7 @@ export function bindVariable(
352
391
  }
353
392
 
354
393
  const isKnownField =
355
- SCALAR_BINDING_FIELDS.has(field) ||
394
+ isNumericVariableBindingField(field) ||
356
395
  STRING_BINDING_FIELDS.has(field) ||
357
396
  BOOLEAN_BINDING_FIELDS.has(field) ||
358
397
  colorFieldMatch
@@ -361,39 +400,49 @@ export function bindVariable(
361
400
  throw new Error(`Unknown binding field "${field}"`)
362
401
  }
363
402
 
403
+ graph.willChangeNode(node)
364
404
  node.boundVariables = { ...node.boundVariables, [field]: variableId }
365
- graph.emitter.emit('node:updated', nodeId, { boundVariables: { ...node.boundVariables } })
366
- markBoundVariablesOverrideOnInstance(graph, nodeId)
405
+ assignVariableBindingUnits(graph, node, field)
406
+ markBoundVariablesOverrideOnInstance(graph, nodeId, field)
407
+ graph.emitter.emit('node:updated', nodeId, {
408
+ boundVariables: { ...node.boundVariables },
409
+ variableBindingScales: { ...node.variableBindingScales }
410
+ })
367
411
  }
368
412
 
369
413
  export function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {
370
414
  const node = graph.nodes.get(nodeId)
371
415
  if (!node) return
372
416
  if (!(field in node.boundVariables)) return
417
+ graph.willChangeNode(node)
373
418
  node.boundVariables = omit(node.boundVariables, [field])
374
- graph.emitter.emit('node:updated', nodeId, { boundVariables: { ...node.boundVariables } })
375
- markBoundVariablesOverrideOnInstance(graph, nodeId)
419
+ node.variableBindingScales = omit(node.variableBindingScales, [field])
420
+ markBoundVariablesOverrideOnInstance(graph, nodeId, field)
421
+ graph.emitter.emit('node:updated', nodeId, {
422
+ boundVariables: { ...node.boundVariables },
423
+ variableBindingScales: { ...node.variableBindingScales }
424
+ })
376
425
  }
377
426
 
378
- function markBoundVariablesOverrideOnInstance(graph: SceneGraph, nodeId: string): void {
427
+ function markBoundVariablesOverrideOnInstance(
428
+ graph: SceneGraph,
429
+ nodeId: string,
430
+ field?: string
431
+ ): void {
379
432
  const node = graph.nodes.get(nodeId)
380
433
  if (!node) return
381
434
 
382
- // Mark the field on the canonical structured state.
383
- if (node.type === 'INSTANCE') {
384
- setInstanceOverride(node.instanceOverrides, node.id, node.id, 'boundVariables')
385
- return
386
- }
387
-
388
- // Walk up to the owning instance for descendant fields.
389
- let current = node
390
- while (current.parentId) {
391
- const parent = graph.nodes.get(current.parentId)
392
- if (!parent) break
393
- if (parent.type === 'INSTANCE') {
394
- setInstanceOverride(parent.instanceOverrides, parent.id, nodeId, 'boundVariables')
395
- break
396
- }
397
- current = parent
398
- }
435
+ const owner = variableBindingOwner(graph, node)
436
+ if (owner.type !== 'INSTANCE') return
437
+ const nearest = findInstanceAncestor(graph, nodeId)
438
+ if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')
439
+ setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')
440
+ if (field)
441
+ setInstanceOverride(
442
+ owner.instanceOverrides,
443
+ owner.id,
444
+ nodeId,
445
+ `boundVariables/${field}`,
446
+ node.boundVariables[field] ?? null
447
+ )
399
448
  }
@@ -1,4 +1,7 @@
1
+ import { uniq } from 'es-toolkit/array'
2
+
1
3
  import type { ComponentPropertyDefinition, SceneNode } from './types'
4
+ import { buildVariantName, parseVariantName } from './variant-name'
2
5
 
3
6
  export interface DerivedVariantProperties {
4
7
  definitions: ComponentPropertyDefinition[]
@@ -46,3 +49,50 @@ export function deriveSlashVariantProperties(
46
49
 
47
50
  return { definitions, variants }
48
51
  }
52
+
53
+ /**
54
+ * Variant properties from names written as `Property=Value` pairs, as Figma names variants:
55
+ * `State=On, Size=Large` gives State and Size. Every component must name at least one pair;
56
+ * a property a component leaves out takes an empty value.
57
+ */
58
+ export function deriveNamedVariantProperties(
59
+ components: ReadonlyArray<Pick<SceneNode, 'id' | 'name'>>,
60
+ createPropertyId: () => string
61
+ ): DerivedVariantProperties | null {
62
+ const parsed = components.map((component) => parseVariantName(component.name))
63
+ if (parsed.some((values) => Object.keys(values).length === 0)) return null
64
+ const names = uniq(parsed.flatMap((values) => Object.keys(values)))
65
+ const definitions: ComponentPropertyDefinition[] = names.map((name) => {
66
+ const options = uniq(parsed.map((values) => values[name] ?? ''))
67
+ return {
68
+ id: createPropertyId(),
69
+ name,
70
+ type: 'VARIANT',
71
+ defaultValue: options[0] ?? '',
72
+ variantOptions: options
73
+ }
74
+ })
75
+ const variants = new Map(
76
+ components.map((component, index) => {
77
+ const componentPropertyValues = Object.fromEntries(
78
+ names.map((name) => [name, parsed[index][name] ?? ''])
79
+ )
80
+ return [
81
+ component.id,
82
+ { componentPropertyValues, name: buildVariantName(componentPropertyValues) }
83
+ ]
84
+ })
85
+ )
86
+ return { definitions, variants }
87
+ }
88
+
89
+ /** Variant properties from component names: slash paths first, else `Property=Value` pairs. */
90
+ export function deriveVariantProperties(
91
+ components: ReadonlyArray<Pick<SceneNode, 'id' | 'name'>>,
92
+ createPropertyId: () => string
93
+ ): DerivedVariantProperties | null {
94
+ return (
95
+ deriveSlashVariantProperties(components, createPropertyId) ??
96
+ deriveNamedVariantProperties(components, createPropertyId)
97
+ )
98
+ }