@open-pencil/scene-graph 0.17.0-beta.2 → 0.17.0-beta.3

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 (244) hide show
  1. package/dist/asset-keys.d.ts +11 -1
  2. package/dist/asset-keys.d.ts.map +1 -1
  3. package/dist/asset-keys.js +16 -1
  4. package/dist/asset-keys.js.map +1 -1
  5. package/dist/checkpoint.d.ts +3 -3
  6. package/dist/checkpoint.d.ts.map +1 -1
  7. package/dist/checkpoint.js +53 -23
  8. package/dist/checkpoint.js.map +1 -1
  9. package/dist/components/index.d.ts +2 -2
  10. package/dist/components/index.js +2 -2
  11. package/dist/components/properties.d.ts +6 -1
  12. package/dist/components/properties.d.ts.map +1 -1
  13. package/dist/components/properties.js +9 -1
  14. package/dist/components/properties.js.map +1 -1
  15. package/dist/constants.d.ts +6 -1
  16. package/dist/constants.d.ts.map +1 -1
  17. package/dist/constants.js +17 -1
  18. package/dist/constants.js.map +1 -1
  19. package/dist/constraints.d.ts +25 -0
  20. package/dist/constraints.d.ts.map +1 -0
  21. package/dist/constraints.js +51 -0
  22. package/dist/constraints.js.map +1 -0
  23. package/dist/coordinate.d.ts +64 -1
  24. package/dist/coordinate.d.ts.map +1 -1
  25. package/dist/coordinate.js +217 -1
  26. package/dist/coordinate.js.map +1 -1
  27. package/dist/copy.d.ts.map +1 -1
  28. package/dist/copy.js +8 -1
  29. package/dist/copy.js.map +1 -1
  30. package/dist/css/index.d.ts +3 -2
  31. package/dist/css/index.js +3 -2
  32. package/dist/css/text.d.ts +28 -1
  33. package/dist/css/text.d.ts.map +1 -1
  34. package/dist/css/text.js +84 -17
  35. package/dist/css/text.js.map +1 -1
  36. package/dist/css/transform.d.ts +34 -0
  37. package/dist/css/transform.d.ts.map +1 -0
  38. package/dist/css/transform.js +320 -0
  39. package/dist/css/transform.js.map +1 -0
  40. package/dist/css/values.d.ts.map +1 -1
  41. package/dist/css/values.js +11 -1
  42. package/dist/css/values.js.map +1 -1
  43. package/dist/figjam/palette.d.ts +1 -1
  44. package/dist/figjam/palette.js +1 -1
  45. package/dist/figjam/palette.js.map +1 -1
  46. package/dist/geometry.d.ts +8 -1
  47. package/dist/geometry.d.ts.map +1 -1
  48. package/dist/geometry.js +19 -8
  49. package/dist/geometry.js.map +1 -1
  50. package/dist/graph.d.ts +48 -12
  51. package/dist/graph.d.ts.map +1 -1
  52. package/dist/graph.js +110 -24
  53. package/dist/graph.js.map +1 -1
  54. package/dist/group-bounds.d.ts +14 -4
  55. package/dist/group-bounds.d.ts.map +1 -1
  56. package/dist/group-bounds.js +76 -11
  57. package/dist/group-bounds.js.map +1 -1
  58. package/dist/hit-test.d.ts +5 -0
  59. package/dist/hit-test.d.ts.map +1 -1
  60. package/dist/hit-test.js +18 -12
  61. package/dist/hit-test.js.map +1 -1
  62. package/dist/images.d.ts +27 -3
  63. package/dist/images.d.ts.map +1 -1
  64. package/dist/images.js +57 -3
  65. package/dist/images.js.map +1 -1
  66. package/dist/index.d.ts +2 -2
  67. package/dist/instances/index.d.ts.map +1 -1
  68. package/dist/instances/index.js +3 -0
  69. package/dist/instances/index.js.map +1 -1
  70. package/dist/instances/placement.js +55 -12
  71. package/dist/instances/placement.js.map +1 -1
  72. package/dist/instances/swap.js +3 -0
  73. package/dist/instances/swap.js.map +1 -1
  74. package/dist/instances/sync.js +34 -13
  75. package/dist/instances/sync.js.map +1 -1
  76. package/dist/node-defaults.d.ts.map +1 -1
  77. package/dist/node-defaults.js +1 -0
  78. package/dist/node-defaults.js.map +1 -1
  79. package/dist/order-keys.d.ts +3 -1
  80. package/dist/order-keys.d.ts.map +1 -1
  81. package/dist/order-keys.js +6 -1
  82. package/dist/order-keys.js.map +1 -1
  83. package/dist/plugin-data/fields.d.ts +2 -0
  84. package/dist/plugin-data/fields.d.ts.map +1 -1
  85. package/dist/plugin-data/fields.js +2 -0
  86. package/dist/plugin-data/fields.js.map +1 -1
  87. package/dist/resize.d.ts +22 -11
  88. package/dist/resize.d.ts.map +1 -1
  89. package/dist/resize.js +227 -93
  90. package/dist/resize.js.map +1 -1
  91. package/dist/scaling/index.d.ts +3 -2
  92. package/dist/scaling/index.js +3 -2
  93. package/dist/scaling/node.d.ts.map +1 -1
  94. package/dist/scaling/node.js +5 -1
  95. package/dist/scaling/node.js.map +1 -1
  96. package/dist/scaling/snapshot.d.ts +25 -0
  97. package/dist/scaling/snapshot.d.ts.map +1 -0
  98. package/dist/scaling/snapshot.js +39 -0
  99. package/dist/scaling/snapshot.js.map +1 -0
  100. package/dist/scaling/tree.d.ts +24 -2
  101. package/dist/scaling/tree.d.ts.map +1 -1
  102. package/dist/scaling/tree.js +37 -14
  103. package/dist/scaling/tree.js.map +1 -1
  104. package/dist/shaders/model.d.ts.map +1 -1
  105. package/dist/shaders/model.js +2 -1
  106. package/dist/shaders/model.js.map +1 -1
  107. package/dist/shared-styles.d.ts +3 -1
  108. package/dist/shared-styles.d.ts.map +1 -1
  109. package/dist/shared-styles.js +7 -1
  110. package/dist/shared-styles.js.map +1 -1
  111. package/dist/slots/authoring.d.ts +3 -2
  112. package/dist/slots/authoring.d.ts.map +1 -1
  113. package/dist/slots/authoring.js +5 -3
  114. package/dist/slots/authoring.js.map +1 -1
  115. package/dist/slots/content.d.ts.map +1 -1
  116. package/dist/slots/content.js +4 -1
  117. package/dist/slots/content.js.map +1 -1
  118. package/dist/text/direction.d.ts +3 -1
  119. package/dist/text/direction.d.ts.map +1 -1
  120. package/dist/text/direction.js +5 -1
  121. package/dist/text/direction.js.map +1 -1
  122. package/dist/transfer/apply.d.ts.map +1 -1
  123. package/dist/transfer/apply.js +1 -6
  124. package/dist/transfer/apply.js.map +1 -1
  125. package/dist/transfer/copied.d.ts +35 -3
  126. package/dist/transfer/copied.d.ts.map +1 -1
  127. package/dist/transfer/copied.js +44 -13
  128. package/dist/transfer/copied.js.map +1 -1
  129. package/dist/transfer/dependencies.d.ts +38 -0
  130. package/dist/transfer/dependencies.d.ts.map +1 -0
  131. package/dist/transfer/dependencies.js +100 -0
  132. package/dist/transfer/dependencies.js.map +1 -0
  133. package/dist/transfer/history.js +0 -1
  134. package/dist/transfer/history.js.map +1 -1
  135. package/dist/transfer/index.d.ts +5 -3
  136. package/dist/transfer/index.js +5 -3
  137. package/dist/transfer/nodes.d.ts.map +1 -1
  138. package/dist/transfer/nodes.js +7 -14
  139. package/dist/transfer/nodes.js.map +1 -1
  140. package/dist/transfer/plan.d.ts +0 -1
  141. package/dist/transfer/plan.js +3 -5
  142. package/dist/transfer/plan.js.map +1 -1
  143. package/dist/transfer/remove.js +5 -2
  144. package/dist/transfer/remove.js.map +1 -1
  145. package/dist/transfer/resources.d.ts +21 -0
  146. package/dist/transfer/resources.d.ts.map +1 -0
  147. package/dist/transfer/resources.js +38 -0
  148. package/dist/transfer/resources.js.map +1 -0
  149. package/dist/transfer/variables.d.ts +8 -1
  150. package/dist/transfer/variables.d.ts.map +1 -1
  151. package/dist/transfer/variables.js +24 -1
  152. package/dist/transfer/variables.js.map +1 -1
  153. package/dist/types.d.ts +47 -2
  154. package/dist/types.d.ts.map +1 -1
  155. package/dist/types.js.map +1 -1
  156. package/dist/undo.d.ts +28 -3
  157. package/dist/undo.d.ts.map +1 -1
  158. package/dist/undo.js +24 -7
  159. package/dist/undo.js.map +1 -1
  160. package/dist/variables/bindings.d.ts +17 -14
  161. package/dist/variables/bindings.d.ts.map +1 -1
  162. package/dist/variables/bindings.js +30 -72
  163. package/dist/variables/bindings.js.map +1 -1
  164. package/dist/variables/fields.d.ts +1 -1
  165. package/dist/variables/fields.js +1 -1
  166. package/dist/variables/fields.js.map +1 -1
  167. package/dist/variables/formula/check.d.ts +1 -1
  168. package/dist/variables/formula/index.d.ts +2 -2
  169. package/dist/variables/formula/index.js +1 -1
  170. package/dist/variables/formula/index.js.map +1 -1
  171. package/dist/variables/formula/print.d.ts +1 -1
  172. package/dist/variables/formula/signatures.js +1 -1
  173. package/dist/variables/index.d.ts +6 -6
  174. package/dist/variables/index.d.ts.map +1 -1
  175. package/dist/variables/index.js +40 -24
  176. package/dist/variables/index.js.map +1 -1
  177. package/dist/variables/paints.d.ts +57 -0
  178. package/dist/variables/paints.d.ts.map +1 -0
  179. package/dist/variables/paints.js +231 -0
  180. package/dist/variables/paints.js.map +1 -0
  181. package/dist/variables/resolution.d.ts +14 -11
  182. package/dist/variables/resolution.d.ts.map +1 -1
  183. package/dist/variables/resolution.js +36 -17
  184. package/dist/variables/resolution.js.map +1 -1
  185. package/dist/variables/subtree.js +17 -0
  186. package/dist/variables/subtree.js.map +1 -0
  187. package/dist/vector-network.d.ts.map +1 -1
  188. package/dist/vector-network.js +2 -8
  189. package/dist/vector-network.js.map +1 -1
  190. package/package.json +8 -1
  191. package/src/asset-keys.ts +20 -0
  192. package/src/checkpoint.ts +87 -32
  193. package/src/components/properties.ts +9 -0
  194. package/src/constants.ts +17 -0
  195. package/src/constraints.ts +60 -0
  196. package/src/coordinate.ts +220 -0
  197. package/src/copy.ts +9 -4
  198. package/src/css/index.ts +17 -1
  199. package/src/css/text.ts +85 -17
  200. package/src/css/transform.ts +266 -0
  201. package/src/css/values.ts +8 -0
  202. package/src/figjam/palette.ts +1 -1
  203. package/src/geometry.ts +20 -9
  204. package/src/graph.ts +128 -42
  205. package/src/group-bounds.ts +84 -17
  206. package/src/hit-test.ts +30 -14
  207. package/src/images.ts +71 -3
  208. package/src/instances/index.ts +4 -0
  209. package/src/instances/placement.ts +63 -10
  210. package/src/instances/swap.ts +5 -0
  211. package/src/instances/sync.ts +48 -21
  212. package/src/node-defaults.ts +1 -0
  213. package/src/order-keys.ts +6 -0
  214. package/src/plugin-data/fields.ts +6 -0
  215. package/src/resize.ts +267 -119
  216. package/src/scaling/index.ts +9 -1
  217. package/src/scaling/node.ts +9 -1
  218. package/src/scaling/snapshot.ts +51 -0
  219. package/src/scaling/tree.ts +63 -19
  220. package/src/shaders/model.ts +2 -3
  221. package/src/shared-styles.ts +8 -0
  222. package/src/slots/authoring.ts +5 -3
  223. package/src/slots/content.ts +4 -1
  224. package/src/text/direction.ts +5 -0
  225. package/src/transfer/apply.ts +1 -13
  226. package/src/transfer/copied.ts +83 -15
  227. package/src/transfer/dependencies.ts +126 -0
  228. package/src/transfer/history.ts +0 -6
  229. package/src/transfer/index.ts +20 -2
  230. package/src/transfer/nodes.ts +10 -26
  231. package/src/transfer/plan.ts +3 -11
  232. package/src/transfer/remove.ts +5 -2
  233. package/src/transfer/resources.ts +54 -0
  234. package/src/transfer/variables.ts +34 -0
  235. package/src/types.ts +55 -1
  236. package/src/undo.ts +48 -10
  237. package/src/variables/bindings.ts +44 -91
  238. package/src/variables/fields.ts +1 -1
  239. package/src/variables/formula/index.ts +3 -1
  240. package/src/variables/index.ts +56 -38
  241. package/src/variables/paints.ts +296 -0
  242. package/src/variables/resolution.ts +39 -28
  243. package/src/variables/subtree.ts +15 -0
  244. package/src/vector-network.ts +4 -2
@@ -8,6 +8,7 @@ import { bindingOverrideField, setInstanceOverride } from '../instances/override
8
8
  import { siblingOrderKeys } from '../order-keys'
9
9
  import type {
10
10
  Effect,
11
+ SceneNode,
11
12
  Variable,
12
13
  VariableCollection,
13
14
  VariableCollectionMode,
@@ -30,13 +31,16 @@ import {
30
31
  TEXT_CONTENT_VARIABLE_TYPES,
31
32
  VISIBILITY_VARIABLE_TYPES
32
33
  } from './fields'
34
+ import { applyBoundPaintColor } from './paints'
33
35
 
34
36
  export * from './resolution'
35
37
 
36
38
  export function addVariable(graph: SceneGraph, variable: Variable): void {
39
+ graph.willChangeVariable(variable.id)
37
40
  graph.variables.set(variable.id, variable)
38
41
  const collection = graph.variableCollections.get(variable.collectionId)
39
42
  if (collection && !collection.variableIds.includes(variable.id)) {
43
+ graph.willChangeCollection(collection.id)
40
44
  collection.variableIds.push(variable.id)
41
45
  }
42
46
  }
@@ -44,9 +48,11 @@ export function addVariable(graph: SceneGraph, variable: Variable): void {
44
48
  export function removeVariable(graph: SceneGraph, id: string): void {
45
49
  const variable = graph.variables.get(id)
46
50
  if (!variable) return
51
+ graph.willChangeVariable(id)
47
52
  graph.variables.delete(id)
48
53
  const collection = graph.variableCollections.get(variable.collectionId)
49
54
  if (collection) {
55
+ graph.willChangeCollection(collection.id)
50
56
  collection.variableIds = collection.variableIds.filter((vid) => vid !== id)
51
57
  }
52
58
  for (const node of graph.nodes.values()) {
@@ -70,10 +76,8 @@ export function removeVariable(graph: SceneGraph, id: string): void {
70
76
  }
71
77
 
72
78
  export function addCollection(graph: SceneGraph, collection: VariableCollection): void {
79
+ graph.willChangeCollection(collection.id)
73
80
  graph.variableCollections.set(collection.id, collection)
74
- if (!graph.activeMode.has(collection.id)) {
75
- graph.activeMode.set(collection.id, collection.defaultModeId)
76
- }
77
81
  }
78
82
 
79
83
  function defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {
@@ -138,12 +142,8 @@ export function removeCollection(graph: SceneGraph, id: string): void {
138
142
  removeVariable(graph, varId)
139
143
  }
140
144
  }
145
+ graph.willChangeCollection(id)
141
146
  graph.variableCollections.delete(id)
142
- graph.activeMode.delete(id)
143
- }
144
-
145
- export function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {
146
- graph.activeMode.set(collectionId, modeId)
147
147
  }
148
148
 
149
149
  export function addMode(
@@ -155,11 +155,13 @@ export function addMode(
155
155
  ): void {
156
156
  const collection = graph.variableCollections.get(collectionId)
157
157
  if (!collection) return
158
+ graph.willChangeCollection(collectionId)
158
159
  collection.modes.push({ modeId, name })
159
160
  const sourceModeId = sourceMode ?? collection.defaultModeId
160
161
  for (const varId of collection.variableIds) {
161
162
  const variable = graph.variables.get(varId)
162
163
  if (!variable) continue
164
+ graph.willChangeVariable(varId)
163
165
  variable.valuesByMode[modeId] = structuredClone(
164
166
  variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]
165
167
  )
@@ -183,16 +185,16 @@ export function createMode(
183
185
  export function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {
184
186
  const collection = graph.variableCollections.get(collectionId)
185
187
  if (!collection || collection.modes.length <= 1) return
188
+ graph.willChangeCollection(collectionId)
186
189
  collection.modes = collection.modes.filter((m) => m.modeId !== modeId)
187
190
  if (collection.defaultModeId === modeId) {
188
191
  collection.defaultModeId = collection.modes[0].modeId
189
192
  }
190
193
  for (const varId of collection.variableIds) {
191
194
  const variable = graph.variables.get(varId)
192
- if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])
193
- }
194
- if (graph.activeMode.get(collectionId) === modeId) {
195
- graph.activeMode.set(collectionId, collection.defaultModeId)
195
+ if (!variable) continue
196
+ graph.willChangeVariable(varId)
197
+ variable.valuesByMode = omit(variable.valuesByMode, [modeId])
196
198
  }
197
199
  }
198
200
 
@@ -205,13 +207,16 @@ export function renameMode(
205
207
  const collection = graph.variableCollections.get(collectionId)
206
208
  if (!collection) return
207
209
  const mode = collection.modes.find((m) => m.modeId === modeId)
208
- if (mode) mode.name = name
210
+ if (!mode) return
211
+ graph.willChangeCollection(collectionId)
212
+ mode.name = name
209
213
  }
210
214
 
211
215
  export function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {
212
216
  const collection = graph.variableCollections.get(collectionId)
213
217
  if (!collection) return
214
218
  if (!collection.modes.some((m) => m.modeId === modeId)) return
219
+ graph.willChangeCollection(collectionId)
215
220
  collection.defaultModeId = modeId
216
221
  collection.modes = withSortPositionsInOrder(modesDefaultFirst(collection))
217
222
  }
@@ -261,6 +266,30 @@ function assertEffectBinding(
261
266
  }
262
267
  }
263
268
 
269
+ /** Checks a paint binding and drops the list's dead top-level binding it replaces. */
270
+ function preparePaintBinding(
271
+ graph: SceneGraph,
272
+ node: SceneNode,
273
+ paint: { list: 'fills' | 'strokes'; index: number },
274
+ variable: Variable,
275
+ field: string
276
+ ): void {
277
+ // Color fields require COLOR variable type
278
+ if (variable.type !== 'COLOR') {
279
+ throw new Error(`Cannot bind ${variable.type} variable to color field "${field}"`)
280
+ }
281
+ // Validate index is within current array bounds
282
+ const currentLength = node[paint.list].length
283
+ if (paint.index >= currentLength) {
284
+ throw new Error(`Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`)
285
+ }
286
+ // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding
287
+ if (paint.list in node.boundVariables) {
288
+ graph.willChangeNode(node)
289
+ node.boundVariables = omit(node.boundVariables, [paint.list])
290
+ }
291
+ }
292
+
264
293
  export function bindVariable(
265
294
  graph: SceneGraph,
266
295
  nodeId: string,
@@ -276,25 +305,8 @@ export function bindVariable(
276
305
  throw new Error(`Variable "${variableId}" not found`)
277
306
  }
278
307
 
279
- // Color fields require COLOR variable type
280
308
  const paint = paintBindingTarget(field)
281
- if (paint) {
282
- if (variable.type !== 'COLOR') {
283
- throw new Error(`Cannot bind ${variable.type} variable to color field "${field}"`)
284
- }
285
- // Validate index is within current array bounds
286
- const currentLength = node[paint.list].length
287
- if (paint.index >= currentLength) {
288
- throw new Error(
289
- `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`
290
- )
291
- }
292
- // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding
293
- if (paint.list in node.boundVariables) {
294
- graph.willChangeNode(node)
295
- node.boundVariables = omit(node.boundVariables, [paint.list])
296
- }
297
- }
309
+ if (paint) preparePaintBinding(graph, node, paint, variable, field)
298
310
 
299
311
  const effect = effectBindingTarget(field)
300
312
  if (effect) assertEffectBinding(node.effects, effect, variable.type, field)
@@ -335,6 +347,8 @@ export function bindVariable(
335
347
  boundVariables: { ...node.boundVariables },
336
348
  variableBindingScales: { ...node.variableBindingScales }
337
349
  })
350
+ // A paint takes its variable's color, alpha as opacity, when it binds, as Figma's does.
351
+ if (paint) applyBoundPaintColor(graph, node, field)
338
352
  }
339
353
 
340
354
  export function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {
@@ -366,14 +380,17 @@ function markBoundVariablesOverrideOnInstance(
366
380
  for (const instance of instances) graph.willChangeNode(instance)
367
381
  if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')
368
382
  setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')
383
+ // Each instance claims the binding it changed alone, so the layer's other bindings keep
384
+ // following their components, as Figma claims only the paint or effect a script edits.
369
385
  if (field)
370
- setInstanceOverride(
371
- owner.instanceOverrides,
372
- owner.id,
373
- nodeId,
374
- bindingOverrideField(field),
375
- node.boundVariables[field] ?? null
376
- )
386
+ for (const instance of uniq(compact([nearest, owner])))
387
+ setInstanceOverride(
388
+ instance.instanceOverrides,
389
+ instance.id,
390
+ nodeId,
391
+ bindingOverrideField(field),
392
+ node.boundVariables[field] ?? null
393
+ )
377
394
  for (const instance of instances)
378
395
  graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
379
396
  }
@@ -382,6 +399,7 @@ export * from './bindings'
382
399
  export * from './corners'
383
400
  export * from './formula'
384
401
  export * from './formula/schema'
402
+ export * from './paints'
385
403
  export * from './schema'
386
404
  export * from './text'
387
405
  export * from './token'
@@ -0,0 +1,296 @@
1
+ import { copyFills, copyStrokes } from '../copy'
2
+ import type { SceneGraph } from '../graph'
3
+ import { hasInstanceOverride } from '../instances/overrides'
4
+ import type { Color } from '../primitives'
5
+ import type { Fill, SceneNode, Stroke } from '../types'
6
+ import { paintBindingTarget, type PaintBindingList } from './fields'
7
+ import { collectionsResolving, getNodeVariableModeId } from './resolution'
8
+ import { subtreeNodes } from './subtree'
9
+
10
+ /**
11
+ * Figma keeps a bound paint's color and opacity as a cache of its variable: it draws and reads
12
+ * what the paint holds, and writes the variable's color into it again only once the color the
13
+ * variable gives that layer changes, so an edit to the paint sticks until then. The color each
14
+ * binding last gave its paint lives here, beside the graph and never saved, by layer and binding
15
+ * field. A layer without an entry, such as one just loaded, pasted, or restored, counts its
16
+ * paint's own color as the last one applied.
17
+ */
18
+ interface AppliedColor {
19
+ readonly variableId: string
20
+ readonly color: Color
21
+ }
22
+
23
+ const appliedColors = new WeakMap<SceneNode, Map<string, AppliedColor>>()
24
+
25
+ const PAINT_LISTS = ['fills', 'strokes'] as const
26
+
27
+ interface BoundPaint {
28
+ readonly field: string
29
+ readonly list: PaintBindingList
30
+ readonly index: number
31
+ readonly variableId: string
32
+ }
33
+
34
+ /** The paints of `node` whose color is bound to a variable, each with a paint there to color. */
35
+ function boundPaints(node: SceneNode): BoundPaint[] {
36
+ const paints: BoundPaint[] = []
37
+ for (const [field, variableId] of Object.entries(node.boundVariables)) {
38
+ const target = paintBindingTarget(field)
39
+ if (target && node[target.list].at(target.index)) paints.push({ field, ...target, variableId })
40
+ }
41
+ return paints
42
+ }
43
+
44
+ /** Whether a layer has a paint whose color is bound to a variable. */
45
+ export function hasBoundPaints(node: SceneNode): boolean {
46
+ for (const field in node.boundVariables) if (paintBindingTarget(field)) return true
47
+ return false
48
+ }
49
+
50
+ /** A paint's color with its opacity as alpha, as a variable's color carries it. */
51
+ function paintColor(paint: Fill): Color {
52
+ return { r: paint.color.r, g: paint.color.g, b: paint.color.b, a: paint.opacity }
53
+ }
54
+
55
+ /** Saved colors are single precision, so a color read back from a file still matches its source. */
56
+ const COLOR_TOLERANCE = 1e-6
57
+
58
+ function sameColor(a: Color, b: Color): boolean {
59
+ return (
60
+ Math.abs(a.r - b.r) <= COLOR_TOLERANCE &&
61
+ Math.abs(a.g - b.g) <= COLOR_TOLERANCE &&
62
+ Math.abs(a.b - b.b) <= COLOR_TOLERANCE &&
63
+ Math.abs(a.a - b.a) <= COLOR_TOLERANCE
64
+ )
65
+ }
66
+
67
+ function lastApplied(node: SceneNode, bound: BoundPaint, paint: Fill): Color {
68
+ const entry = appliedColors.get(node)?.get(bound.field)
69
+ return entry?.variableId === bound.variableId ? entry.color : paintColor(paint)
70
+ }
71
+
72
+ /**
73
+ * A layer copied from another keeps the colors its bindings last applied there, so the copy's
74
+ * paints, edits included, stay as they are until their variables' colors for it change.
75
+ */
76
+ export function copyAppliedBoundPaints(source: SceneNode, copy: SceneNode): void {
77
+ const entries = appliedColors.get(source)
78
+ if (entries) appliedColors.set(copy, new Map(entries))
79
+ }
80
+
81
+ function recordApplied(node: SceneNode, bound: BoundPaint, color: Color): void {
82
+ let entries = appliedColors.get(node)
83
+ if (!entries) {
84
+ entries = new Map()
85
+ appliedColors.set(node, entries)
86
+ }
87
+ entries.set(bound.field, { variableId: bound.variableId, color: { ...color } })
88
+ }
89
+
90
+ /** The variable's RGB at full alpha in the paint, and its alpha as the paint's opacity. */
91
+ function applyColor(paint: Fill, color: Color): void {
92
+ paint.color = { ...color, a: 1 }
93
+ paint.opacity = color.a
94
+ }
95
+
96
+ /** Whether `paint` already shows `color` as a bound paint stores it. */
97
+ function showsColor(paint: Fill, color: Color): boolean {
98
+ return sameColor(paintColor(paint), color) && paint.color.a === 1
99
+ }
100
+
101
+ type PaintLists = Pick<Partial<SceneNode>, 'fills' | 'strokes'>
102
+
103
+ /**
104
+ * Whether `node` is an instance, or a layer an instance copies from its component, with a paint
105
+ * list neither it nor an instance around it overrides: such paints follow the component, and
106
+ * refreshing them is no edit.
107
+ */
108
+ export function copiesComponentPaints(
109
+ graph: SceneGraph,
110
+ node: SceneNode,
111
+ list: PaintBindingList
112
+ ): boolean {
113
+ const walk = { copied: false }
114
+ const overriding = graph.closest(node.id, (current) => {
115
+ if (current.type !== 'INSTANCE') return false
116
+ walk.copied = true
117
+ return hasInstanceOverride(current.instanceOverrides, current.id, node.id, list)
118
+ })
119
+ return walk.copied && !overriding
120
+ }
121
+
122
+ /**
123
+ * Writes refreshed paints. A copy's paints that follow its component are derived values that a
124
+ * save leaves to the component, not edits written over it.
125
+ */
126
+ function writePaints(graph: SceneGraph, node: SceneNode, changes: PaintLists): void {
127
+ const derived = PAINT_LISTS.every(
128
+ (list) => !changes[list] || copiesComponentPaints(graph, node, list)
129
+ )
130
+ const write = () => graph.updateNode(node.id, changes)
131
+ if (derived) graph.applyComponentDerivedDuring(write)
132
+ else write()
133
+ }
134
+
135
+ /**
136
+ * Writes into each bound paint the color its variable gives the layer now, where that differs
137
+ * from the color last applied, or wherever `forced` says, and records what each binding gives.
138
+ */
139
+ function refresh(graph: SceneGraph, node: SceneNode, forced: (field: string) => boolean): void {
140
+ let fills: Fill[] | undefined
141
+ let strokes: Stroke[] | undefined
142
+ for (const bound of boundPaints(node)) {
143
+ const color = graph.resolveColorVariableForNode(node.id, bound.variableId)
144
+ const paint = node[bound.list].at(bound.index)
145
+ if (!color || !paint) continue
146
+ const last = lastApplied(node, bound, paint)
147
+ recordApplied(node, bound, color)
148
+ if ((!forced(bound.field) && sameColor(last, color)) || showsColor(paint, color)) continue
149
+ if (bound.list === 'fills') {
150
+ fills ??= copyFills(node.fills)
151
+ applyColor(fills[bound.index], color)
152
+ } else {
153
+ strokes ??= copyStrokes(node.strokes)
154
+ applyColor(strokes[bound.index], color)
155
+ }
156
+ }
157
+ const changes: PaintLists = {}
158
+ if (fills) changes.fills = fills
159
+ if (strokes) changes.strokes = strokes
160
+ if (fills || strokes) writePaints(graph, node, changes)
161
+ }
162
+
163
+ const NONE_FORCED = (): boolean => false
164
+ const ALL_FORCED = (): boolean => true
165
+
166
+ /**
167
+ * Refreshes a layer's bound paints: each takes its variable's color for the layer, alpha as
168
+ * opacity, once that color differs from the one last applied, discarding edits made since, as
169
+ * Figma refreshes them when a variable's value or a layer's mode changes.
170
+ */
171
+ export function refreshBoundPaints(graph: SceneGraph, node: SceneNode): void {
172
+ if (hasBoundPaints(node)) refresh(graph, node, NONE_FORCED)
173
+ }
174
+
175
+ /** Gives one bound paint its variable's color for the layer, as binding it does in Figma. */
176
+ export function applyBoundPaintColor(graph: SceneGraph, node: SceneNode, field: string): void {
177
+ if (paintBindingTarget(field)) refresh(graph, node, (bound) => bound === field)
178
+ }
179
+
180
+ /**
181
+ * Gives every bound paint in this subtree its variable's color where it sits. A new instance
182
+ * or a layer an instance sync adds is a copy, which shows its variables in its own context rather
183
+ * than whatever its component's paints hold.
184
+ */
185
+ export function applyBoundPaintColorsIn(graph: SceneGraph, rootId: string): void {
186
+ for (const node of subtreeNodes(graph, [rootId]))
187
+ if (hasBoundPaints(node)) refresh(graph, node, ALL_FORCED)
188
+ }
189
+
190
+ /** Refreshes the bound paints in this subtree whose variables now give their layers another color. */
191
+ export function refreshBoundPaintsIn(graph: SceneGraph, rootId: string): void {
192
+ for (const node of subtreeNodes(graph, [rootId])) refreshBoundPaints(graph, node)
193
+ }
194
+
195
+ /**
196
+ * Records, for the paint lists a write sets, the colors their variables give the layer now, so a
197
+ * paint written with another color or opacity keeps it until that color changes.
198
+ */
199
+ export function recordWrittenBoundPaints(
200
+ graph: SceneGraph,
201
+ node: SceneNode,
202
+ written: PaintLists
203
+ ): void {
204
+ for (const bound of boundPaints(node)) {
205
+ if (!written[bound.list]) continue
206
+ const color = graph.resolveColorVariableForNode(node.id, bound.variableId)
207
+ if (color) recordApplied(node, bound, color)
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Refreshes the bound paints in a moved layer's subtree that resolve through a collection whose
213
+ * mode the move changed, as Figma does when a layer enters a frame or page in another mode. A
214
+ * move between parents in the same modes, or of layers that bind no paint, costs no more than
215
+ * comparing those modes.
216
+ */
217
+ export function refreshMovedBoundPaints(
218
+ graph: SceneGraph,
219
+ nodeId: string,
220
+ previousParentId: string | null | undefined
221
+ ): void {
222
+ if (graph.isApplyingImportedState || graph.variableCollections.size === 0) return
223
+ const parentId = graph.nodes.get(nodeId)?.parentId
224
+ if (!parentId) return
225
+ const previous = previousParentId && graph.nodes.has(previousParentId) ? previousParentId : null
226
+ const changed = new Set(
227
+ [...graph.variableCollections.keys()].filter(
228
+ (id) =>
229
+ !previous ||
230
+ getNodeVariableModeId(graph, previous, id) !== getNodeVariableModeId(graph, parentId, id)
231
+ )
232
+ )
233
+ if (changed.size === 0) return
234
+ const reaches = new Map<string, boolean>()
235
+ const reachesChanged = (variableId: string) => {
236
+ let found = reaches.get(variableId)
237
+ if (found === undefined) {
238
+ found = [...collectionsResolving(graph, [variableId])].some((id) => changed.has(id))
239
+ reaches.set(variableId, found)
240
+ }
241
+ return found
242
+ }
243
+ for (const node of subtreeNodes(graph, [nodeId])) {
244
+ if (boundPaints(node).some((bound) => reachesChanged(bound.variableId)))
245
+ refresh(graph, node, NONE_FORCED)
246
+ }
247
+ }
248
+
249
+ function reboundPaint(
250
+ target: SceneNode,
251
+ bindings: Readonly<Record<string, string>>,
252
+ list: PaintBindingList
253
+ ): boolean {
254
+ return target[list].some((_, index) => {
255
+ const field = `${list}/${index}/color`
256
+ return field in bindings && bindings[field] !== target.boundVariables[field]
257
+ })
258
+ }
259
+
260
+ /**
261
+ * A copy's bound paints are its own cache, as Figma keeps them per layer, so a component's edit
262
+ * to its paint's color or opacity does not reach them. An instance sync writing a copy's paints
263
+ * keeps the color and opacity of each one still bound to the same variable, and gives it the
264
+ * variable's color for the copy once that differs from the one last applied, or when it binds
265
+ * anew. `updates` holds what the sync writes, whose paints this sets in place.
266
+ */
267
+ export function keepCopyBoundPaints(
268
+ graph: SceneGraph,
269
+ target: SceneNode,
270
+ updates: Partial<SceneNode>
271
+ ): void {
272
+ const bindings = updates.boundVariables ?? target.boundVariables
273
+ for (const list of PAINT_LISTS) {
274
+ // A paint the component binds anew keeps its own paint otherwise, but takes the new color.
275
+ if (!updates[list] && reboundPaint(target, bindings, list))
276
+ Object.assign(updates, {
277
+ [list]: list === 'fills' ? copyFills(target.fills) : copyStrokes(target.strokes)
278
+ })
279
+ updates[list]?.forEach((paint, index) => {
280
+ const field = `${list}/${index}/color`
281
+ const variableId = bindings[field]
282
+ if (!variableId) return
283
+ const bound = { field, list, index, variableId }
284
+ const own = target[list].at(index)
285
+ const keeps = own !== undefined && target.boundVariables[field] === variableId
286
+ if (keeps) {
287
+ paint.color = { ...own.color }
288
+ paint.opacity = own.opacity
289
+ }
290
+ const color = graph.resolveColorVariableForNode(target.id, variableId)
291
+ if (!color) return
292
+ if (!keeps || !sameColor(lastApplied(target, bound, own), color)) applyColor(paint, color)
293
+ recordApplied(target, bound, color)
294
+ })
295
+ }
296
+ }
@@ -2,26 +2,20 @@ import type { SceneGraph } from '../graph'
2
2
  import type { Color } from '../primitives'
3
3
  import type { Variable, VariableLiteral, VariableValue } from '../types'
4
4
  import { MAX_FORMULA_DEPTH, VariableFormulaError } from './formula/tree'
5
- import { resolveVariableValue } from './value'
5
+ import { resolveVariableValue, variableValueReferences } from './value'
6
6
 
7
- export function getActiveModeId(graph: SceneGraph, collectionId: string): string {
8
- const mode = graph.activeMode.get(collectionId)
9
- if (mode) return mode
10
- const collection = graph.variableCollections.get(collectionId)
11
- return collection?.defaultModeId ?? ''
7
+ function defaultModeId(graph: SceneGraph, collectionId: string): string {
8
+ return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''
12
9
  }
13
10
 
14
11
  /**
15
- * What a node without an explicit mode falls back to: the mode the editor shows (`active`), or
16
- * the collection's default (`default`), which is what a saved document means to other tools.
12
+ * The mode a node is in for a collection: the nearest explicit mode on it or an ancestor (the page
13
+ * included), else the collection's default, as Figma resolves it.
17
14
  */
18
- export type VariableModeFallback = 'active' | 'default'
19
-
20
15
  export function getNodeVariableModeId(
21
16
  graph: SceneGraph,
22
17
  nodeId: string,
23
- collectionId: string,
24
- fallback: VariableModeFallback = 'active'
18
+ collectionId: string
25
19
  ): string {
26
20
  let node = graph.nodes.get(nodeId)
27
21
  while (node) {
@@ -29,9 +23,30 @@ export function getNodeVariableModeId(
29
23
  if (modeId) return modeId
30
24
  node = node.parentId ? graph.nodes.get(node.parentId) : undefined
31
25
  }
32
- if (fallback === 'default')
33
- return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''
34
- return getActiveModeId(graph, collectionId)
26
+ return defaultModeId(graph, collectionId)
27
+ }
28
+
29
+ /**
30
+ * The collections whose modes decide what these variables resolve to: their own, and those of the
31
+ * variables they alias, at any depth and in any mode.
32
+ */
33
+ export function collectionsResolving(
34
+ graph: SceneGraph,
35
+ variableIds: Iterable<string>
36
+ ): Set<string> {
37
+ const pending = [...variableIds]
38
+ const seen = new Set<string>()
39
+ const collections = new Set<string>()
40
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
41
+ if (seen.has(id)) continue
42
+ seen.add(id)
43
+ const variable = graph.variables.get(id)
44
+ if (!variable) continue
45
+ collections.add(variable.collectionId)
46
+ for (const value of Object.values(variable.valuesByMode))
47
+ pending.push(...variableValueReferences(value))
48
+ }
49
+ return collections
35
50
  }
36
51
 
37
52
  export function resolveVariable(
@@ -47,7 +62,7 @@ export function resolveVariable(
47
62
  (collectionId) =>
48
63
  modeId && initial?.collectionId === collectionId
49
64
  ? modeId
50
- : getActiveModeId(graph, collectionId),
65
+ : defaultModeId(graph, collectionId),
51
66
  visited
52
67
  )
53
68
  }
@@ -252,10 +267,9 @@ export function resolveNumberVariable(graph: SceneGraph, variableId: string): nu
252
267
  export function resolveColorVariableForNode(
253
268
  graph: SceneGraph,
254
269
  nodeId: string,
255
- variableId: string,
256
- fallback: VariableModeFallback = 'active'
270
+ variableId: string
257
271
  ): Color | undefined {
258
- const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
272
+ const value = resolveVariableForNode(graph, nodeId, variableId)
259
273
  if (value && typeof value === 'object' && 'r' in value) return value
260
274
  return undefined
261
275
  }
@@ -263,10 +277,9 @@ export function resolveColorVariableForNode(
263
277
  export function resolveNumberVariableForNode(
264
278
  graph: SceneGraph,
265
279
  nodeId: string,
266
- variableId: string,
267
- fallback: VariableModeFallback = 'active'
280
+ variableId: string
268
281
  ): number | undefined {
269
- const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
282
+ const value = resolveVariableForNode(graph, nodeId, variableId)
270
283
  return typeof value === 'number' ? value : undefined
271
284
  }
272
285
 
@@ -274,20 +287,18 @@ export function resolveNumberVariableForNode(
274
287
  export function resolveVariableForNode(
275
288
  graph: SceneGraph,
276
289
  nodeId: string,
277
- variableId: string,
278
- fallback: VariableModeFallback = 'active'
290
+ variableId: string
279
291
  ): VariableLiteral | undefined {
280
292
  return resolveInModes(graph, variableId, (collectionId) =>
281
- getNodeVariableModeId(graph, nodeId, collectionId, fallback)
293
+ getNodeVariableModeId(graph, nodeId, collectionId)
282
294
  )
283
295
  }
284
296
 
285
297
  export function resolveStringVariableForNode(
286
298
  graph: SceneGraph,
287
299
  nodeId: string,
288
- variableId: string,
289
- fallback: VariableModeFallback = 'active'
300
+ variableId: string
290
301
  ): string | undefined {
291
- const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
302
+ const value = resolveVariableForNode(graph, nodeId, variableId)
292
303
  return typeof value === 'string' ? value : undefined
293
304
  }
@@ -0,0 +1,15 @@
1
+ import type { SceneGraph } from '../graph'
2
+ import type { SceneNode } from '../types'
3
+
4
+ /** The layers in these subtrees, the roots included, that a binding change can reach. */
5
+ export function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {
6
+ const nodes: SceneNode[] = []
7
+ const pending = [...roots]
8
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
9
+ const node = graph.getNode(id)
10
+ if (!node) continue
11
+ nodes.push(node)
12
+ pending.push(...node.childIds)
13
+ }
14
+ return nodes
15
+ }
@@ -352,8 +352,10 @@ function segmentToSVG(
352
352
  ): string {
353
353
  const start = forward ? vertices[seg.start] : vertices[seg.end]
354
354
  const end = forward ? vertices[seg.end] : vertices[seg.start]
355
- const ts = forward ? seg.tangentStart : { x: -seg.tangentEnd.x, y: -seg.tangentEnd.y }
356
- const te = forward ? seg.tangentEnd : { x: -seg.tangentStart.x, y: -seg.tangentStart.y }
355
+ // Tangents are relative to their own vertex (`segmentToAbsolute`), so tracing a segment end to
356
+ // start swaps them but keeps their sign: each control point stays beside its vertex.
357
+ const ts = forward ? seg.tangentStart : seg.tangentEnd
358
+ const te = forward ? seg.tangentEnd : seg.tangentStart
357
359
 
358
360
  const isStraight =
359
361
  Math.abs(ts.x) < 0.001 &&