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

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