@pairdraw/scene-graph 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/dist/components/index.d.ts +2 -2
  2. package/dist/components/index.js +2 -2
  3. package/dist/components/properties.d.ts +6 -1
  4. package/dist/components/properties.d.ts.map +1 -1
  5. package/dist/components/properties.js +14 -3
  6. package/dist/components/properties.js.map +1 -1
  7. package/dist/copy.d.ts.map +1 -1
  8. package/dist/copy.js +1 -0
  9. package/dist/copy.js.map +1 -1
  10. package/dist/css/gradient.d.ts +23 -0
  11. package/dist/css/gradient.d.ts.map +1 -0
  12. package/dist/css/gradient.js +404 -0
  13. package/dist/css/gradient.js.map +1 -0
  14. package/dist/css/index.d.ts +2 -1
  15. package/dist/css/index.js +2 -1
  16. package/dist/css/shadows.d.ts.map +1 -1
  17. package/dist/css/shadows.js +2 -13
  18. package/dist/css/shadows.js.map +1 -1
  19. package/dist/css/values.js +24 -1
  20. package/dist/css/values.js.map +1 -1
  21. package/dist/font-style.d.ts +2 -1
  22. package/dist/font-style.d.ts.map +1 -1
  23. package/dist/font-style.js +31 -6
  24. package/dist/font-style.js.map +1 -1
  25. package/dist/geometry.d.ts +10 -1
  26. package/dist/geometry.d.ts.map +1 -1
  27. package/dist/geometry.js +21 -6
  28. package/dist/geometry.js.map +1 -1
  29. package/dist/graph.d.ts +49 -3
  30. package/dist/graph.d.ts.map +1 -1
  31. package/dist/graph.js +179 -17
  32. package/dist/graph.js.map +1 -1
  33. package/dist/hit-test.d.ts +3 -1
  34. package/dist/hit-test.d.ts.map +1 -1
  35. package/dist/hit-test.js +38 -23
  36. package/dist/hit-test.js.map +1 -1
  37. package/dist/icons/index.d.ts +2 -2
  38. package/dist/icons/index.js +2 -2
  39. package/dist/icons/model.d.ts +8 -2
  40. package/dist/icons/model.d.ts.map +1 -1
  41. package/dist/icons/model.js +10 -1
  42. package/dist/icons/model.js.map +1 -1
  43. package/dist/index.d.ts +2 -2
  44. package/dist/instances/assignments.js +40 -6
  45. package/dist/instances/assignments.js.map +1 -1
  46. package/dist/instances/fields.d.ts +2 -2
  47. package/dist/instances/fields.d.ts.map +1 -1
  48. package/dist/instances/fields.js +18 -1
  49. package/dist/instances/fields.js.map +1 -1
  50. package/dist/instances/index.d.ts +38 -2
  51. package/dist/instances/index.d.ts.map +1 -1
  52. package/dist/instances/index.js +134 -15
  53. package/dist/instances/index.js.map +1 -1
  54. package/dist/instances/overrides.d.ts +10 -1
  55. package/dist/instances/overrides.d.ts.map +1 -1
  56. package/dist/instances/overrides.js +28 -2
  57. package/dist/instances/overrides.js.map +1 -1
  58. package/dist/instances/placement.js +1 -1
  59. package/dist/instances/placement.js.map +1 -1
  60. package/dist/instances/swap-overrides.js +94 -0
  61. package/dist/instances/swap-overrides.js.map +1 -0
  62. package/dist/instances/sync.js +90 -12
  63. package/dist/instances/sync.js.map +1 -1
  64. package/dist/layout/draw-order.d.ts +11 -0
  65. package/dist/layout/draw-order.d.ts.map +1 -0
  66. package/dist/layout/draw-order.js +14 -0
  67. package/dist/layout/draw-order.js.map +1 -0
  68. package/dist/layout/index.d.ts +2 -1
  69. package/dist/layout/index.js +2 -1
  70. package/dist/node-defaults.d.ts +11 -1
  71. package/dist/node-defaults.d.ts.map +1 -1
  72. package/dist/node-defaults.js +16 -1
  73. package/dist/node-defaults.js.map +1 -1
  74. package/dist/order-keys.d.ts +3 -1
  75. package/dist/order-keys.d.ts.map +1 -1
  76. package/dist/order-keys.js +6 -1
  77. package/dist/order-keys.js.map +1 -1
  78. package/dist/resize.d.ts +29 -9
  79. package/dist/resize.d.ts.map +1 -1
  80. package/dist/resize.js +95 -62
  81. package/dist/resize.js.map +1 -1
  82. package/dist/shared-styles.d.ts.map +1 -1
  83. package/dist/shared-styles.js +1 -8
  84. package/dist/shared-styles.js.map +1 -1
  85. package/dist/slots/authoring.d.ts +3 -2
  86. package/dist/slots/authoring.d.ts.map +1 -1
  87. package/dist/slots/authoring.js +5 -3
  88. package/dist/slots/authoring.js.map +1 -1
  89. package/dist/slots/content.d.ts.map +1 -1
  90. package/dist/slots/content.js +4 -1
  91. package/dist/slots/content.js.map +1 -1
  92. package/dist/source-metadata.d.ts +4 -2
  93. package/dist/source-metadata.d.ts.map +1 -1
  94. package/dist/source-metadata.js +10 -3
  95. package/dist/source-metadata.js.map +1 -1
  96. package/dist/strokes.d.ts +39 -0
  97. package/dist/strokes.d.ts.map +1 -0
  98. package/dist/strokes.js +104 -0
  99. package/dist/strokes.js.map +1 -0
  100. package/dist/text/direction.d.ts +6 -2
  101. package/dist/text/direction.d.ts.map +1 -1
  102. package/dist/text/direction.js +2 -1
  103. package/dist/text/direction.js.map +1 -1
  104. package/dist/text/index.d.ts +3 -3
  105. package/dist/text/index.js +3 -3
  106. package/dist/text/lengths.d.ts +6 -1
  107. package/dist/text/lengths.d.ts.map +1 -1
  108. package/dist/text/lengths.js +10 -1
  109. package/dist/text/lengths.js.map +1 -1
  110. package/dist/text/overflow.d.ts +22 -6
  111. package/dist/text/overflow.d.ts.map +1 -1
  112. package/dist/text/overflow.js +24 -6
  113. package/dist/text/overflow.js.map +1 -1
  114. package/dist/transfer/nodes.js +9 -5
  115. package/dist/transfer/nodes.js.map +1 -1
  116. package/dist/types.d.ts +18 -2
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/dist/undo.d.ts +36 -1
  120. package/dist/undo.d.ts.map +1 -1
  121. package/dist/undo.js +52 -2
  122. package/dist/undo.js.map +1 -1
  123. package/dist/variables/bindings.d.ts +14 -6
  124. package/dist/variables/bindings.d.ts.map +1 -1
  125. package/dist/variables/bindings.js +42 -67
  126. package/dist/variables/bindings.js.map +1 -1
  127. package/dist/variables/formula/signatures.js +1 -1
  128. package/dist/variables/index.d.ts +10 -4
  129. package/dist/variables/index.d.ts.map +1 -1
  130. package/dist/variables/index.js +58 -15
  131. package/dist/variables/index.js.map +1 -1
  132. package/dist/variables/paints.d.ts +101 -0
  133. package/dist/variables/paints.d.ts.map +1 -0
  134. package/dist/variables/paints.js +313 -0
  135. package/dist/variables/paints.js.map +1 -0
  136. package/dist/variables/resolution.d.ts +14 -1
  137. package/dist/variables/resolution.d.ts.map +1 -1
  138. package/dist/variables/resolution.js +44 -4
  139. package/dist/variables/resolution.js.map +1 -1
  140. package/dist/variables/subtree.js +17 -0
  141. package/dist/variables/subtree.js.map +1 -0
  142. package/package.json +6 -1
  143. package/src/components/properties.ts +17 -2
  144. package/src/copy.ts +1 -0
  145. package/src/css/gradient.ts +438 -0
  146. package/src/css/index.ts +1 -0
  147. package/src/css/shadows.ts +2 -18
  148. package/src/css/values.ts +27 -1
  149. package/src/font-style.ts +38 -4
  150. package/src/geometry.ts +25 -6
  151. package/src/graph.ts +207 -17
  152. package/src/hit-test.ts +67 -24
  153. package/src/icons/model.ts +11 -1
  154. package/src/instances/assignments.ts +65 -7
  155. package/src/instances/fields.ts +21 -0
  156. package/src/instances/index.ts +237 -14
  157. package/src/instances/overrides.ts +36 -1
  158. package/src/instances/placement.ts +5 -1
  159. package/src/instances/swap-overrides.ts +123 -0
  160. package/src/instances/sync.ts +139 -12
  161. package/src/layout/draw-order.ts +13 -0
  162. package/src/layout/index.ts +1 -0
  163. package/src/node-defaults.ts +21 -0
  164. package/src/order-keys.ts +6 -0
  165. package/src/resize.ts +133 -69
  166. package/src/shared-styles.ts +1 -3
  167. package/src/slots/authoring.ts +5 -3
  168. package/src/slots/content.ts +4 -1
  169. package/src/source-metadata.ts +18 -3
  170. package/src/strokes.ts +121 -0
  171. package/src/text/direction.ts +7 -5
  172. package/src/text/lengths.ts +10 -0
  173. package/src/text/overflow.ts +30 -7
  174. package/src/transfer/nodes.ts +7 -5
  175. package/src/types.ts +17 -0
  176. package/src/undo.ts +79 -2
  177. package/src/variables/bindings.ts +52 -74
  178. package/src/variables/index.ts +80 -14
  179. package/src/variables/paints.ts +413 -0
  180. package/src/variables/resolution.ts +56 -5
  181. package/src/variables/subtree.ts +15 -0
package/src/undo.ts CHANGED
@@ -5,10 +5,34 @@ export interface UndoEntry {
5
5
  coalesceKey?: string
6
6
  }
7
7
 
8
+ /**
9
+ * Committed history, kept aside while another graph is open so a document opened in the same
10
+ * editor never inherits the last one's steps.
11
+ */
12
+ export interface UndoHistory {
13
+ readonly undo: readonly UndoEntry[]
14
+ readonly redo: readonly UndoEntry[]
15
+ }
16
+
8
17
  export interface UndoManagerOptions {
9
18
  limit?: number
10
19
  /** Called after recording, undoing, redoing, or clearing committed history. */
11
20
  onChange?: () => void
21
+ /**
22
+ * The edited-field marks an edit adds. A step takes its marks back when undone and puts them
23
+ * back when redone, so a layer ends a step exactly as it began one, marks included.
24
+ */
25
+ marks?: UndoSourceMarks
26
+ }
27
+
28
+ /** Marks an edit left on layers, kept by the graph for one undo step. */
29
+ export interface UndoSourceMarks {
30
+ /** The marks added since the last step, which that step owns. */
31
+ take: () => Array<[nodeId: string, field: string]>
32
+ add: (nodeId: string, fields: readonly string[]) => void
33
+ remove: (nodeId: string, fields: readonly string[]) => void
34
+ /** Runs a replay that writes values only, so it marks no field of its own. */
35
+ preserve: (run: () => void) => void
12
36
  }
13
37
 
14
38
  interface UndoBatch {
@@ -29,10 +53,12 @@ export class UndoManager {
29
53
  private readonly settlers = new Set<() => void>()
30
54
  private readonly limit: number
31
55
  private readonly onChange: (() => void) | undefined
56
+ private readonly marks: UndoSourceMarks | undefined
32
57
 
33
58
  constructor(options: UndoManagerOptions = {}) {
34
59
  this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT
35
60
  this.onChange = options.onChange
61
+ this.marks = options.marks
36
62
  }
37
63
 
38
64
  apply(entry: UndoEntry): void {
@@ -49,12 +75,43 @@ export class UndoManager {
49
75
  }
50
76
 
51
77
  record(entry: UndoEntry): void {
78
+ const marked = this.withSourceMarks(entry)
52
79
  const batch = this.currentBatch
53
80
  if (batch) {
54
- batch.entries.push(entry)
81
+ batch.entries.push(marked)
55
82
  return
56
83
  }
57
- this.pushUndoEntry(entry)
84
+ this.pushUndoEntry(marked)
85
+ }
86
+
87
+ /**
88
+ * The step's replay writes values without marking them, then the marks the edit added come
89
+ * back on redo and go with it on undo.
90
+ */
91
+ private withSourceMarks(entry: UndoEntry): UndoEntry {
92
+ const marks = this.marks
93
+ if (!marks) return entry
94
+ const taken = marks.take()
95
+ const byNode = new Map<string, string[]>()
96
+ for (const [id, field] of taken) {
97
+ const fields = byNode.get(id)
98
+ if (fields) fields.push(field)
99
+ else byNode.set(id, [field])
100
+ }
101
+ return {
102
+ ...entry,
103
+ forward: () => {
104
+ // Redo repeats the edit, marks its layout adds included, then keeps the marks the step
105
+ // owned even if the replay wrote fewer fields than the edit did.
106
+ entry.forward()
107
+ for (const [id, fields] of byNode) marks.add(id, fields)
108
+ },
109
+ inverse: () => {
110
+ // Undo puts a state back rather than editing, so it marks nothing of its own.
111
+ marks.preserve(() => entry.inverse())
112
+ for (const [id, fields] of byNode) marks.remove(id, fields)
113
+ }
114
+ }
58
115
  }
59
116
 
60
117
  /**
@@ -141,9 +198,29 @@ export class UndoManager {
141
198
  this.undoStack = []
142
199
  this.redoStack = []
143
200
  this.discardBatches()
201
+ this.marks?.take()
144
202
  this.onChange?.()
145
203
  }
146
204
 
205
+ /**
206
+ * Takes the committed history out, for the graph it was recorded on, and leaves this one empty;
207
+ * `adoptHistory` puts it back when that graph opens again.
208
+ */
209
+ takeHistory(): UndoHistory {
210
+ const history = { undo: this.undoStack, redo: this.redoStack }
211
+ this.undoStack = []
212
+ this.redoStack = []
213
+ this.discardBatches()
214
+ return history
215
+ }
216
+
217
+ /** Makes `history`, recorded on the graph now open, the committed one. */
218
+ adoptHistory(history: UndoHistory | undefined): void {
219
+ this.undoStack = history ? [...history.undo] : []
220
+ this.redoStack = history ? [...history.redo] : []
221
+ this.discardBatches()
222
+ }
223
+
147
224
  /** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */
148
225
  get isReplaying(): boolean {
149
226
  return this.replaying > 0
@@ -1,15 +1,16 @@
1
1
  import { isEqual } from 'es-toolkit/predicate'
2
2
 
3
3
  import type { VariableModeFallback } from '.'
4
- import { copyFills, copyStrokes } from '../copy'
5
4
  import type { SceneGraph } from '../graph'
6
5
  import { readIcon } from '../icons/model'
7
6
  import { ICON_NAME } from '../icons/schema'
8
- import { hasInstanceOverride } from '../instances'
9
- import type { Color } from '../primitives'
7
+ import { hasInstanceOverride } from '../instances/overrides'
10
8
  import { pixelLength } from '../text/lengths'
11
- import type { Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'
12
- import { NUMERIC_FIELDS, isNumericVariableBindingField, paintBindingTarget } from './fields'
9
+ import type { SceneNode, StyleRun, TextLength } from '../types'
10
+ import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
11
+ import { refreshBoundPaints } from './paints'
12
+ import { collectionsResolving } from './resolution'
13
+ import { subtreeNodes } from './subtree'
13
14
  import { variableFontFamily, variableText, variableTruthy } from './text'
14
15
  import { runBindingScale } from './units'
15
16
  import { variableValueReferences } from './value'
@@ -50,6 +51,12 @@ export function assignVariableBindingUnits(
50
51
  /** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */
51
52
  const TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])
52
53
 
54
+ /** Whether the instance a layer sits in, or the instance itself, overrides one of its fields. */
55
+ function overriddenInInstance(graph: SceneGraph, nodeId: string, field: string): boolean {
56
+ const instance = graph.closest(nodeId, (node) => node.type === 'INSTANCE')
57
+ return !!instance && hasInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
58
+ }
59
+
53
60
  /** A bound number as the field stores it. */
54
61
  export function boundNumberValue(field: string, value: number): number | TextLength {
55
62
  return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value
@@ -67,7 +74,7 @@ export function resolvedNumericBindings(
67
74
  const updates: Partial<SceneNode> = {}
68
75
  for (const [field, variableId] of Object.entries(node.boundVariables)) {
69
76
  if (!NUMERIC_FIELDS.has(field)) continue
70
- if ((field === 'width' || field === 'height') && hasInstanceOverride(graph, node.id, field))
77
+ if ((field === 'width' || field === 'height') && overriddenInInstance(graph, node.id, field))
71
78
  continue
72
79
  const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)
73
80
  if (value === undefined || !Number.isFinite(value)) continue
@@ -98,7 +105,7 @@ export function resolvedValueBindings(
98
105
  const updates: Partial<SceneNode> = {}
99
106
  const resolve = (field: 'text' | 'fontFamily' | 'visible') => {
100
107
  const variableId = node.boundVariables[field]
101
- if (!variableId || hasInstanceOverride(graph, node.id, field)) return undefined
108
+ if (!variableId || overriddenInInstance(graph, node.id, field)) return undefined
102
109
  return graph.resolveVariableForNode(node.id, variableId, fallback)
103
110
  }
104
111
  const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined
@@ -125,7 +132,7 @@ export function resolvedIconBinding(
125
132
  const icon = readIcon(node)
126
133
  if (!icon) return undefined
127
134
  const variableId = node.boundVariables['iconName']
128
- if (!variableId || hasInstanceOverride(graph, node.id, 'iconName')) return undefined
135
+ if (!variableId || overriddenInInstance(graph, node.id, 'iconName')) return undefined
129
136
  const resolved = graph.resolveVariableForNode(node.id, variableId, fallback)
130
137
  if (typeof resolved !== 'string') return undefined
131
138
  const name = resolved.trim()
@@ -181,43 +188,6 @@ function boundVariableIds(node: SceneNode): string[] {
181
188
  ].filter((id): id is string => typeof id === 'string')
182
189
  }
183
190
 
184
- /**
185
- * A bound paint takes its whole color from the variable, alpha included, the way Figma stores
186
- * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
187
- */
188
- function applyBoundColor(paint: Fill | Stroke, color: Color): void {
189
- paint.color = { ...color, a: 1 }
190
- paint.opacity = color.a
191
- }
192
-
193
- /** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */
194
- export function resolvedPaintBindings(
195
- graph: SceneGraph,
196
- node: SceneNode,
197
- fallback: VariableModeFallback = 'active'
198
- ): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {
199
- // Most nodes bind nothing, so no copy is made until a paint binding is actually found.
200
- const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}
201
- for (const field in node.boundVariables) {
202
- if (!field.endsWith('/color')) continue
203
- const paint = paintBindingTarget(field)
204
- if (!paint) continue
205
- const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback)
206
- const { index } = paint
207
- if (!color) continue
208
- if (paint.list === 'fills') {
209
- if (!node.fills[index]) continue
210
- changes.fills ??= copyFills(node.fills)
211
- applyBoundColor(changes.fills[index], color)
212
- } else {
213
- if (!node.strokes[index]) continue
214
- changes.strokes ??= copyStrokes(node.strokes)
215
- applyBoundColor(changes.strokes[index], color)
216
- }
217
- }
218
- return changes
219
- }
220
-
221
191
  /**
222
192
  * The layers a reconcile looks at: those bound to these variables, directly or through a variable
223
193
  * aliasing them, or the layers in these subtrees. Without a scope, every layer.
@@ -244,36 +214,12 @@ export function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<strin
244
214
  return found
245
215
  }
246
216
 
247
- function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {
248
- const nodes: SceneNode[] = []
249
- const pending = [...roots]
250
- for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
251
- const node = graph.getNode(id)
252
- if (!node) continue
253
- nodes.push(node)
254
- pending.push(...node.childIds)
255
- }
256
- return nodes
257
- }
258
-
259
217
  /**
260
218
  * The collections whose variables the layers in these subtrees resolve: those they bind, and
261
219
  * those the bound variables alias, so a mode set on the subtrees can change what they show.
262
220
  */
263
221
  export function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string> {
264
- const pending = subtreeNodes(graph, roots).flatMap(boundVariableIds)
265
- const seen = new Set<string>()
266
- const collections = new Set<string>()
267
- for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
268
- if (seen.has(id)) continue
269
- seen.add(id)
270
- const variable = graph.variables.get(id)
271
- if (!variable) continue
272
- collections.add(variable.collectionId)
273
- for (const value of Object.values(variable.valuesByMode))
274
- pending.push(...variableValueReferences(value))
275
- }
276
- return collections
222
+ return collectionsResolving(graph, subtreeNodes(graph, roots).flatMap(boundVariableIds))
277
223
  }
278
224
 
279
225
  /**
@@ -294,13 +240,17 @@ function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterab
294
240
  }
295
241
 
296
242
  /**
297
- * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, without authoring
298
- * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved
299
- * values differ from their bindings elsewhere in the document are left as saved.
243
+ * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, and
244
+ * refresh bound paints whose variable's color for the layer changed (`refreshBoundPaints`),
245
+ * without authoring instance overrides. A scope limits it to the layers a change can reach, so
246
+ * layers whose saved values differ from their bindings elsewhere in the document are left as
247
+ * saved.
300
248
  */
301
249
  export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {
302
250
  const changed: string[] = []
303
- for (const node of scopedNodes(graph, scope)) {
251
+ const nodes = [...scopedNodes(graph, scope)]
252
+ for (const node of nodes) refreshBoundPaints(graph, node)
253
+ for (const node of nodes) {
304
254
  const updates = {
305
255
  ...resolvedNumericBindings(graph, node),
306
256
  ...resolvedValueBindings(graph, node),
@@ -312,3 +262,31 @@ export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScop
312
262
  }
313
263
  return changed
314
264
  }
265
+
266
+ /** A layer list whose items carry their own bindings, keyed by position such as `fills/1/color`. */
267
+ export type BoundLayerList = 'fills' | 'strokes' | 'effects'
268
+
269
+ /**
270
+ * `boundVariables` once the `list` items are rebuilt from `sources`, where `sources[i]` is the
271
+ * position the new item `i` had before, or null for an added item. A binding moves with its item
272
+ * and goes with a removed one, as Figma keeps a binding on its paint or effect.
273
+ */
274
+ export function listBindingsAfterEdit(
275
+ boundVariables: Readonly<Record<string, string>>,
276
+ list: BoundLayerList,
277
+ sources: readonly (number | null)[]
278
+ ): Record<string, string> {
279
+ const prefix = `${list}/`
280
+ const moved: Record<string, string> = {}
281
+ for (const [field, variableId] of Object.entries(boundVariables)) {
282
+ if (!field.startsWith(prefix)) {
283
+ moved[field] = variableId
284
+ continue
285
+ }
286
+ const [index, ...property] = field.slice(prefix.length).split('/')
287
+ const next = sources.indexOf(Number(index))
288
+ if (next !== -1 && property.length > 0)
289
+ moved[`${prefix}${next}/${property.join('/')}`] = variableId
290
+ }
291
+ return moved
292
+ }
@@ -1,10 +1,15 @@
1
- import { partition } from 'es-toolkit/array'
1
+ import { compact, partition, sortBy, uniq } from 'es-toolkit/array'
2
2
  import { omit, omitBy } from 'es-toolkit/object'
3
3
 
4
4
  import { BLACK } from '../constants'
5
5
  import type { SceneGraph } from '../graph'
6
6
  import { findInstanceAncestor } from '../instances'
7
- import { bindingOverrideField, setInstanceOverride } from '../instances/overrides'
7
+ import {
8
+ bindingOverrideField,
9
+ setInstanceOverride,
10
+ variableModeOverrideField
11
+ } from '../instances/overrides'
12
+ import { siblingOrderKeys } from '../order-keys'
8
13
  import { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'
9
14
  import type {
10
15
  SceneNode,
@@ -30,6 +35,7 @@ import {
30
35
  VISIBILITY_VARIABLE_TYPES,
31
36
  type PaintBindingList
32
37
  } from './fields'
38
+ import { applyBoundPaintColor } from './paints'
33
39
  import { pinnedRunBindingScales } from './units'
34
40
 
35
41
  export * from './resolution'
@@ -157,6 +163,14 @@ export function removeCollection(graph: SceneGraph, id: string): void {
157
163
  }
158
164
  graph.variableCollections.delete(id)
159
165
  graph.activeMode.delete(id)
166
+ // A layer that chose one of its modes has nothing left to choose from.
167
+ for (const node of graph.nodes.values()) {
168
+ if (!(id in node.variableModes)) continue
169
+ const variableModes = omit(node.variableModes, [id])
170
+ graph.willChangeNode(node)
171
+ node.variableModes = variableModes
172
+ graph.emitter.emit('node:updated', node.id, { variableModes })
173
+ }
160
174
  }
161
175
 
162
176
  export function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {
@@ -202,12 +216,26 @@ export function removeMode(graph: SceneGraph, collectionId: string, modeId: stri
202
216
  if (!collection || collection.modes.length <= 1) return
203
217
  collection.modes = collection.modes.filter((m) => m.modeId !== modeId)
204
218
  if (collection.defaultModeId === modeId) {
205
- collection.defaultModeId = collection.modes[0].modeId
219
+ // The next default is the next listed mode, as Figma picks it, not the next saved entry.
220
+ collection.defaultModeId = modesInListedOrder(collection)[0].modeId
206
221
  }
207
222
  for (const varId of collection.variableIds) {
208
223
  const variable = graph.variables.get(varId)
209
224
  if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])
210
225
  }
226
+ // A layer that chose the mode goes back to the collection's default, and an instance keeps no
227
+ // override naming a mode that is gone, which would otherwise come back on a later sync.
228
+ const overrideField = variableModeOverrideField(collectionId)
229
+ for (const node of graph.nodes.values()) {
230
+ if (node.variableModes[collectionId] !== modeId) continue
231
+ const variableModes = omit(node.variableModes, [collectionId])
232
+ graph.willChangeNode(node)
233
+ node.variableModes = variableModes
234
+ node.instanceOverrides.self.delete(overrideField)
235
+ for (const overrides of node.instanceOverrides.descendants.values())
236
+ overrides.delete(overrideField)
237
+ graph.emitter.emit('node:updated', node.id, { variableModes })
238
+ }
211
239
  if (graph.activeMode.get(collectionId) === modeId) {
212
240
  graph.activeMode.set(collectionId, collection.defaultModeId)
213
241
  }
@@ -230,15 +258,43 @@ export function setDefaultMode(graph: SceneGraph, collectionId: string, modeId:
230
258
  if (!collection) return
231
259
  if (!collection.modes.some((m) => m.modeId === modeId)) return
232
260
  collection.defaultModeId = modeId
233
- collection.modes = modesDefaultFirst(collection)
261
+ if (collection.modes.every((mode) => !mode.sortPosition)) {
262
+ // No sort positions carry an order of their own: the array is the order, so the new
263
+ // default moves first in it, as a collection created here has always done.
264
+ collection.modes = modesDefaultFirst(collection)
265
+ return
266
+ }
267
+ // The saved array order stays the file's own; the new default sorts first by its sort
268
+ // position, so the listed order shows it first and a re-import reads it as the default.
269
+ const listed = modesDefaultFirst(collection)
270
+ const positions = siblingOrderKeys(listed.map((mode) => mode.sortPosition))
271
+ const byId = new Map(listed.map((mode, index) => [mode.modeId, positions[index]]))
272
+ collection.modes = collection.modes.map((mode) => ({
273
+ ...mode,
274
+ sortPosition: byId.get(mode.modeId) ?? mode.sortPosition
275
+ }))
234
276
  }
235
277
 
236
- /** Figma has no default-mode field: the first mode is the default. */
278
+ /** Figma has no default-mode field: the first listed mode is the default. */
237
279
  export function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {
238
- const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)
280
+ const [defaults, rest] = partition(
281
+ modesInListedOrder(collection),
282
+ (m) => m.modeId === collection.defaultModeId
283
+ )
239
284
  return [...defaults, ...rest]
240
285
  }
241
286
 
287
+ /**
288
+ * The modes as Figma lists them: by `sortPosition`, modes without one following in saved order.
289
+ * The collection's own array keeps the file's saved order, which an export writes back as it was.
290
+ */
291
+ export function modesInListedOrder(collection: VariableCollection): VariableCollectionMode[] {
292
+ return sortBy(collection.modes, [
293
+ (mode) => !mode.sortPosition,
294
+ (mode) => mode.sortPosition ?? ''
295
+ ])
296
+ }
297
+
242
298
  export function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {
243
299
  const collection = graph.variableCollections.get(collectionId)
244
300
  if (!collection) return []
@@ -326,7 +382,6 @@ export function bindVariable(
326
382
  throw new Error(`Variable "${variableId}" not found`)
327
383
  }
328
384
 
329
- // Color fields require COLOR variable type
330
385
  const paint = paintBindingTarget(field)
331
386
  if (paint) {
332
387
  if (variable.type !== 'COLOR') {
@@ -341,6 +396,7 @@ export function bindVariable(
341
396
  }
342
397
  // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding
343
398
  if (paint.list in node.boundVariables) {
399
+ graph.willChangeNode(node)
344
400
  node.boundVariables = omit(node.boundVariables, [paint.list])
345
401
  }
346
402
  }
@@ -389,6 +445,8 @@ export function bindVariable(
389
445
  variableBindingScales: { ...node.variableBindingScales },
390
446
  ...runs
391
447
  })
448
+ // A paint takes its variable's color, alpha as opacity, when it binds, as Figma's does.
449
+ if (paint) applyBoundPaintColor(graph, node, field)
392
450
  }
393
451
 
394
452
  export function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {
@@ -418,22 +476,30 @@ function markBoundVariablesOverrideOnInstance(
418
476
  const owner = variableBindingOwner(graph, node)
419
477
  if (owner.type !== 'INSTANCE') return
420
478
  const nearest = findInstanceAncestor(graph, nodeId)
479
+ const instances = uniq(compact([nearest, owner])).filter((x) => x.id !== nodeId)
480
+ for (const instance of instances) graph.willChangeNode(instance)
421
481
  if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')
422
482
  setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')
483
+ // Each instance claims the binding it changed alone, so the layer's other bindings keep
484
+ // following their components, as Figma claims only the paint or effect a script edits.
423
485
  if (field)
424
- setInstanceOverride(
425
- owner.instanceOverrides,
426
- owner.id,
427
- nodeId,
428
- bindingOverrideField(field),
429
- node.boundVariables[field] ?? null
430
- )
486
+ for (const instance of instances)
487
+ setInstanceOverride(
488
+ instance.instanceOverrides,
489
+ instance.id,
490
+ nodeId,
491
+ bindingOverrideField(field),
492
+ node.boundVariables[field] ?? null
493
+ )
494
+ for (const instance of instances)
495
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
431
496
  }
432
497
 
433
498
  export * from './bindings'
434
499
  export * from './corners'
435
500
  export * from './formula'
436
501
  export * from './formula/schema'
502
+ export * from './paints'
437
503
  export * from './schema'
438
504
  export * from './text'
439
505
  export * from './token'