@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
@@ -0,0 +1,313 @@
1
+ import { hasInstanceOverride } from "../instances/overrides.js";
2
+ import { copyFills, copyStrokes } from "../copy.js";
3
+ import { paintBindingTarget } from "./fields.js";
4
+ import { collectionsResolving, getNodeExplicitVariableModeId } from "./resolution.js";
5
+ import { subtreeNodes } from "./subtree.js";
6
+ import { isEqual } from "es-toolkit/predicate";
7
+ //#region src/variables/paints.ts
8
+ const appliedColors = /* @__PURE__ */ new WeakMap();
9
+ const PAINT_LISTS = ["fills", "strokes"];
10
+ /** The paints of `node` whose color is bound to a variable, each with a paint there to color. */
11
+ function boundPaints(node) {
12
+ const paints = [];
13
+ for (const [field, variableId] of Object.entries(node.boundVariables)) {
14
+ const target = paintBindingTarget(field);
15
+ if (target && node[target.list].at(target.index)) paints.push({
16
+ field,
17
+ ...target,
18
+ variableId
19
+ });
20
+ }
21
+ return paints;
22
+ }
23
+ /** Whether a layer has a paint whose color is bound to a variable. */
24
+ function hasBoundPaints(node) {
25
+ for (const field in node.boundVariables) if (paintBindingTarget(field)) return true;
26
+ return false;
27
+ }
28
+ /**
29
+ * Whether a binding's paint holds a color this graph applied or recorded for it. A layer without
30
+ * an entry, such as one just imported or built with its bindings, has a stored color nothing
31
+ * vouches for: readers show its variable's color until a write or refresh records one.
32
+ */
33
+ function paintColorApplied(node, field) {
34
+ return appliedColors.get(node)?.has(field) ?? false;
35
+ }
36
+ /** A paint's color with its opacity as alpha, as a variable's color carries it. */
37
+ function paintColor(paint) {
38
+ return {
39
+ r: paint.color.r,
40
+ g: paint.color.g,
41
+ b: paint.color.b,
42
+ a: paint.opacity
43
+ };
44
+ }
45
+ /** Saved colors are single precision, so a color read back from a file still matches its source. */
46
+ const COLOR_TOLERANCE = 1e-6;
47
+ function sameColor(a, b) {
48
+ return Math.abs(a.r - b.r) <= COLOR_TOLERANCE && Math.abs(a.g - b.g) <= COLOR_TOLERANCE && Math.abs(a.b - b.b) <= COLOR_TOLERANCE && Math.abs(a.a - b.a) <= COLOR_TOLERANCE;
49
+ }
50
+ /**
51
+ * The modes set for a layer, or null, in the collections a variable resolves through. Figma
52
+ * refreshes a bound paint whenever one of them changes, even to a mode giving the same color.
53
+ */
54
+ function explicitModes(graph, node, variableId) {
55
+ const modes = {};
56
+ for (const collectionId of collectionsResolving(graph, [variableId])) modes[collectionId] = getNodeExplicitVariableModeId(graph, node.id, collectionId);
57
+ return modes;
58
+ }
59
+ /** Whether the color a binding last applied is stale: another color, or set in other modes. */
60
+ function staleApplied(node, bound, paint, color, modes) {
61
+ const entry = appliedColors.get(node)?.get(bound.field);
62
+ if (entry?.variableId !== bound.variableId) return !sameColor(paintColor(paint), color);
63
+ return !sameColor(entry.color, color) || !isEqual(entry.modes, modes);
64
+ }
65
+ /**
66
+ * A layer copied from another keeps the colors its bindings last applied there, so the copy's
67
+ * paints, edits included, stay as they are until their variables' colors for it change.
68
+ */
69
+ function copyAppliedBoundPaints(source, copy) {
70
+ const entries = appliedColors.get(source);
71
+ if (entries) appliedColors.set(copy, new Map(entries));
72
+ }
73
+ /**
74
+ * The colors the bindings of the layers `nodeIds` names last applied, captured when they are
75
+ * copied, so a paste counts what the copied paints were applied from, not what the source has now.
76
+ */
77
+ function captureAppliedBoundPaints(graph, nodeIds) {
78
+ const captured = /* @__PURE__ */ new Map();
79
+ for (const id of nodeIds) {
80
+ const node = graph.nodes.get(id);
81
+ const entries = node && appliedColors.get(node);
82
+ if (entries) captured.set(id, new Map(entries));
83
+ }
84
+ return captured;
85
+ }
86
+ /**
87
+ * Pasted layers keep their paints, edits included, as Figma's copies do. One copied in this
88
+ * document takes the colors its source's bindings had last applied when it was copied, so a paste
89
+ * into another mode refreshes them as a move there would; one from elsewhere counts the colors
90
+ * its variables give it now as applied, as a loaded document does. `copies` maps each copied
91
+ * layer's id to its copy's.
92
+ */
93
+ function keepPastedBoundPaints(graph, copies, applied) {
94
+ for (const [sourceId, copyId] of copies) {
95
+ const copy = graph.nodes.get(copyId);
96
+ if (!copy || !hasBoundPaints(copy)) continue;
97
+ const entries = applied.get(sourceId);
98
+ if (!entries) {
99
+ recordWrittenBoundPaints(graph, copy, {
100
+ fills: copy.fills,
101
+ strokes: copy.strokes
102
+ });
103
+ continue;
104
+ }
105
+ appliedColors.set(copy, new Map(entries));
106
+ refresh(graph, copy, NONE_FORCED);
107
+ }
108
+ }
109
+ function recordApplied(node, bound, color, modes) {
110
+ let entries = appliedColors.get(node);
111
+ if (!entries) {
112
+ entries = /* @__PURE__ */ new Map();
113
+ appliedColors.set(node, entries);
114
+ }
115
+ entries.set(bound.field, {
116
+ variableId: bound.variableId,
117
+ color: { ...color },
118
+ modes
119
+ });
120
+ }
121
+ /** The variable's RGB at full alpha in the paint, and its alpha as the paint's opacity. */
122
+ function applyColor(paint, color) {
123
+ paint.color = {
124
+ ...color,
125
+ a: 1
126
+ };
127
+ paint.opacity = color.a;
128
+ }
129
+ /** Whether `paint` already shows `color` as a bound paint stores it. */
130
+ function showsColor(paint, color) {
131
+ return sameColor(paintColor(paint), color) && paint.color.a === 1;
132
+ }
133
+ /**
134
+ * Whether `node` is an instance, or a layer an instance copies from its component, with a paint
135
+ * list neither it nor an instance around it overrides: such paints follow the component, and
136
+ * refreshing them is no edit.
137
+ */
138
+ function copiesComponentPaints(graph, node, list) {
139
+ const walk = { copied: false };
140
+ const overriding = graph.closest(node.id, (current) => {
141
+ if (current.type !== "INSTANCE") return false;
142
+ walk.copied = true;
143
+ return hasInstanceOverride(current.instanceOverrides, current.id, node.id, list);
144
+ });
145
+ return walk.copied && !overriding;
146
+ }
147
+ /**
148
+ * Writes refreshed paints. A copy's paints that follow its component are derived values that a
149
+ * save leaves to the component, not edits written over it.
150
+ */
151
+ function writePaints(graph, node, changes) {
152
+ const derived = PAINT_LISTS.every((list) => !changes[list] || copiesComponentPaints(graph, node, list));
153
+ const write = () => graph.updateNode(node.id, changes);
154
+ if (derived) graph.applyComponentDerivedDuring(write);
155
+ else write();
156
+ }
157
+ /**
158
+ * Writes into each bound paint the color its variable gives the layer now, where that differs
159
+ * from the color last applied, or wherever `forced` says, and records what each binding gives.
160
+ */
161
+ function refresh(graph, node, forced) {
162
+ let fills;
163
+ let strokes;
164
+ for (const bound of boundPaints(node)) {
165
+ const color = graph.resolveColorVariableForNode(node.id, bound.variableId);
166
+ const paint = node[bound.list].at(bound.index);
167
+ if (!color || !paint) continue;
168
+ const modes = explicitModes(graph, node, bound.variableId);
169
+ const stale = staleApplied(node, bound, paint, color, modes);
170
+ recordApplied(node, bound, color, modes);
171
+ if (!forced(bound.field) && !stale || showsColor(paint, color)) continue;
172
+ if (bound.list === "fills") {
173
+ fills ??= copyFills(node.fills);
174
+ applyColor(fills[bound.index], color);
175
+ } else {
176
+ strokes ??= copyStrokes(node.strokes);
177
+ applyColor(strokes[bound.index], color);
178
+ }
179
+ }
180
+ const changes = {};
181
+ if (fills) changes.fills = fills;
182
+ if (strokes) changes.strokes = strokes;
183
+ if (fills || strokes) writePaints(graph, node, changes);
184
+ }
185
+ const NONE_FORCED = () => false;
186
+ const ALL_FORCED = () => true;
187
+ /**
188
+ * Refreshes a layer's bound paints: each takes its variable's color for the layer, alpha as
189
+ * opacity, once that color differs from the one last applied, discarding edits made since, as
190
+ * Figma refreshes them when a variable's value or a layer's mode changes.
191
+ */
192
+ function refreshBoundPaints(graph, node) {
193
+ if (hasBoundPaints(node)) refresh(graph, node, NONE_FORCED);
194
+ }
195
+ /** Gives one bound paint its variable's color for the layer, as binding it does in Figma. */
196
+ function applyBoundPaintColor(graph, node, field) {
197
+ if (paintBindingTarget(field)) refresh(graph, node, (bound) => bound === field);
198
+ }
199
+ /**
200
+ * Gives every bound paint in this subtree its variable's color where it sits. A new instance
201
+ * or a layer an instance sync adds is a copy, which shows its variables in its own context rather
202
+ * than whatever its component's paints hold.
203
+ */
204
+ function applyBoundPaintColorsIn(graph, rootId) {
205
+ for (const node of subtreeNodes(graph, [rootId])) if (hasBoundPaints(node)) refresh(graph, node, ALL_FORCED);
206
+ }
207
+ /** Refreshes the bound paints in this subtree whose variables now give their layers another color. */
208
+ function refreshBoundPaintsIn(graph, rootId) {
209
+ for (const node of subtreeNodes(graph, [rootId])) refreshBoundPaints(graph, node);
210
+ }
211
+ /**
212
+ * Records, for the paint lists a write sets, the colors their variables give the layer now, so a
213
+ * paint written with another color or opacity keeps it until that color changes.
214
+ */
215
+ function recordWrittenBoundPaints(graph, node, written) {
216
+ for (const bound of boundPaints(node)) {
217
+ if (!written[bound.list]) continue;
218
+ const color = graph.resolveColorVariableForNode(node.id, bound.variableId);
219
+ if (color) recordApplied(node, bound, color, explicitModes(graph, node, bound.variableId));
220
+ }
221
+ }
222
+ /**
223
+ * The fills and strokes a layer shows: its stored paints, except a bound paint no applied color
224
+ * vouches for takes its variable's color for the layer, alpha as opacity, as Figma shows a layer
225
+ * whose saved cache is stale on import. Nothing is written or recorded; a copy pasted unlinked
226
+ * keeps the colors it showed.
227
+ */
228
+ function shownPaintBindings(graph, node) {
229
+ const changes = {};
230
+ for (const bound of boundPaints(node)) {
231
+ if (paintColorApplied(node, bound.field)) continue;
232
+ const color = graph.resolveColorVariableForNode(node.id, bound.variableId);
233
+ const paint = node[bound.list].at(bound.index);
234
+ if (!color || !paint || showsColor(paint, color)) continue;
235
+ if (bound.list === "fills") {
236
+ changes.fills ??= copyFills(node.fills);
237
+ applyColor(changes.fills[bound.index], color);
238
+ } else {
239
+ changes.strokes ??= copyStrokes(node.strokes);
240
+ applyColor(changes.strokes[bound.index], color);
241
+ }
242
+ }
243
+ return changes;
244
+ }
245
+ /**
246
+ * Refreshes the bound paints in a moved layer's subtree that resolve through a collection whose
247
+ * mode set the move changed, as Figma does when a layer enters a frame or page that sets another
248
+ * mode, or one where none was. A move between parents setting the same modes, or of layers that
249
+ * bind no paint, costs no more than comparing those modes.
250
+ */
251
+ function refreshMovedBoundPaints(graph, nodeId, previousParentId) {
252
+ if (graph.isApplyingImportedState || graph.variableCollections.size === 0) return;
253
+ const parentId = graph.nodes.get(nodeId)?.parentId;
254
+ if (!parentId) return;
255
+ const previous = previousParentId && graph.nodes.has(previousParentId) ? previousParentId : null;
256
+ const changed = new Set([...graph.variableCollections.keys()].filter((id) => !previous || getNodeExplicitVariableModeId(graph, previous, id) !== getNodeExplicitVariableModeId(graph, parentId, id)));
257
+ if (changed.size === 0) return;
258
+ const reaches = /* @__PURE__ */ new Map();
259
+ const reachesChanged = (variableId) => {
260
+ let found = reaches.get(variableId);
261
+ if (found === void 0) {
262
+ found = [...collectionsResolving(graph, [variableId])].some((id) => changed.has(id));
263
+ reaches.set(variableId, found);
264
+ }
265
+ return found;
266
+ };
267
+ for (const node of subtreeNodes(graph, [nodeId])) if (boundPaints(node).some((bound) => reachesChanged(bound.variableId))) refresh(graph, node, NONE_FORCED);
268
+ }
269
+ function reboundPaint(target, bindings, list) {
270
+ return target[list].some((_, index) => {
271
+ const field = `${list}/${index}/color`;
272
+ return field in bindings && bindings[field] !== target.boundVariables[field];
273
+ });
274
+ }
275
+ /**
276
+ * A copy's bound paints are its own cache, as Figma keeps them per layer, so a component's edit
277
+ * to its paint's color or opacity does not reach them. An instance sync writing a copy's paints
278
+ * keeps the color and opacity of each one still bound to the same variable, and gives it the
279
+ * variable's color for the copy once that differs from the one last applied, or when it binds
280
+ * anew. `updates` holds what the sync writes, whose paints this sets in place.
281
+ */
282
+ function keepCopyBoundPaints(graph, target, updates) {
283
+ const bindings = updates.boundVariables ?? target.boundVariables;
284
+ for (const list of PAINT_LISTS) {
285
+ if (!updates[list] && reboundPaint(target, bindings, list)) Object.assign(updates, { [list]: list === "fills" ? copyFills(target.fills) : copyStrokes(target.strokes) });
286
+ updates[list]?.forEach((paint, index) => {
287
+ const field = `${list}/${index}/color`;
288
+ const variableId = bindings[field];
289
+ if (!variableId) return;
290
+ const bound = {
291
+ field,
292
+ list,
293
+ index,
294
+ variableId
295
+ };
296
+ const own = target[list].at(index);
297
+ const keeps = own !== void 0 && target.boundVariables[field] === variableId;
298
+ if (keeps) {
299
+ paint.color = { ...own.color };
300
+ paint.opacity = own.opacity;
301
+ }
302
+ const color = graph.resolveColorVariableForNode(target.id, variableId);
303
+ if (!color) return;
304
+ const modes = explicitModes(graph, target, variableId);
305
+ if (!keeps || staleApplied(target, bound, own, color, modes)) applyColor(paint, color);
306
+ recordApplied(target, bound, color, modes);
307
+ });
308
+ }
309
+ }
310
+ //#endregion
311
+ export { applyBoundPaintColor, applyBoundPaintColorsIn, captureAppliedBoundPaints, copiesComponentPaints, copyAppliedBoundPaints, hasBoundPaints, keepCopyBoundPaints, keepPastedBoundPaints, paintColorApplied, recordWrittenBoundPaints, refreshBoundPaints, refreshBoundPaintsIn, refreshMovedBoundPaints, shownPaintBindings };
312
+
313
+ //# sourceMappingURL=paints.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paints.js","names":[],"sources":["../../src/variables/paints.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport { copyFills, copyStrokes } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { hasInstanceOverride } from '../instances/overrides'\nimport type { Color } from '../primitives'\nimport type { Fill, SceneNode, Stroke } from '../types'\nimport { paintBindingTarget, type PaintBindingList } from './fields'\nimport { collectionsResolving, getNodeExplicitVariableModeId } from './resolution'\nimport { subtreeNodes } from './subtree'\n\n/**\n * Figma keeps a bound paint's color and opacity as a cache of its variable: it draws and reads\n * what the paint holds, and writes the variable's color into it again only once the color the\n * variable gives that layer changes, or the mode set for the layer changes, so an edit to the\n * paint sticks until then. The color each binding last gave its paint, and the modes set for the\n * layer then, live here, beside the graph and never saved, by layer and binding field. A layer\n * without an entry, such as one just restored, counts its paint's own color as the last one\n * applied, in the modes it has now.\n */\nexport interface AppliedColor {\n readonly variableId: string\n readonly color: Color\n /** The mode set for the layer, or null, in each collection the variable resolves through. */\n readonly modes: Readonly<Record<string, string | null>>\n}\n\nconst appliedColors = new WeakMap<SceneNode, Map<string, AppliedColor>>()\n\nconst PAINT_LISTS = ['fills', 'strokes'] as const\n\ninterface BoundPaint {\n readonly field: string\n readonly list: PaintBindingList\n readonly index: number\n readonly variableId: string\n}\n\n/** The paints of `node` whose color is bound to a variable, each with a paint there to color. */\nfunction boundPaints(node: SceneNode): BoundPaint[] {\n const paints: BoundPaint[] = []\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n const target = paintBindingTarget(field)\n if (target && node[target.list].at(target.index)) paints.push({ field, ...target, variableId })\n }\n return paints\n}\n\n/** Whether a layer has a paint whose color is bound to a variable. */\nexport function hasBoundPaints(node: SceneNode): boolean {\n for (const field in node.boundVariables) if (paintBindingTarget(field)) return true\n return false\n}\n\n/**\n * Whether a binding's paint holds a color this graph applied or recorded for it. A layer without\n * an entry, such as one just imported or built with its bindings, has a stored color nothing\n * vouches for: readers show its variable's color until a write or refresh records one.\n */\nexport function paintColorApplied(node: SceneNode, field: string): boolean {\n return appliedColors.get(node)?.has(field) ?? false\n}\n\n/** A paint's color with its opacity as alpha, as a variable's color carries it. */\nfunction paintColor(paint: Fill): Color {\n return { r: paint.color.r, g: paint.color.g, b: paint.color.b, a: paint.opacity }\n}\n\n/** Saved colors are single precision, so a color read back from a file still matches its source. */\nconst COLOR_TOLERANCE = 1e-6\n\nfunction sameColor(a: Color, b: Color): boolean {\n return (\n Math.abs(a.r - b.r) <= COLOR_TOLERANCE &&\n Math.abs(a.g - b.g) <= COLOR_TOLERANCE &&\n Math.abs(a.b - b.b) <= COLOR_TOLERANCE &&\n Math.abs(a.a - b.a) <= COLOR_TOLERANCE\n )\n}\n\n/**\n * The modes set for a layer, or null, in the collections a variable resolves through. Figma\n * refreshes a bound paint whenever one of them changes, even to a mode giving the same color.\n */\nfunction explicitModes(\n graph: SceneGraph,\n node: SceneNode,\n variableId: string\n): Record<string, string | null> {\n const modes: Record<string, string | null> = {}\n for (const collectionId of collectionsResolving(graph, [variableId]))\n modes[collectionId] = getNodeExplicitVariableModeId(graph, node.id, collectionId)\n return modes\n}\n\n/** Whether the color a binding last applied is stale: another color, or set in other modes. */\nfunction staleApplied(\n node: SceneNode,\n bound: BoundPaint,\n paint: Fill,\n color: Color,\n modes: Readonly<Record<string, string | null>>\n): boolean {\n const entry = appliedColors.get(node)?.get(bound.field)\n if (entry?.variableId !== bound.variableId) return !sameColor(paintColor(paint), color)\n return !sameColor(entry.color, color) || !isEqual(entry.modes, modes)\n}\n\n/**\n * A layer copied from another keeps the colors its bindings last applied there, so the copy's\n * paints, edits included, stay as they are until their variables' colors for it change.\n */\nexport function copyAppliedBoundPaints(source: SceneNode, copy: SceneNode): void {\n const entries = appliedColors.get(source)\n if (entries) appliedColors.set(copy, new Map(entries))\n}\n\n/** The colors copied layers' bindings last applied, by layer id, as a copy captured them. */\nexport type AppliedBoundPaints = ReadonlyMap<string, ReadonlyMap<string, AppliedColor>>\n\n/**\n * The colors the bindings of the layers `nodeIds` names last applied, captured when they are\n * copied, so a paste counts what the copied paints were applied from, not what the source has now.\n */\nexport function captureAppliedBoundPaints(\n graph: SceneGraph,\n nodeIds: Iterable<string>\n): AppliedBoundPaints {\n const captured = new Map<string, ReadonlyMap<string, AppliedColor>>()\n for (const id of nodeIds) {\n const node = graph.nodes.get(id)\n const entries = node && appliedColors.get(node)\n if (entries) captured.set(id, new Map(entries))\n }\n return captured\n}\n\n/**\n * Pasted layers keep their paints, edits included, as Figma's copies do. One copied in this\n * document takes the colors its source's bindings had last applied when it was copied, so a paste\n * into another mode refreshes them as a move there would; one from elsewhere counts the colors\n * its variables give it now as applied, as a loaded document does. `copies` maps each copied\n * layer's id to its copy's.\n */\nexport function keepPastedBoundPaints(\n graph: SceneGraph,\n copies: ReadonlyMap<string, string>,\n applied: AppliedBoundPaints\n): void {\n for (const [sourceId, copyId] of copies) {\n const copy = graph.nodes.get(copyId)\n if (!copy || !hasBoundPaints(copy)) continue\n const entries = applied.get(sourceId)\n if (!entries) {\n recordWrittenBoundPaints(graph, copy, { fills: copy.fills, strokes: copy.strokes })\n continue\n }\n appliedColors.set(copy, new Map(entries))\n refresh(graph, copy, NONE_FORCED)\n }\n}\n\nfunction recordApplied(\n node: SceneNode,\n bound: BoundPaint,\n color: Color,\n modes: Readonly<Record<string, string | null>>\n): void {\n let entries = appliedColors.get(node)\n if (!entries) {\n entries = new Map()\n appliedColors.set(node, entries)\n }\n entries.set(bound.field, { variableId: bound.variableId, color: { ...color }, modes })\n}\n\n/** The variable's RGB at full alpha in the paint, and its alpha as the paint's opacity. */\nfunction applyColor(paint: Fill, color: Color): void {\n paint.color = { ...color, a: 1 }\n paint.opacity = color.a\n}\n\n/** Whether `paint` already shows `color` as a bound paint stores it. */\nfunction showsColor(paint: Fill, color: Color): boolean {\n return sameColor(paintColor(paint), color) && paint.color.a === 1\n}\n\ntype PaintLists = Pick<Partial<SceneNode>, 'fills' | 'strokes'>\n\n/**\n * Whether `node` is an instance, or a layer an instance copies from its component, with a paint\n * list neither it nor an instance around it overrides: such paints follow the component, and\n * refreshing them is no edit.\n */\nexport function copiesComponentPaints(\n graph: SceneGraph,\n node: SceneNode,\n list: PaintBindingList\n): boolean {\n const walk = { copied: false }\n const overriding = graph.closest(node.id, (current) => {\n if (current.type !== 'INSTANCE') return false\n walk.copied = true\n return hasInstanceOverride(current.instanceOverrides, current.id, node.id, list)\n })\n return walk.copied && !overriding\n}\n\n/**\n * Writes refreshed paints. A copy's paints that follow its component are derived values that a\n * save leaves to the component, not edits written over it.\n */\nfunction writePaints(graph: SceneGraph, node: SceneNode, changes: PaintLists): void {\n const derived = PAINT_LISTS.every(\n (list) => !changes[list] || copiesComponentPaints(graph, node, list)\n )\n const write = () => graph.updateNode(node.id, changes)\n if (derived) graph.applyComponentDerivedDuring(write)\n else write()\n}\n\n/**\n * Writes into each bound paint the color its variable gives the layer now, where that differs\n * from the color last applied, or wherever `forced` says, and records what each binding gives.\n */\nfunction refresh(graph: SceneGraph, node: SceneNode, forced: (field: string) => boolean): void {\n let fills: Fill[] | undefined\n let strokes: Stroke[] | undefined\n for (const bound of boundPaints(node)) {\n const color = graph.resolveColorVariableForNode(node.id, bound.variableId)\n const paint = node[bound.list].at(bound.index)\n if (!color || !paint) continue\n const modes = explicitModes(graph, node, bound.variableId)\n const stale = staleApplied(node, bound, paint, color, modes)\n recordApplied(node, bound, color, modes)\n if ((!forced(bound.field) && !stale) || showsColor(paint, color)) continue\n if (bound.list === 'fills') {\n fills ??= copyFills(node.fills)\n applyColor(fills[bound.index], color)\n } else {\n strokes ??= copyStrokes(node.strokes)\n applyColor(strokes[bound.index], color)\n }\n }\n const changes: PaintLists = {}\n if (fills) changes.fills = fills\n if (strokes) changes.strokes = strokes\n if (fills || strokes) writePaints(graph, node, changes)\n}\n\nconst NONE_FORCED = (): boolean => false\nconst ALL_FORCED = (): boolean => true\n\n/**\n * Refreshes a layer's bound paints: each takes its variable's color for the layer, alpha as\n * opacity, once that color differs from the one last applied, discarding edits made since, as\n * Figma refreshes them when a variable's value or a layer's mode changes.\n */\nexport function refreshBoundPaints(graph: SceneGraph, node: SceneNode): void {\n if (hasBoundPaints(node)) refresh(graph, node, NONE_FORCED)\n}\n\n/** Gives one bound paint its variable's color for the layer, as binding it does in Figma. */\nexport function applyBoundPaintColor(graph: SceneGraph, node: SceneNode, field: string): void {\n if (paintBindingTarget(field)) refresh(graph, node, (bound) => bound === field)\n}\n\n/**\n * Gives every bound paint in this subtree its variable's color where it sits. A new instance\n * or a layer an instance sync adds is a copy, which shows its variables in its own context rather\n * than whatever its component's paints hold.\n */\nexport function applyBoundPaintColorsIn(graph: SceneGraph, rootId: string): void {\n for (const node of subtreeNodes(graph, [rootId]))\n if (hasBoundPaints(node)) refresh(graph, node, ALL_FORCED)\n}\n\n/** Refreshes the bound paints in this subtree whose variables now give their layers another color. */\nexport function refreshBoundPaintsIn(graph: SceneGraph, rootId: string): void {\n for (const node of subtreeNodes(graph, [rootId])) refreshBoundPaints(graph, node)\n}\n\n/**\n * Records, for the paint lists a write sets, the colors their variables give the layer now, so a\n * paint written with another color or opacity keeps it until that color changes.\n */\nexport function recordWrittenBoundPaints(\n graph: SceneGraph,\n node: SceneNode,\n written: PaintLists\n): void {\n for (const bound of boundPaints(node)) {\n if (!written[bound.list]) continue\n const color = graph.resolveColorVariableForNode(node.id, bound.variableId)\n if (color) recordApplied(node, bound, color, explicitModes(graph, node, bound.variableId))\n }\n}\n\n/**\n * The fills and strokes a layer shows: its stored paints, except a bound paint no applied color\n * vouches for takes its variable's color for the layer, alpha as opacity, as Figma shows a layer\n * whose saved cache is stale on import. Nothing is written or recorded; a copy pasted unlinked\n * keeps the colors it showed.\n */\nexport function shownPaintBindings(\n graph: SceneGraph,\n node: SceneNode\n): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {\n const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}\n for (const bound of boundPaints(node)) {\n if (paintColorApplied(node, bound.field)) continue\n const color = graph.resolveColorVariableForNode(node.id, bound.variableId)\n const paint = node[bound.list].at(bound.index)\n if (!color || !paint || showsColor(paint, color)) continue\n if (bound.list === 'fills') {\n changes.fills ??= copyFills(node.fills)\n applyColor(changes.fills[bound.index], color)\n } else {\n changes.strokes ??= copyStrokes(node.strokes)\n applyColor(changes.strokes[bound.index], color)\n }\n }\n return changes\n}\n\n/**\n * Refreshes the bound paints in a moved layer's subtree that resolve through a collection whose\n * mode set the move changed, as Figma does when a layer enters a frame or page that sets another\n * mode, or one where none was. A move between parents setting the same modes, or of layers that\n * bind no paint, costs no more than comparing those modes.\n */\nexport function refreshMovedBoundPaints(\n graph: SceneGraph,\n nodeId: string,\n previousParentId: string | null | undefined\n): void {\n if (graph.isApplyingImportedState || graph.variableCollections.size === 0) return\n const parentId = graph.nodes.get(nodeId)?.parentId\n if (!parentId) return\n const previous = previousParentId && graph.nodes.has(previousParentId) ? previousParentId : null\n const changed = new Set(\n [...graph.variableCollections.keys()].filter(\n (id) =>\n !previous ||\n getNodeExplicitVariableModeId(graph, previous, id) !==\n getNodeExplicitVariableModeId(graph, parentId, id)\n )\n )\n if (changed.size === 0) return\n const reaches = new Map<string, boolean>()\n const reachesChanged = (variableId: string) => {\n let found = reaches.get(variableId)\n if (found === undefined) {\n found = [...collectionsResolving(graph, [variableId])].some((id) => changed.has(id))\n reaches.set(variableId, found)\n }\n return found\n }\n for (const node of subtreeNodes(graph, [nodeId])) {\n if (boundPaints(node).some((bound) => reachesChanged(bound.variableId)))\n refresh(graph, node, NONE_FORCED)\n }\n}\n\nfunction reboundPaint(\n target: SceneNode,\n bindings: Readonly<Record<string, string>>,\n list: PaintBindingList\n): boolean {\n return target[list].some((_, index) => {\n const field = `${list}/${index}/color`\n return field in bindings && bindings[field] !== target.boundVariables[field]\n })\n}\n\n/**\n * A copy's bound paints are its own cache, as Figma keeps them per layer, so a component's edit\n * to its paint's color or opacity does not reach them. An instance sync writing a copy's paints\n * keeps the color and opacity of each one still bound to the same variable, and gives it the\n * variable's color for the copy once that differs from the one last applied, or when it binds\n * anew. `updates` holds what the sync writes, whose paints this sets in place.\n */\nexport function keepCopyBoundPaints(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>\n): void {\n const bindings = updates.boundVariables ?? target.boundVariables\n for (const list of PAINT_LISTS) {\n // A paint the component binds anew keeps its own paint otherwise, but takes the new color.\n if (!updates[list] && reboundPaint(target, bindings, list))\n Object.assign(updates, {\n [list]: list === 'fills' ? copyFills(target.fills) : copyStrokes(target.strokes)\n })\n updates[list]?.forEach((paint, index) => {\n const field = `${list}/${index}/color`\n const variableId = bindings[field]\n if (!variableId) return\n const bound = { field, list, index, variableId }\n const own = target[list].at(index)\n const keeps = own !== undefined && target.boundVariables[field] === variableId\n if (keeps) {\n paint.color = { ...own.color }\n paint.opacity = own.opacity\n }\n const color = graph.resolveColorVariableForNode(target.id, variableId)\n if (!color) return\n const modes = explicitModes(graph, target, variableId)\n if (!keeps || staleApplied(target, bound, own, color, modes)) applyColor(paint, color)\n recordApplied(target, bound, color, modes)\n })\n }\n}\n"],"mappings":";;;;;;;AA2BA,MAAM,gCAAgB,IAAI,QAA8C;AAExE,MAAM,cAAc,CAAC,SAAS,SAAS;;AAUvC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,QAAQ,OAAO,OAAO,KAAK;EAC3C,CAAC;CACH;AACF"}
@@ -3,6 +3,12 @@ import { VariableFormulaError } from "./formula/tree.js";
3
3
  import { SceneGraph } from "../graph.js";
4
4
  import { Variable, VariableLiteral, VariableValue } from "../types.js";
5
5
  //#region src/variables/resolution.d.ts
6
+ /**
7
+ * The modes a node draws in for every collection: its ancestors' explicit modes from the outside
8
+ * in, then its own. A copy that re-parents a node, such as an export of one layer, keeps this on
9
+ * the node so it still resolves its variables as the canvas does.
10
+ */
11
+ declare function resolvedVariableModes(graph: SceneGraph, nodeId: string): Record<string, string>;
6
12
  declare function getActiveModeId(graph: SceneGraph, collectionId: string): string;
7
13
  /**
8
14
  * What a node without an explicit mode falls back to: the mode the editor shows (`active`), or
@@ -10,6 +16,13 @@ declare function getActiveModeId(graph: SceneGraph, collectionId: string): strin
10
16
  */
11
17
  type VariableModeFallback = 'active' | 'default';
12
18
  declare function getNodeVariableModeId(graph: SceneGraph, nodeId: string, collectionId: string, fallback?: VariableModeFallback): string;
19
+ /** The nearest mode set on a node or an ancestor for a collection, or null where none is. */
20
+ declare function getNodeExplicitVariableModeId(graph: SceneGraph, nodeId: string, collectionId: string): string | null;
21
+ /**
22
+ * The collections whose modes decide what these variables resolve to: their own, and those of the
23
+ * variables they alias, at any depth and in any mode.
24
+ */
25
+ declare function collectionsResolving(graph: SceneGraph, variableIds: Iterable<string>): Set<string>;
13
26
  declare function resolveVariable(graph: SceneGraph, variableId: string, modeId?: string, visited?: Set<string>): VariableLiteral | undefined;
14
27
  declare class VariableResolutionError extends VariableFormulaError {
15
28
  readonly code: 'cycle' | 'depth' | 'missing-variable' | 'missing-value' | 'type' | 'non-finite';
@@ -35,5 +48,5 @@ declare function resolveNumberVariableForNode(graph: SceneGraph, nodeId: string,
35
48
  declare function resolveVariableForNode(graph: SceneGraph, nodeId: string, variableId: string, fallback?: VariableModeFallback): VariableLiteral | undefined;
36
49
  declare function resolveStringVariableForNode(graph: SceneGraph, nodeId: string, variableId: string, fallback?: VariableModeFallback): string | undefined;
37
50
  //#endregion
38
- export { NodeVariableResolver, VariableModeFallback, VariableResolutionError, createBatchVariableResolver, getActiveModeId, getNodeVariableModeId, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, variableValueInMode };
51
+ export { NodeVariableResolver, VariableModeFallback, VariableResolutionError, collectionsResolving, createBatchVariableResolver, getActiveModeId, getNodeExplicitVariableModeId, getNodeVariableModeId, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolvedVariableModes, variableValueInMode };
39
52
  //# sourceMappingURL=resolution.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolution.d.ts","names":[],"sources":["../../src/variables/resolution.ts"],"mappings":";;;;;iBAMgB,gBAAgB,OAAO,YAAY;;;;;KAWvC;iBAEI,sBACd,OAAO,YACP,gBACA,sBACA,WAAU;iBAaI,gBACd,OAAO,YACP,oBACA,iBACA,UAAU,cACT;cAaU,gCAAgC;WAGhC;WACA;EAHF;EAEE,YAAA,wFACA,oBACT;;;;;;iBAYY,uBACd,OAAO,YACP,oBACA,UAAU,iCACV,WAAQ,aACR,OAAO,YAAY,kBACnB,YAAY,oBAAoB,iBAC/B;;iBA2Ha,oBACd,OAAO,YACP,UAAU,UACV,iBACC;KAQS,wBACV,gBACA,uBACG;;iBAGW,4BAA4B,OAAO,aAAa;iBAqBhD,qBAAqB,OAAO,YAAY,qBAAqB;iBAM7D,sBAAsB,OAAO,YAAY;iBAKzC,4BACd,OAAO,YACP,gBACA,oBACA,WAAU,uBACT;iBAMa,6BACd,OAAO,YACP,gBACA,oBACA,WAAU;;iBAOI,uBACd,OAAO,YACP,gBACA,oBACA,WAAU,uBACT;iBAMa,6BACd,OAAO,YACP,gBACA,oBACA,WAAU"}
1
+ {"version":3,"file":"resolution.d.ts","names":[],"sources":["../../src/variables/resolution.ts"],"mappings":";;;;;;;;;;iBAWgB,sBAAsB,OAAO,YAAY,iBAAiB;iBAY1D,gBAAgB,OAAO,YAAY;;;;;KAWvC;iBAEI,sBACd,OAAO,YACP,gBACA,sBACA,WAAU;;iBAUI,8BACd,OAAO,YACP,gBACA;;;;;iBAec,qBACd,OAAO,YACP,aAAa,mBACZ;iBAgBa,gBACd,OAAO,YACP,oBACA,iBACA,UAAU,cACT;cAaU,gCAAgC;WAGhC;WACA;EAHF;EAEE,YAAA,wFACA,oBACT;;;;;;iBAYY,uBACd,OAAO,YACP,oBACA,UAAU,iCACV,WAAQ,aACR,OAAO,YAAY,kBACnB,YAAY,oBAAoB,iBAC/B;;iBA2Ha,oBACd,OAAO,YACP,UAAU,UACV,iBACC;KAQS,wBACV,gBACA,uBACG;;iBAGW,4BAA4B,OAAO,aAAa;iBAqBhD,qBAAqB,OAAO,YAAY,qBAAqB;iBAM7D,sBAAsB,OAAO,YAAY;iBAKzC,4BACd,OAAO,YACP,gBACA,oBACA,WAAU,uBACT;iBAMa,6BACd,OAAO,YACP,gBACA,oBACA,WAAU;;iBAOI,uBACd,OAAO,YACP,gBACA,oBACA,WAAU,uBACT;iBAMa,6BACd,OAAO,YACP,gBACA,oBACA,WAAU"}
@@ -1,20 +1,60 @@
1
1
  import { VariableFormulaError } from "./formula/tree.js";
2
- import { resolveVariableValue } from "./value.js";
2
+ import { resolveVariableValue, variableValueReferences } from "./value.js";
3
3
  //#region src/variables/resolution.ts
4
+ /**
5
+ * The modes a node draws in for every collection: its ancestors' explicit modes from the outside
6
+ * in, then its own. A copy that re-parents a node, such as an export of one layer, keeps this on
7
+ * the node so it still resolves its variables as the canvas does.
8
+ */
9
+ function resolvedVariableModes(graph, nodeId) {
10
+ const chain = [];
11
+ let node = graph.nodes.get(nodeId);
12
+ while (node) {
13
+ chain.push(node);
14
+ node = node.parentId ? graph.nodes.get(node.parentId) : void 0;
15
+ }
16
+ const modes = {};
17
+ for (const ancestor of chain.reverse()) Object.assign(modes, ancestor.variableModes);
18
+ return modes;
19
+ }
4
20
  function getActiveModeId(graph, collectionId) {
5
21
  const mode = graph.activeMode.get(collectionId);
6
22
  if (mode) return mode;
7
23
  return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
8
24
  }
9
25
  function getNodeVariableModeId(graph, nodeId, collectionId, fallback = "active") {
26
+ const explicit = getNodeExplicitVariableModeId(graph, nodeId, collectionId);
27
+ if (explicit !== null) return explicit;
28
+ if (fallback === "default") return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
29
+ return getActiveModeId(graph, collectionId);
30
+ }
31
+ /** The nearest mode set on a node or an ancestor for a collection, or null where none is. */
32
+ function getNodeExplicitVariableModeId(graph, nodeId, collectionId) {
10
33
  let node = graph.nodes.get(nodeId);
11
34
  while (node) {
12
35
  const modeId = node.variableModes[collectionId];
13
36
  if (modeId) return modeId;
14
37
  node = node.parentId ? graph.nodes.get(node.parentId) : void 0;
15
38
  }
16
- if (fallback === "default") return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
17
- return getActiveModeId(graph, collectionId);
39
+ return null;
40
+ }
41
+ /**
42
+ * The collections whose modes decide what these variables resolve to: their own, and those of the
43
+ * variables they alias, at any depth and in any mode.
44
+ */
45
+ function collectionsResolving(graph, variableIds) {
46
+ const pending = [...variableIds];
47
+ const seen = /* @__PURE__ */ new Set();
48
+ const collections = /* @__PURE__ */ new Set();
49
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
50
+ if (seen.has(id)) continue;
51
+ seen.add(id);
52
+ const variable = graph.variables.get(id);
53
+ if (!variable) continue;
54
+ collections.add(variable.collectionId);
55
+ for (const value of Object.values(variable.valuesByMode)) pending.push(...variableValueReferences(value));
56
+ }
57
+ return collections;
18
58
  }
19
59
  function resolveVariable(graph, variableId, modeId, visited) {
20
60
  const initial = graph.variables.get(variableId);
@@ -149,6 +189,6 @@ function resolveStringVariableForNode(graph, nodeId, variableId, fallback = "act
149
189
  return typeof value === "string" ? value : void 0;
150
190
  }
151
191
  //#endregion
152
- export { VariableResolutionError, createBatchVariableResolver, getActiveModeId, getNodeVariableModeId, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, variableValueInMode };
192
+ export { VariableResolutionError, collectionsResolving, createBatchVariableResolver, getActiveModeId, getNodeExplicitVariableModeId, getNodeVariableModeId, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolvedVariableModes, variableValueInMode };
153
193
 
154
194
  //# sourceMappingURL=resolution.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolution.js","names":[],"sources":["../../src/variables/resolution.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport type { Color } from '../primitives'\nimport type { Variable, VariableLiteral, VariableValue } from '../types'\nimport { MAX_FORMULA_DEPTH, VariableFormulaError } from './formula/tree'\nimport { resolveVariableValue } from './value'\n\nexport function getActiveModeId(graph: SceneGraph, collectionId: string): string {\n const mode = graph.activeMode.get(collectionId)\n if (mode) return mode\n const collection = graph.variableCollections.get(collectionId)\n return collection?.defaultModeId ?? ''\n}\n\n/**\n * What a node without an explicit mode falls back to: the mode the editor shows (`active`), or\n * the collection's default (`default`), which is what a saved document means to other tools.\n */\nexport type VariableModeFallback = 'active' | 'default'\n\nexport function getNodeVariableModeId(\n graph: SceneGraph,\n nodeId: string,\n collectionId: string,\n fallback: VariableModeFallback = 'active'\n): string {\n let node = graph.nodes.get(nodeId)\n while (node) {\n const modeId = node.variableModes[collectionId]\n if (modeId) return modeId\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n if (fallback === 'default')\n return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''\n return getActiveModeId(graph, collectionId)\n}\n\nexport function resolveVariable(\n graph: SceneGraph,\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n): VariableLiteral | undefined {\n const initial = graph.variables.get(variableId)\n return resolveInModes(\n graph,\n variableId,\n (collectionId) =>\n modeId && initial?.collectionId === collectionId\n ? modeId\n : getActiveModeId(graph, collectionId),\n visited\n )\n}\n\nexport class VariableResolutionError extends VariableFormulaError {\n override name = 'VariableResolutionError'\n constructor(\n readonly code: 'cycle' | 'depth' | 'missing-variable' | 'missing-value' | 'type' | 'non-finite',\n readonly variableId: string,\n message: string\n ) {\n super(message)\n }\n}\n\nconst RESULT_TYPES = { FLOAT: 'number', BOOLEAN: 'boolean', STRING: 'string', COLOR: 'object' }\n\n/**\n * Resolve a draft or saved definition with identical mode, dependency and error semantics. A\n * memo shares values between lookups in one mode context; without one, nothing is cached.\n */\nexport function resolveVariableInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting = new Set<string>(),\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n if (visiting.has(variableId))\n throw new VariableResolutionError('cycle', variableId, 'Circular variable reference')\n if (visiting.size >= MAX_FORMULA_DEPTH)\n throw new VariableResolutionError('depth', variableId, 'Too many linked variables')\n const variable = graph.variables.get(variableId)\n if (!variable)\n throw new VariableResolutionError(\n 'missing-variable',\n variableId,\n `Missing variable: ${variableId}`\n )\n const value =\n overrides?.get(variableId) ??\n variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (value === undefined)\n throw new VariableResolutionError(\n 'missing-value',\n variableId,\n `Missing value: ${variable.name}`\n )\n return evaluateDefinition(graph, variable, value, modeFor, visiting, memo, overrides)\n}\n\n/** Resolve one variable's definition in its mode context, its dependencies in theirs. */\nfunction evaluateDefinition(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting: Set<string>,\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const variableId = variable.id\n visiting.add(variableId)\n try {\n const result = resolveVariableValue(value, (id) =>\n resolveVariableInModes(graph, id, modeFor, visiting, memo, overrides)\n )\n if (result === undefined || typeof result !== RESULT_TYPES[variable.type])\n throw new VariableResolutionError('type', variableId, `Wrong result type: ${variable.name}`)\n if (typeof result === 'number' && !Number.isFinite(result))\n throw new VariableResolutionError(\n 'non-finite',\n variableId,\n `Non-finite value: ${variable.name}`\n )\n // Failures can depend on the current path's depth. Only completed values are reusable.\n memo?.set(variableId, result)\n return result\n } finally {\n visiting.delete(variableId)\n }\n}\n\n/**\n * What the canvas draws for a variable, or nothing when it cannot be resolved. Literals and alias\n * chains, which most bindings are, resolve in a loop; an expression on the way takes the full\n * resolver, whose diagnostics the canvas does not need.\n */\nfunction resolveInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n const initial = graph.variables.get(variableId)\n if (!initial) return undefined\n let id = variableId\n for (let depth = visiting?.size ?? 0; depth < MAX_FORMULA_DEPTH; depth++) {\n const variable = id === variableId ? initial : graph.variables.get(id)\n if (!variable || visiting?.has(id)) return undefined\n const value = variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (typeof value === 'object' && 'aliasId' in value) {\n id = value.aliasId\n continue\n }\n const result =\n typeof value === 'object' && 'expression' in value\n ? resolveExpression(graph, variable, value, modeFor, visiting, memo)\n : value\n return drawable(result, initial.type)\n }\n return undefined\n}\n\n/** A formula shares its dependencies' values for the length of one resolution. */\nfunction resolveExpression(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n try {\n return evaluateDefinition(\n graph,\n variable,\n value,\n modeFor,\n visiting ?? new Set(),\n memo ?? new Map()\n )\n } catch {\n return undefined\n }\n}\n\n/** A resolved value the canvas can draw for a variable of this type, or nothing. */\nfunction drawable(value: VariableValue | undefined, type: Variable['type']) {\n if (value === undefined || typeof value !== RESULT_TYPES[type]) return undefined\n if (typeof value === 'object' && !('r' in value)) return undefined\n return typeof value === 'number' && !Number.isFinite(value) ? undefined : value\n}\n\n/** Shared mode fallback for canvas resolution and formula draft validation. */\nexport function variableValueInMode(\n graph: SceneGraph,\n variable: Variable,\n modeId: string\n): VariableValue | undefined {\n const values = variable.valuesByMode\n if (Object.hasOwn(values, modeId)) return values[modeId]\n const defaultMode = graph.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''\n if (Object.hasOwn(values, defaultMode)) return values[defaultMode]\n return Object.values(values).at(0)\n}\n\nexport type NodeVariableResolver = (\n nodeId: string,\n variableId: string\n) => VariableLiteral | undefined\n\n/** One read/reconcile operation only: equal mode contexts share results, edits start a new cache. */\nexport function createBatchVariableResolver(graph: SceneGraph): NodeVariableResolver {\n const collections = [...graph.variableCollections.keys()]\n const contexts = new Map<string, Map<string, VariableLiteral>>()\n return (nodeId, variableId) => {\n const modes = collections.map((id) => getNodeVariableModeId(graph, nodeId, id))\n const key = JSON.stringify(modes)\n let memo = contexts.get(key)\n if (!memo) {\n memo = new Map()\n contexts.set(key, memo)\n }\n return resolveInModes(\n graph,\n variableId,\n (id) => modes[collections.indexOf(id)] ?? '',\n undefined,\n memo\n )\n }\n}\n\nexport function resolveColorVariable(graph: SceneGraph, variableId: string): Color | undefined {\n const value = resolveVariable(graph, variableId)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariable(graph: SceneGraph, variableId: string): number | undefined {\n const value = resolveVariable(graph, variableId)\n return typeof value === 'number' ? value : undefined\n}\n\nexport function resolveColorVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): Color | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId, fallback)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): number | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId, fallback)\n return typeof value === 'number' ? value : undefined\n}\n\n/** A variable's value in the mode a node is in, aliases followed. */\nexport function resolveVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): VariableLiteral | undefined {\n return resolveInModes(graph, variableId, (collectionId) =>\n getNodeVariableModeId(graph, nodeId, collectionId, fallback)\n )\n}\n\nexport function resolveStringVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): string | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId, fallback)\n return typeof value === 'string' ? value : undefined\n}\n"],"mappings":";;;AAMA,SAAgB,gBAAgB,OAAmB,cAA8B;CAC/E,MAAM,OAAO,MAAM,WAAW,IAAI,YAAY;CAC9C,IAAI,MAAM,OAAO;CAEjB,OADmB,MAAM,oBAAoB,IAAI,YACjC,CAAC,EAAE,iBAAiB;AACtC;AAQA,SAAgB,sBACd,OACA,QACA,cACA,WAAiC,UACzB;CACR,IAAI,OAAO,MAAM,MAAM,IAAI,MAAM;CACjC,OAAO,MAAM;EACX,MAAM,SAAS,KAAK,cAAc;EAClC,IAAI,QAAQ,OAAO;EACnB,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAC1D;CACA,IAAI,aAAa,WACf,OAAO,MAAM,oBAAoB,IAAI,YAAY,CAAC,EAAE,iBAAiB;CACvE,OAAO,gBAAgB,OAAO,YAAY;AAC5C;AAEA,SAAgB,gBACd,OACA,YACA,QACA,SAC6B;CAC7B,MAAM,UAAU,MAAM,UAAU,IAAI,UAAU;CAC9C,OAAO,eACL,OACA,aACC,iBACC,UAAU,SAAS,iBAAiB,eAChC,SACA,gBAAgB,O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;AAEjE;AAEA,SAAgB,6BACd,OACA,QACA,YACA,WAAiC,UACb;CACpB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,YAAY,QAAQ;CACxE,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;AAGA,SAAgB,uBACd,OACA,QACA,YACA,WAAiC,UACJ;CAC7B,OAAO,eAAe,OAAO,aAAa,iBACxC,sBAAsB,OAAO,QAAQ,cAAc,QAAQ,CAC7D;AACF;AAEA,SAAgB,6BACd,OACA,QACA,YACA,WAAiC,UACb;CACpB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,YAAY,QAAQ;CACxE,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C"}
1
+ {"version":3,"file":"resolution.js","names":[],"sources":["../../src/variables/resolution.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport type { Color } from '../primitives'\nimport type { SceneNode, Variable, VariableLiteral, VariableValue } from '../types'\nimport { MAX_FORMULA_DEPTH, VariableFormulaError } from './formula/tree'\nimport { resolveVariableValue, variableValueReferences } from './value'\n\n/**\n * The modes a node draws in for every collection: its ancestors' explicit modes from the outside\n * in, then its own. A copy that re-parents a node, such as an export of one layer, keeps this on\n * the node so it still resolves its variables as the canvas does.\n */\nexport function resolvedVariableModes(graph: SceneGraph, nodeId: string): Record<string, string> {\n const chain: SceneNode[] = []\n let node = graph.nodes.get(nodeId)\n while (node) {\n chain.push(node)\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n const modes: Record<string, string> = {}\n for (const ancestor of chain.reverse()) Object.assign(modes, ancestor.variableModes)\n return modes\n}\n\nexport function getActiveModeId(graph: SceneGraph, collectionId: string): string {\n const mode = graph.activeMode.get(collectionId)\n if (mode) return mode\n const collection = graph.variableCollections.get(collectionId)\n return collection?.defaultModeId ?? ''\n}\n\n/**\n * What a node without an explicit mode falls back to: the mode the editor shows (`active`), or\n * the collection's default (`default`), which is what a saved document means to other tools.\n */\nexport type VariableModeFallback = 'active' | 'default'\n\nexport function getNodeVariableModeId(\n graph: SceneGraph,\n nodeId: string,\n collectionId: string,\n fallback: VariableModeFallback = 'active'\n): string {\n const explicit = getNodeExplicitVariableModeId(graph, nodeId, collectionId)\n if (explicit !== null) return explicit\n if (fallback === 'default')\n return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''\n return getActiveModeId(graph, collectionId)\n}\n\n/** The nearest mode set on a node or an ancestor for a collection, or null where none is. */\nexport function getNodeExplicitVariableModeId(\n graph: SceneGraph,\n nodeId: string,\n collectionId: string\n): string | null {\n let node = graph.nodes.get(nodeId)\n while (node) {\n const modeId = node.variableModes[collectionId]\n if (modeId) return modeId\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n return null\n}\n\n/**\n * The collections whose modes decide what these variables resolve to: their own, and those of the\n * variables they alias, at any depth and in any mode.\n */\nexport function collectionsResolving(\n graph: SceneGraph,\n variableIds: Iterable<string>\n): Set<string> {\n const pending = [...variableIds]\n const seen = new Set<string>()\n const collections = new Set<string>()\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (seen.has(id)) continue\n seen.add(id)\n const variable = graph.variables.get(id)\n if (!variable) continue\n collections.add(variable.collectionId)\n for (const value of Object.values(variable.valuesByMode))\n pending.push(...variableValueReferences(value))\n }\n return collections\n}\n\nexport function resolveVariable(\n graph: SceneGraph,\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n): VariableLiteral | undefined {\n const initial = graph.variables.get(variableId)\n return resolveInModes(\n graph,\n variableId,\n (collectionId) =>\n modeId && initial?.collectionId === collectionId\n ? modeId\n : getActiveModeId(graph, collectionId),\n visited\n )\n}\n\nexport class VariableResolutionError extends VariableFormulaError {\n override name = 'VariableResolutionError'\n constructor(\n readonly code: 'cycle' | 'depth' | 'missing-variable' | 'missing-value' | 'type' | 'non-finite',\n readonly variableId: string,\n message: string\n ) {\n super(message)\n }\n}\n\nconst RESULT_TYPES = { FLOAT: 'number', BOOLEAN: 'boolean', STRING: 'string', COLOR: 'object' }\n\n/**\n * Resolve a draft or saved definition with identical mode, dependency and error semantics. A\n * memo shares values between lookups in one mode context; without one, nothing is cached.\n */\nexport function resolveVariableInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting = new Set<string>(),\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n if (visiting.has(variableId))\n throw new VariableResolutionError('cycle', variableId, 'Circular variable reference')\n if (visiting.size >= MAX_FORMULA_DEPTH)\n throw new VariableResolutionError('depth', variableId, 'Too many linked variables')\n const variable = graph.variables.get(variableId)\n if (!variable)\n throw new VariableResolutionError(\n 'missing-variable',\n variableId,\n `Missing variable: ${variableId}`\n )\n const value =\n overrides?.get(variableId) ??\n variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (value === undefined)\n throw new VariableResolutionError(\n 'missing-value',\n variableId,\n `Missing value: ${variable.name}`\n )\n return evaluateDefinition(graph, variable, value, modeFor, visiting, memo, overrides)\n}\n\n/** Resolve one variable's definition in its mode context, its dependencies in theirs. */\nfunction evaluateDefinition(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting: Set<string>,\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const variableId = variable.id\n visiting.add(variableId)\n try {\n const result = resolveVariableValue(value, (id) =>\n resolveVariableInModes(graph, id, modeFor, visiting, memo, overrides)\n )\n if (result === undefined || typeof result !== RESULT_TYPES[variable.type])\n throw new VariableResolutionError('type', variableId, `Wrong result type: ${variable.name}`)\n if (typeof result === 'number' && !Number.isFinite(result))\n throw new VariableResolutionError(\n 'non-finite',\n variableId,\n `Non-finite value: ${variable.name}`\n )\n // Failures can depend on the current path's depth. Only completed values are reusable.\n memo?.set(variableId, result)\n return result\n } finally {\n visiting.delete(variableId)\n }\n}\n\n/**\n * What the canvas draws for a variable, or nothing when it cannot be resolved. Literals and alias\n * chains, which most bindings are, resolve in a loop; an expression on the way takes the full\n * resolver, whose diagnostics the canvas does not need.\n */\nfunction resolveInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n const initial = graph.variables.get(variableId)\n if (!initial) return undefined\n let id = variableId\n for (let depth = visiting?.size ?? 0; depth < MAX_FORMULA_DEPTH; depth++) {\n const variable = id === variableId ? initial : graph.variables.get(id)\n if (!variable || visiting?.has(id)) return undefined\n const value = variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (typeof value === 'object' && 'aliasId' in value) {\n id = value.aliasId\n continue\n }\n const result =\n typeof value === 'object' && 'expression' in value\n ? resolveExpression(graph, variable, value, modeFor, visiting, memo)\n : value\n return drawable(result, initial.type)\n }\n return undefined\n}\n\n/** A formula shares its dependencies' values for the length of one resolution. */\nfunction resolveExpression(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n try {\n return evaluateDefinition(\n graph,\n variable,\n value,\n modeFor,\n visiting ?? new Set(),\n memo ?? new Map()\n )\n } catch {\n return undefined\n }\n}\n\n/** A resolved value the canvas can draw for a variable of this type, or nothing. */\nfunction drawable(value: VariableValue | undefined, type: Variable['type']) {\n if (value === undefined || typeof value !== RESULT_TYPES[type]) return undefined\n if (typeof value === 'object' && !('r' in value)) return undefined\n return typeof value === 'number' && !Number.isFinite(value) ? undefined : value\n}\n\n/** Shared mode fallback for canvas resolution and formula draft validation. */\nexport function variableValueInMode(\n graph: SceneGraph,\n variable: Variable,\n modeId: string\n): VariableValue | undefined {\n const values = variable.valuesByMode\n if (Object.hasOwn(values, modeId)) return values[modeId]\n const defaultMode = graph.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''\n if (Object.hasOwn(values, defaultMode)) return values[defaultMode]\n return Object.values(values).at(0)\n}\n\nexport type NodeVariableResolver = (\n nodeId: string,\n variableId: string\n) => VariableLiteral | undefined\n\n/** One read/reconcile operation only: equal mode contexts share results, edits start a new cache. */\nexport function createBatchVariableResolver(graph: SceneGraph): NodeVariableResolver {\n const collections = [...graph.variableCollections.keys()]\n const contexts = new Map<string, Map<string, VariableLiteral>>()\n return (nodeId, variableId) => {\n const modes = collections.map((id) => getNodeVariableModeId(graph, nodeId, id))\n const key = JSON.stringify(modes)\n let memo = contexts.get(key)\n if (!memo) {\n memo = new Map()\n contexts.set(key, memo)\n }\n return resolveInModes(\n graph,\n variableId,\n (id) => modes[collections.indexOf(id)] ?? '',\n undefined,\n memo\n )\n }\n}\n\nexport function resolveColorVariable(graph: SceneGraph, variableId: string): Color | undefined {\n const value = resolveVariable(graph, variableId)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariable(graph: SceneGraph, variableId: string): number | undefined {\n const value = resolveVariable(graph, variableId)\n return typeof value === 'number' ? value : undefined\n}\n\nexport function resolveColorVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): Color | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId, fallback)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): number | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId, fallback)\n return typeof value === 'number' ? value : undefined\n}\n\n/** A variable's value in the mode a node is in, aliases followed. */\nexport function resolveVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): VariableLiteral | undefined {\n return resolveInModes(graph, variableId, (collectionId) =>\n getNodeVariableModeId(graph, nodeId, collectionId, fallback)\n )\n}\n\nexport function resolveStringVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string,\n fallback: VariableModeFallback = 'active'\n): string | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId, fallback)\n return typeof value === 'string' ? value : undefined\n}\n"],"mappings":";;;;;;;;AAWA,SAAgB,sBAAsB,OAAmB,QAAwC;CAC/F,MAAM,QAAqB,CAAC;CAC5B,IAAI,OAAO,MAAM,MAAM,IAAI,MAAM;CACjC,OAAO,MAAM;EACX,MAAM,KAAK,IAAI;EACf,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAC1D;CACA,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,YAAY,MAAM,QAAQ,GAAG,OAAO,OAAO,OAAO,SAAS,aAAa;CACnF,OAAO;AACT;AAEA,SAAgB,gBAAgB,OAAmB,cAA8B;CAC/E,MAAM,OAAO,MAAM,WAAW,IAAI,YAAY;CAC9C,IAAI,MAAM,OAAO;CAEjB,OADmB,MAAM,oBAAoB,IAAI,YACjC,CAAC,EAAE,iBAAiB;AACtC;AAQA,SAAgB,sBACd,OACA,QACA,cACA,WAAiC,UACzB;CACR,MAAM,WAAW,8BAA8B,OAAO,QAAQ,YAAY;CAC1E,IAAI,aAAa,MAAM,OAAO;CAC9B,IAAI,aAAa,WACf,OAAO,MAAM,oBAAoB,IAAI,YAAY,CAAC,EAAE,iBAAiB;CACvE,OAAO,gBAAgB,OAAO,YAAY;AAC5C;;AAGA,SAAgB,8BACd,OACA,QACA,cACe;CACf,IAAI,OAAO,MAAM,MAAM,IAAI,MAAM;CACjC,OAAO,MAAM;EACX,MAAM,SAAS,KAAK,cAAc;EAClC,IAAI,QAAQ,OAAO;EACnB,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAC1D;CACA,OAAO;AACT;;;;;AAMA,SAAgB,qBACd,OACA,aACa;CACb,MAAM,UAAU,CAAC,GAAG,WAAW;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AAM;GACT,uBAAO,IAAI,IAAI;GACf,SAAS,IAAI,KAAK,IAAI;EACxB;EACA,OAAO,eACL,OACA,aACC,OAAO,MAAM,YAAY,QAAQ,EAAE,MAAM,IAC1C,KAAA,GACA,IACF;CACF;AACF;AAEA,SAAgB,qBAAqB,OAAmB,YAAuC;CAC7F,MAAM,QAAQ,gBAAgB,OAAO,UAAU;CAC/C,IAAI,SAAS,OAAO,UAAU,YAAY,OAAO,OAAO,OAAO;AAEjE;AAEA,SAAgB,sBAAsB,OAAmB,YAAwC;CAC/F,MAAM,QAAQ,gBAAgB,OAAO,UAAU;CAC/C,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAgB,4BACd,OACA,QACA,YACA,WAAiC,UACd;CACnB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,YAAY,QAAQ;CACxE,IAAI,SAAS,OAAO,UAAU,YAAY,OAAO,OAAO,OAAO;AAEjE;AAEA,SAAgB,6BACd,OACA,QACA,YACA,WAAiC,UACb;CACpB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,YAAY,QAAQ;CACxE,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;AAGA,SAAgB,uBACd,OACA,QACA,YACA,WAAiC,UACJ;CAC7B,OAAO,eAAe,OAAO,aAAa,iBACxC,sBAAsB,OAAO,QAAQ,cAAc,QAAQ,CAC7D;AACF;AAEA,SAAgB,6BACd,OACA,QACA,YACA,WAAiC,UACb;CACpB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,YAAY,QAAQ;CACxE,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C"}
@@ -0,0 +1,17 @@
1
+ //#region src/variables/subtree.ts
2
+ /** The layers in these subtrees, the roots included, that a binding change can reach. */
3
+ function subtreeNodes(graph, roots) {
4
+ const nodes = [];
5
+ const pending = [...roots];
6
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
7
+ const node = graph.getNode(id);
8
+ if (!node) continue;
9
+ nodes.push(node);
10
+ pending.push(...node.childIds);
11
+ }
12
+ return nodes;
13
+ }
14
+ //#endregion
15
+ export { subtreeNodes };
16
+
17
+ //# sourceMappingURL=subtree.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subtree.js","names":[],"sources":["../../src/variables/subtree.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport type { SceneNode } from '../types'\n\n/** The layers in these subtrees, the roots included, that a binding change can reach. */\nexport function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {\n const nodes: SceneNode[] = []\n const pending = [...roots]\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n const node = graph.getNode(id)\n if (!node) continue\n nodes.push(node)\n pending.push(...node.childIds)\n }\n return nodes\n}\n"],"mappings":";;AAIA,SAAgB,aAAa,OAAmB,OAAsC;CACpF,MAAM,QAAqB,CAAC;CAC5B,MAAM,UAAU,CAAC,GAAG,KAAK;CACzB,KAAK,IAAI,KAAK,QAAQ,IAAI,GAAG,OAAO,KAAA,GAAW,KAAK,QAAQ,IAAI,GAAG;EACjE,MAAM,OAAO,MAAM,QAAQ,EAAE;EAC7B,IAAI,CAAC,MAAM;EACX,MAAM,KAAK,IAAI;EACf,QAAQ,KAAK,GAAG,KAAK,QAAQ;CAC/B;CACA,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/scene-graph",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -300,6 +300,11 @@
300
300
  "import": "./dist/statuses/index.js",
301
301
  "default": "./dist/statuses/index.js"
302
302
  },
303
+ "./strokes": {
304
+ "types": "./dist/strokes.d.ts",
305
+ "import": "./dist/strokes.js",
306
+ "default": "./dist/strokes.js"
307
+ },
303
308
  "./text": {
304
309
  "types": "./dist/text/index.d.ts",
305
310
  "import": "./dist/text/index.js",
@@ -1,5 +1,5 @@
1
1
  import type { SceneGraph } from '../graph'
2
- import { findInstanceAncestor } from '../instances'
2
+ import { findInstanceAncestor, recordAssignmentOverride } from '../instances'
3
3
  import { instanceMainComponent } from '../instances/main-component'
4
4
  import { setInstanceOverride } from '../instances/overrides'
5
5
  import { walkInstanceSources } from '../instances/source-walk'
@@ -16,6 +16,15 @@ export interface ComponentPropertyTarget {
16
16
  source: SceneNode
17
17
  }
18
18
 
19
+ /**
20
+ * The component that defines a main component's properties: its set when it is a variant,
21
+ * since variants own no properties of their own (desktop 126), else the component itself.
22
+ */
23
+ export function propertyOwner(graph: SceneGraph, component: SceneNode): SceneNode {
24
+ const parent = component.parentId ? graph.getNode(component.parentId) : undefined
25
+ return component.type === 'COMPONENT' && parent?.type === 'COMPONENT_SET' ? parent : component
26
+ }
27
+
19
28
  export function componentPropertyOwners(graph: SceneGraph, instance: SceneNode): SceneNode[] {
20
29
  if (instance.type !== 'INSTANCE') return []
21
30
  const component = instanceMainComponent(graph, instance)
@@ -163,12 +172,18 @@ export function applyComponentPropertyValue(
163
172
  } else if (target) {
164
173
  applyInstanceSwapProperty(graph, instance, targets, target)
165
174
  }
175
+ const previous = instance.componentPropertyAssignments[definition.id]
176
+ const assigned = definition.type === 'INSTANCE_SWAP' && target ? target.id : value
166
177
  graph.updateNode(instance.id, {
167
178
  componentPropertyAssignments: {
168
179
  ...instance.componentPropertyAssignments,
169
- [definition.id]: definition.type === 'INSTANCE_SWAP' && target ? target.id : value
180
+ [definition.id]: assigned
170
181
  }
171
182
  })
183
+ // Assigning a nested instance's property is an edit of the instance above it, so it outranks
184
+ // a text override at that same level. Reapplying the value a property already has (a variant
185
+ // swap, a reload) is not an edit and records nothing.
186
+ if (previous !== assigned) recordAssignmentOverride(graph, instance.id, definition.id, value)
172
187
  return definition.type === 'INSTANCE_SWAP' ? target : instance
173
188
  }
174
189