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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +596 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +573 -521
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2021 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/fields/text.js +36 -0
  34. package/dist/chunks/fields/text.js.map +1 -0
  35. package/dist/chunks/group-bounds.js +104 -0
  36. package/dist/chunks/group-bounds.js.map +1 -0
  37. package/dist/chunks/icons/glyph.js +147 -0
  38. package/dist/chunks/icons/glyph.js.map +1 -0
  39. package/dist/chunks/index.js +1711 -661
  40. package/dist/chunks/index.js.map +1 -1
  41. package/dist/color.d.ts +72 -0
  42. package/dist/color.d.ts.map +1 -0
  43. package/dist/color.js +3 -0
  44. package/dist/constants.d.ts +2 -2
  45. package/dist/constants.js +2 -2
  46. package/dist/constants2.d.ts +3 -1
  47. package/dist/constants2.d.ts.map +1 -1
  48. package/dist/coordinate.d.ts +2 -448
  49. package/dist/coordinate.js +2 -2
  50. package/dist/copy.d.ts +1 -1
  51. package/dist/copy.js +1 -1
  52. package/dist/css.d.ts +39 -0
  53. package/dist/css.d.ts.map +1 -0
  54. package/dist/css.js +3 -0
  55. package/dist/geometry.d.ts +1 -1
  56. package/dist/geometry.js +1 -1
  57. package/dist/gradient.d.ts +51 -0
  58. package/dist/gradient.d.ts.map +1 -0
  59. package/dist/gradient.js +132 -0
  60. package/dist/gradient.js.map +1 -0
  61. package/dist/guides.d.ts +2 -2
  62. package/dist/guides.js +39 -0
  63. package/dist/guides.js.map +1 -0
  64. package/dist/hit-test.d.ts +2 -9
  65. package/dist/hit-test.js +154 -18
  66. package/dist/hit-test.js.map +1 -1
  67. package/dist/index.d.ts +4 -8
  68. package/dist/index.js +20 -5
  69. package/dist/instances.d.ts +2 -2
  70. package/dist/instances.js +2 -2
  71. package/dist/layout.d.ts +2 -0
  72. package/dist/layout.js +4 -0
  73. package/dist/node-defaults.d.ts +2 -8
  74. package/dist/node-defaults.js +2 -2
  75. package/dist/order-keys.d.ts +39 -0
  76. package/dist/order-keys.d.ts.map +1 -0
  77. package/dist/order-keys.js +136 -0
  78. package/dist/order-keys.js.map +1 -0
  79. package/dist/parse-path.d.ts +7 -1
  80. package/dist/parse-path.d.ts.map +1 -1
  81. package/dist/parse-path.js +6 -2
  82. package/dist/parse-path.js.map +1 -1
  83. package/dist/polygon.d.ts +53 -0
  84. package/dist/polygon.d.ts.map +1 -0
  85. package/dist/polygon.js +205 -0
  86. package/dist/polygon.js.map +1 -0
  87. package/dist/preview.d.ts +1 -1
  88. package/dist/random.d.ts +7 -0
  89. package/dist/random.d.ts.map +1 -0
  90. package/dist/random.js +2 -0
  91. package/dist/resize.d.ts +11 -2
  92. package/dist/resize.d.ts.map +1 -1
  93. package/dist/resize.js +2 -184
  94. package/dist/snap.d.ts +1 -1
  95. package/dist/text-direction.d.ts +13 -0
  96. package/dist/text-direction.d.ts.map +1 -0
  97. package/dist/text-direction.js +31 -0
  98. package/dist/text-direction.js.map +1 -0
  99. package/dist/text-picture.d.ts +1 -1
  100. package/dist/text-picture.d.ts.map +1 -1
  101. package/dist/text.d.ts +2 -0
  102. package/dist/text.js +3 -0
  103. package/dist/types.d.ts +2063 -13
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -1
  106. package/dist/types2.d.ts +2 -2
  107. package/dist/undo.d.ts +2 -2
  108. package/dist/undo.js +2 -2
  109. package/dist/undo2.d.ts +29 -1
  110. package/dist/undo2.d.ts.map +1 -1
  111. package/dist/variables.d.ts +2 -29
  112. package/dist/variables.js +2 -2
  113. package/dist/variant-properties.d.ts +9 -1
  114. package/dist/variant-properties.d.ts.map +1 -1
  115. package/dist/variant-properties.js +36 -1
  116. package/dist/variant-properties.js.map +1 -1
  117. package/dist/vector-network.d.ts +1 -1
  118. package/dist/vector-network.js +1 -1
  119. package/package.json +60 -9
  120. package/src/behaviours/kinds.ts +185 -0
  121. package/src/behaviours/layers.ts +51 -0
  122. package/src/behaviours/model.ts +192 -0
  123. package/src/behaviours/schema.ts +58 -0
  124. package/src/behaviours/spec.ts +223 -0
  125. package/src/buffered-events.ts +64 -0
  126. package/src/color/contrast.ts +31 -0
  127. package/src/color/index.ts +88 -0
  128. package/src/color/management.ts +210 -0
  129. package/src/color/normalize.ts +7 -0
  130. package/src/color/okhcl.ts +201 -0
  131. package/src/comments/document.ts +51 -0
  132. package/src/comments/list.ts +52 -0
  133. package/src/comments/merge.ts +63 -0
  134. package/src/comments/threads.ts +156 -0
  135. package/src/components/exposure.ts +61 -0
  136. package/src/components/properties.ts +18 -15
  137. package/src/components/variants.ts +53 -0
  138. package/src/constants.ts +2 -0
  139. package/src/coordinate.ts +100 -43
  140. package/src/copy.ts +13 -5
  141. package/src/css/grid.ts +70 -0
  142. package/src/css/index.ts +9 -0
  143. package/src/css/layout.ts +53 -0
  144. package/src/css/shadows.ts +68 -0
  145. package/src/css/values.ts +42 -0
  146. package/src/export-format.ts +12 -0
  147. package/src/fields/geometry.ts +11 -0
  148. package/src/fields/text.ts +35 -0
  149. package/src/gradient.ts +166 -0
  150. package/src/group-bounds.ts +131 -0
  151. package/src/guides.ts +39 -0
  152. package/src/hit-test.ts +219 -25
  153. package/src/icons/glyph.ts +128 -0
  154. package/src/icons/model.ts +54 -0
  155. package/src/icons/schema.ts +18 -0
  156. package/src/index.ts +343 -55
  157. package/src/instance-overrides.ts +27 -0
  158. package/src/instances/copies.ts +239 -0
  159. package/src/instances/cycles.ts +73 -0
  160. package/src/instances/fields.ts +143 -0
  161. package/src/instances/main-component.ts +19 -0
  162. package/src/instances/placement.ts +29 -0
  163. package/src/instances/source-walk.ts +41 -0
  164. package/src/instances/sync.ts +599 -0
  165. package/src/instances.ts +122 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +1 -1
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/slots/authoring.ts +101 -0
  187. package/src/slots/content.ts +124 -0
  188. package/src/slots/frames.ts +160 -0
  189. package/src/slots/limits.ts +49 -0
  190. package/src/text/direction.ts +55 -0
  191. package/src/text/index.ts +2 -0
  192. package/src/text/lists.ts +138 -0
  193. package/src/text/paragraphs.ts +241 -0
  194. package/src/{text-picture.ts → text/picture.ts} +21 -29
  195. package/src/transfer/apply.ts +84 -0
  196. package/src/transfer/history.ts +49 -0
  197. package/src/transfer/identity.ts +16 -0
  198. package/src/transfer/index.ts +6 -0
  199. package/src/transfer/nodes.ts +108 -0
  200. package/src/transfer/plan.ts +107 -0
  201. package/src/transfer/references.ts +9 -0
  202. package/src/transfer/remove.ts +39 -0
  203. package/src/transfer/validation.ts +54 -0
  204. package/src/transfer/variables.ts +82 -0
  205. package/src/types.ts +221 -11
  206. package/src/undo.ts +54 -2
  207. package/src/variables/bindings.ts +186 -0
  208. package/src/variables/fields.ts +43 -0
  209. package/src/variables/token.ts +14 -0
  210. package/src/variables/units.ts +15 -0
  211. package/src/variables.ts +118 -69
  212. package/src/variant-properties.ts +50 -0
  213. package/dist/chunks/components/properties.js.map +0 -1
  214. package/dist/chunks/export-scale.js +0 -19
  215. package/dist/chunks/export-scale.js.map +0 -1
  216. package/dist/coordinate.d.ts.map +0 -1
  217. package/dist/coordinate2.d.ts +0 -2
  218. package/dist/guides2.d.ts +0 -11
  219. package/dist/guides2.d.ts.map +0 -1
  220. package/dist/hit-test.d.ts.map +0 -1
  221. package/dist/layout-guides.d.ts +0 -2
  222. package/dist/layout-guides.js +0 -2
  223. package/dist/layout-guides2.d.ts +0 -16
  224. package/dist/layout-guides2.d.ts.map +0 -1
  225. package/dist/node-defaults.d.ts.map +0 -1
  226. package/dist/preview2.d.ts +0 -12
  227. package/dist/preview2.d.ts.map +0 -1
  228. package/dist/resize.js.map +0 -1
  229. package/dist/variables.d.ts.map +0 -1
  230. package/dist/vector-network2.d.ts +0 -32
  231. package/dist/vector-network2.d.ts.map +0 -1
  232. package/src/instance-overrides.test.ts +0 -67
@@ -1,9 +1,18 @@
1
- import { BLACK, CONTAINER_TYPES, cloneNodeProps, createDefaultNode, createInstance, detachInstance, getInstances, getMainComponent, normalizeVectorNetwork, populateInstanceChildren, rotatedBBox, setInstanceOverride, swapInstanceComponent, syncInstances } from "./components/properties.js";
2
- import { getAbsolutePosition } from "./coordinate.js";
1
+ import { CONTAINER_TYPES, cloneNodeProps, copyFills, copyStrokes, createDefaultNode, getInstanceOverride, normalizeVectorNetwork, remapInstanceOverrideState, rotatedBBox, setInstanceOverride } from "./color/index.js";
2
+ import { BLACK, TRANSPARENT } from "./color/contrast.js";
3
+ import { BOOLEAN_BINDING_FIELDS, NUMERIC_FIELDS, STRING_BINDING_FIELDS, cloneChildrenWithMapping, createInstance, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, isNumericVariableBindingField, ownsSlotContent, paragraphStyleAt, populateInstanceChildren, scaleNodeChanges, scaleVariableBindingUnits, slotPropertyId, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, textParagraphRanges } from "./components/exposure.js";
4
+ import { OPEN_PENCIL_PLUGIN_DATA, readAllPluginData, withAllPluginData } from "./behaviours/layers.js";
5
+ import { SIZE_FIELDS, TRANSFORM_FIELDS } from "./fields/geometry.js";
6
+ import { TEXT_LAYOUT_FIELDS, TEXT_SHAPING_FIELDS } from "./fields/text.js";
7
+ import { computeImageHash } from "../images.js";
8
+ import { randomHex, randomIndex } from "./comments/list.js";
9
+ import { Matrix, getAbsolutePosition, getNodeLocalMatrix, getParentWorldMatrix, isTranslationOnly, localTransformFromWorld } from "./coordinate.js";
3
10
  import { removeStaleBindings } from "./bindings.js";
11
+ import { BufferedSceneEmitter } from "./buffered-events.js";
4
12
  import { bindNodeEvents } from "./events.js";
5
- import { hitTest, hitTestDeep, hitTestFrame } from "../hit-test.js";
6
- import { createNanoEvents } from "nanoevents";
13
+ import { hitTest, hitTestDeep, hitTestDropTarget, hitTestOpenContainer, hitTestSelectable, isOpenContainer, isPointInNode } from "../hit-test.js";
14
+ import { partition, uniq } from "es-toolkit/array";
15
+ import { isEqual } from "es-toolkit/predicate";
7
16
  import { omit, omitBy } from "es-toolkit/object";
8
17
  //#region src/mutation-impact.ts
9
18
  function createSceneMutationImpact() {
@@ -15,32 +24,42 @@ function createSceneMutationImpact() {
15
24
  deletedNodeIds: /* @__PURE__ */ new Set()
16
25
  };
17
26
  }
18
- /** Collects the actual graph nodes and parent containers touched by an operation. */
19
- async function collectSceneMutation(graph, operation) {
20
- const impact = createSceneMutationImpact();
21
- const unbind = graph.onNodeEvents({
27
+ /** Records into `impact` the nodes and parent containers the graph's edits touch, until unbound. */
28
+ function recordSceneMutations(graph, impact, shouldRecord = () => true) {
29
+ return graph.onNodeEvents({
22
30
  created: (node) => {
31
+ if (!shouldRecord()) return;
23
32
  impact.createdNodeIds.add(node.id);
24
33
  impact.changedNodeIds.add(node.id);
25
34
  if (node.parentId) impact.currentParentIds.add(node.parentId);
26
35
  },
27
- updated: (id) => impact.changedNodeIds.add(id),
36
+ updated: (id) => {
37
+ if (shouldRecord()) impact.changedNodeIds.add(id);
38
+ },
28
39
  deleted: (id, parentId) => {
40
+ if (!shouldRecord()) return;
29
41
  if (parentId) impact.previousParentIds.add(parentId);
30
42
  impact.deletedNodeIds.add(id);
31
43
  impact.changedNodeIds.add(id);
32
44
  },
33
45
  reparented: (nodeId, oldParentId, newParentId) => {
46
+ if (!shouldRecord()) return;
34
47
  impact.changedNodeIds.add(nodeId);
35
48
  if (oldParentId) impact.previousParentIds.add(oldParentId);
36
49
  impact.currentParentIds.add(newParentId);
37
50
  },
38
51
  reordered: (nodeId, parentId, _index, previousParentId) => {
52
+ if (!shouldRecord()) return;
39
53
  impact.changedNodeIds.add(nodeId);
40
54
  if (previousParentId && previousParentId !== parentId) impact.previousParentIds.add(previousParentId);
41
55
  impact.currentParentIds.add(parentId);
42
56
  }
43
57
  });
58
+ }
59
+ /** Collects the actual graph nodes and parent containers touched by an operation. */
60
+ async function collectSceneMutation(graph, operation) {
61
+ const impact = createSceneMutationImpact();
62
+ const unbind = recordSceneMutations(graph, impact);
44
63
  try {
45
64
  return {
46
65
  result: await operation(),
@@ -51,523 +70,178 @@ async function collectSceneMutation(graph, operation) {
51
70
  }
52
71
  }
53
72
  function mutationLayoutScopeIds(impact) {
54
- return [.../* @__PURE__ */ new Set([
73
+ return uniq([
55
74
  ...impact.changedNodeIds,
56
75
  ...impact.previousParentIds,
57
76
  ...impact.currentParentIds
58
- ])];
77
+ ]);
59
78
  }
60
79
  //#endregion
61
- //#region src/snap.ts
62
- const DEFAULT_SNAP_THRESHOLD = 5;
63
- function getEdges(node) {
64
- return rotatedBBox(node.x, node.y, node.width, node.height, node.rotation);
65
- }
66
- function computeSnap(movingIds, movingBounds, allNodes, threshold = DEFAULT_SNAP_THRESHOLD) {
67
- const targets = allNodes.filter((n) => !movingIds.has(n.id));
68
- if (targets.length === 0) return {
69
- dx: 0,
70
- dy: 0,
71
- guides: []
72
- };
73
- const m = {
74
- left: movingBounds.x,
75
- right: movingBounds.x + movingBounds.width,
76
- centerX: movingBounds.x + movingBounds.width / 2,
77
- top: movingBounds.y,
78
- bottom: movingBounds.y + movingBounds.height,
79
- centerY: movingBounds.y + movingBounds.height / 2
80
- };
81
- let bestDx = Infinity;
82
- let bestDy = Infinity;
83
- const guides = [];
84
- for (const target of targets) {
85
- const t = getEdges(target);
86
- const xPairs = [
87
- [m.left, t.left],
88
- [m.left, t.right],
89
- [m.right, t.left],
90
- [m.right, t.right],
91
- [m.centerX, t.centerX]
92
- ];
93
- for (const [mVal, tVal] of xPairs) {
94
- const d = tVal - mVal;
95
- if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDx)) {
96
- if (Math.abs(d) < Math.abs(bestDx)) {
97
- bestDx = d;
98
- guides.length = guides.filter((g) => g.axis === "y").length ? guides.length : guides.length;
99
- for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "x") guides.splice(i, 1);
100
- }
101
- if (Math.abs(d) === Math.abs(bestDx)) {
102
- const minY = Math.min(m.top, t.top);
103
- const maxY = Math.max(m.bottom, t.bottom);
104
- guides.push({
105
- axis: "x",
106
- position: tVal,
107
- from: minY,
108
- to: maxY
109
- });
110
- }
111
- }
112
- }
113
- const yPairs = [
114
- [m.top, t.top],
115
- [m.top, t.bottom],
116
- [m.bottom, t.top],
117
- [m.bottom, t.bottom],
118
- [m.centerY, t.centerY]
119
- ];
120
- for (const [mVal, tVal] of yPairs) {
121
- const d = tVal - mVal;
122
- if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDy)) {
123
- if (Math.abs(d) < Math.abs(bestDy)) {
124
- for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "y") guides.splice(i, 1);
125
- bestDy = d;
126
- }
127
- if (Math.abs(d) === Math.abs(bestDy)) {
128
- const minX = Math.min(m.left, t.left);
129
- const maxX = Math.max(m.right, t.right);
130
- guides.push({
131
- axis: "y",
132
- position: tVal,
133
- from: minX,
134
- to: maxX
135
- });
136
- }
137
- }
138
- }
80
+ //#region src/variables/bindings.ts
81
+ /** New declarations belong to the outermost occurrence, bounded by a component definition. */
82
+ function variableBindingOwner(graph, node) {
83
+ let owner = node;
84
+ let current = node;
85
+ while (current) {
86
+ if (current.type === "COMPONENT" || current.type === "COMPONENT_SET") break;
87
+ if (current.type === "INSTANCE") owner = current;
88
+ current = current.parentId ? graph.getNode(current.parentId) : void 0;
139
89
  }
140
- return {
141
- dx: Math.abs(bestDx) <= threshold ? bestDx : 0,
142
- dy: Math.abs(bestDy) <= threshold ? bestDy : 0,
143
- guides
90
+ return owner;
91
+ }
92
+ function assignVariableBindingUnits(graph, node, field) {
93
+ if (!isNumericVariableBindingField(field)) return;
94
+ const owner = variableBindingOwner(graph, node);
95
+ node.variableBindingScales = {
96
+ ...node.variableBindingScales,
97
+ [field]: owner.variableAssignmentScales[field] ?? 1
144
98
  };
145
99
  }
146
- function computeSelectionBounds(nodes) {
147
- if (nodes.length === 0) return null;
148
- let minX = Infinity;
149
- let minY = Infinity;
150
- let maxX = -Infinity;
151
- let maxY = -Infinity;
152
- for (const n of nodes) {
153
- const edges = getEdges(n);
154
- minX = Math.min(minX, edges.left);
155
- minY = Math.min(minY, edges.top);
156
- maxX = Math.max(maxX, edges.right);
157
- maxY = Math.max(maxY, edges.bottom);
158
- }
159
- return {
160
- x: minX,
161
- y: minY,
162
- width: maxX - minX,
163
- height: maxY - minY
100
+ /**
101
+ * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields
102
+ * whose stored value differs. A width or height an instance overrides keeps its own value.
103
+ */
104
+ function resolvedNumericBindings(graph, node, fallback = "active") {
105
+ const updates = {};
106
+ for (const [field, variableId] of Object.entries(node.boundVariables)) {
107
+ if (!NUMERIC_FIELDS.has(field)) continue;
108
+ if ((field === "width" || field === "height") && hasInstanceOverride(graph, node.id, field)) continue;
109
+ const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
110
+ if (value === void 0 || !Number.isFinite(value)) continue;
111
+ const effective = value * (node.variableBindingScales[field] ?? 1);
112
+ if (!Number.isFinite(effective)) continue;
113
+ const next = field === "opacity" ? Math.max(0, Math.min(1, effective)) : effective;
114
+ if (node[field] !== next) Object.assign(updates, { [field]: next });
115
+ }
116
+ return updates;
117
+ }
118
+ /**
119
+ * The text and visibility a node's string and boolean bindings resolve to in its mode, for the
120
+ * fields whose stored value differs. Text or visibility an instance overrides, which typing in a
121
+ * layer or toggling its eye records, keeps its own value, as an overridden width or height does.
122
+ * A bound font family is left as stored: changing it needs the font loaded, which resolving a
123
+ * binding cannot do.
124
+ */
125
+ function resolvedValueBindings(graph, node, fallback = "active") {
126
+ const updates = {};
127
+ const resolve = (field) => {
128
+ const variableId = node.boundVariables[field];
129
+ if (!variableId || hasInstanceOverride(graph, node.id, field)) return void 0;
130
+ return graph.resolveVariableForNode(node.id, variableId, fallback);
164
131
  };
132
+ const text = node.type === "TEXT" ? resolve("text") : void 0;
133
+ if (typeof text === "string" && text !== node.text) updates.text = text;
134
+ const visible = resolve("visible");
135
+ if (typeof visible === "boolean" && visible !== node.visible) updates.visible = visible;
136
+ return updates;
165
137
  }
166
- //#endregion
167
- //#region src/layout-guides.ts
168
- const MAX_LAYOUT_GUIDE_LINES = 1e4;
169
- function normalizedCount(grid) {
170
- const value = grid.count ?? grid.numSections ?? 1;
171
- if (!Number.isFinite(value)) return 0;
172
- return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)));
138
+ /**
139
+ * A bound paint takes its whole color from the variable, alpha included, the way Figma stores
140
+ * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
141
+ */
142
+ function applyBoundColor(paint, color) {
143
+ paint.color = {
144
+ ...color,
145
+ a: 1
146
+ };
147
+ paint.opacity = color.a;
173
148
  }
174
- function pattern(grid) {
175
- if (grid.pattern === "GRID" || grid.pattern === "ROWS") return grid.pattern;
176
- if (grid.axis === "Y") return "ROWS";
177
- return "COLUMNS";
149
+ /** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */
150
+ function resolvedPaintBindings(graph, node, fallback = "active") {
151
+ const changes = {};
152
+ for (const field in node.boundVariables) {
153
+ if (!field.endsWith("/color")) continue;
154
+ const match = /^(fills|strokes)\/(\d+)\/color$/.exec(field);
155
+ if (!match) continue;
156
+ const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback);
157
+ const index = Number(match[2]);
158
+ if (!color) continue;
159
+ if (match[1] === "fills") {
160
+ if (!node.fills[index]) continue;
161
+ changes.fills ??= copyFills(node.fills);
162
+ applyBoundColor(changes.fills[index], color);
163
+ } else {
164
+ if (!node.strokes[index]) continue;
165
+ changes.strokes ??= copyStrokes(node.strokes);
166
+ applyBoundColor(changes.strokes[index], color);
167
+ }
168
+ }
169
+ return changes;
178
170
  }
179
- function alignment(grid) {
180
- const value = grid.alignment ?? grid.type;
181
- if (value === "CENTER" || value === "MAX" || value === "STRETCH") return value;
182
- return "MIN";
171
+ /** These variables and every variable that aliases one of them, at any depth and in any mode. */
172
+ function variablesResolvingThrough(graph, ids) {
173
+ const found = new Set(ids);
174
+ let grew = true;
175
+ while (grew) {
176
+ grew = false;
177
+ for (const variable of graph.variables.values()) {
178
+ if (found.has(variable.id)) continue;
179
+ if (Object.values(variable.valuesByMode).some((value) => typeof value === "object" && "aliasId" in value && found.has(value.aliasId))) {
180
+ found.add(variable.id);
181
+ grew = true;
182
+ }
183
+ }
184
+ }
185
+ return found;
183
186
  }
184
- function sectionSize(nodeSize, grid) {
185
- const fixed = grid.sectionSize ?? 0;
186
- if (alignment(grid) !== "STRETCH") return fixed;
187
- const count = normalizedCount(grid);
188
- const gutter = grid.gutterSize ?? 0;
189
- return (nodeSize - (grid.offset ?? 0) * 2 - Math.max(0, count - 1) * gutter) / count;
187
+ function subtreeNodes(graph, roots) {
188
+ const nodes = [];
189
+ const pending = [...roots];
190
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
191
+ const node = graph.getNode(id);
192
+ if (!node) continue;
193
+ nodes.push(node);
194
+ pending.push(...node.childIds);
195
+ }
196
+ return nodes;
190
197
  }
191
- function start(nodeSize, grid, size) {
192
- const count = normalizedCount(grid);
193
- const gutter = grid.gutterSize ?? 0;
194
- const offset = grid.offset ?? 0;
195
- const span = count * size + Math.max(0, count - 1) * gutter;
196
- if (alignment(grid) === "CENTER") return (nodeSize - span) / 2 + offset;
197
- if (alignment(grid) === "MAX") return nodeSize - span - offset;
198
- return offset;
198
+ function scopedNodes(graph, scope) {
199
+ if (!scope) return graph.getAllNodes();
200
+ if ("subtrees" in scope) return subtreeNodes(graph, scope.subtrees);
201
+ const variables = variablesResolvingThrough(graph, scope.variables);
202
+ return [...graph.getAllNodes()].filter((node) => Object.values(node.boundVariables).some((id) => variables.has(id)));
199
203
  }
200
- function layoutGuideSections(node, grid) {
201
- if (grid.visible === false || pattern(grid) === "GRID") return [];
202
- const axis = pattern(grid) === "ROWS" ? "y" : "x";
203
- const nodeSize = axis === "x" ? node.width : node.height;
204
- const size = sectionSize(nodeSize, grid);
205
- const count = normalizedCount(grid);
206
- if (count <= 0 || size <= 0) return [];
207
- const first = start(nodeSize, grid, size);
208
- const step = size + (grid.gutterSize ?? 0);
209
- return Array.from({ length: count }, (_, index) => {
210
- const sectionStart = first + index * step;
211
- return {
212
- axis,
213
- start: sectionStart,
214
- end: sectionStart + size
204
+ /**
205
+ * Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
206
+ * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved
207
+ * values differ from their bindings elsewhere in the document are left as saved.
208
+ */
209
+ function reconcileVariableBindings(graph, scope) {
210
+ const changed = [];
211
+ for (const node of scopedNodes(graph, scope)) {
212
+ const updates = {
213
+ ...resolvedNumericBindings(graph, node),
214
+ ...resolvedValueBindings(graph, node)
215
215
  };
216
- });
217
- }
218
- function layoutGuideLines(node, grid) {
219
- if (grid.visible === false) return [];
220
- const gridPattern = pattern(grid);
221
- const lines = [];
222
- if (gridPattern === "GRID") {
223
- const size = grid.sectionSize ?? 0;
224
- if (size <= 0) return lines;
225
- for (let index = 0, x = grid.offset ?? 0; x <= node.width && index < MAX_LAYOUT_GUIDE_LINES; index++, x += size) lines.push({
226
- axis: "x",
227
- position: x
228
- });
229
- for (let index = 0, y = grid.offset ?? 0; y <= node.height && index < MAX_LAYOUT_GUIDE_LINES; index++, y += size) lines.push({
230
- axis: "y",
231
- position: y
232
- });
233
- return lines;
216
+ if (Object.keys(updates).length === 0) continue;
217
+ graph.updateNode(node.id, updates);
218
+ changed.push(node.id);
234
219
  }
235
- const sections = layoutGuideSections(node, grid);
236
- for (const section of sections) lines.push({
237
- axis: section.axis,
238
- position: section.start
239
- }, {
240
- axis: section.axis,
241
- position: section.end
242
- });
243
- return lines;
220
+ return changed;
244
221
  }
245
222
  //#endregion
246
- //#region src/shared-styles.ts
247
- const STYLE_REF_KEYS = {
248
- fill: "fillStyleId",
249
- stroke: "strokeStyleId",
250
- text: "textStyleId",
251
- effect: "effectStyleId",
252
- grid: "gridStyleId"
253
- };
254
- const STYLE_TYPES = {
255
- fill: "FILL",
256
- stroke: "FILL",
257
- text: "TEXT",
258
- effect: "EFFECT",
259
- grid: "GRID"
260
- };
261
- const TEXT_STYLE_KEYS = /* @__PURE__ */ new Set([
262
- "fontFamily",
263
- "fontWeight",
264
- "italic",
265
- "fontSize",
266
- "lineHeight",
267
- "letterSpacing",
268
- "textDecoration",
269
- "textCase",
270
- "fontFeatures"
271
- ]);
272
- function sharedStyleRefKey(kind) {
273
- return STYLE_REF_KEYS[kind];
274
- }
275
- function sharedStyleTypeForKind(kind) {
276
- return STYLE_TYPES[kind];
223
+ //#region src/variables.ts
224
+ function addVariable(graph, variable) {
225
+ graph.variables.set(variable.id, variable);
226
+ const collection = graph.variableCollections.get(variable.collectionId);
227
+ if (collection && !collection.variableIds.includes(variable.id)) collection.variableIds.push(variable.id);
277
228
  }
278
- function getSharedStyles(graph, kind) {
279
- const type = sharedStyleTypeForKind(kind);
280
- const styles = [];
281
- for (const node of graph.getAllNodes()) {
282
- if (node.sharedStyleType !== type || !node.source.id) continue;
283
- styles.push({
284
- id: node.source.id,
285
- nodeId: node.id,
286
- name: node.name,
287
- type
229
+ function removeVariable(graph, id) {
230
+ const variable = graph.variables.get(id);
231
+ if (!variable) return;
232
+ graph.variables.delete(id);
233
+ const collection = graph.variableCollections.get(variable.collectionId);
234
+ if (collection) collection.variableIds = collection.variableIds.filter((vid) => vid !== id);
235
+ for (const node of graph.nodes.values()) {
236
+ if (!Object.values(node.boundVariables).includes(id)) continue;
237
+ graph.willChangeNode(node);
238
+ node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id);
239
+ node.variableBindingScales = omitBy(node.variableBindingScales, (_, field) => !(field in node.boundVariables));
240
+ graph.emitter.emit("node:updated", node.id, {
241
+ boundVariables: { ...node.boundVariables },
242
+ variableBindingScales: { ...node.variableBindingScales }
288
243
  });
289
- }
290
- return styles.sort((left, right) => left.name.localeCompare(right.name));
291
- }
292
- function styleDetachmentChanges(node, changes) {
293
- const next = { ...changes };
294
- if ("fills" in changes && !("fillStyleId" in changes) && node.fillStyleId) next.fillStyleId = null;
295
- if ("strokes" in changes && !("strokeStyleId" in changes) && node.strokeStyleId) next.strokeStyleId = null;
296
- if ("effects" in changes && !("effectStyleId" in changes) && node.effectStyleId) next.effectStyleId = null;
297
- if ("layoutGrids" in changes && !("gridStyleId" in changes) && node.gridStyleId) next.gridStyleId = null;
298
- if (Object.keys(changes).some((key) => TEXT_STYLE_KEYS.has(key)) && !("textStyleId" in changes) && node.textStyleId) next.textStyleId = null;
299
- return next;
300
- }
301
- //#endregion
302
- //#region src/undo.ts
303
- const DEFAULT_HISTORY_LIMIT = 200;
304
- var UndoManager = class {
305
- undoStack = [];
306
- redoStack = [];
307
- batches = [];
308
- limit;
309
- onChange;
310
- constructor(options = {}) {
311
- this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT;
312
- this.onChange = options.onChange;
313
- }
314
- apply(entry) {
315
- this.execute(entry);
316
- }
317
- execute(entry) {
318
- entry.forward();
319
- this.record(entry);
320
- }
321
- push(entry) {
322
- this.record(entry);
323
- }
324
- record(entry) {
325
- const batch = this.currentBatch;
326
- if (batch) {
327
- batch.entries.push(entry);
328
- return;
329
- }
330
- this.pushUndoEntry(entry);
331
- }
332
- undo() {
333
- const entry = this.undoStack.pop();
334
- if (!entry) return null;
335
- entry.inverse();
336
- this.redoStack.push(entry);
337
- this.onChange?.();
338
- return entry.label;
339
- }
340
- redo() {
341
- const entry = this.redoStack.pop();
342
- if (!entry) return null;
343
- entry.forward();
344
- this.undoStack.push(entry);
345
- this.onChange?.();
346
- return entry.label;
347
- }
348
- beginBatch(label, coalesceKey) {
349
- this.batches.push({
350
- label,
351
- entries: [],
352
- coalesceKey
353
- });
354
- }
355
- commitBatch() {
356
- const batch = this.batches.pop();
357
- if (!batch || batch.entries.length === 0) return;
358
- const entry = this.createBatchEntry(batch);
359
- const parentBatch = this.currentBatch;
360
- if (parentBatch) parentBatch.entries.push(entry);
361
- else this.pushUndoEntry(entry);
362
- }
363
- runBatch(label, fn, coalesceKey) {
364
- this.beginBatch(label, coalesceKey);
365
- try {
366
- const result = fn();
367
- this.commitBatch();
368
- return result;
369
- } catch (error) {
370
- this.rollbackBatch();
371
- throw error;
372
- }
373
- }
374
- rollbackBatch() {
375
- const batch = this.batches.pop();
376
- if (!batch) return;
377
- for (const entry of batch.entries.toReversed()) entry.inverse();
378
- }
379
- /** Abandon provisional history without replaying it or changing committed undo/redo entries. */
380
- discardBatches() {
381
- this.batches = [];
382
- }
383
- clear() {
384
- this.undoStack = [];
385
- this.redoStack = [];
386
- this.discardBatches();
387
- this.onChange?.();
388
- }
389
- get isBatching() {
390
- return this.batches.length > 0;
391
- }
392
- get canUndo() {
393
- return this.undoStack.length > 0;
394
- }
395
- get canRedo() {
396
- return this.redoStack.length > 0;
397
- }
398
- get undoLabel() {
399
- return this.undoStack.at(-1)?.label ?? null;
400
- }
401
- get redoLabel() {
402
- return this.redoStack.at(-1)?.label ?? null;
403
- }
404
- get currentBatch() {
405
- return this.batches.at(-1) ?? null;
406
- }
407
- createBatchEntry(batch) {
408
- return {
409
- label: batch.label,
410
- forward: () => batch.entries.forEach((entry) => entry.forward()),
411
- inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()),
412
- coalesceKey: batch.coalesceKey
413
- };
414
- }
415
- pushUndoEntry(entry) {
416
- const previous = this.undoStack.at(-1);
417
- if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) this.undoStack[this.undoStack.length - 1] = {
418
- ...entry,
419
- inverse: previous.inverse
420
- };
421
- else this.undoStack.push(entry);
422
- this.redoStack = [];
423
- this.trimUndoStack();
424
- this.onChange?.();
425
- }
426
- trimUndoStack() {
427
- if (!Number.isFinite(this.limit) || this.limit <= 0) return;
428
- const overflow = this.undoStack.length - this.limit;
429
- if (overflow > 0) this.undoStack.splice(0, overflow);
430
- }
431
- };
432
- //#endregion
433
- //#region src/text-picture.ts
434
- /**
435
- * Invalidate cached Skia textPicture (Paragraph snapshot). Includes width/height
436
- * because wrapping/layout depends on the box.
437
- */
438
- const TEXT_PICTURE_KEYS = /* @__PURE__ */ new Set([
439
- "text",
440
- "fontSize",
441
- "fontFamily",
442
- "fontWeight",
443
- "italic",
444
- "textAlignHorizontal",
445
- "textDirection",
446
- "textAlignVertical",
447
- "lineHeight",
448
- "letterSpacing",
449
- "textDecoration",
450
- "textCase",
451
- "styleRuns",
452
- "fills",
453
- "width",
454
- "height"
455
- ]);
456
- const GLYPH_AFFECTING_KEYS = /* @__PURE__ */ new Set([
457
- "text",
458
- "fontSize",
459
- "fontFamily",
460
- "fontWeight",
461
- "italic",
462
- "textDirection",
463
- "lineHeight",
464
- "letterSpacing",
465
- "textCase",
466
- "styleRuns"
467
- ]);
468
- /**
469
- * Shared by SceneGraph.updateNode and updateNodePreview (drag hot path) so the
470
- * two invalidation rules cannot drift. Glyphs are kept when the caller
471
- * replaces them in the same update (resize supplies scaled copies).
472
- */
473
- function textCacheInvalidationChanges(node, changes) {
474
- const invalidated = {};
475
- const keys = Object.keys(changes);
476
- if (node.textPicture && keys.some((key) => TEXT_PICTURE_KEYS.has(key))) invalidated.textPicture = null;
477
- const glyphsInvalidated = keys.some((key) => GLYPH_AFFECTING_KEYS.has(key));
478
- if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {
479
- invalidated.derivedTextGlyphs = null;
480
- invalidated.textPathData = null;
481
- }
482
- return invalidated;
483
- }
484
- function invalidateTextCaches(node, changes) {
485
- Object.assign(node, textCacheInvalidationChanges(node, changes));
486
- }
487
- //#endregion
488
- //#region src/preview.ts
489
- const LAYOUT_AFFECTING_KEYS = /* @__PURE__ */ new Set([
490
- "x",
491
- "y",
492
- "width",
493
- "height",
494
- "rotation",
495
- "flipX",
496
- "flipY",
497
- "parentId",
498
- "childIds",
499
- "layoutMode",
500
- "layoutDirection",
501
- "layoutWrap",
502
- "primaryAxisSizing",
503
- "counterAxisSizing",
504
- "itemSpacing",
505
- "counterAxisSpacing",
506
- "paddingTop",
507
- "paddingRight",
508
- "paddingBottom",
509
- "paddingLeft",
510
- "layoutGrow",
511
- "layoutAlignSelf",
512
- "layoutPositioning",
513
- "minWidth",
514
- "maxWidth",
515
- "minHeight",
516
- "maxHeight",
517
- "visible",
518
- "text",
519
- "fontSize",
520
- "lineHeight",
521
- "letterSpacing",
522
- "styleRuns",
523
- "textAutoResize"
524
- ]);
525
- function updateNodePreview(graph, id, changes, beforeUpdate) {
526
- const node = graph.nodes.get(id);
527
- if (!node) return null;
528
- changes = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== void 0));
529
- if (Object.keys(changes).every((key) => node[key] === changes[key])) return null;
530
- if (Object.keys(changes).some((key) => LAYOUT_AFFECTING_KEYS.has(key))) graph.clearAbsPosCache();
531
- let normalizedChanges = changes;
532
- if (node.type === "TEXT") normalizedChanges = {
533
- ...textCacheInvalidationChanges(node, changes),
534
- ...changes
535
- };
536
- if (changes.vectorNetwork) normalizedChanges = {
537
- ...normalizedChanges,
538
- vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
539
- };
540
- beforeUpdate?.(node, normalizedChanges);
541
- graph.positionPreviewVersion++;
542
- Object.assign(node, normalizedChanges);
543
- return normalizedChanges;
544
- }
545
- //#endregion
546
- //#region src/source-metadata.ts
547
- function markSourceFieldsEdited(node, changeKeys) {
548
- if (changeKeys.length === 0) return;
549
- const editedFields = new Set(node.source.editedFields);
550
- for (const key of changeKeys) editedFields.add(key);
551
- node.source.editedFields = [...editedFields];
552
- }
553
- //#endregion
554
- //#region src/variables.ts
555
- function addVariable(graph, variable) {
556
- graph.variables.set(variable.id, variable);
557
- const collection = graph.variableCollections.get(variable.collectionId);
558
- if (collection && !collection.variableIds.includes(variable.id)) collection.variableIds.push(variable.id);
559
- }
560
- function removeVariable(graph, id) {
561
- const variable = graph.variables.get(id);
562
- if (!variable) return;
563
- graph.variables.delete(id);
564
- const collection = graph.variableCollections.get(variable.collectionId);
565
- if (collection) collection.variableIds = collection.variableIds.filter((vid) => vid !== id);
566
- for (const node of graph.nodes.values()) {
567
- if (!Object.values(node.boundVariables).includes(id)) continue;
568
- node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id);
569
- graph.emitter.emit("node:updated", node.id, { boundVariables: { ...node.boundVariables } });
570
- markBoundVariablesOverrideOnInstance(graph, node.id);
244
+ markBoundVariablesOverrideOnInstance(graph, node.id);
571
245
  }
572
246
  }
573
247
  function addCollection(graph, collection) {
@@ -627,13 +301,14 @@ function getActiveModeId(graph, collectionId) {
627
301
  if (mode) return mode;
628
302
  return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
629
303
  }
630
- function getNodeVariableModeId(graph, nodeId, collectionId) {
304
+ function getNodeVariableModeId(graph, nodeId, collectionId, fallback = "active") {
631
305
  let node = graph.nodes.get(nodeId);
632
306
  while (node) {
633
307
  const modeId = node.variableModes[collectionId];
634
308
  if (modeId) return modeId;
635
309
  node = node.parentId ? graph.nodes.get(node.parentId) : void 0;
636
310
  }
311
+ if (fallback === "default") return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
637
312
  return getActiveModeId(graph, collectionId);
638
313
  }
639
314
  function setActiveMode(graph, collectionId, modeId) {
@@ -653,6 +328,13 @@ function addMode(graph, collectionId, modeId, name, sourceMode) {
653
328
  variable.valuesByMode[modeId] = structuredClone(variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]);
654
329
  }
655
330
  }
331
+ /** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */
332
+ function createMode(graph, generateId, collectionId, name, sourceMode) {
333
+ if (!graph.variableCollections.has(collectionId)) return void 0;
334
+ const modeId = generateId();
335
+ addMode(graph, collectionId, modeId, name, sourceMode);
336
+ return modeId;
337
+ }
656
338
  function removeMode(graph, collectionId, modeId) {
657
339
  const collection = graph.variableCollections.get(collectionId);
658
340
  if (!collection || collection.modes.length <= 1) return;
@@ -675,144 +357,1372 @@ function setDefaultMode(graph, collectionId, modeId) {
675
357
  if (!collection) return;
676
358
  if (!collection.modes.some((m) => m.modeId === modeId)) return;
677
359
  collection.defaultModeId = modeId;
360
+ collection.modes = modesDefaultFirst(collection);
361
+ }
362
+ /** Figma has no default-mode field: the first mode is the default. */
363
+ function modesDefaultFirst(collection) {
364
+ const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId);
365
+ return [...defaults, ...rest];
366
+ }
367
+ function resolveVariable(graph, variableId, modeId, visited) {
368
+ if (visited?.has(variableId)) return void 0;
369
+ const variable = graph.variables.get(variableId);
370
+ if (!variable) return void 0;
371
+ const collection = graph.variableCollections.get(variable.collectionId);
372
+ const preferredModeId = modeId ?? getActiveModeId(graph, variable.collectionId);
373
+ const fallbackModeId = collection?.defaultModeId;
374
+ let value = Object.hasOwn(variable.valuesByMode, preferredModeId) ? variable.valuesByMode[preferredModeId] : void 0;
375
+ if (value === void 0 && fallbackModeId && Object.hasOwn(variable.valuesByMode, fallbackModeId)) value = variable.valuesByMode[fallbackModeId];
376
+ value ??= Object.values(variable.valuesByMode)[0];
377
+ if (value && typeof value === "object" && "aliasId" in value) {
378
+ const seen = visited ?? /* @__PURE__ */ new Set();
379
+ seen.add(variableId);
380
+ return resolveVariable(graph, value.aliasId, preferredModeId, seen);
381
+ }
382
+ return value;
383
+ }
384
+ function resolveColorVariable(graph, variableId) {
385
+ const value = resolveVariable(graph, variableId);
386
+ if (value && typeof value === "object" && "r" in value) return value;
387
+ }
388
+ function resolveNumberVariable(graph, variableId) {
389
+ const value = resolveVariable(graph, variableId);
390
+ return typeof value === "number" ? value : void 0;
391
+ }
392
+ function resolveColorVariableForNode(graph, nodeId, variableId, fallback = "active") {
393
+ const variable = graph.variables.get(variableId);
394
+ if (!variable) return void 0;
395
+ const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback));
396
+ if (value && typeof value === "object" && "r" in value) return value;
397
+ }
398
+ function resolveNumberVariableForNode(graph, nodeId, variableId, fallback = "active") {
399
+ const variable = graph.variables.get(variableId);
400
+ if (!variable) return void 0;
401
+ const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback));
402
+ return typeof value === "number" ? value : void 0;
403
+ }
404
+ /** A variable's value in the mode a node is in, aliases followed. */
405
+ function resolveVariableForNode(graph, nodeId, variableId, fallback = "active") {
406
+ const variable = graph.variables.get(variableId);
407
+ if (!variable) return void 0;
408
+ return resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback));
409
+ }
410
+ function resolveStringVariableForNode(graph, nodeId, variableId, fallback = "active") {
411
+ const value = resolveVariableForNode(graph, nodeId, variableId, fallback);
412
+ return typeof value === "string" ? value : void 0;
413
+ }
414
+ function getVariablesForCollection(graph, collectionId) {
415
+ const collection = graph.variableCollections.get(collectionId);
416
+ if (!collection) return [];
417
+ return collection.variableIds.map((id) => graph.variables.get(id)).filter((v) => v !== void 0);
418
+ }
419
+ function getVariablesByType(graph, type) {
420
+ return [...graph.variables.values()].filter((v) => v.type === type);
421
+ }
422
+ function bindVariable(graph, nodeId, field, variableId) {
423
+ const node = graph.nodes.get(nodeId);
424
+ if (!node) return;
425
+ const variable = graph.variables.get(variableId);
426
+ if (!variable) throw new Error(`Variable "${variableId}" not found`);
427
+ const colorFieldMatch = field.match(/^(fills|strokes)\/(\d+)\/color$/);
428
+ if (colorFieldMatch) {
429
+ if (variable.type !== "COLOR") throw new Error(`Cannot bind ${variable.type} variable to color field "${field}"`);
430
+ const arrayKey = colorFieldMatch[1];
431
+ const index = Number.parseInt(colorFieldMatch[2], 10);
432
+ const currentLength = node[arrayKey]?.length ?? 0;
433
+ if (index >= currentLength) throw new Error(`Index ${index} out of range for ${arrayKey} (length ${currentLength})`);
434
+ const topLevelKey = colorFieldMatch[1];
435
+ if (topLevelKey in node.boundVariables) node.boundVariables = omit(node.boundVariables, [topLevelKey]);
436
+ }
437
+ if (isNumericVariableBindingField(field) && variable.type !== "FLOAT") throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`);
438
+ if (STRING_BINDING_FIELDS.has(field) && variable.type !== "STRING") throw new Error(`Cannot bind ${variable.type} variable to string field "${field}"`);
439
+ if (BOOLEAN_BINDING_FIELDS.has(field) && variable.type !== "BOOLEAN") throw new Error(`Cannot bind ${variable.type} variable to boolean field "${field}"`);
440
+ if (!(isNumericVariableBindingField(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || colorFieldMatch)) throw new Error(`Unknown binding field "${field}"`);
441
+ graph.willChangeNode(node);
442
+ node.boundVariables = {
443
+ ...node.boundVariables,
444
+ [field]: variableId
445
+ };
446
+ assignVariableBindingUnits(graph, node, field);
447
+ markBoundVariablesOverrideOnInstance(graph, nodeId, field);
448
+ graph.emitter.emit("node:updated", nodeId, {
449
+ boundVariables: { ...node.boundVariables },
450
+ variableBindingScales: { ...node.variableBindingScales }
451
+ });
452
+ }
453
+ function unbindVariable(graph, nodeId, field) {
454
+ const node = graph.nodes.get(nodeId);
455
+ if (!node) return;
456
+ if (!(field in node.boundVariables)) return;
457
+ graph.willChangeNode(node);
458
+ node.boundVariables = omit(node.boundVariables, [field]);
459
+ node.variableBindingScales = omit(node.variableBindingScales, [field]);
460
+ markBoundVariablesOverrideOnInstance(graph, nodeId, field);
461
+ graph.emitter.emit("node:updated", nodeId, {
462
+ boundVariables: { ...node.boundVariables },
463
+ variableBindingScales: { ...node.variableBindingScales }
464
+ });
465
+ }
466
+ function markBoundVariablesOverrideOnInstance(graph, nodeId, field) {
467
+ const node = graph.nodes.get(nodeId);
468
+ if (!node) return;
469
+ const owner = variableBindingOwner(graph, node);
470
+ if (owner.type !== "INSTANCE") return;
471
+ const nearest = findInstanceAncestor(graph, nodeId);
472
+ if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, "boundVariables");
473
+ setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, "boundVariables");
474
+ if (field) setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, `boundVariables/${field}`, node.boundVariables[field] ?? null);
475
+ }
476
+ //#endregion
477
+ //#region src/variables/token.ts
478
+ /** `rem` tokens are stored in canvas pixels and shown against this root font size. */
479
+ const ROOT_FONT_SIZE_PX = 16;
480
+ /** The stored number for a value typed in a unit: `1.5` in `rem` is 24 canvas pixels. */
481
+ function tokenNumberFromUnit(value, unit) {
482
+ return unit === "rem" ? value * 16 : value;
483
+ }
484
+ /** A stored number as it reads in its unit: 24 canvas pixels in `rem` is `1.5`. */
485
+ function tokenNumberInUnit(value, unit) {
486
+ return unit === "rem" ? value / 16 : value;
487
+ }
488
+ //#endregion
489
+ //#region src/scaling/tree.ts
490
+ const MIN_SCALE = .01;
491
+ const RESCALABLE_NODE_TYPES = /* @__PURE__ */ new Set([
492
+ "BOOLEAN_OPERATION",
493
+ "COMPONENT",
494
+ "COMPONENT_SET",
495
+ "ELLIPSE",
496
+ "FRAME",
497
+ "GROUP",
498
+ "INSTANCE",
499
+ "LINE",
500
+ "POLYGON",
501
+ "RECTANGLE",
502
+ "STAR",
503
+ "TEXT",
504
+ "VECTOR"
505
+ ]);
506
+ /** Scale a node tree from the root node's top-left, matching Figma's Scale tool. */
507
+ function rescaleNodeTree(graph, rootId, scale) {
508
+ if (!Number.isFinite(scale)) throw new TypeError("Scale must be a finite number");
509
+ if (scale < MIN_SCALE) throw new RangeError(`Scale must be at least ${MIN_SCALE}`);
510
+ const root = graph.getNode(rootId);
511
+ if (!root || !RESCALABLE_NODE_TYPES.has(root.type)) throw new Error("rescale() is not supported on this node");
512
+ const nodes = [root];
513
+ const collect = (node) => {
514
+ for (const childId of node.childIds) {
515
+ const child = graph.getNode(childId);
516
+ if (!child) continue;
517
+ nodes.push(child);
518
+ collect(child);
519
+ }
520
+ };
521
+ collect(root);
522
+ for (const node of nodes) graph.updateNode(node.id, {
523
+ ...scaleNodeChanges(node, scale, node.id !== rootId),
524
+ ...scaleVariableBindingUnits(node, scale),
525
+ componentScale: findInstanceAncestor(graph, node.id) ? node.componentScale * scale : node.componentScale
526
+ });
527
+ }
528
+ //#endregion
529
+ //#region src/transfer/references.ts
530
+ function requireTransferReference(ids, id, kind) {
531
+ const value = ids.get(id);
532
+ if (!value) throw new Error(`Missing ${kind} transfer mapping: ${id}`);
533
+ return value;
534
+ }
535
+ //#endregion
536
+ //#region src/transfer/nodes.ts
537
+ function semanticTransferReferences(node) {
538
+ return [
539
+ ...node.componentId ? [node.componentId] : [],
540
+ ...Object.values(node.boundVariables),
541
+ ...[
542
+ node.fillStyleId,
543
+ node.strokeStyleId,
544
+ node.textStyleId,
545
+ node.effectStyleId,
546
+ node.gridStyleId
547
+ ].filter((id) => !!id),
548
+ ...node.fillGeometry.flatMap((path) => path.fillStyleId ? [path.fillStyleId] : []),
549
+ ...node.strokeGeometry.flatMap((path) => path.fillStyleId ? [path.fillStyleId] : []),
550
+ ...Object.entries(node.componentPropertyAssignments).flatMap(([id, value]) => [id, value]),
551
+ ...node.componentPropertyReferences.map((reference) => reference.propertyId),
552
+ ...node.componentPropertyDefinitions.flatMap((definition) => [definition.id, ...definition.type === "INSTANCE_SWAP" && definition.defaultValue ? [definition.defaultValue] : []]),
553
+ ...node.instanceOverrides.descendants.keys(),
554
+ ...[...node.instanceOverrides.self, ...[...node.instanceOverrides.descendants.values()].flatMap((fields) => [...fields])].flatMap(([field, value]) => typeof value === "string" && (field === "componentId" || field === "sourceComponentId" || field.startsWith("boundVariables/")) ? [value] : [])
555
+ ];
556
+ }
557
+ /** Prepare runtime references without rewriting original format identities or ordinary text. */
558
+ function prepareNodeTransfer(source, refs) {
559
+ const node = (id) => requireTransferReference(refs.nodes, id, "node");
560
+ const variable = (id) => requireTransferReference(refs.variables, id, "variable");
561
+ const property = (id) => requireTransferReference(refs.properties, id, "property");
562
+ const style = (id) => requireTransferReference(refs.styles, id, "style");
563
+ const propertyValue = (id, value) => {
564
+ const type = refs.propertyTypes.get(id);
565
+ if (!type) throw new Error(`Missing property transfer type: ${id}`);
566
+ return type === "INSTANCE_SWAP" && value ? node(value) : value;
567
+ };
568
+ const values = (entries) => Object.fromEntries(Object.entries(entries).map(([id, value]) => [property(id), propertyValue(id, value)]));
569
+ const result = cloneNodeProps(source, null);
570
+ result.componentId = source.componentId ? node(source.componentId) : null;
571
+ result.instanceOverrides = remapInstanceOverrideState(source.instanceOverrides, {
572
+ node,
573
+ variable
574
+ });
575
+ result.boundVariables = Object.fromEntries(Object.entries(source.boundVariables).map(([field, id]) => [field, variable(id)]));
576
+ result.variableModes = Object.fromEntries(Object.entries(source.variableModes).map(([collection, mode]) => [requireTransferReference(refs.collections, collection, "collection"), requireTransferReference(refs.modes, mode, "mode")]));
577
+ for (const field of [
578
+ "fillStyleId",
579
+ "strokeStyleId",
580
+ "textStyleId",
581
+ "effectStyleId",
582
+ "gridStyleId"
583
+ ]) result[field] = source[field] ? style(source[field]) : null;
584
+ for (const paths of [result.fillGeometry, result.strokeGeometry]) for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId);
585
+ result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
586
+ ...structuredClone(definition),
587
+ id: property(definition.id),
588
+ defaultValue: propertyValue(definition.id, definition.defaultValue)
589
+ }));
590
+ result.componentPropertyReferences = source.componentPropertyReferences.map((reference) => ({
591
+ ...reference,
592
+ propertyId: property(reference.propertyId)
593
+ }));
594
+ result.componentPropertyAssignments = values(source.componentPropertyAssignments);
595
+ result.componentPropertyValues = { ...source.componentPropertyValues };
596
+ return result;
597
+ }
598
+ //#endregion
599
+ //#region src/transfer/remove.ts
600
+ /** Refuse to remove transferred content that has acquired external dependents. */
601
+ function removeGraphTransfer(graph, plan) {
602
+ const nodes = new Set(plan.nodes.map((node) => node.id));
603
+ const variables = new Set(plan.variables.map((variable) => variable.id));
604
+ const collections = new Set(plan.collections.map((collection) => collection.id));
605
+ const referencesOwned = (value) => {
606
+ if (typeof value === "string") return nodes.has(value) || variables.has(value) || collections.has(value);
607
+ if (!value || typeof value !== "object" || ArrayBuffer.isView(value)) return false;
608
+ if (value instanceof Map) return [...value].some(([key, item]) => referencesOwned(key) || referencesOwned(item));
609
+ return Object.values(value).some(referencesOwned);
610
+ };
611
+ for (const node of graph.getAllNodes()) {
612
+ if (nodes.has(node.id)) {
613
+ if (node.childIds.some((id) => !nodes.has(id))) throw new Error("Transferred node has non-owned children");
614
+ continue;
615
+ }
616
+ if (semanticTransferReferences(node).some(referencesOwned)) throw new Error(`Transferred content is referenced by ${node.id}`);
617
+ }
618
+ for (const variable of graph.variables.values()) if (!variables.has(variable.id) && referencesOwned(variable.valuesByMode)) throw new Error("Transferred variable has external aliases");
619
+ graph.withBufferedEvents(() => {
620
+ for (const node of plan.nodes.toReversed()) graph.deleteNode(node.id);
621
+ for (const id of variables) graph.variables.delete(id);
622
+ for (const id of collections) {
623
+ graph.variableCollections.delete(id);
624
+ graph.activeMode.delete(id);
625
+ }
626
+ });
627
+ }
628
+ //#endregion
629
+ //#region src/transfer/history.ts
630
+ /** Capture post-placement state for redo; this does not authorize deleting shared resources. */
631
+ function captureTransferredState(graph, original) {
632
+ const requireValue = (value, kind, id) => {
633
+ if (value === void 0) throw new Error(`Missing transferred ${kind} ${id}`);
634
+ return value;
635
+ };
636
+ return {
637
+ nodeIds: new Map(original.nodeIds),
638
+ rootIds: [...original.rootIds],
639
+ dependencyPageIds: [...original.dependencyPageIds],
640
+ nodes: original.nodes.map((entry) => {
641
+ const node = requireValue(graph.getNode(entry.id), "node", entry.id);
642
+ if (!node.parentId) throw new Error(`Missing transferred parent ${entry.id}`);
643
+ return {
644
+ id: node.id,
645
+ type: node.type,
646
+ parentId: node.parentId,
647
+ props: cloneNodeProps(node, null)
648
+ };
649
+ }),
650
+ variables: original.variables.map((variable) => structuredClone(requireValue(graph.variables.get(variable.id), "variable", variable.id))),
651
+ collections: original.collections.map((collection) => structuredClone(requireValue(graph.variableCollections.get(collection.id), "collection", collection.id))),
652
+ activeModes: new Map(original.collections.map((collection) => [collection.id, requireValue(graph.activeMode.get(collection.id), "active mode", collection.id)])),
653
+ images: new Map([...original.images.keys()].map((hash) => [hash, requireValue(graph.images.get(hash), "image", hash).slice()]))
654
+ };
655
+ }
656
+ //#endregion
657
+ //#region src/transfer/identity.ts
658
+ function variableIdentityReferences(variables, collections) {
659
+ return {
660
+ variables: new Map(variables.map((variable) => [variable.id, variable.id])),
661
+ collections: new Map(collections.map((collection) => [collection.id, collection.id])),
662
+ modes: new Map(collections.flatMap((collection) => collection.modes.map((mode) => [mode.modeId, mode.modeId])))
663
+ };
664
+ }
665
+ //#endregion
666
+ //#region src/transfer/validation.ts
667
+ /** Revalidate mutable plan references without allocating or registering destination nodes. */
668
+ function validateTransferReferences(target, plan) {
669
+ const nodes = new Map(plan.nodes.map((entry) => [entry.id, createDefaultNode(() => entry.id, entry.type, entry.props)]));
670
+ const identities = new Map([...nodes.keys()].map((id) => [id, id]));
671
+ const properties = /* @__PURE__ */ new Map();
672
+ const propertyTypes = /* @__PURE__ */ new Map();
673
+ for (const node of nodes.values()) for (const definition of node.componentPropertyDefinitions) {
674
+ const previous = propertyTypes.get(definition.id);
675
+ if (previous && previous !== definition.type) throw new Error(`Conflicting transfer property ${definition.id}`);
676
+ properties.set(definition.id, definition.id);
677
+ propertyTypes.set(definition.id, definition.type);
678
+ }
679
+ const collections = new Map(plan.collections.map((collection) => [collection.id, collection]));
680
+ const references = {
681
+ nodes: identities,
682
+ styles: identities,
683
+ properties,
684
+ propertyTypes,
685
+ ...variableIdentityReferences(plan.variables, plan.collections)
686
+ };
687
+ for (const node of nodes.values()) {
688
+ prepareNodeTransfer(node, references);
689
+ for (const [collection, mode] of Object.entries(node.variableModes)) if (!collections.get(collection)?.modes.some((entry) => entry.modeId === mode)) throw new Error(`Invalid node variable mode ${node.id}`);
690
+ }
691
+ const roots = /* @__PURE__ */ new Set([...plan.rootIds, ...plan.dependencyPageIds]);
692
+ if (roots.size !== plan.rootIds.length + plan.dependencyPageIds.length) throw new Error("Repeated transfer root");
693
+ for (const entry of plan.nodes) {
694
+ if (roots.has(entry.id) === nodes.has(entry.parentId)) throw new Error(`Invalid transfer root topology ${entry.id}`);
695
+ if (plan.dependencyPageIds.includes(entry.id) && (entry.type !== "CANVAS" || !entry.props.internalOnly || entry.parentId !== target.rootId)) throw new Error(`Invalid transfer dependency page ${entry.id}`);
696
+ }
697
+ }
698
+ //#endregion
699
+ //#region src/transfer/variables.ts
700
+ function assertUniqueMappings(ids, kind) {
701
+ if (new Set(ids.values()).size !== ids.size) throw new Error(`Colliding ${kind} transfer mappings`);
702
+ }
703
+ function assertResourceOwnership(variables, collections) {
704
+ const sets = new Map(collections.map((collection) => [collection.id, collection]));
705
+ const tokens = new Map(variables.map((variable) => [variable.id, variable]));
706
+ if (sets.size !== collections.length || tokens.size !== variables.length) throw new Error("Duplicate source variable resource");
707
+ for (const collection of collections) {
708
+ const modes = new Set(collection.modes.map((mode) => mode.modeId));
709
+ if (!modes.has(collection.defaultModeId) || modes.size !== collection.modes.length) throw new Error(`Invalid modes for collection ${collection.id}`);
710
+ for (const id of collection.variableIds) if (tokens.get(id)?.collectionId !== collection.id) throw new Error(`Invalid variable membership ${id} in ${collection.id}`);
711
+ }
712
+ for (const variable of variables) {
713
+ const collection = sets.get(variable.collectionId);
714
+ if (!collection?.variableIds.includes(variable.id)) throw new Error(`Missing collection membership for ${variable.id}`);
715
+ const modes = new Set(collection.modes.map((mode) => mode.modeId));
716
+ for (const mode of Object.keys(variable.valuesByMode)) if (!modes.has(mode)) throw new Error(`Unknown mode ${mode} for ${variable.id}`);
717
+ }
718
+ }
719
+ /** Prepare isolated resource copies; never mutate the source or destination graph. */
720
+ function prepareVariableTransfer(variables, collections, references) {
721
+ assertResourceOwnership(variables, collections);
722
+ assertUniqueMappings(references.variables, "variable");
723
+ assertUniqueMappings(references.collections, "collection");
724
+ assertUniqueMappings(references.modes, "mode");
725
+ const value = (input) => {
726
+ if (typeof input === "object" && "aliasId" in input) return { aliasId: requireTransferReference(references.variables, input.aliasId, "variable alias") };
727
+ return structuredClone(input);
728
+ };
729
+ return {
730
+ collections: collections.map((collection) => ({
731
+ ...structuredClone(collection),
732
+ id: requireTransferReference(references.collections, collection.id, "collection"),
733
+ defaultModeId: requireTransferReference(references.modes, collection.defaultModeId, "mode"),
734
+ modes: collection.modes.map((mode) => ({
735
+ ...mode,
736
+ modeId: requireTransferReference(references.modes, mode.modeId, "mode")
737
+ })),
738
+ variableIds: collection.variableIds.map((id) => requireTransferReference(references.variables, id, "variable"))
739
+ })),
740
+ variables: variables.map((variable) => ({
741
+ ...structuredClone(variable),
742
+ id: requireTransferReference(references.variables, variable.id, "variable"),
743
+ collectionId: requireTransferReference(references.collections, variable.collectionId, "collection"),
744
+ valuesByMode: Object.fromEntries(Object.entries(variable.valuesByMode).map(([mode, input]) => [requireTransferReference(references.modes, mode, "mode"), value(input)]))
745
+ }))
746
+ };
747
+ }
748
+ //#endregion
749
+ //#region src/transfer/apply.ts
750
+ function validate(target, plan) {
751
+ validateTransferReferences(target, plan);
752
+ const reserved = /* @__PURE__ */ new Set([
753
+ ...target.nodes.keys(),
754
+ ...target.variables.keys(),
755
+ ...target.variableCollections.keys()
756
+ ]);
757
+ const claim = (id) => {
758
+ if (reserved.has(id)) throw new Error(`Transfer identity collision ${id}`);
759
+ reserved.add(id);
760
+ };
761
+ prepareVariableTransfer(plan.variables, plan.collections, variableIdentityReferences(plan.variables, plan.collections));
762
+ for (const [id, mode] of plan.activeModes) if (!plan.collections.find((collection) => collection.id === id)?.modes.some((entry) => entry.modeId === mode)) throw new Error(`Invalid transferred active mode ${id}:${mode}`);
763
+ for (const collection of plan.collections) claim(collection.id);
764
+ for (const variable of plan.variables) claim(variable.id);
765
+ const parents = new Set(target.nodes.keys());
766
+ for (const node of plan.nodes) {
767
+ claim(node.id);
768
+ if ("id" in node.props || "parentId" in node.props || "childIds" in node.props) throw new Error("Transfer props cannot override hierarchy identity");
769
+ if (!parents.has(node.parentId)) throw new Error(`Missing transfer parent ${node.parentId}`);
770
+ parents.add(node.id);
771
+ }
772
+ for (const id of [...plan.rootIds, ...plan.dependencyPageIds]) if (!plan.nodes.some((node) => node.id === id)) throw new Error(`Missing transfer root ${id}`);
773
+ for (const node of plan.nodes) if (node.props.componentId && !parents.has(node.props.componentId)) throw new Error(`Missing transfer component ${node.props.componentId}`);
774
+ for (const [hash, bytes] of plan.images) {
775
+ const existing = target.images.get(hash);
776
+ if (existing && !isEqual(existing, bytes)) throw new Error(`Transfer image collision ${hash}`);
777
+ }
778
+ }
779
+ /** Revalidate at insertion time. Event-delivery failures after commit are not rollback failures. */
780
+ function applyGraphTransfer(target, input) {
781
+ const plan = structuredClone(input);
782
+ validate(target, plan);
783
+ const imageIds = [...plan.images.keys()].filter((hash) => !target.images.has(hash));
784
+ target.withBufferedEvents(() => {
785
+ try {
786
+ for (const collection of plan.collections) target.addCollection(collection);
787
+ for (const variable of plan.variables) target.addVariable(variable);
788
+ for (const [id, mode] of plan.activeModes) target.activeMode.set(id, mode);
789
+ for (const [hash, bytes] of plan.images) if (!target.images.has(hash)) target.images.set(hash, bytes);
790
+ for (const node of plan.nodes) target.createNodeWithId(node.id, node.type, node.parentId, {
791
+ ...node.props,
792
+ childIds: []
793
+ });
794
+ } catch (error) {
795
+ for (const node of plan.nodes.toReversed()) if (target.getNode(node.id)) target.deleteNode(node.id);
796
+ for (const variable of plan.variables) target.variables.delete(variable.id);
797
+ for (const collection of plan.collections) {
798
+ target.variableCollections.delete(collection.id);
799
+ target.activeMode.delete(collection.id);
800
+ }
801
+ for (const hash of imageIds) target.images.delete(hash);
802
+ throw error;
803
+ }
804
+ });
805
+ }
806
+ //#endregion
807
+ //#region src/transfer/plan.ts
808
+ /** Preflight a self-contained fragment; allocation does not insert anything into the target. */
809
+ function prepareGraphTransfer(input) {
810
+ const { source, target, parentId } = input;
811
+ if (!target.getNode(parentId)) throw new Error(`Missing transfer parent ${parentId}`);
812
+ const reserved = /* @__PURE__ */ new Set([
813
+ ...target.nodes.keys(),
814
+ ...target.variables.keys(),
815
+ ...target.variableCollections.keys()
816
+ ]);
817
+ for (const collection of target.variableCollections.values()) for (const mode of collection.modes) reserved.add(mode.modeId);
818
+ let sequence = 0;
819
+ const namespace = crypto.randomUUID();
820
+ const allocate = () => {
821
+ let id = `${namespace}:${sequence++}`;
822
+ while (reserved.has(id)) id = `${namespace}:${sequence++}`;
823
+ reserved.add(id);
824
+ return id;
825
+ };
826
+ const ordered = [];
827
+ const seen = /* @__PURE__ */ new Set();
828
+ const visit = (id) => {
829
+ if (seen.has(id)) throw new Error(`Repeated transfer node ${id}`);
830
+ const node = source.getNode(id);
831
+ if (!node) throw new Error(`Missing transfer source ${id}`);
832
+ seen.add(id);
833
+ ordered.push(node);
834
+ for (const child of node.childIds) visit(child);
835
+ };
836
+ for (const id of [...input.dependencyPageIds, ...input.rootIds]) visit(id);
837
+ const nodes = new Map(ordered.map((node) => [node.id, allocate()]));
838
+ const variables = new Map([...source.variables.keys()].map((id) => [id, allocate()]));
839
+ const collections = new Map([...source.variableCollections.keys()].map((id) => [id, allocate()]));
840
+ const modes = /* @__PURE__ */ new Map();
841
+ for (const collection of source.variableCollections.values()) for (const mode of collection.modes) if (!modes.has(mode.modeId)) modes.set(mode.modeId, allocate());
842
+ const properties = /* @__PURE__ */ new Map();
843
+ const propertyTypes = /* @__PURE__ */ new Map();
844
+ for (const node of ordered) for (const definition of node.componentPropertyDefinitions) {
845
+ if (propertyTypes.has(definition.id) && propertyTypes.get(definition.id) !== definition.type) throw new Error(`Conflicting property type ${definition.id}`);
846
+ propertyTypes.set(definition.id, definition.type);
847
+ if (!properties.has(definition.id)) properties.set(definition.id, allocate());
848
+ }
849
+ const references = {
850
+ nodes,
851
+ variables,
852
+ collections,
853
+ modes,
854
+ properties,
855
+ propertyTypes,
856
+ styles: nodes
857
+ };
858
+ const resources = prepareVariableTransfer([...source.variables.values()], [...source.variableCollections.values()], references);
859
+ const mapped = (id) => {
860
+ const value = nodes.get(id);
861
+ if (!value) throw new Error(`Missing transfer node mapping ${id}`);
862
+ return value;
863
+ };
864
+ const roots = new Set(input.rootIds);
865
+ const dependencies = new Set(input.dependencyPageIds);
866
+ const destinationParent = (node) => {
867
+ if (roots.has(node.id)) return parentId;
868
+ if (dependencies.has(node.id)) return target.rootId;
869
+ return mapped(node.parentId ?? "");
870
+ };
871
+ return {
872
+ nodeIds: nodes,
873
+ rootIds: input.rootIds.map(mapped),
874
+ dependencyPageIds: input.dependencyPageIds.map(mapped),
875
+ nodes: ordered.map((node) => ({
876
+ id: mapped(node.id),
877
+ type: node.type,
878
+ parentId: destinationParent(node),
879
+ props: prepareNodeTransfer(node, references)
880
+ })),
881
+ ...resources,
882
+ activeModes: new Map([...source.activeMode].map(([collection, mode]) => [requireTransferReference(collections, collection, "collection"), requireTransferReference(modes, mode, "mode")])),
883
+ images: new Map([...source.images].map(([hash, bytes]) => [hash, bytes.slice()]))
884
+ };
885
+ }
886
+ //#endregion
887
+ //#region src/slots/content.ts
888
+ function parentOf(graph, node) {
889
+ return node.parentId ? graph.nodes.get(node.parentId) : void 0;
890
+ }
891
+ function nearestInstance(graph, node) {
892
+ let current = parentOf(graph, node);
893
+ while (current && current.type !== "INSTANCE") current = parentOf(graph, current);
894
+ return current;
895
+ }
896
+ function slotScope(graph, parentId) {
897
+ let current = graph.nodes.get(parentId);
898
+ while (current) {
899
+ const propertyId = slotPropertyId(current);
900
+ if (propertyId) {
901
+ const instance = nearestInstance(graph, current);
902
+ return instance ? {
903
+ kind: "slot",
904
+ frame: current,
905
+ instance,
906
+ propertyId
907
+ } : { kind: "free" };
908
+ }
909
+ if (current.type === "INSTANCE") return {
910
+ kind: "locked",
911
+ instance: current
912
+ };
913
+ current = parentOf(graph, current);
914
+ }
915
+ return { kind: "free" };
916
+ }
917
+ /** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */
918
+ function descendants(graph, node, enterInstances) {
919
+ const result = [];
920
+ const visit = (parent) => {
921
+ for (const childId of parent.childIds) {
922
+ const child = graph.nodes.get(childId);
923
+ if (!child) continue;
924
+ result.push(child);
925
+ if (enterInstances || child.type !== "INSTANCE") visit(child);
926
+ }
927
+ };
928
+ visit(node);
929
+ return result;
930
+ }
931
+ /**
932
+ * Make the instance own its slot's content, as Figma does on the first edit: the layers
933
+ * stay where they are, but stop following the component. Overrides the instance held for
934
+ * them become their own values, or move to the nested instance they belong to.
935
+ */
936
+ function claimSlotContent(graph, scope) {
937
+ const { frame, instance, propertyId } = scope;
938
+ if (ownsSlotContent(graph, frame, propertyId)) return;
939
+ const overrides = instance.instanceOverrides;
940
+ for (const node of descendants(graph, frame, false)) {
941
+ overrides.descendants.delete(node.id);
942
+ if (node.type !== "INSTANCE") {
943
+ graph.updateNode(node.id, { componentId: null });
944
+ continue;
945
+ }
946
+ for (const inner of descendants(graph, node, true)) {
947
+ const fields = overrides.descendants.get(inner.id);
948
+ if (!fields) continue;
949
+ for (const [field, value] of fields) if (field !== "sourceComponentId") setInstanceOverride(node.instanceOverrides, node.id, inner.id, field, value);
950
+ overrides.descendants.delete(inner.id);
951
+ }
952
+ graph.updateNode(node.id, { instanceOverrides: node.instanceOverrides });
953
+ }
954
+ graph.updateNode(instance.id, {
955
+ instanceOverrides: overrides,
956
+ componentPropertyAssignments: {
957
+ ...instance.componentPropertyAssignments,
958
+ [propertyId]: ""
959
+ }
960
+ });
961
+ }
962
+ /** The component layer an instance layer was cloned from. */
963
+ function componentSource(instance, node) {
964
+ const mapped = getInstanceOverride(instance.instanceOverrides, instance.id, node.id, "sourceComponentId");
965
+ return typeof mapped === "string" ? mapped : node.componentId;
966
+ }
967
+ /** Return the slot to its component's content: the instance stops owning it. */
968
+ function resetSlotContent(graph, scope) {
969
+ const { frame, instance, propertyId } = scope;
970
+ for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId);
971
+ const assignments = { ...instance.componentPropertyAssignments };
972
+ Reflect.deleteProperty(assignments, propertyId);
973
+ graph.updateNode(instance.id, { componentPropertyAssignments: assignments });
974
+ const source = componentSource(instance, frame);
975
+ if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id);
976
+ }
977
+ /** Remove everything from the slot; the instance keeps owning it, now empty. */
978
+ function clearSlotContent(graph, scope) {
979
+ claimSlotContent(graph, scope);
980
+ for (const childId of Array.from(scope.frame.childIds)) graph.deleteNode(childId);
981
+ }
982
+ //#endregion
983
+ //#region src/slots/authoring.ts
984
+ /** The settings a new slot starts with: no limits, any layer allowed. */
985
+ const DEFAULT_SLOT_SETTINGS = {
986
+ allowPreferredValuesOnly: false,
987
+ displayEmptyByDefault: false,
988
+ stretchChildOnInsert: false
989
+ };
990
+ /**
991
+ * The main component a layer belongs to, which defines the slots inside it. Layers of an
992
+ * instance are not authored there, so a layer under an instance has none.
993
+ */
994
+ function slotOwner(graph, node) {
995
+ let current = node.parentId ? graph.getNode(node.parentId) : void 0;
996
+ while (current && current.type !== "CANVAS") {
997
+ if (current.type === "COMPONENT") return current;
998
+ if (current.type === "INSTANCE") return void 0;
999
+ current = current.parentId ? graph.getNode(current.parentId) : void 0;
1000
+ }
1001
+ }
1002
+ /** Whether a frame inside a main component can become a slot. */
1003
+ function canCreateSlot(graph, node) {
1004
+ return node.type === "FRAME" && !slotPropertyId(node) && !!slotOwner(graph, node);
1005
+ }
1006
+ function uniqueSlotName(owner, base) {
1007
+ const taken = new Set(owner.componentPropertyDefinitions.map((definition) => definition.name));
1008
+ if (!taken.has(base)) return base;
1009
+ let index = 2;
1010
+ while (taken.has(`${base} ${index}`)) index++;
1011
+ return `${base} ${index}`;
1012
+ }
1013
+ /**
1014
+ * Make a frame of a main component a slot: define a SLOT property, named after the frame, on
1015
+ * the component and bind the frame's children to it. Instances pick up the slot on their next
1016
+ * sync.
1017
+ */
1018
+ function createSlotProperty(graph, frameId, id) {
1019
+ const frame = graph.getNode(frameId);
1020
+ const owner = frame && canCreateSlot(graph, frame) ? slotOwner(graph, frame) : void 0;
1021
+ if (!frame || !owner) return null;
1022
+ const definition = {
1023
+ id,
1024
+ name: uniqueSlotName(owner, frame.name.trim() || "Slot"),
1025
+ type: "SLOT",
1026
+ defaultValue: "",
1027
+ preferredValues: [],
1028
+ slotSettings: { ...DEFAULT_SLOT_SETTINGS }
1029
+ };
1030
+ graph.updateNode(owner.id, { componentPropertyDefinitions: [...owner.componentPropertyDefinitions, definition] });
1031
+ graph.updateNode(frame.id, { componentPropertyReferences: [...frame.componentPropertyReferences, {
1032
+ propertyId: id,
1033
+ field: "SLOT_CONTENT"
1034
+ }] });
1035
+ return definition;
1036
+ }
1037
+ /** Change a slot property's name, description, preferred components, or limits. */
1038
+ function updateSlotProperty(graph, ownerId, propertyId, patch) {
1039
+ const owner = graph.getNode(ownerId);
1040
+ const current = owner?.componentPropertyDefinitions.find((definition) => definition.id === propertyId && definition.type === "SLOT");
1041
+ if (!owner || !current) return false;
1042
+ const { slotSettings, ...fields } = patch;
1043
+ const next = {
1044
+ ...current,
1045
+ ...fields,
1046
+ slotSettings: {
1047
+ ...DEFAULT_SLOT_SETTINGS,
1048
+ ...current.slotSettings,
1049
+ ...slotSettings
1050
+ }
1051
+ };
1052
+ graph.updateNode(owner.id, { componentPropertyDefinitions: owner.componentPropertyDefinitions.map((definition) => definition.id === propertyId ? next : definition) });
1053
+ return true;
1054
+ }
1055
+ //#endregion
1056
+ //#region src/slots/limits.ts
1057
+ /** Whether a component is among a slot's preferred values, by id, key, or library key. */
1058
+ function isPreferredComponent(component, preferredValues = []) {
1059
+ if (!component) return false;
1060
+ return [
1061
+ component.id,
1062
+ component.componentKey,
1063
+ component.sourceLibraryKey
1064
+ ].some((value) => !!value && preferredValues.includes(value));
1065
+ }
1066
+ /** Content layers a preferred-only slot does not allow: anything but preferred instances. */
1067
+ function nonPreferredLayers(graph, definition, content) {
1068
+ if (!definition.slotSettings?.allowPreferredValuesOnly) return [];
1069
+ return content.filter((node) => node.type !== "INSTANCE" || !isPreferredComponent(node.componentId ? graph.getNode(node.componentId) : void 0, definition.preferredValues));
1070
+ }
1071
+ /** The limits a slot's content breaks; below-minimum and above-maximum exclude each other. */
1072
+ function slotLimitViolations(graph, definition, content) {
1073
+ const settings = definition.slotSettings;
1074
+ const violations = [];
1075
+ if (settings?.minChildren !== void 0 && content.length < settings.minChildren) violations.push("BELOW_MIN");
1076
+ else if (settings?.maxChildren !== void 0 && content.length > settings.maxChildren) violations.push("ABOVE_MAX");
1077
+ if (nonPreferredLayers(graph, definition, content).length) violations.push("HAS_NON_PREFERRED");
1078
+ return violations;
1079
+ }
1080
+ //#endregion
1081
+ //#region src/shaders/model.ts
1082
+ /** Every shader a node's fills and strokes draw, whether or not a paint still shows it. */
1083
+ function readShaderPaints(node) {
1084
+ return readAllPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.shader);
1085
+ }
1086
+ /**
1087
+ * The shader a fill or stroke of `node` draws: an image paint whose image is a shader's frame.
1088
+ * Null for any other paint, including one whose image was replaced, which then draws as the
1089
+ * image it holds.
1090
+ */
1091
+ function shaderOfPaint(node, paint) {
1092
+ if (paint.type !== "IMAGE" || !paint.imageHash) return null;
1093
+ return readShaderPaints(node).find((shader) => shader.image === paint.imageHash) ?? null;
1094
+ }
1095
+ /** Whether any paint of `node` draws a shader. */
1096
+ function hasShaderPaint(node) {
1097
+ return [...node.fills, ...node.strokes].some((paint) => shaderOfPaint(node, paint) !== null);
1098
+ }
1099
+ /**
1100
+ * The node's plugin data with `shaders` set by their image, keeping only shaders a fill or
1101
+ * stroke of `paints` still shows, so removing or replacing a paint leaves no entry behind.
1102
+ */
1103
+ function withShaderPaints(node, paints, shaders = []) {
1104
+ const shown = new Set(paints.flatMap((paint) => paint.type === "IMAGE" && paint.imageHash ? [paint.imageHash] : []));
1105
+ const byImage = new Map(readShaderPaints(node).map((shader) => [shader.image, shader]));
1106
+ for (const shader of shaders) byImage.set(shader.image, shader);
1107
+ return withAllPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.shader, [...byImage.values()].filter((shader) => shown.has(shader.image)));
1108
+ }
1109
+ /**
1110
+ * A new paint that draws `preset`, and the shader entry it shows. Its image names a frame not yet
1111
+ * rendered, unique to this paint, so no other paint's entry claims it until the frame is drawn.
1112
+ */
1113
+ function createShaderPaint(preset) {
1114
+ const image = randomHex(20);
1115
+ return {
1116
+ paint: {
1117
+ type: "IMAGE",
1118
+ color: TRANSPARENT,
1119
+ opacity: 1,
1120
+ visible: true,
1121
+ imageHash: image,
1122
+ imageScaleMode: "FILL"
1123
+ },
1124
+ shader: {
1125
+ image,
1126
+ preset: structuredClone(preset)
1127
+ }
1128
+ };
1129
+ }
1130
+ /** A short key that tells one preset from another, which a rendered frame records. */
1131
+ function shaderPresetKey(preset) {
1132
+ return computeImageHash(new TextEncoder().encode(JSON.stringify(preset)));
1133
+ }
1134
+ /**
1135
+ * Whether a shader's frame was rendered for its preset at the size `node` has now, so undoing a
1136
+ * preset change after reopening the document does not keep a frame of the newer preset.
1137
+ */
1138
+ function isShaderFrameCurrent(shader, size) {
1139
+ const { frame } = shader;
1140
+ return frame !== void 0 && frame.preset === shaderPresetKey(shader.preset) && Math.round(frame.width) === Math.round(size.width) && Math.round(frame.height) === Math.round(size.height);
1141
+ }
1142
+ //#endregion
1143
+ //#region src/snap.ts
1144
+ const DEFAULT_SNAP_THRESHOLD = 5;
1145
+ function getEdges(node) {
1146
+ return rotatedBBox(node.x, node.y, node.width, node.height, node.rotation);
1147
+ }
1148
+ function computeSnap(movingIds, movingBounds, allNodes, threshold = DEFAULT_SNAP_THRESHOLD) {
1149
+ const targets = allNodes.filter((n) => !movingIds.has(n.id));
1150
+ if (targets.length === 0) return {
1151
+ dx: 0,
1152
+ dy: 0,
1153
+ guides: []
1154
+ };
1155
+ const m = {
1156
+ left: movingBounds.x,
1157
+ right: movingBounds.x + movingBounds.width,
1158
+ centerX: movingBounds.x + movingBounds.width / 2,
1159
+ top: movingBounds.y,
1160
+ bottom: movingBounds.y + movingBounds.height,
1161
+ centerY: movingBounds.y + movingBounds.height / 2
1162
+ };
1163
+ let bestDx = Infinity;
1164
+ let bestDy = Infinity;
1165
+ const guides = [];
1166
+ for (const target of targets) {
1167
+ const t = getEdges(target);
1168
+ const xPairs = [
1169
+ [m.left, t.left],
1170
+ [m.left, t.right],
1171
+ [m.right, t.left],
1172
+ [m.right, t.right],
1173
+ [m.centerX, t.centerX]
1174
+ ];
1175
+ for (const [mVal, tVal] of xPairs) {
1176
+ const d = tVal - mVal;
1177
+ if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDx)) {
1178
+ if (Math.abs(d) < Math.abs(bestDx)) {
1179
+ bestDx = d;
1180
+ guides.length = guides.filter((g) => g.axis === "y").length ? guides.length : guides.length;
1181
+ for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "x") guides.splice(i, 1);
1182
+ }
1183
+ if (Math.abs(d) === Math.abs(bestDx)) {
1184
+ const minY = Math.min(m.top, t.top);
1185
+ const maxY = Math.max(m.bottom, t.bottom);
1186
+ guides.push({
1187
+ axis: "x",
1188
+ position: tVal,
1189
+ from: minY,
1190
+ to: maxY
1191
+ });
1192
+ }
1193
+ }
1194
+ }
1195
+ const yPairs = [
1196
+ [m.top, t.top],
1197
+ [m.top, t.bottom],
1198
+ [m.bottom, t.top],
1199
+ [m.bottom, t.bottom],
1200
+ [m.centerY, t.centerY]
1201
+ ];
1202
+ for (const [mVal, tVal] of yPairs) {
1203
+ const d = tVal - mVal;
1204
+ if (Math.abs(d) < threshold && Math.abs(d) <= Math.abs(bestDy)) {
1205
+ if (Math.abs(d) < Math.abs(bestDy)) {
1206
+ for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "y") guides.splice(i, 1);
1207
+ bestDy = d;
1208
+ }
1209
+ if (Math.abs(d) === Math.abs(bestDy)) {
1210
+ const minX = Math.min(m.left, t.left);
1211
+ const maxX = Math.max(m.right, t.right);
1212
+ guides.push({
1213
+ axis: "y",
1214
+ position: tVal,
1215
+ from: minX,
1216
+ to: maxX
1217
+ });
1218
+ }
1219
+ }
1220
+ }
1221
+ }
1222
+ return {
1223
+ dx: Math.abs(bestDx) <= threshold ? bestDx : 0,
1224
+ dy: Math.abs(bestDy) <= threshold ? bestDy : 0,
1225
+ guides
1226
+ };
1227
+ }
1228
+ function computeSelectionBounds(nodes) {
1229
+ if (nodes.length === 0) return null;
1230
+ let minX = Infinity;
1231
+ let minY = Infinity;
1232
+ let maxX = -Infinity;
1233
+ let maxY = -Infinity;
1234
+ for (const n of nodes) {
1235
+ const edges = getEdges(n);
1236
+ minX = Math.min(minX, edges.left);
1237
+ minY = Math.min(minY, edges.top);
1238
+ maxX = Math.max(maxX, edges.right);
1239
+ maxY = Math.max(maxY, edges.bottom);
1240
+ }
1241
+ return {
1242
+ x: minX,
1243
+ y: minY,
1244
+ width: maxX - minX,
1245
+ height: maxY - minY
1246
+ };
1247
+ }
1248
+ //#endregion
1249
+ //#region src/layout/guides.ts
1250
+ const MAX_LAYOUT_GUIDE_LINES = 1e4;
1251
+ function normalizedCount(grid) {
1252
+ const value = grid.count ?? grid.numSections ?? 1;
1253
+ if (!Number.isFinite(value)) return 0;
1254
+ return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)));
1255
+ }
1256
+ function pattern(grid) {
1257
+ if (grid.pattern === "GRID" || grid.pattern === "ROWS") return grid.pattern;
1258
+ if (grid.axis === "Y") return "ROWS";
1259
+ return "COLUMNS";
1260
+ }
1261
+ function alignment(grid) {
1262
+ const value = grid.alignment ?? grid.type;
1263
+ if (value === "CENTER" || value === "MAX" || value === "STRETCH") return value;
1264
+ return "MIN";
1265
+ }
1266
+ function sectionSize(nodeSize, grid) {
1267
+ const fixed = grid.sectionSize ?? 0;
1268
+ if (alignment(grid) !== "STRETCH") return fixed;
1269
+ const count = normalizedCount(grid);
1270
+ const gutter = grid.gutterSize ?? 0;
1271
+ return (nodeSize - (grid.offset ?? 0) * 2 - Math.max(0, count - 1) * gutter) / count;
1272
+ }
1273
+ function start(nodeSize, grid, size) {
1274
+ const count = normalizedCount(grid);
1275
+ const gutter = grid.gutterSize ?? 0;
1276
+ const offset = grid.offset ?? 0;
1277
+ const span = count * size + Math.max(0, count - 1) * gutter;
1278
+ if (alignment(grid) === "CENTER") return (nodeSize - span) / 2 + offset;
1279
+ if (alignment(grid) === "MAX") return nodeSize - span - offset;
1280
+ return offset;
1281
+ }
1282
+ function layoutGuideSections(node, grid) {
1283
+ if (grid.visible === false || pattern(grid) === "GRID") return [];
1284
+ const axis = pattern(grid) === "ROWS" ? "y" : "x";
1285
+ const nodeSize = axis === "x" ? node.width : node.height;
1286
+ const size = sectionSize(nodeSize, grid);
1287
+ const count = normalizedCount(grid);
1288
+ if (count <= 0 || size <= 0) return [];
1289
+ const first = start(nodeSize, grid, size);
1290
+ const step = size + (grid.gutterSize ?? 0);
1291
+ return Array.from({ length: count }, (_, index) => {
1292
+ const sectionStart = first + index * step;
1293
+ return {
1294
+ axis,
1295
+ start: sectionStart,
1296
+ end: sectionStart + size
1297
+ };
1298
+ });
1299
+ }
1300
+ function layoutGuideLines(node, grid) {
1301
+ if (grid.visible === false) return [];
1302
+ const gridPattern = pattern(grid);
1303
+ const lines = [];
1304
+ if (gridPattern === "GRID") {
1305
+ const size = grid.sectionSize ?? 0;
1306
+ if (size <= 0) return lines;
1307
+ for (let index = 0, x = grid.offset ?? 0; x <= node.width && index < MAX_LAYOUT_GUIDE_LINES; index++, x += size) lines.push({
1308
+ axis: "x",
1309
+ position: x
1310
+ });
1311
+ for (let index = 0, y = grid.offset ?? 0; y <= node.height && index < MAX_LAYOUT_GUIDE_LINES; index++, y += size) lines.push({
1312
+ axis: "y",
1313
+ position: y
1314
+ });
1315
+ return lines;
1316
+ }
1317
+ const sections = layoutGuideSections(node, grid);
1318
+ for (const section of sections) lines.push({
1319
+ axis: section.axis,
1320
+ position: section.start
1321
+ }, {
1322
+ axis: section.axis,
1323
+ position: section.end
1324
+ });
1325
+ return lines;
1326
+ }
1327
+ //#endregion
1328
+ //#region src/layout/sizing.ts
1329
+ function primaryAxis(mode) {
1330
+ return mode === "VERTICAL" ? "VERTICAL" : "HORIZONTAL";
1331
+ }
1332
+ /** The auto-layout parent that sizes a node's fill, or `undefined` when nothing does. */
1333
+ function fillingParent(parent, node) {
1334
+ if (!parent || parent.layoutMode === "NONE" || node.layoutPositioning === "ABSOLUTE") return void 0;
1335
+ return parent;
1336
+ }
1337
+ function graphParent(graph, node) {
1338
+ return node.parentId ? graph.getNode(node.parentId) : void 0;
1339
+ }
1340
+ function fills(parent, node, axis) {
1341
+ if (parent.layoutMode === "NONE") return false;
1342
+ if (axis === primaryAxis(parent.layoutMode)) return node.layoutGrow > 0;
1343
+ if (node.layoutAlignSelf === "STRETCH") return true;
1344
+ return node.layoutAlignSelf === "AUTO" && parent.layoutMode !== "GRID" && parent.counterAxisAlign === "STRETCH";
1345
+ }
1346
+ function ownSizingField(node, axis) {
1347
+ if (node.layoutMode === "NONE") return void 0;
1348
+ return axis === primaryAxis(node.layoutMode) ? "primaryAxisSizing" : "counterAxisSizing";
1349
+ }
1350
+ function textHugs(autoResize, axis) {
1351
+ if (autoResize === "WIDTH_AND_HEIGHT") return true;
1352
+ return axis === "VERTICAL" && autoResize === "HEIGHT";
1353
+ }
1354
+ function hugs(node, axis) {
1355
+ if (node.type === "TEXT") return textHugs(node.textAutoResize, axis);
1356
+ const field = ownSizingField(node, axis);
1357
+ return field !== void 0 && node[field] === "HUG";
1358
+ }
1359
+ /** The node's sizing along `axis`: fill from its parent, else its own hug, else fixed. */
1360
+ function layoutSizing(graph, node, axis) {
1361
+ return layoutSizingInParent(graphParent(graph, node), node, axis);
1362
+ }
1363
+ /** `layoutSizing` for code that holds the parent rather than the graph. */
1364
+ function layoutSizingInParent(parentNode, node, axis) {
1365
+ const parent = fillingParent(parentNode, node);
1366
+ if (parent && fills(parent, node, axis)) return "FILL";
1367
+ if (hugs(node, axis) && (parent || node.layoutMode !== "NONE")) return "HUG";
1368
+ return "FIXED";
1369
+ }
1370
+ /** The sizings this node accepts on either axis, in Figma's order. */
1371
+ function layoutSizingOptions(graph, node) {
1372
+ return [
1373
+ "FIXED",
1374
+ "HUG",
1375
+ "FILL"
1376
+ ].filter((value) => layoutSizingError(graph, node, value) === void 0);
1377
+ }
1378
+ /** Figma's reason for refusing `value` on this node, or `undefined` when it applies. */
1379
+ function layoutSizingError(graph, node, value) {
1380
+ const parent = graphParent(graph, node);
1381
+ const inAutoLayout = parent !== void 0 && parent.layoutMode !== "NONE";
1382
+ if (!inAutoLayout && node.layoutMode === "NONE") return "node must be an auto-layout frame or a child of an auto-layout frame";
1383
+ if (value === "FILL") {
1384
+ if (!inAutoLayout) return "FILL can only be set on children of auto-layout frames";
1385
+ if (node.layoutPositioning === "ABSOLUTE") return "FILL cannot be set on absolute positioned auto-layout children";
1386
+ }
1387
+ if (value === "HUG" && node.layoutMode === "NONE" && node.type !== "TEXT") return "HUG can only be set on auto-layout frames or text children of auto-layout frames";
1388
+ }
1389
+ /** The text auto-resize that hugs the content along the axes given. */
1390
+ function textAutoResizeFor(hugsWidth, hugsHeight) {
1391
+ if (hugsWidth && hugsHeight) return "WIDTH_AND_HEIGHT";
1392
+ return hugsHeight ? "HEIGHT" : "NONE";
1393
+ }
1394
+ function textSizingUpdates(graph, node, axis, value) {
1395
+ const other = axis === "HORIZONTAL" ? "VERTICAL" : "HORIZONTAL";
1396
+ const hugsAxis = value === "HUG";
1397
+ const hugsOther = layoutSizing(graph, node, other) === "HUG";
1398
+ const autoResize = axis === "HORIZONTAL" ? textAutoResizeFor(hugsAxis, hugsOther) : textAutoResizeFor(hugsOther, hugsAxis);
1399
+ if (autoResize === "NONE" && node.textAutoResize === "TRUNCATE") return {};
1400
+ return autoResize === node.textAutoResize ? {} : { textAutoResize: autoResize };
1401
+ }
1402
+ /**
1403
+ * The fields that set the node's sizing along `axis` to `value`, as Figma's setter writes
1404
+ * them. A value Figma refuses yields no updates; `layoutSizingError` says why.
1405
+ */
1406
+ function layoutSizingUpdates(graph, node, axis, value) {
1407
+ if (layoutSizingError(graph, node, value) !== void 0) return {};
1408
+ const updates = {};
1409
+ const parent = fillingParent(graphParent(graph, node), node);
1410
+ if (parent && parent.layoutMode !== "NONE") {
1411
+ const fill = value === "FILL";
1412
+ if (axis === primaryAxis(parent.layoutMode)) {
1413
+ if (fill !== node.layoutGrow > 0) updates.layoutGrow = fill ? 1 : 0;
1414
+ } else if (fill && node.layoutAlignSelf !== "STRETCH") updates.layoutAlignSelf = "STRETCH";
1415
+ else if (!fill && fills(parent, node, axis)) updates.layoutAlignSelf = parent.layoutMode !== "GRID" && parent.counterAxisAlign === "STRETCH" ? "MIN" : "AUTO";
1416
+ }
1417
+ const field = ownSizingField(node, axis);
1418
+ if (field) {
1419
+ const own = value === "HUG" ? "HUG" : "FIXED";
1420
+ if (node[field] !== own) updates[field] = own;
1421
+ }
1422
+ if (node.type === "TEXT") Object.assign(updates, textSizingUpdates(graph, node, axis, value));
1423
+ return updates;
1424
+ }
1425
+ /**
1426
+ * The fields that make a child fill `axis` of a parent laid out as `parentLayout`, for a node
1427
+ * an importer builds before it joins the graph. Under a parent without auto layout, such as a
1428
+ * staging parent the node leaves when placed, both are set, so it fills whichever axis its
1429
+ * eventual parent stacks along.
1430
+ */
1431
+ function fillSizingFields(parentLayout, axis) {
1432
+ if (parentLayout === "NONE") return {
1433
+ layoutGrow: 1,
1434
+ layoutAlignSelf: "STRETCH"
1435
+ };
1436
+ return axis === primaryAxis(parentLayout) ? { layoutGrow: 1 } : { layoutAlignSelf: "STRETCH" };
1437
+ }
1438
+ /** An auto-layout frame's own sizing when it hugs or fixes its width and height. */
1439
+ function autoLayoutSizingFields(direction, width, height) {
1440
+ const horizontal = primaryAxis(direction) === "HORIZONTAL";
1441
+ return {
1442
+ primaryAxisSizing: horizontal ? width : height,
1443
+ counterAxisSizing: horizontal ? height : width
1444
+ };
1445
+ }
1446
+ //#endregion
1447
+ //#region src/text/lists.ts
1448
+ /** The marker of an unordered item, at every level. */
1449
+ const LIST_BULLET = "•";
1450
+ const NUMBER_FORMATS = [
1451
+ "DECIMAL",
1452
+ "LOWER_ALPHA",
1453
+ "LOWER_ROMAN"
1454
+ ];
1455
+ /** Ordered items count in decimal, then letters, then roman numerals, repeating as they nest. */
1456
+ function listNumberFormat(level) {
1457
+ return NUMBER_FORMATS[(Math.max(1, level) - 1) % NUMBER_FORMATS.length];
1458
+ }
1459
+ function alphabetic(value) {
1460
+ let letters = "";
1461
+ for (let rest = value; rest > 0; rest = Math.floor((rest - 1) / 26)) letters = String.fromCharCode(97 + (rest - 1) % 26) + letters;
1462
+ return letters;
1463
+ }
1464
+ const ROMAN_DIGITS = [
1465
+ [1e3, "m"],
1466
+ [900, "cm"],
1467
+ [500, "d"],
1468
+ [400, "cd"],
1469
+ [100, "c"],
1470
+ [90, "xc"],
1471
+ [50, "l"],
1472
+ [40, "xl"],
1473
+ [10, "x"],
1474
+ [9, "ix"],
1475
+ [5, "v"],
1476
+ [4, "iv"],
1477
+ [1, "i"]
1478
+ ];
1479
+ function roman(value) {
1480
+ let rest = value;
1481
+ let numeral = "";
1482
+ for (const [amount, digits] of ROMAN_DIGITS) for (; rest >= amount; rest -= amount) numeral += digits;
1483
+ return numeral;
678
1484
  }
679
- function resolveVariable(graph, variableId, modeId, visited) {
680
- if (visited?.has(variableId)) return void 0;
681
- const variable = graph.variables.get(variableId);
682
- if (!variable) return void 0;
683
- const collection = graph.variableCollections.get(variable.collectionId);
684
- const preferredModeId = modeId ?? getActiveModeId(graph, variable.collectionId);
685
- const fallbackModeId = collection?.defaultModeId;
686
- let value = Object.hasOwn(variable.valuesByMode, preferredModeId) ? variable.valuesByMode[preferredModeId] : void 0;
687
- if (value === void 0 && fallbackModeId && Object.hasOwn(variable.valuesByMode, fallbackModeId)) value = variable.valuesByMode[fallbackModeId];
688
- value ??= Object.values(variable.valuesByMode)[0];
689
- if (value && typeof value === "object" && "aliasId" in value) {
690
- const seen = visited ?? /* @__PURE__ */ new Set();
691
- seen.add(variableId);
692
- return resolveVariable(graph, value.aliasId, preferredModeId, seen);
1485
+ /** An ordered item's number as its level writes it, without the period. */
1486
+ function formatListNumber(ordinal, format) {
1487
+ if (format === "LOWER_ALPHA") return alphabetic(ordinal);
1488
+ if (format === "LOWER_ROMAN") return roman(ordinal);
1489
+ return String(ordinal);
1490
+ }
1491
+ /**
1492
+ * The list items of a text, numbered as Figma numbers them: each level counts its own items,
1493
+ * a deeper item leaves the count above it running, a shallower one restarts the counts below
1494
+ * it, and a plain paragraph or an item of the other list type restarts the count.
1495
+ */
1496
+ function textListItems(text, paragraphs) {
1497
+ if (!paragraphs.some((paragraph) => paragraph.listType !== "NONE")) return [];
1498
+ const items = [];
1499
+ const counts = [];
1500
+ let groupStart = -1;
1501
+ for (const [paragraph, range] of textParagraphRanges(text).entries()) {
1502
+ const style = paragraphStyleAt(paragraphs, paragraph);
1503
+ if (style.listType === "NONE") {
1504
+ counts.length = 0;
1505
+ groupStart = -1;
1506
+ continue;
1507
+ }
1508
+ const level = Math.max(1, style.indentation);
1509
+ counts.length = Math.min(counts.length, level);
1510
+ const current = counts[level - 1];
1511
+ const continues = current?.listType === style.listType;
1512
+ const count = continues ? current.count + 1 : 1;
1513
+ counts[level - 1] = {
1514
+ listType: style.listType,
1515
+ count
1516
+ };
1517
+ const shallower = counts.slice(0, level - 1).some((entry) => entry !== void 0);
1518
+ if (groupStart === -1 || !continues && !shallower) groupStart = paragraph;
1519
+ const marker = style.listType === "UNORDERED" ? "•" : `${formatListNumber(count, listNumberFormat(level))}.`;
1520
+ items.push({
1521
+ ...range,
1522
+ paragraph,
1523
+ listType: style.listType,
1524
+ level,
1525
+ ordinal: count,
1526
+ marker,
1527
+ startsList: !continues,
1528
+ groupStart
1529
+ });
693
1530
  }
694
- return value;
1531
+ return items;
695
1532
  }
696
- function resolveColorVariable(graph, variableId) {
697
- const value = resolveVariable(graph, variableId);
698
- if (value && typeof value === "object" && "r" in value) return value;
1533
+ /**
1534
+ * Digits in the largest number of a top-level ordered item. Figma widens the indent of every
1535
+ * ordered item by the extra digits, so a list's numbers line up past nine.
1536
+ */
1537
+ function topLevelNumberDigits(items) {
1538
+ let largest = 0;
1539
+ for (const item of items) if (item.listType === "ORDERED" && item.level === 1) largest = Math.max(largest, item.ordinal);
1540
+ return largest === 0 ? 0 : String(largest).length;
699
1541
  }
700
- function resolveNumberVariable(graph, variableId) {
701
- const value = resolveVariable(graph, variableId);
702
- return typeof value === "number" ? value : void 0;
1542
+ //#endregion
1543
+ //#region src/shared-styles.ts
1544
+ const STYLE_REF_KEYS = {
1545
+ fill: "fillStyleId",
1546
+ stroke: "strokeStyleId",
1547
+ text: "textStyleId",
1548
+ effect: "effectStyleId",
1549
+ grid: "gridStyleId"
1550
+ };
1551
+ const STYLE_TYPES = {
1552
+ fill: "FILL",
1553
+ stroke: "FILL",
1554
+ text: "TEXT",
1555
+ effect: "EFFECT",
1556
+ grid: "GRID"
1557
+ };
1558
+ const TEXT_STYLE_KEYS = /* @__PURE__ */ new Set([
1559
+ "fontFamily",
1560
+ "fontWeight",
1561
+ "italic",
1562
+ "fontSize",
1563
+ "lineHeight",
1564
+ "letterSpacing",
1565
+ "textDecoration",
1566
+ "textCase",
1567
+ "fontFeatures"
1568
+ ]);
1569
+ function sharedStyleRefKey(kind) {
1570
+ return STYLE_REF_KEYS[kind];
703
1571
  }
704
- function resolveColorVariableForNode(graph, nodeId, variableId) {
705
- const variable = graph.variables.get(variableId);
706
- if (!variable) return void 0;
707
- const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId));
708
- if (value && typeof value === "object" && "r" in value) return value;
1572
+ function sharedStyleTypeForKind(kind) {
1573
+ return STYLE_TYPES[kind];
709
1574
  }
710
- function resolveNumberVariableForNode(graph, nodeId, variableId) {
711
- const variable = graph.variables.get(variableId);
712
- if (!variable) return void 0;
713
- const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId));
714
- return typeof value === "number" ? value : void 0;
1575
+ function getSharedStyles(graph, kind) {
1576
+ const type = sharedStyleTypeForKind(kind);
1577
+ const styles = [];
1578
+ for (const node of graph.getAllNodes()) {
1579
+ if (node.sharedStyleType !== type || !node.source.id) continue;
1580
+ styles.push({
1581
+ id: node.source.id,
1582
+ nodeId: node.id,
1583
+ name: node.name,
1584
+ type
1585
+ });
1586
+ }
1587
+ return styles.sort((left, right) => left.name.localeCompare(right.name));
715
1588
  }
716
- function getVariablesForCollection(graph, collectionId) {
717
- const collection = graph.variableCollections.get(collectionId);
718
- if (!collection) return [];
719
- return collection.variableIds.map((id) => graph.variables.get(id)).filter((v) => v !== void 0);
1589
+ function styleDetachmentChanges(node, changes) {
1590
+ const next = { ...changes };
1591
+ if ("fills" in changes && !("fillStyleId" in changes) && node.fillStyleId) next.fillStyleId = null;
1592
+ if ("strokes" in changes && !("strokeStyleId" in changes) && node.strokeStyleId) next.strokeStyleId = null;
1593
+ if ("effects" in changes && !("effectStyleId" in changes) && node.effectStyleId) next.effectStyleId = null;
1594
+ if ("layoutGrids" in changes && !("gridStyleId" in changes) && node.gridStyleId) next.gridStyleId = null;
1595
+ if (Object.keys(changes).some((key) => TEXT_STYLE_KEYS.has(key)) && !("textStyleId" in changes) && node.textStyleId) next.textStyleId = null;
1596
+ return next;
720
1597
  }
721
- function getVariablesByType(graph, type) {
722
- return [...graph.variables.values()].filter((v) => v.type === type);
1598
+ //#endregion
1599
+ //#region src/text/picture.ts
1600
+ /**
1601
+ * Invalidate cached Skia textPicture (Paragraph snapshot). Includes width/height
1602
+ * because wrapping/layout depends on the box.
1603
+ */
1604
+ const TEXT_PICTURE_KEYS = /* @__PURE__ */ new Set([
1605
+ ...TEXT_SHAPING_FIELDS,
1606
+ "textDecoration",
1607
+ "fills",
1608
+ "width",
1609
+ "height"
1610
+ ]);
1611
+ const GLYPH_AFFECTING_KEYS = new Set(TEXT_SHAPING_FIELDS);
1612
+ /**
1613
+ * Shared by SceneGraph.updateNode and updateNodePreview (drag hot path) so the
1614
+ * two invalidation rules cannot drift. Glyphs are kept when the caller
1615
+ * replaces them in the same update (resize supplies scaled copies).
1616
+ */
1617
+ function textCacheInvalidationChanges(node, changes) {
1618
+ const invalidated = {};
1619
+ const keys = Object.keys(changes).filter((key) => !isEqual(node[key], changes[key]));
1620
+ if (node.textPicture && keys.some((key) => TEXT_PICTURE_KEYS.has(key))) invalidated.textPicture = null;
1621
+ const glyphsInvalidated = keys.some((key) => GLYPH_AFFECTING_KEYS.has(key)) || TEXT_LAYOUT_FIELDS.some((key) => keys.includes(key));
1622
+ if (glyphsInvalidated && !("derivedLayout" in changes)) invalidated.derivedLayout = null;
1623
+ if (node.derivedTextGlyphs && glyphsInvalidated && !changes.derivedTextGlyphs) {
1624
+ if (!(!!node.textPathData && keys.every((key) => key === "width" || key === "height"))) {
1625
+ invalidated.derivedTextGlyphs = null;
1626
+ invalidated.textPathData = null;
1627
+ }
1628
+ }
1629
+ return invalidated;
723
1630
  }
724
- const SCALAR_BINDING_FIELDS = /* @__PURE__ */ new Set([
725
- "opacity",
1631
+ function invalidateTextCaches(node, changes) {
1632
+ Object.assign(node, textCacheInvalidationChanges(node, changes));
1633
+ }
1634
+ //#endregion
1635
+ //#region src/preview.ts
1636
+ const LAYOUT_AFFECTING_KEYS = /* @__PURE__ */ new Set([
1637
+ "x",
1638
+ "y",
726
1639
  "width",
727
1640
  "height",
728
- "cornerRadius",
729
- "fontSize",
730
- "letterSpacing",
731
- "lineHeight",
1641
+ "rotation",
1642
+ "flipX",
1643
+ "flipY",
1644
+ "parentId",
1645
+ "childIds",
1646
+ "layoutMode",
1647
+ "layoutDirection",
1648
+ "layoutWrap",
1649
+ "primaryAxisSizing",
1650
+ "counterAxisSizing",
732
1651
  "itemSpacing",
733
- "strokeWeight",
734
- "paddingLeft",
735
- "paddingRight",
1652
+ "counterAxisSpacing",
736
1653
  "paddingTop",
1654
+ "paddingRight",
737
1655
  "paddingBottom",
738
- "counterAxisSpacing",
739
- "topLeftRadius",
740
- "topRightRadius",
741
- "bottomLeftRadius",
742
- "bottomRightRadius",
743
- "rotation",
744
- "x",
745
- "y",
1656
+ "paddingLeft",
1657
+ "layoutGrow",
1658
+ "layoutAlignSelf",
1659
+ "layoutPositioning",
746
1660
  "minWidth",
747
1661
  "maxWidth",
748
1662
  "minHeight",
749
1663
  "maxHeight",
750
- "borderTopWeight",
751
- "borderBottomWeight",
752
- "borderLeftWeight",
753
- "borderRightWeight",
754
- "gridRowGap",
755
- "gridColumnGap"
1664
+ "visible",
1665
+ "text",
1666
+ "fontSize",
1667
+ "lineHeight",
1668
+ "letterSpacing",
1669
+ "styleRuns",
1670
+ "textAutoResize"
756
1671
  ]);
757
- const STRING_BINDING_FIELDS = /* @__PURE__ */ new Set(["fontFamily"]);
758
- const BOOLEAN_BINDING_FIELDS = /* @__PURE__ */ new Set(["visible"]);
759
- function bindVariable(graph, nodeId, field, variableId) {
760
- const node = graph.nodes.get(nodeId);
761
- if (!node) return;
762
- const variable = graph.variables.get(variableId);
763
- if (!variable) throw new Error(`Variable "${variableId}" not found`);
764
- const colorFieldMatch = field.match(/^(fills|strokes)\/(\d+)\/color$/);
765
- if (colorFieldMatch) {
766
- if (variable.type !== "COLOR") throw new Error(`Cannot bind ${variable.type} variable to color field "${field}"`);
767
- const arrayKey = colorFieldMatch[1];
768
- const index = Number.parseInt(colorFieldMatch[2], 10);
769
- const currentLength = node[arrayKey]?.length ?? 0;
770
- if (index >= currentLength) throw new Error(`Index ${index} out of range for ${arrayKey} (length ${currentLength})`);
771
- const topLevelKey = colorFieldMatch[1];
772
- if (topLevelKey in node.boundVariables) node.boundVariables = omit(node.boundVariables, [topLevelKey]);
773
- }
774
- if (SCALAR_BINDING_FIELDS.has(field) && variable.type !== "FLOAT") throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`);
775
- if (STRING_BINDING_FIELDS.has(field) && variable.type !== "STRING") throw new Error(`Cannot bind ${variable.type} variable to string field "${field}"`);
776
- if (BOOLEAN_BINDING_FIELDS.has(field) && variable.type !== "BOOLEAN") throw new Error(`Cannot bind ${variable.type} variable to boolean field "${field}"`);
777
- if (!(SCALAR_BINDING_FIELDS.has(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || colorFieldMatch)) throw new Error(`Unknown binding field "${field}"`);
778
- node.boundVariables = {
779
- ...node.boundVariables,
780
- [field]: variableId
1672
+ function updateNodePreview(graph, id, changes, beforeUpdate) {
1673
+ const node = graph.nodes.get(id);
1674
+ if (!node) return null;
1675
+ changes = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== void 0));
1676
+ if (Object.keys(changes).every((key) => node[key] === changes[key])) return null;
1677
+ if (Object.keys(changes).some((key) => LAYOUT_AFFECTING_KEYS.has(key))) graph.clearAbsPosCache();
1678
+ let normalizedChanges = changes;
1679
+ if (node.type === "TEXT") normalizedChanges = {
1680
+ ...textCacheInvalidationChanges(node, changes),
1681
+ ...changes
781
1682
  };
782
- graph.emitter.emit("node:updated", nodeId, { boundVariables: { ...node.boundVariables } });
783
- markBoundVariablesOverrideOnInstance(graph, nodeId);
784
- }
785
- function unbindVariable(graph, nodeId, field) {
786
- const node = graph.nodes.get(nodeId);
787
- if (!node) return;
788
- if (!(field in node.boundVariables)) return;
789
- node.boundVariables = omit(node.boundVariables, [field]);
790
- graph.emitter.emit("node:updated", nodeId, { boundVariables: { ...node.boundVariables } });
791
- markBoundVariablesOverrideOnInstance(graph, nodeId);
1683
+ if (changes.vectorNetwork) normalizedChanges = {
1684
+ ...normalizedChanges,
1685
+ vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
1686
+ };
1687
+ beforeUpdate?.(node, normalizedChanges);
1688
+ graph.positionPreviewVersion++;
1689
+ Object.assign(node, normalizedChanges);
1690
+ return normalizedChanges;
792
1691
  }
793
- function markBoundVariablesOverrideOnInstance(graph, nodeId) {
794
- const node = graph.nodes.get(nodeId);
795
- if (!node) return;
796
- if (node.type === "INSTANCE") {
797
- setInstanceOverride(node.instanceOverrides, node.id, node.id, "boundVariables");
798
- return;
799
- }
800
- let current = node;
801
- while (current.parentId) {
802
- const parent = graph.nodes.get(current.parentId);
803
- if (!parent) break;
804
- if (parent.type === "INSTANCE") {
805
- setInstanceOverride(parent.instanceOverrides, parent.id, nodeId, "boundVariables");
806
- break;
807
- }
808
- current = parent;
809
- }
1692
+ //#endregion
1693
+ //#region src/source-metadata.ts
1694
+ function markSourceFieldsEdited(node, changeKeys) {
1695
+ if (changeKeys.length === 0) return;
1696
+ const editedFields = new Set(node.source.editedFields);
1697
+ for (const key of changeKeys) editedFields.add(key);
1698
+ node.source.editedFields = [...editedFields];
810
1699
  }
811
1700
  //#endregion
812
1701
  //#region src/index.ts
1702
+ /** Figma reads both parts of a GUID as signed 32-bit integers and drops records beyond them. */
1703
+ const MAX_ID_SESSION = 2147483647;
1704
+ /** Sessions 0 and 1 hold FIG's document and internal-resource records and counter GUIDs. */
1705
+ const FIRST_RANDOM_SESSION = 2;
1706
+ /** A random session, as Yjs picks each document's `clientID`, so processes never share IDs. */
1707
+ function randomIdSession() {
1708
+ return FIRST_RANDOM_SESSION + randomIndex(2147483646);
1709
+ }
1710
+ let idSession = randomIdSession();
813
1711
  let nextLocalID = 1;
1712
+ /**
1713
+ * Sets the session part of the IDs this process mints, as in Figma's `sessionID:localID` GUIDs.
1714
+ * Every process starts in a random session, so layers that the editor, the CLI, or MCP add to
1715
+ * copies of one file never share IDs. Tests and fixtures that need the same IDs on every run
1716
+ * set a fixed session or give the graph its own generator. Returns the previous session.
1717
+ */
1718
+ function setIdSession(sessionId) {
1719
+ if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > MAX_ID_SESSION) throw new RangeError("sessionId must be a non-negative 31-bit integer");
1720
+ const previous = idSession;
1721
+ idSession = sessionId;
1722
+ return previous;
1723
+ }
814
1724
  function generateId() {
815
- return `0:${nextLocalID++}`;
1725
+ return `${idSession}:${nextLocalID++}`;
816
1726
  }
817
1727
  function stripUndefinedProps(obj) {
818
1728
  const result = {};
@@ -823,6 +1733,7 @@ function stripUndefinedProps(obj) {
823
1733
  return result;
824
1734
  }
825
1735
  var SceneGraph = class SceneGraph {
1736
+ idGenerator;
826
1737
  nodes = /* @__PURE__ */ new Map();
827
1738
  images = /* @__PURE__ */ new Map();
828
1739
  variables = /* @__PURE__ */ new Map();
@@ -834,16 +1745,21 @@ var SceneGraph = class SceneGraph {
834
1745
  figSchemaDeflated = null;
835
1746
  documentColorSpace = "srgb";
836
1747
  enabledLibraries = /* @__PURE__ */ new Map();
837
- emitter = createNanoEvents();
1748
+ emitter = new BufferedSceneEmitter();
838
1749
  absPosCache = /* @__PURE__ */ new Map();
839
1750
  previewMutationDepth = 0;
840
1751
  previewObservers = [];
1752
+ changeObservers = /* @__PURE__ */ new Set();
841
1753
  sourceMetadataPreservationDepth = 0;
1754
+ importedStateApplicationDepth = 0;
1755
+ importedIdGenerator;
842
1756
  layoutMutationDepth = 0;
1757
+ derivedLayoutDepth = 0;
843
1758
  positionPreviewVersion = 0;
844
1759
  instanceIndex = /* @__PURE__ */ new Map();
845
- constructor() {
846
- const root = createDefaultNode(generateId, "FRAME", {
1760
+ constructor(idGenerator = generateId) {
1761
+ this.idGenerator = idGenerator;
1762
+ const root = createDefaultNode(this.idGenerator, "FRAME", {
847
1763
  name: "Document",
848
1764
  width: 0,
849
1765
  height: 0
@@ -871,6 +1787,21 @@ var SceneGraph = class SceneGraph {
871
1787
  onNodeEvents(handlers) {
872
1788
  return bindNodeEvents(this.emitter, handlers);
873
1789
  }
1790
+ /**
1791
+ * Tells `observer` about each node an edit adds and, before it changes, each node it is about
1792
+ * to change, so a recorder can keep the node as it was. Unlike node events these are never
1793
+ * buffered. Graph methods report the nodes they change; code that writes into a node directly
1794
+ * reports it with `willChangeNode` first.
1795
+ */
1796
+ observeNodeChanges(observer) {
1797
+ this.changeObservers.add(observer);
1798
+ return () => this.changeObservers.delete(observer);
1799
+ }
1800
+ /** Tells `observeNodeChanges` observers that `node` is about to change. */
1801
+ willChangeNode(node) {
1802
+ if (!node) return;
1803
+ for (const observer of this.changeObservers) observer.before(node);
1804
+ }
874
1805
  countDescendants(nodeId) {
875
1806
  const node = this.nodes.get(nodeId);
876
1807
  if (!node) return 0;
@@ -895,10 +1826,14 @@ var SceneGraph = class SceneGraph {
895
1826
  addCollection(this, collection);
896
1827
  }
897
1828
  createVariable(name, type, collectionId, value) {
898
- return createVariable(this, generateId, name, type, collectionId, value);
1829
+ return createVariable(this, () => this.generateEntityId(), name, type, collectionId, value);
899
1830
  }
900
1831
  createCollection(name) {
901
- return createCollection(this, generateId, name);
1832
+ const issued = /* @__PURE__ */ new Set();
1833
+ return createCollection(this, () => this.generateEntityId(issued), name);
1834
+ }
1835
+ createMode(collectionId, name, sourceModeId) {
1836
+ return createMode(this, () => this.generateEntityId(), collectionId, name, sourceModeId);
902
1837
  }
903
1838
  removeCollection(id) {
904
1839
  removeCollection(this, id);
@@ -933,11 +1868,17 @@ var SceneGraph = class SceneGraph {
933
1868
  resolveNumberVariable(variableId) {
934
1869
  return resolveNumberVariable(this, variableId);
935
1870
  }
936
- resolveColorVariableForNode(nodeId, variableId) {
937
- return resolveColorVariableForNode(this, nodeId, variableId);
1871
+ resolveColorVariableForNode(nodeId, variableId, fallback) {
1872
+ return resolveColorVariableForNode(this, nodeId, variableId, fallback);
938
1873
  }
939
- resolveNumberVariableForNode(nodeId, variableId) {
940
- return resolveNumberVariableForNode(this, nodeId, variableId);
1874
+ resolveNumberVariableForNode(nodeId, variableId, fallback) {
1875
+ return resolveNumberVariableForNode(this, nodeId, variableId, fallback);
1876
+ }
1877
+ resolveVariableForNode(nodeId, variableId, fallback) {
1878
+ return resolveVariableForNode(this, nodeId, variableId, fallback);
1879
+ }
1880
+ resolveStringVariableForNode(nodeId, variableId, fallback) {
1881
+ return resolveStringVariableForNode(this, nodeId, variableId, fallback);
941
1882
  }
942
1883
  getVariablesForCollection(collectionId) {
943
1884
  return getVariablesForCollection(this, collectionId);
@@ -961,12 +1902,25 @@ var SceneGraph = class SceneGraph {
961
1902
  return node ? CONTAINER_TYPES.has(node.type) : false;
962
1903
  }
963
1904
  isDescendant(childId, ancestorId) {
964
- let current = this.nodes.get(childId);
965
- while (current) {
966
- if (current.id === ancestorId) return true;
1905
+ return this.closest(childId, (node) => node.id === ancestorId) !== void 0;
1906
+ }
1907
+ /**
1908
+ * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes
1909
+ * as the graph holds, so a parent cycle in bad data cannot hang it.
1910
+ */
1911
+ closest(id, match) {
1912
+ let current = this.nodes.get(id);
1913
+ for (let steps = 0; current && steps < this.nodes.size; steps++) {
1914
+ if (match(current)) return current;
967
1915
  current = current.parentId ? this.nodes.get(current.parentId) : void 0;
968
1916
  }
969
- return false;
1917
+ }
1918
+ /**
1919
+ * The page a node is on: the node itself for a page, its nearest page ancestor otherwise, and
1920
+ * null for the document root or a node on no page.
1921
+ */
1922
+ pageOf(id) {
1923
+ return this.closest(id, (node) => node.type === "CANVAS")?.id ?? null;
970
1924
  }
971
1925
  clearAbsPosCache() {
972
1926
  this.absPosCache.clear();
@@ -993,14 +1947,38 @@ var SceneGraph = class SceneGraph {
993
1947
  height: node?.height ?? 0
994
1948
  };
995
1949
  }
996
- generateNodeId() {
997
- let id = generateId();
998
- while (this.nodes.has(id)) id = generateId();
999
- return id;
1950
+ /**
1951
+ * An ID no entity uses; `issued` also excludes IDs handed out earlier in the same creation.
1952
+ * A generator that returns more taken IDs than the graph holds must be repeating itself, so
1953
+ * it counts as exhausted then; a fixed cap would reject a sequence walking past a large import.
1954
+ */
1955
+ generateEntityId(issued) {
1956
+ let limit = Infinity;
1957
+ for (let attempt = 0; attempt < limit; attempt++) {
1958
+ const id = (this.importedIdGenerator ?? this.idGenerator)();
1959
+ if (this.isEntityIdTaken(id) || issued?.has(id)) {
1960
+ if (limit === Infinity) limit = this.entityIdCount() + (issued?.size ?? 0) + 1;
1961
+ continue;
1962
+ }
1963
+ issued?.add(id);
1964
+ return id;
1965
+ }
1966
+ throw new Error("The ID generator only returned IDs that are in use");
1967
+ }
1968
+ entityIdCount() {
1969
+ let count = this.nodes.size + this.variables.size + this.variableCollections.size;
1970
+ for (const collection of this.variableCollections.values()) count += collection.modes.length;
1971
+ return count;
1972
+ }
1973
+ isEntityIdTaken(id) {
1974
+ if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id)) return true;
1975
+ for (const collection of this.variableCollections.values()) for (const mode of collection.modes) if (mode.modeId === id) return true;
1976
+ return false;
1000
1977
  }
1001
1978
  registerNode(node, parentId) {
1002
1979
  node.parentId = parentId;
1003
1980
  this.nodes.set(node.id, node);
1981
+ for (const observer of this.changeObservers) observer.created(node);
1004
1982
  if (node.type === "INSTANCE" && node.componentId) {
1005
1983
  let set = this.instanceIndex.get(node.componentId);
1006
1984
  if (!set) {
@@ -1012,28 +1990,32 @@ var SceneGraph = class SceneGraph {
1012
1990
  this.emitter.emit("node:created", node);
1013
1991
  return node;
1014
1992
  }
1993
+ /** Publish synchronous graph events only after the supplied mutation succeeds. */
1994
+ withBufferedEvents(action) {
1995
+ return this.emitter.batch(action);
1996
+ }
1015
1997
  createNode(type, parentId, overrides = {}) {
1016
- const node = createDefaultNode(() => this.generateNodeId(), type, overrides);
1017
- this.nodes.get(parentId)?.childIds.push(node.id);
1998
+ const node = createDefaultNode(() => this.generateEntityId(), type, overrides);
1999
+ const parent = this.nodes.get(parentId);
2000
+ this.willChangeNode(parent);
2001
+ parent?.childIds.push(node.id);
1018
2002
  return this.registerNode(node, parentId);
1019
2003
  }
1020
2004
  createNodeWithId(id, type, parentId, overrides = {}) {
1021
2005
  const node = createDefaultNode(() => id, type, overrides);
1022
2006
  node.id = id;
1023
2007
  const parent = parentId ? this.nodes.get(parentId) : void 0;
1024
- if (parent && !parent.childIds.includes(id)) parent.childIds.push(id);
2008
+ if (parent && !parent.childIds.includes(id)) {
2009
+ this.willChangeNode(parent);
2010
+ parent.childIds.push(id);
2011
+ }
1025
2012
  return this.registerNode(node, parentId);
1026
2013
  }
1027
2014
  static TEXT_PICTURE_KEYS = TEXT_PICTURE_KEYS;
1028
2015
  static GLYPH_AFFECTING_KEYS = GLYPH_AFFECTING_KEYS;
1029
2016
  static LAYOUT_AFFECTING_KEYS = /* @__PURE__ */ new Set([
1030
- "x",
1031
- "y",
1032
- "width",
1033
- "height",
1034
- "rotation",
1035
- "flipX",
1036
- "flipY",
2017
+ ...TRANSFORM_FIELDS,
2018
+ ...SIZE_FIELDS,
1037
2019
  "layoutMode",
1038
2020
  "layoutDirection",
1039
2021
  "itemSpacing",
@@ -1062,7 +2044,8 @@ var SceneGraph = class SceneGraph {
1062
2044
  "minWidth",
1063
2045
  "maxWidth",
1064
2046
  "minHeight",
1065
- "maxHeight"
2047
+ "maxHeight",
2048
+ "targetAspectRatio"
1066
2049
  ]);
1067
2050
  runPreviewUpdates(fn, beforeUpdate) {
1068
2051
  this.previewMutationDepth++;
@@ -1077,11 +2060,43 @@ var SceneGraph = class SceneGraph {
1077
2060
  preserveSourceMetadataDuring(fn) {
1078
2061
  this.sourceMetadataPreservationDepth++;
1079
2062
  try {
1080
- fn();
2063
+ return fn();
1081
2064
  } finally {
1082
2065
  this.sourceMetadataPreservationDepth--;
1083
2066
  }
1084
2067
  }
2068
+ get isPreservingSourceMetadata() {
2069
+ return this.sourceMetadataPreservationDepth > 0;
2070
+ }
2071
+ applyImportedStateDuring(fn, idGenerator) {
2072
+ const previousGenerator = this.importedIdGenerator;
2073
+ this.importedIdGenerator = idGenerator ?? previousGenerator;
2074
+ this.importedStateApplicationDepth++;
2075
+ try {
2076
+ return this.preserveSourceMetadataDuring(fn);
2077
+ } finally {
2078
+ this.importedStateApplicationDepth--;
2079
+ this.importedIdGenerator = previousGenerator;
2080
+ }
2081
+ }
2082
+ get isApplyingImportedState() {
2083
+ return this.importedStateApplicationDepth > 0;
2084
+ }
2085
+ /**
2086
+ * Lays out what the document already holds: a page as it loads, or again once its fonts
2087
+ * arrive. What this writes derives from the document; an edit's own layout is not this.
2088
+ */
2089
+ applyDerivedLayoutDuring(fn) {
2090
+ this.derivedLayoutDepth++;
2091
+ try {
2092
+ fn();
2093
+ } finally {
2094
+ this.derivedLayoutDepth--;
2095
+ }
2096
+ }
2097
+ get isApplyingDerivedLayout() {
2098
+ return this.derivedLayoutDepth > 0;
2099
+ }
1085
2100
  withLayoutMutations(fn) {
1086
2101
  this.layoutMutationDepth++;
1087
2102
  try {
@@ -1122,6 +2137,7 @@ var SceneGraph = class SceneGraph {
1122
2137
  }
1123
2138
  applyNodeChanges(node, changes, absent = []) {
1124
2139
  const { id } = node;
2140
+ this.willChangeNode(node);
1125
2141
  if (absent.length) {
1126
2142
  changes = { ...changes };
1127
2143
  for (const key of absent) Reflect.set(changes, key, void 0);
@@ -1139,7 +2155,7 @@ var SceneGraph = class SceneGraph {
1139
2155
  }
1140
2156
  }
1141
2157
  if (node.type === "TEXT") invalidateTextCaches(node, changes);
1142
- if (this.sourceMetadataPreservationDepth === 0) markSourceFieldsEdited(node, Object.keys(changes));
2158
+ if (this.sourceMetadataPreservationDepth === 0 && !this.isApplyingLayout) markSourceFieldsEdited(node, Object.keys(changes));
1143
2159
  if (changes.vectorNetwork) changes = {
1144
2160
  ...changes,
1145
2161
  vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
@@ -1159,20 +2175,28 @@ var SceneGraph = class SceneGraph {
1159
2175
  if (!newParent) return;
1160
2176
  if (node.parentId === newParentId) return;
1161
2177
  const oldParentId = node.parentId;
2178
+ this.willChangeNode(node);
2179
+ this.willChangeNode(oldParent);
2180
+ this.willChangeNode(newParent);
1162
2181
  this.absPosCache.clear();
1163
- const absPos = this.getAbsolutePosition(nodeId);
1164
- const newParentNode = this.nodes.get(newParentId);
1165
- const newParentAbs = newParentId === this.rootId || newParentNode?.type === "CANVAS" ? {
1166
- x: 0,
1167
- y: 0
1168
- } : this.getAbsolutePosition(newParentId);
2182
+ const oldParentWorld = this.parentWorldMatrix(oldParent);
2183
+ const newParentWorld = this.parentWorldMatrix(newParent);
1169
2184
  if (oldParent) oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId);
1170
2185
  node.parentId = newParentId;
1171
2186
  newParent.childIds.push(nodeId);
1172
- node.x = absPos.x - newParentAbs.x;
1173
- node.y = absPos.y - newParentAbs.y;
2187
+ if (isTranslationOnly(oldParentWorld) && isTranslationOnly(newParentWorld)) {
2188
+ node.x += oldParentWorld[2] - newParentWorld[2];
2189
+ node.y += oldParentWorld[5] - newParentWorld[5];
2190
+ } else {
2191
+ const world = Matrix.multiply(oldParentWorld, getNodeLocalMatrix(node));
2192
+ const local = localTransformFromWorld(node, world, newParentWorld);
2193
+ if (local) Object.assign(node, local);
2194
+ }
1174
2195
  this.emitter.emit("node:reparented", nodeId, oldParentId, newParentId);
1175
2196
  }
2197
+ parentWorldMatrix(parent) {
2198
+ return getParentWorldMatrix(parent, this);
2199
+ }
1176
2200
  reorderChild(nodeId, parentId, insertIndex) {
1177
2201
  const node = this.nodes.get(nodeId);
1178
2202
  if (!node) return;
@@ -1180,6 +2204,9 @@ var SceneGraph = class SceneGraph {
1180
2204
  const oldParent = previousParentId ? this.nodes.get(previousParentId) : void 0;
1181
2205
  const newParent = this.nodes.get(parentId);
1182
2206
  if (!newParent || this.isDescendant(parentId, nodeId)) return;
2207
+ this.willChangeNode(node);
2208
+ this.willChangeNode(oldParent);
2209
+ this.willChangeNode(newParent);
1183
2210
  if (oldParent) oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId);
1184
2211
  let idx = insertIndex;
1185
2212
  if (oldParent === newParent && idx > (!oldParent.childIds.includes(nodeId) ? idx : oldParent.childIds.length)) {}
@@ -1195,6 +2222,9 @@ var SceneGraph = class SceneGraph {
1195
2222
  if (!node || !newParent || childId === parentId || this.isDescendant(parentId, childId)) return;
1196
2223
  const previousParentId = node.parentId;
1197
2224
  const oldParent = previousParentId ? this.getNode(previousParentId) : void 0;
2225
+ this.willChangeNode(node);
2226
+ this.willChangeNode(oldParent);
2227
+ this.willChangeNode(newParent);
1198
2228
  if (oldParent) oldParent.childIds = oldParent.childIds.filter((id) => id !== childId);
1199
2229
  newParent.childIds = newParent.childIds.filter((id) => id !== childId);
1200
2230
  newParent.childIds.splice(index, 0, childId);
@@ -1205,8 +2235,10 @@ var SceneGraph = class SceneGraph {
1205
2235
  deleteNode(id) {
1206
2236
  const node = this.nodes.get(id);
1207
2237
  if (!node || id === this.rootId) return;
2238
+ this.willChangeNode(node);
1208
2239
  if (node.parentId) {
1209
2240
  const parent = this.nodes.get(node.parentId);
2241
+ this.willChangeNode(parent);
1210
2242
  if (parent) parent.childIds = parent.childIds.filter((cid) => cid !== id);
1211
2243
  }
1212
2244
  for (const childId of Array.from(node.childIds)) this.deleteNode(childId);
@@ -1220,8 +2252,20 @@ var SceneGraph = class SceneGraph {
1220
2252
  hitTestDeep(px, py, scopeId) {
1221
2253
  return hitTestDeep(this, px, py, scopeId);
1222
2254
  }
1223
- hitTestFrame(px, py, excludeIds, scopeId) {
1224
- return hitTestFrame(this, px, py, excludeIds, scopeId);
2255
+ hitTestSelectable(px, py, scopeId, selectedIds) {
2256
+ return hitTestSelectable(this, px, py, scopeId, selectedIds);
2257
+ }
2258
+ hitTestOpenContainer(px, py, scopeId) {
2259
+ return hitTestOpenContainer(this, px, py, scopeId);
2260
+ }
2261
+ isOpenContainer(nodeId) {
2262
+ return isOpenContainer(this, nodeId);
2263
+ }
2264
+ isPointInNode(nodeId, px, py) {
2265
+ return isPointInNode(this, nodeId, px, py);
2266
+ }
2267
+ hitTestDropTarget(px, py, excludeIds, scopeId, options) {
2268
+ return hitTestDropTarget(this, px, py, excludeIds, scopeId, options);
1225
2269
  }
1226
2270
  cloneTree(sourceId, parentId, overrides = {}) {
1227
2271
  const src = this.nodes.get(sourceId);
@@ -1245,12 +2289,18 @@ var SceneGraph = class SceneGraph {
1245
2289
  populateInstanceChildren(instanceId, componentId, mode = "deep") {
1246
2290
  populateInstanceChildren(this, instanceId, componentId, mode);
1247
2291
  }
1248
- swapInstanceComponent(instanceId, componentId) {
1249
- swapInstanceComponent(this, instanceId, componentId);
2292
+ swapInstanceComponent(instanceId, componentId, options) {
2293
+ swapInstanceComponent(this, instanceId, componentId, options);
1250
2294
  }
1251
2295
  syncInstances(componentId) {
1252
2296
  syncInstances(this, componentId);
1253
2297
  }
2298
+ syncInstancesTogether(componentIds) {
2299
+ syncInstancesTogether(this, componentIds);
2300
+ }
2301
+ syncInstance(instanceId) {
2302
+ syncInstance(this, instanceId);
2303
+ }
1254
2304
  detachInstance(instanceId) {
1255
2305
  detachInstance(this, instanceId);
1256
2306
  }
@@ -1278,6 +2328,6 @@ var SceneGraph = class SceneGraph {
1278
2328
  }
1279
2329
  };
1280
2330
  //#endregion
1281
- export { GLYPH_AFFECTING_KEYS, SceneGraph, TEXT_PICTURE_KEYS, UndoManager, addCollection, addMode, addVariable, bindVariable, collectSceneMutation, computeSelectionBounds, computeSnap, createCollection, createSceneMutationImpact, createVariable, generateId, getActiveModeId, getNodeVariableModeId, getSharedStyles, getVariablesByType, getVariablesForCollection, invalidateTextCaches, layoutGuideLines, layoutGuideSections, markSourceFieldsEdited, mutationLayoutScopeIds, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveVariable, setActiveMode, setDefaultMode, sharedStyleRefKey, sharedStyleTypeForKind, styleDetachmentChanges, textCacheInvalidationChanges, unbindVariable, updateNodePreview };
2331
+ export { DEFAULT_SLOT_SETTINGS, GLYPH_AFFECTING_KEYS, LIST_BULLET, ROOT_FONT_SIZE_PX, SceneGraph, TEXT_PICTURE_KEYS, addCollection, addMode, addVariable, applyGraphTransfer, assignVariableBindingUnits, autoLayoutSizingFields, bindVariable, canCreateSlot, captureTransferredState, claimSlotContent, clearSlotContent, collectSceneMutation, computeSelectionBounds, computeSnap, createCollection, createMode, createSceneMutationImpact, createShaderPaint, createSlotProperty, createVariable, fillSizingFields, formatListNumber, generateId, getActiveModeId, getNodeVariableModeId, getSharedStyles, getVariablesByType, getVariablesForCollection, hasShaderPaint, invalidateTextCaches, isPreferredComponent, isShaderFrameCurrent, layoutGuideLines, layoutGuideSections, layoutSizing, layoutSizingError, layoutSizingInParent, layoutSizingOptions, layoutSizingUpdates, listNumberFormat, markSourceFieldsEdited, modesDefaultFirst, mutationLayoutScopeIds, nonPreferredLayers, prepareGraphTransfer, prepareNodeTransfer, prepareVariableTransfer, readShaderPaints, reconcileVariableBindings, recordSceneMutations, removeCollection, removeGraphTransfer, removeMode, removeVariable, renameMode, rescaleNodeTree, resetSlotContent, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolvedNumericBindings, resolvedPaintBindings, resolvedValueBindings, setActiveMode, setDefaultMode, setIdSession, shaderOfPaint, shaderPresetKey, sharedStyleRefKey, sharedStyleTypeForKind, slotLimitViolations, slotOwner, slotScope, styleDetachmentChanges, textAutoResizeFor, textCacheInvalidationChanges, textListItems, tokenNumberFromUnit, tokenNumberInUnit, topLevelNumberDigits, unbindVariable, updateNodePreview, updateSlotProperty, variableBindingOwner, variablesResolvingThrough, withShaderPaints };
1282
2332
 
1283
2333
  //# sourceMappingURL=index.js.map