@open-pencil/scene-graph 0.13.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 (91) hide show
  1. package/README.md +5 -0
  2. package/dist/chunks/bindings.js +18 -0
  3. package/dist/chunks/bindings.js.map +1 -0
  4. package/dist/chunks/coordinate.js +293 -0
  5. package/dist/chunks/coordinate.js.map +1 -0
  6. package/dist/chunks/copy.js +576 -0
  7. package/dist/chunks/copy.js.map +1 -0
  8. package/dist/chunks/events.js +18 -0
  9. package/dist/chunks/events.js.map +1 -0
  10. package/dist/chunks/export-scale.js +19 -0
  11. package/dist/chunks/export-scale.js.map +1 -0
  12. package/dist/chunks/font-style.js +95 -0
  13. package/dist/chunks/font-style.js.map +1 -0
  14. package/dist/constants.d.ts +2 -0
  15. package/dist/constants.js +19 -0
  16. package/dist/constants.js.map +1 -0
  17. package/dist/constants2.d.ts +10 -0
  18. package/dist/constants2.d.ts.map +1 -0
  19. package/dist/coordinate.d.ts +352 -0
  20. package/dist/coordinate.d.ts.map +1 -0
  21. package/dist/coordinate.js +2 -0
  22. package/dist/coordinate2.d.ts +2 -0
  23. package/dist/copy.d.ts +2 -0
  24. package/dist/copy.js +2 -0
  25. package/dist/geometry.d.ts +2 -0
  26. package/dist/geometry.js +431 -0
  27. package/dist/geometry.js.map +1 -0
  28. package/dist/hit-test.d.ts +10 -0
  29. package/dist/hit-test.d.ts.map +1 -0
  30. package/dist/hit-test.js +97 -0
  31. package/dist/hit-test.js.map +1 -0
  32. package/dist/images.d.ts +2 -0
  33. package/dist/images.js +45 -0
  34. package/dist/images.js.map +1 -0
  35. package/dist/images2.d.ts +5 -0
  36. package/dist/images2.d.ts.map +1 -0
  37. package/dist/index.d.ts +9 -0
  38. package/dist/index.js +9 -0
  39. package/dist/instances.d.ts +2 -0
  40. package/dist/instances.js +2 -0
  41. package/dist/matrix.d.ts +2 -0
  42. package/dist/matrix.js +2 -0
  43. package/dist/matrix2.d.ts +17 -0
  44. package/dist/matrix2.d.ts.map +1 -0
  45. package/dist/node-defaults.d.ts +9 -0
  46. package/dist/node-defaults.d.ts.map +1 -0
  47. package/dist/node-defaults.js +2 -0
  48. package/dist/parse-path.d.ts +23 -0
  49. package/dist/parse-path.d.ts.map +1 -0
  50. package/dist/parse-path.js +159 -0
  51. package/dist/parse-path.js.map +1 -0
  52. package/dist/preview.d.ts +12 -0
  53. package/dist/preview.d.ts.map +1 -0
  54. package/dist/preview.js +2 -0
  55. package/dist/primitives.d.ts +2 -0
  56. package/dist/primitives.js +0 -0
  57. package/dist/primitives2.d.ts +42 -0
  58. package/dist/primitives2.d.ts.map +1 -0
  59. package/dist/resize.d.ts +16 -0
  60. package/dist/resize.d.ts.map +1 -0
  61. package/dist/resize.js +136 -0
  62. package/dist/resize.js.map +1 -0
  63. package/dist/snap.d.ts +2 -0
  64. package/dist/snap.js +2 -0
  65. package/dist/source-metadata.d.ts +7 -0
  66. package/dist/source-metadata.d.ts.map +1 -0
  67. package/dist/source-metadata.js +2 -0
  68. package/dist/text-picture.d.ts +7 -0
  69. package/dist/text-picture.d.ts.map +1 -0
  70. package/dist/text-picture.js +2 -0
  71. package/dist/types.d.ts +2 -0
  72. package/dist/types.js +1296 -0
  73. package/dist/types.js.map +1 -0
  74. package/dist/types2.d.ts +430 -0
  75. package/dist/types2.d.ts.map +1 -0
  76. package/dist/undo.d.ts +2 -0
  77. package/dist/undo.js +2 -0
  78. package/dist/undo2.d.ts +40 -0
  79. package/dist/undo2.d.ts.map +1 -0
  80. package/dist/variables.d.ts +30 -0
  81. package/dist/variables.d.ts.map +1 -0
  82. package/dist/variables.js +2 -0
  83. package/dist/variant-name.d.ts +6 -0
  84. package/dist/variant-name.d.ts.map +1 -0
  85. package/dist/variant-name.js +17 -0
  86. package/dist/variant-name.js.map +1 -0
  87. package/dist/vector-network.d.ts +2 -0
  88. package/dist/vector-network.js +2 -0
  89. package/dist/vector-network2.d.ts +33 -0
  90. package/dist/vector-network2.d.ts.map +1 -0
  91. package/package.json +157 -0
package/dist/types.js ADDED
@@ -0,0 +1,1296 @@
1
+ import { BLACK } from "./constants.js";
2
+ import { CONTAINER_TYPES, cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns, createDefaultNode, normalizeVectorNetwork } from "./chunks/copy.js";
3
+ import { rotatedBBox } from "./geometry.js";
4
+ import { getAbsolutePosition } from "./chunks/coordinate.js";
5
+ import { removeStaleBindings } from "./chunks/bindings.js";
6
+ import { bindNodeEvents } from "./chunks/events.js";
7
+ import { hitTest, hitTestDeep, hitTestFrame } from "./hit-test.js";
8
+ import { createNanoEvents } from "nanoevents";
9
+ import { omit, omitBy } from "es-toolkit/object";
10
+ //#region src/instances.ts
11
+ const INSTANCE_SYNC_PROPS = [
12
+ "width",
13
+ "height",
14
+ "minWidth",
15
+ "maxWidth",
16
+ "minHeight",
17
+ "maxHeight",
18
+ "fills",
19
+ "strokes",
20
+ "effects",
21
+ "opacity",
22
+ "cornerRadius",
23
+ "topLeftRadius",
24
+ "topRightRadius",
25
+ "bottomRightRadius",
26
+ "bottomLeftRadius",
27
+ "independentCorners",
28
+ "layoutMode",
29
+ "layoutDirection",
30
+ "layoutWrap",
31
+ "primaryAxisAlign",
32
+ "counterAxisAlign",
33
+ "primaryAxisSizing",
34
+ "counterAxisSizing",
35
+ "itemSpacing",
36
+ "counterAxisSpacing",
37
+ "paddingTop",
38
+ "paddingRight",
39
+ "paddingBottom",
40
+ "paddingLeft",
41
+ "gridTemplateColumns",
42
+ "gridTemplateRows",
43
+ "gridColumnGap",
44
+ "gridRowGap",
45
+ "gridPosition",
46
+ "clipsContent",
47
+ "independentStrokeWeights",
48
+ "borderTopWeight",
49
+ "borderRightWeight",
50
+ "borderBottomWeight",
51
+ "borderLeftWeight",
52
+ "boundVariables",
53
+ "variableModes"
54
+ ];
55
+ function setSceneProp(target, key, value) {
56
+ target[key] = value;
57
+ }
58
+ function copyProp(target, source, key) {
59
+ if (key === "fills") setSceneProp(target, key, copyFills(source.fills));
60
+ else if (key === "strokes") setSceneProp(target, key, copyStrokes(source.strokes));
61
+ else if (key === "effects") setSceneProp(target, key, copyEffects(source.effects));
62
+ else if (key === "styleRuns") setSceneProp(target, key, copyStyleRuns(source.styleRuns));
63
+ else if (key === "boundVariables") setSceneProp(target, key, { ...source.boundVariables });
64
+ else if (key === "variableModes") setSceneProp(target, key, { ...source.variableModes });
65
+ else if (key === "gridPosition") setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null);
66
+ else {
67
+ const value = source[key];
68
+ setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value);
69
+ }
70
+ }
71
+ function cloneChildrenWithMapping(graph, sourceParentId, destParentId, mode = "deep") {
72
+ const sourceParent = graph.nodes.get(sourceParentId);
73
+ if (!sourceParent) return;
74
+ for (const childId of sourceParent.childIds) {
75
+ const src = graph.nodes.get(childId);
76
+ if (!src) continue;
77
+ const clone = graph.createNode(src.type, destParentId, cloneNodeProps(src, childId, mode));
78
+ if (src.childIds.length > 0) cloneChildrenWithMapping(graph, childId, clone.id, mode);
79
+ }
80
+ }
81
+ function syncChildren(graph, compParentId, instParentId, overrides) {
82
+ const compParent = graph.nodes.get(compParentId);
83
+ const instParent = graph.nodes.get(instParentId);
84
+ if (!compParent || !instParent) return;
85
+ const instChildMap = /* @__PURE__ */ new Map();
86
+ for (const childId of instParent.childIds) {
87
+ const child = graph.nodes.get(childId);
88
+ if (!child) continue;
89
+ const sourceComponentId = overrides[`${child.id}:sourceComponentId`];
90
+ const mappedComponentId = typeof sourceComponentId === "string" ? sourceComponentId : child.componentId;
91
+ if (mappedComponentId) instChildMap.set(mappedComponentId, child);
92
+ }
93
+ for (const compChildId of compParent.childIds) if (!instChildMap.has(compChildId)) {
94
+ const src = graph.nodes.get(compChildId);
95
+ if (!src) continue;
96
+ const clone = graph.createNode(src.type, instParentId, cloneNodeProps(src, compChildId));
97
+ if (src.childIds.length > 0) cloneChildrenWithMapping(graph, compChildId, clone.id);
98
+ instChildMap.set(compChildId, clone);
99
+ }
100
+ for (const compChildId of compParent.childIds) {
101
+ const compChild = graph.nodes.get(compChildId);
102
+ const instChild = instChildMap.get(compChildId);
103
+ if (!compChild || !instChild) continue;
104
+ for (const key of INSTANCE_SYNC_PROPS) {
105
+ if (`${instChild.id}:${key}` in overrides) continue;
106
+ copyProp(instChild, compChild, key);
107
+ }
108
+ for (const key of [
109
+ "name",
110
+ "text",
111
+ "fontSize",
112
+ "fontWeight",
113
+ "fontFamily",
114
+ "textDirection"
115
+ ]) {
116
+ if (`${instChild.id}:${key}` in overrides) continue;
117
+ copyProp(instChild, compChild, key);
118
+ }
119
+ if (compChild.childIds.length > 0 && !(`${instChild.id}:componentId` in overrides)) syncChildren(graph, compChildId, instChild.id, overrides);
120
+ }
121
+ const compChildOrder = compParent.childIds;
122
+ instParent.childIds.sort((a, b) => {
123
+ const nodeA = graph.nodes.get(a);
124
+ const nodeB = graph.nodes.get(b);
125
+ const sourceA = nodeA ? overrides[`${nodeA.id}:sourceComponentId`] : void 0;
126
+ const sourceB = nodeB ? overrides[`${nodeB.id}:sourceComponentId`] : void 0;
127
+ const mappedA = typeof sourceA === "string" ? sourceA : nodeA?.componentId;
128
+ const mappedB = typeof sourceB === "string" ? sourceB : nodeB?.componentId;
129
+ return (mappedA ? compChildOrder.indexOf(mappedA) : -1) - (mappedB ? compChildOrder.indexOf(mappedB) : -1);
130
+ });
131
+ }
132
+ function copyInstanceComponentProps(component) {
133
+ const props = {};
134
+ for (const key of INSTANCE_SYNC_PROPS) copyProp(props, component, key);
135
+ return props;
136
+ }
137
+ function createInstance(graph, componentId, parentId, overrides = {}) {
138
+ const component = graph.nodes.get(componentId);
139
+ if (component?.type !== "COMPONENT") return null;
140
+ const props = {
141
+ ...copyInstanceComponentProps(component),
142
+ name: component.name,
143
+ componentId
144
+ };
145
+ const instance = graph.createNode("INSTANCE", parentId, {
146
+ ...props,
147
+ ...overrides
148
+ });
149
+ cloneChildrenWithMapping(graph, component.id, instance.id);
150
+ return instance;
151
+ }
152
+ function populateInstanceChildren(graph, instanceId, componentId, mode = "deep") {
153
+ const instance = graph.nodes.get(instanceId);
154
+ const component = graph.nodes.get(componentId);
155
+ if (!instance || !component || instance.type !== "INSTANCE") return;
156
+ cloneChildrenWithMapping(graph, componentId, instanceId, mode);
157
+ }
158
+ function swapInstanceComponent(graph, instanceId, componentId) {
159
+ const instance = graph.nodes.get(instanceId);
160
+ const component = graph.nodes.get(componentId);
161
+ if (!instance || component?.type !== "COMPONENT" || instance.type !== "INSTANCE") return;
162
+ const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : void 0;
163
+ const updates = { componentId };
164
+ for (const key of INSTANCE_SYNC_PROPS) {
165
+ if (key in instance.overrides) continue;
166
+ copyProp(updates, component, key);
167
+ }
168
+ if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name;
169
+ const childIds = Array.from(instance.childIds);
170
+ for (const childId of childIds) graph.deleteNode(childId);
171
+ graph.updateNode(instanceId, updates);
172
+ cloneChildrenWithMapping(graph, componentId, instanceId);
173
+ }
174
+ function syncInstances(graph, componentId) {
175
+ const component = graph.nodes.get(componentId);
176
+ if (component?.type !== "COMPONENT") return;
177
+ for (const instance of getInstances(graph, componentId)) {
178
+ for (const key of INSTANCE_SYNC_PROPS) {
179
+ if (key in instance.overrides) continue;
180
+ copyProp(instance, component, key);
181
+ }
182
+ syncChildren(graph, component.id, instance.id, instance.overrides);
183
+ }
184
+ }
185
+ function detachInstance(graph, instanceId) {
186
+ const node = graph.nodes.get(instanceId);
187
+ if (node?.type !== "INSTANCE") return;
188
+ if (node.componentId) graph.instanceIndex.get(node.componentId)?.delete(instanceId);
189
+ node.type = "FRAME";
190
+ node.componentId = null;
191
+ node.overrides = {};
192
+ }
193
+ function getMainComponent(graph, instanceId) {
194
+ const node = graph.nodes.get(instanceId);
195
+ if (!node?.componentId) return void 0;
196
+ return graph.nodes.get(node.componentId);
197
+ }
198
+ function getInstances(graph, componentId) {
199
+ const ids = graph.instanceIndex.get(componentId);
200
+ if (!ids) return [];
201
+ const instances = [];
202
+ for (const id of ids) {
203
+ const node = graph.nodes.get(id);
204
+ if (node) instances.push(node);
205
+ }
206
+ return instances;
207
+ }
208
+ //#endregion
209
+ //#region src/snap.ts
210
+ const SNAP_THRESHOLD = 5;
211
+ function getEdges(node) {
212
+ return rotatedBBox(node.x, node.y, node.width, node.height, node.rotation);
213
+ }
214
+ function computeSnap(movingIds, movingBounds, allNodes) {
215
+ const targets = allNodes.filter((n) => !movingIds.has(n.id));
216
+ if (targets.length === 0) return {
217
+ dx: 0,
218
+ dy: 0,
219
+ guides: []
220
+ };
221
+ const m = {
222
+ left: movingBounds.x,
223
+ right: movingBounds.x + movingBounds.width,
224
+ centerX: movingBounds.x + movingBounds.width / 2,
225
+ top: movingBounds.y,
226
+ bottom: movingBounds.y + movingBounds.height,
227
+ centerY: movingBounds.y + movingBounds.height / 2
228
+ };
229
+ let bestDx = Infinity;
230
+ let bestDy = Infinity;
231
+ const guides = [];
232
+ for (const target of targets) {
233
+ const t = getEdges(target);
234
+ const xPairs = [
235
+ [m.left, t.left],
236
+ [m.left, t.right],
237
+ [m.right, t.left],
238
+ [m.right, t.right],
239
+ [m.centerX, t.centerX]
240
+ ];
241
+ for (const [mVal, tVal] of xPairs) {
242
+ const d = tVal - mVal;
243
+ if (Math.abs(d) < SNAP_THRESHOLD && Math.abs(d) <= Math.abs(bestDx)) {
244
+ if (Math.abs(d) < Math.abs(bestDx)) {
245
+ bestDx = d;
246
+ guides.length = guides.filter((g) => g.axis === "y").length ? guides.length : guides.length;
247
+ for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "x") guides.splice(i, 1);
248
+ }
249
+ if (Math.abs(d) === Math.abs(bestDx)) {
250
+ const minY = Math.min(m.top, t.top);
251
+ const maxY = Math.max(m.bottom, t.bottom);
252
+ guides.push({
253
+ axis: "x",
254
+ position: tVal,
255
+ from: minY,
256
+ to: maxY
257
+ });
258
+ }
259
+ }
260
+ }
261
+ const yPairs = [
262
+ [m.top, t.top],
263
+ [m.top, t.bottom],
264
+ [m.bottom, t.top],
265
+ [m.bottom, t.bottom],
266
+ [m.centerY, t.centerY]
267
+ ];
268
+ for (const [mVal, tVal] of yPairs) {
269
+ const d = tVal - mVal;
270
+ if (Math.abs(d) < SNAP_THRESHOLD && Math.abs(d) <= Math.abs(bestDy)) {
271
+ if (Math.abs(d) < Math.abs(bestDy)) {
272
+ for (let i = guides.length - 1; i >= 0; i--) if (guides[i].axis === "y") guides.splice(i, 1);
273
+ bestDy = d;
274
+ }
275
+ if (Math.abs(d) === Math.abs(bestDy)) {
276
+ const minX = Math.min(m.left, t.left);
277
+ const maxX = Math.max(m.right, t.right);
278
+ guides.push({
279
+ axis: "y",
280
+ position: tVal,
281
+ from: minX,
282
+ to: maxX
283
+ });
284
+ }
285
+ }
286
+ }
287
+ }
288
+ return {
289
+ dx: Math.abs(bestDx) <= SNAP_THRESHOLD ? bestDx : 0,
290
+ dy: Math.abs(bestDy) <= SNAP_THRESHOLD ? bestDy : 0,
291
+ guides
292
+ };
293
+ }
294
+ function computeSelectionBounds(nodes) {
295
+ if (nodes.length === 0) return null;
296
+ let minX = Infinity;
297
+ let minY = Infinity;
298
+ let maxX = -Infinity;
299
+ let maxY = -Infinity;
300
+ for (const n of nodes) {
301
+ const edges = getEdges(n);
302
+ minX = Math.min(minX, edges.left);
303
+ minY = Math.min(minY, edges.top);
304
+ maxX = Math.max(maxX, edges.right);
305
+ maxY = Math.max(maxY, edges.bottom);
306
+ }
307
+ return {
308
+ x: minX,
309
+ y: minY,
310
+ width: maxX - minX,
311
+ height: maxY - minY
312
+ };
313
+ }
314
+ //#endregion
315
+ //#region src/shared-styles.ts
316
+ const STYLE_REF_KEYS = {
317
+ fill: "fillStyleId",
318
+ stroke: "strokeStyleId",
319
+ text: "textStyleId",
320
+ effect: "effectStyleId",
321
+ grid: "gridStyleId"
322
+ };
323
+ const STYLE_TYPES = {
324
+ fill: "FILL",
325
+ stroke: "FILL",
326
+ text: "TEXT",
327
+ effect: "EFFECT",
328
+ grid: "GRID"
329
+ };
330
+ const TEXT_STYLE_KEYS = /* @__PURE__ */ new Set([
331
+ "fontFamily",
332
+ "fontWeight",
333
+ "italic",
334
+ "fontSize",
335
+ "lineHeight",
336
+ "letterSpacing",
337
+ "textDecoration",
338
+ "textCase",
339
+ "fontFeatures"
340
+ ]);
341
+ function sharedStyleRefKey(kind) {
342
+ return STYLE_REF_KEYS[kind];
343
+ }
344
+ function sharedStyleTypeForKind(kind) {
345
+ return STYLE_TYPES[kind];
346
+ }
347
+ function getSharedStyles(graph, kind) {
348
+ const type = sharedStyleTypeForKind(kind);
349
+ const styles = [];
350
+ for (const node of graph.getAllNodes()) {
351
+ if (node.sharedStyleType !== type || !node.source.id) continue;
352
+ styles.push({
353
+ id: node.source.id,
354
+ nodeId: node.id,
355
+ name: node.name,
356
+ type
357
+ });
358
+ }
359
+ return styles.sort((left, right) => left.name.localeCompare(right.name));
360
+ }
361
+ function styleDetachmentChanges(node, changes) {
362
+ const next = { ...changes };
363
+ if ("fills" in changes && !("fillStyleId" in changes) && node.fillStyleId) next.fillStyleId = null;
364
+ if ("strokes" in changes && !("strokeStyleId" in changes) && node.strokeStyleId) next.strokeStyleId = null;
365
+ if ("effects" in changes && !("effectStyleId" in changes) && node.effectStyleId) next.effectStyleId = null;
366
+ if ("layoutGrids" in changes && !("gridStyleId" in changes) && node.gridStyleId) next.gridStyleId = null;
367
+ if (Object.keys(changes).some((key) => TEXT_STYLE_KEYS.has(key)) && !("textStyleId" in changes) && node.textStyleId) next.textStyleId = null;
368
+ return next;
369
+ }
370
+ //#endregion
371
+ //#region src/undo.ts
372
+ const DEFAULT_HISTORY_LIMIT = 200;
373
+ var UndoManager = class {
374
+ undoStack = [];
375
+ redoStack = [];
376
+ batches = [];
377
+ limit;
378
+ constructor(options = {}) {
379
+ this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT;
380
+ }
381
+ apply(entry) {
382
+ this.execute(entry);
383
+ }
384
+ execute(entry) {
385
+ entry.forward();
386
+ this.record(entry);
387
+ }
388
+ push(entry) {
389
+ this.record(entry);
390
+ }
391
+ record(entry) {
392
+ const batch = this.currentBatch;
393
+ if (batch) {
394
+ batch.entries.push(entry);
395
+ return;
396
+ }
397
+ this.pushUndoEntry(entry);
398
+ }
399
+ undo() {
400
+ const entry = this.undoStack.pop();
401
+ if (!entry) return null;
402
+ entry.inverse();
403
+ this.redoStack.push(entry);
404
+ return entry.label;
405
+ }
406
+ redo() {
407
+ const entry = this.redoStack.pop();
408
+ if (!entry) return null;
409
+ entry.forward();
410
+ this.undoStack.push(entry);
411
+ return entry.label;
412
+ }
413
+ beginBatch(label, coalesceKey) {
414
+ this.batches.push({
415
+ label,
416
+ entries: [],
417
+ coalesceKey
418
+ });
419
+ }
420
+ commitBatch() {
421
+ const batch = this.batches.pop();
422
+ if (!batch || batch.entries.length === 0) return;
423
+ const entry = this.createBatchEntry(batch);
424
+ const parentBatch = this.currentBatch;
425
+ if (parentBatch) parentBatch.entries.push(entry);
426
+ else this.pushUndoEntry(entry);
427
+ }
428
+ runBatch(label, fn, coalesceKey) {
429
+ this.beginBatch(label, coalesceKey);
430
+ try {
431
+ const result = fn();
432
+ this.commitBatch();
433
+ return result;
434
+ } catch (error) {
435
+ this.rollbackBatch();
436
+ throw error;
437
+ }
438
+ }
439
+ rollbackBatch() {
440
+ const batch = this.batches.pop();
441
+ if (!batch) return;
442
+ for (const entry of batch.entries.toReversed()) entry.inverse();
443
+ }
444
+ clear() {
445
+ this.undoStack = [];
446
+ this.redoStack = [];
447
+ this.batches = [];
448
+ }
449
+ get isBatching() {
450
+ return this.batches.length > 0;
451
+ }
452
+ get canUndo() {
453
+ return this.undoStack.length > 0;
454
+ }
455
+ get canRedo() {
456
+ return this.redoStack.length > 0;
457
+ }
458
+ get undoLabel() {
459
+ return this.undoStack.at(-1)?.label ?? null;
460
+ }
461
+ get redoLabel() {
462
+ return this.redoStack.at(-1)?.label ?? null;
463
+ }
464
+ get currentBatch() {
465
+ return this.batches.at(-1) ?? null;
466
+ }
467
+ createBatchEntry(batch) {
468
+ return {
469
+ label: batch.label,
470
+ forward: () => batch.entries.forEach((entry) => entry.forward()),
471
+ inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()),
472
+ coalesceKey: batch.coalesceKey
473
+ };
474
+ }
475
+ pushUndoEntry(entry) {
476
+ const previous = this.undoStack.at(-1);
477
+ if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) this.undoStack[this.undoStack.length - 1] = {
478
+ ...entry,
479
+ inverse: previous.inverse
480
+ };
481
+ else this.undoStack.push(entry);
482
+ this.redoStack = [];
483
+ this.trimUndoStack();
484
+ }
485
+ trimUndoStack() {
486
+ if (!Number.isFinite(this.limit) || this.limit <= 0) return;
487
+ const overflow = this.undoStack.length - this.limit;
488
+ if (overflow > 0) this.undoStack.splice(0, overflow);
489
+ }
490
+ };
491
+ //#endregion
492
+ //#region src/text-picture.ts
493
+ const TEXT_PICTURE_KEYS = /* @__PURE__ */ new Set([
494
+ "text",
495
+ "fontSize",
496
+ "fontFamily",
497
+ "fontWeight",
498
+ "italic",
499
+ "textAlignHorizontal",
500
+ "textDirection",
501
+ "textAlignVertical",
502
+ "lineHeight",
503
+ "letterSpacing",
504
+ "textDecoration",
505
+ "textCase",
506
+ "styleRuns",
507
+ "fills",
508
+ "width",
509
+ "height"
510
+ ]);
511
+ /** Properties that change imported glyph outlines or per-glyph positioning. */
512
+ const GLYPH_AFFECTING_KEYS = /* @__PURE__ */ new Set([
513
+ "text",
514
+ "fontSize",
515
+ "fontFamily",
516
+ "fontWeight",
517
+ "italic",
518
+ "textDirection",
519
+ "lineHeight",
520
+ "letterSpacing",
521
+ "textCase",
522
+ "styleRuns"
523
+ ]);
524
+ //#endregion
525
+ //#region src/preview.ts
526
+ const LAYOUT_AFFECTING_KEYS = /* @__PURE__ */ new Set([
527
+ "x",
528
+ "y",
529
+ "width",
530
+ "height",
531
+ "rotation",
532
+ "parentId",
533
+ "childIds",
534
+ "layoutMode",
535
+ "layoutDirection",
536
+ "layoutWrap",
537
+ "primaryAxisSizing",
538
+ "counterAxisSizing",
539
+ "itemSpacing",
540
+ "counterAxisSpacing",
541
+ "paddingTop",
542
+ "paddingRight",
543
+ "paddingBottom",
544
+ "paddingLeft",
545
+ "layoutGrow",
546
+ "layoutAlignSelf",
547
+ "layoutPositioning",
548
+ "minWidth",
549
+ "maxWidth",
550
+ "minHeight",
551
+ "maxHeight",
552
+ "visible",
553
+ "text",
554
+ "fontSize",
555
+ "lineHeight",
556
+ "letterSpacing",
557
+ "styleRuns",
558
+ "textAutoResize"
559
+ ]);
560
+ function updateNodePreview(graph, id, changes) {
561
+ const node = graph.nodes.get(id);
562
+ if (!node) return null;
563
+ changes = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== void 0));
564
+ if (Object.keys(changes).every((key) => node[key] === changes[key])) return null;
565
+ if (Object.keys(changes).some((key) => LAYOUT_AFFECTING_KEYS.has(key))) graph.clearAbsPosCache();
566
+ if (node.type === "TEXT") {
567
+ const textChanged = Object.keys(changes).some((key) => TEXT_PICTURE_KEYS.has(key));
568
+ if (node.textPicture && textChanged) node.textPicture = null;
569
+ const glyphChanged = Object.keys(changes).some((key) => GLYPH_AFFECTING_KEYS.has(key));
570
+ if (node.figmaDerivedTextGlyphs && glyphChanged) node.figmaDerivedTextGlyphs = null;
571
+ }
572
+ const normalizedChanges = changes.vectorNetwork ? {
573
+ ...changes,
574
+ vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
575
+ } : changes;
576
+ graph.positionPreviewVersion++;
577
+ Object.assign(node, normalizedChanges);
578
+ return normalizedChanges;
579
+ }
580
+ //#endregion
581
+ //#region src/source-metadata.ts
582
+ function markSourceFieldsEdited(node, changeKeys) {
583
+ if (changeKeys.length === 0) return;
584
+ const editedFields = new Set(node.source.editedFields);
585
+ for (const key of changeKeys) editedFields.add(key);
586
+ node.source.editedFields = [...editedFields];
587
+ }
588
+ //#endregion
589
+ //#region src/variables.ts
590
+ function addVariable(graph, variable) {
591
+ graph.variables.set(variable.id, variable);
592
+ const collection = graph.variableCollections.get(variable.collectionId);
593
+ if (collection && !collection.variableIds.includes(variable.id)) collection.variableIds.push(variable.id);
594
+ }
595
+ function removeVariable(graph, id) {
596
+ const variable = graph.variables.get(id);
597
+ if (!variable) return;
598
+ graph.variables.delete(id);
599
+ const collection = graph.variableCollections.get(variable.collectionId);
600
+ if (collection) collection.variableIds = collection.variableIds.filter((vid) => vid !== id);
601
+ for (const node of graph.nodes.values()) {
602
+ if (!Object.values(node.boundVariables).includes(id)) continue;
603
+ node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id);
604
+ graph.emitter.emit("node:updated", node.id, { boundVariables: { ...node.boundVariables } });
605
+ markBoundVariablesOverrideOnInstance(graph, node.id);
606
+ }
607
+ }
608
+ function addCollection(graph, collection) {
609
+ graph.variableCollections.set(collection.id, collection);
610
+ if (!graph.activeMode.has(collection.id)) graph.activeMode.set(collection.id, collection.defaultModeId);
611
+ }
612
+ function defaultVariableValue(type, value) {
613
+ if (value !== void 0) return value;
614
+ if (type === "COLOR") return { ...BLACK };
615
+ if (type === "FLOAT") return 0;
616
+ if (type === "BOOLEAN") return false;
617
+ return "";
618
+ }
619
+ function createVariable(graph, generateId, name, type, collectionId, value) {
620
+ const collection = graph.variableCollections.get(collectionId);
621
+ if (!collection) throw new Error(`Collection "${collectionId}" not found`);
622
+ const id = generateId();
623
+ const defaultValue = defaultVariableValue(type, value);
624
+ const valuesByMode = {};
625
+ for (const mode of collection.modes) valuesByMode[mode.modeId] = structuredClone(defaultValue);
626
+ const variable = {
627
+ id,
628
+ name,
629
+ type,
630
+ collectionId,
631
+ valuesByMode,
632
+ description: "",
633
+ hiddenFromPublishing: false
634
+ };
635
+ addVariable(graph, variable);
636
+ return variable;
637
+ }
638
+ function createCollection(graph, generateId, name) {
639
+ const id = generateId();
640
+ const modeId = generateId();
641
+ const collection = {
642
+ id,
643
+ name,
644
+ modes: [{
645
+ modeId,
646
+ name: "Mode 1"
647
+ }],
648
+ defaultModeId: modeId,
649
+ variableIds: []
650
+ };
651
+ addCollection(graph, collection);
652
+ return collection;
653
+ }
654
+ function removeCollection(graph, id) {
655
+ const collection = graph.variableCollections.get(id);
656
+ if (collection) for (const varId of Array.from(collection.variableIds)) removeVariable(graph, varId);
657
+ graph.variableCollections.delete(id);
658
+ graph.activeMode.delete(id);
659
+ }
660
+ function getActiveModeId(graph, collectionId) {
661
+ const mode = graph.activeMode.get(collectionId);
662
+ if (mode) return mode;
663
+ return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
664
+ }
665
+ function getNodeVariableModeId(graph, nodeId, collectionId) {
666
+ let node = graph.nodes.get(nodeId);
667
+ while (node) {
668
+ const modeId = node.variableModes[collectionId];
669
+ if (modeId) return modeId;
670
+ node = node.parentId ? graph.nodes.get(node.parentId) : void 0;
671
+ }
672
+ return getActiveModeId(graph, collectionId);
673
+ }
674
+ function setActiveMode(graph, collectionId, modeId) {
675
+ graph.activeMode.set(collectionId, modeId);
676
+ }
677
+ function addMode(graph, collectionId, modeId, name, sourceMode) {
678
+ const collection = graph.variableCollections.get(collectionId);
679
+ if (!collection) return;
680
+ collection.modes.push({
681
+ modeId,
682
+ name
683
+ });
684
+ const sourceModeId = sourceMode ?? collection.defaultModeId;
685
+ for (const varId of collection.variableIds) {
686
+ const variable = graph.variables.get(varId);
687
+ if (!variable) continue;
688
+ variable.valuesByMode[modeId] = structuredClone(variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]);
689
+ }
690
+ }
691
+ function removeMode(graph, collectionId, modeId) {
692
+ const collection = graph.variableCollections.get(collectionId);
693
+ if (!collection || collection.modes.length <= 1) return;
694
+ collection.modes = collection.modes.filter((m) => m.modeId !== modeId);
695
+ if (collection.defaultModeId === modeId) collection.defaultModeId = collection.modes[0].modeId;
696
+ for (const varId of collection.variableIds) {
697
+ const variable = graph.variables.get(varId);
698
+ if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId]);
699
+ }
700
+ if (graph.activeMode.get(collectionId) === modeId) graph.activeMode.set(collectionId, collection.defaultModeId);
701
+ }
702
+ function renameMode(graph, collectionId, modeId, name) {
703
+ const collection = graph.variableCollections.get(collectionId);
704
+ if (!collection) return;
705
+ const mode = collection.modes.find((m) => m.modeId === modeId);
706
+ if (mode) mode.name = name;
707
+ }
708
+ function setDefaultMode(graph, collectionId, modeId) {
709
+ const collection = graph.variableCollections.get(collectionId);
710
+ if (!collection) return;
711
+ if (!collection.modes.some((m) => m.modeId === modeId)) return;
712
+ collection.defaultModeId = modeId;
713
+ }
714
+ function resolveVariable(graph, variableId, modeId, visited) {
715
+ if (visited?.has(variableId)) return void 0;
716
+ const variable = graph.variables.get(variableId);
717
+ if (!variable) return void 0;
718
+ const collection = graph.variableCollections.get(variable.collectionId);
719
+ const preferredModeId = modeId ?? getActiveModeId(graph, variable.collectionId);
720
+ const fallbackModeId = collection?.defaultModeId;
721
+ let value = Object.hasOwn(variable.valuesByMode, preferredModeId) ? variable.valuesByMode[preferredModeId] : void 0;
722
+ if (value === void 0 && fallbackModeId && Object.hasOwn(variable.valuesByMode, fallbackModeId)) value = variable.valuesByMode[fallbackModeId];
723
+ value ??= Object.values(variable.valuesByMode)[0];
724
+ if (value && typeof value === "object" && "aliasId" in value) {
725
+ const seen = visited ?? /* @__PURE__ */ new Set();
726
+ seen.add(variableId);
727
+ return resolveVariable(graph, value.aliasId, preferredModeId, seen);
728
+ }
729
+ return value;
730
+ }
731
+ function resolveColorVariable(graph, variableId) {
732
+ const value = resolveVariable(graph, variableId);
733
+ if (value && typeof value === "object" && "r" in value) return value;
734
+ }
735
+ function resolveNumberVariable(graph, variableId) {
736
+ const value = resolveVariable(graph, variableId);
737
+ return typeof value === "number" ? value : void 0;
738
+ }
739
+ function resolveColorVariableForNode(graph, nodeId, variableId) {
740
+ const variable = graph.variables.get(variableId);
741
+ if (!variable) return void 0;
742
+ const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId));
743
+ if (value && typeof value === "object" && "r" in value) return value;
744
+ }
745
+ function resolveNumberVariableForNode(graph, nodeId, variableId) {
746
+ const variable = graph.variables.get(variableId);
747
+ if (!variable) return void 0;
748
+ const value = resolveVariable(graph, variableId, getNodeVariableModeId(graph, nodeId, variable.collectionId));
749
+ return typeof value === "number" ? value : void 0;
750
+ }
751
+ function getVariablesForCollection(graph, collectionId) {
752
+ const collection = graph.variableCollections.get(collectionId);
753
+ if (!collection) return [];
754
+ return collection.variableIds.map((id) => graph.variables.get(id)).filter((v) => v !== void 0);
755
+ }
756
+ function getVariablesByType(graph, type) {
757
+ return [...graph.variables.values()].filter((v) => v.type === type);
758
+ }
759
+ const SCALAR_BINDING_FIELDS = /* @__PURE__ */ new Set([
760
+ "opacity",
761
+ "width",
762
+ "height",
763
+ "cornerRadius",
764
+ "fontSize",
765
+ "letterSpacing",
766
+ "lineHeight",
767
+ "itemSpacing",
768
+ "strokeWeight",
769
+ "paddingLeft",
770
+ "paddingRight",
771
+ "paddingTop",
772
+ "paddingBottom",
773
+ "counterAxisSpacing",
774
+ "topLeftRadius",
775
+ "topRightRadius",
776
+ "bottomLeftRadius",
777
+ "bottomRightRadius",
778
+ "rotation",
779
+ "x",
780
+ "y",
781
+ "minWidth",
782
+ "maxWidth",
783
+ "minHeight",
784
+ "maxHeight",
785
+ "borderTopWeight",
786
+ "borderBottomWeight",
787
+ "borderLeftWeight",
788
+ "borderRightWeight",
789
+ "gridRowGap",
790
+ "gridColumnGap"
791
+ ]);
792
+ const STRING_BINDING_FIELDS = /* @__PURE__ */ new Set(["fontFamily"]);
793
+ const BOOLEAN_BINDING_FIELDS = /* @__PURE__ */ new Set(["visible"]);
794
+ function bindVariable(graph, nodeId, field, variableId) {
795
+ const node = graph.nodes.get(nodeId);
796
+ if (!node) return;
797
+ const variable = graph.variables.get(variableId);
798
+ if (!variable) throw new Error(`Variable "${variableId}" not found`);
799
+ const colorFieldMatch = field.match(/^(fills|strokes)\/(\d+)\/color$/);
800
+ if (colorFieldMatch) {
801
+ if (variable.type !== "COLOR") throw new Error(`Cannot bind ${variable.type} variable to color field "${field}"`);
802
+ const arrayKey = colorFieldMatch[1];
803
+ const index = Number.parseInt(colorFieldMatch[2], 10);
804
+ const currentLength = node[arrayKey]?.length ?? 0;
805
+ if (index >= currentLength) throw new Error(`Index ${index} out of range for ${arrayKey} (length ${currentLength})`);
806
+ const topLevelKey = colorFieldMatch[1];
807
+ if (topLevelKey in node.boundVariables) node.boundVariables = omit(node.boundVariables, [topLevelKey]);
808
+ }
809
+ if (SCALAR_BINDING_FIELDS.has(field) && variable.type !== "FLOAT") throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`);
810
+ if (STRING_BINDING_FIELDS.has(field) && variable.type !== "STRING") throw new Error(`Cannot bind ${variable.type} variable to string field "${field}"`);
811
+ if (BOOLEAN_BINDING_FIELDS.has(field) && variable.type !== "BOOLEAN") throw new Error(`Cannot bind ${variable.type} variable to boolean field "${field}"`);
812
+ if (!(SCALAR_BINDING_FIELDS.has(field) || STRING_BINDING_FIELDS.has(field) || BOOLEAN_BINDING_FIELDS.has(field) || colorFieldMatch)) throw new Error(`Unknown binding field "${field}"`);
813
+ node.boundVariables = {
814
+ ...node.boundVariables,
815
+ [field]: variableId
816
+ };
817
+ graph.emitter.emit("node:updated", nodeId, { boundVariables: { ...node.boundVariables } });
818
+ markBoundVariablesOverrideOnInstance(graph, nodeId);
819
+ }
820
+ function unbindVariable(graph, nodeId, field) {
821
+ const node = graph.nodes.get(nodeId);
822
+ if (!node) return;
823
+ if (!(field in node.boundVariables)) return;
824
+ node.boundVariables = omit(node.boundVariables, [field]);
825
+ graph.emitter.emit("node:updated", nodeId, { boundVariables: { ...node.boundVariables } });
826
+ markBoundVariablesOverrideOnInstance(graph, nodeId);
827
+ }
828
+ function markBoundVariablesOverrideOnInstance(graph, nodeId) {
829
+ const node = graph.nodes.get(nodeId);
830
+ if (!node) return;
831
+ if (node.type === "INSTANCE") {
832
+ node.overrides["boundVariables"] = true;
833
+ return;
834
+ }
835
+ let current = node;
836
+ while (current.parentId) {
837
+ const parent = graph.nodes.get(current.parentId);
838
+ if (!parent) break;
839
+ if (parent.type === "INSTANCE") {
840
+ parent.overrides[`${nodeId}:boundVariables`] = true;
841
+ break;
842
+ }
843
+ current = parent;
844
+ }
845
+ }
846
+ //#endregion
847
+ //#region src/index.ts
848
+ let nextLocalID = 1;
849
+ function generateId() {
850
+ return `0:${nextLocalID++}`;
851
+ }
852
+ var SceneGraph = class SceneGraph {
853
+ nodes = /* @__PURE__ */ new Map();
854
+ images = /* @__PURE__ */ new Map();
855
+ variables = /* @__PURE__ */ new Map();
856
+ variableCollections = /* @__PURE__ */ new Map();
857
+ activeMode = /* @__PURE__ */ new Map();
858
+ rootId;
859
+ figKiwiVersion = null;
860
+ /** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */
861
+ figSchemaDeflated = null;
862
+ documentColorSpace = "display-p3";
863
+ emitter = createNanoEvents();
864
+ absPosCache = /* @__PURE__ */ new Map();
865
+ previewMutationDepth = 0;
866
+ sourceMetadataPreservationDepth = 0;
867
+ layoutMutationDepth = 0;
868
+ positionPreviewVersion = 0;
869
+ instanceIndex = /* @__PURE__ */ new Map();
870
+ constructor() {
871
+ const root = createDefaultNode(generateId, "FRAME", {
872
+ name: "Document",
873
+ width: 0,
874
+ height: 0
875
+ });
876
+ this.rootId = root.id;
877
+ this.nodes.set(root.id, root);
878
+ this.addPage("Page 1");
879
+ }
880
+ addPage(name) {
881
+ return this.createNode("CANVAS", this.rootId, {
882
+ name,
883
+ width: 0,
884
+ height: 0
885
+ });
886
+ }
887
+ getPages(includeInternal = false) {
888
+ return this.getChildren(this.rootId).filter((n) => n.type === "CANVAS" && (includeInternal || !n.internalOnly));
889
+ }
890
+ getAllNodes() {
891
+ return this.nodes.values();
892
+ }
893
+ getNode(id) {
894
+ return this.nodes.get(id);
895
+ }
896
+ onNodeEvents(handlers) {
897
+ return bindNodeEvents(this.emitter, handlers);
898
+ }
899
+ countDescendants(nodeId) {
900
+ const node = this.nodes.get(nodeId);
901
+ if (!node) return 0;
902
+ let count = 0;
903
+ const stack = [...node.childIds];
904
+ while (stack.length > 0) {
905
+ const id = stack.pop();
906
+ if (id === void 0) break;
907
+ count++;
908
+ const child = this.nodes.get(id);
909
+ if (child) for (const childId of child.childIds) stack.push(childId);
910
+ }
911
+ return count;
912
+ }
913
+ addVariable(variable) {
914
+ addVariable(this, variable);
915
+ }
916
+ removeVariable(id) {
917
+ removeVariable(this, id);
918
+ }
919
+ addCollection(collection) {
920
+ addCollection(this, collection);
921
+ }
922
+ createVariable(name, type, collectionId, value) {
923
+ return createVariable(this, generateId, name, type, collectionId, value);
924
+ }
925
+ createCollection(name) {
926
+ return createCollection(this, generateId, name);
927
+ }
928
+ removeCollection(id) {
929
+ removeCollection(this, id);
930
+ }
931
+ getActiveModeId(collectionId) {
932
+ return getActiveModeId(this, collectionId);
933
+ }
934
+ getNodeVariableModeId(nodeId, collectionId) {
935
+ return getNodeVariableModeId(this, nodeId, collectionId);
936
+ }
937
+ setActiveMode(collectionId, modeId) {
938
+ setActiveMode(this, collectionId, modeId);
939
+ }
940
+ addMode(collectionId, modeId, name, sourceMode) {
941
+ addMode(this, collectionId, modeId, name, sourceMode);
942
+ }
943
+ removeMode(collectionId, modeId) {
944
+ removeMode(this, collectionId, modeId);
945
+ }
946
+ renameMode(collectionId, modeId, name) {
947
+ renameMode(this, collectionId, modeId, name);
948
+ }
949
+ setDefaultMode(collectionId, modeId) {
950
+ setDefaultMode(this, collectionId, modeId);
951
+ }
952
+ resolveVariable(variableId, modeId, visited) {
953
+ return resolveVariable(this, variableId, modeId, visited);
954
+ }
955
+ resolveColorVariable(variableId) {
956
+ return resolveColorVariable(this, variableId);
957
+ }
958
+ resolveNumberVariable(variableId) {
959
+ return resolveNumberVariable(this, variableId);
960
+ }
961
+ resolveColorVariableForNode(nodeId, variableId) {
962
+ return resolveColorVariableForNode(this, nodeId, variableId);
963
+ }
964
+ resolveNumberVariableForNode(nodeId, variableId) {
965
+ return resolveNumberVariableForNode(this, nodeId, variableId);
966
+ }
967
+ getVariablesForCollection(collectionId) {
968
+ return getVariablesForCollection(this, collectionId);
969
+ }
970
+ getVariablesByType(type) {
971
+ return getVariablesByType(this, type);
972
+ }
973
+ bindVariable(nodeId, field, variableId) {
974
+ bindVariable(this, nodeId, field, variableId);
975
+ }
976
+ unbindVariable(nodeId, field) {
977
+ unbindVariable(this, nodeId, field);
978
+ }
979
+ getChildren(id) {
980
+ const node = this.nodes.get(id);
981
+ if (!node) return [];
982
+ return node.childIds.map((cid) => this.nodes.get(cid)).filter((n) => n !== void 0);
983
+ }
984
+ isContainer(id) {
985
+ const node = this.nodes.get(id);
986
+ return node ? CONTAINER_TYPES.has(node.type) : false;
987
+ }
988
+ isDescendant(childId, ancestorId) {
989
+ let current = this.nodes.get(childId);
990
+ while (current) {
991
+ if (current.id === ancestorId) return true;
992
+ current = current.parentId ? this.nodes.get(current.parentId) : void 0;
993
+ }
994
+ return false;
995
+ }
996
+ clearAbsPosCache() {
997
+ this.absPosCache.clear();
998
+ }
999
+ getAbsolutePosition(id) {
1000
+ const cached = this.absPosCache.get(id);
1001
+ if (cached) return cached;
1002
+ const node = this.getNode(id);
1003
+ if (!node) return {
1004
+ x: 0,
1005
+ y: 0
1006
+ };
1007
+ const result = getAbsolutePosition(node, this);
1008
+ this.absPosCache.set(id, result);
1009
+ return result;
1010
+ }
1011
+ getAbsoluteBounds(id) {
1012
+ const pos = this.getAbsolutePosition(id);
1013
+ const node = this.nodes.get(id);
1014
+ return {
1015
+ x: pos.x,
1016
+ y: pos.y,
1017
+ width: node?.width ?? 0,
1018
+ height: node?.height ?? 0
1019
+ };
1020
+ }
1021
+ generateNodeId() {
1022
+ let id = generateId();
1023
+ while (this.nodes.has(id)) id = generateId();
1024
+ return id;
1025
+ }
1026
+ registerNode(node, parentId) {
1027
+ node.parentId = parentId;
1028
+ this.nodes.set(node.id, node);
1029
+ if (node.type === "INSTANCE" && node.componentId) {
1030
+ let set = this.instanceIndex.get(node.componentId);
1031
+ if (!set) {
1032
+ set = /* @__PURE__ */ new Set();
1033
+ this.instanceIndex.set(node.componentId, set);
1034
+ }
1035
+ set.add(node.id);
1036
+ }
1037
+ this.emitter.emit("node:created", node);
1038
+ return node;
1039
+ }
1040
+ createNode(type, parentId, overrides = {}) {
1041
+ const node = createDefaultNode(() => this.generateNodeId(), type, overrides);
1042
+ this.nodes.get(parentId)?.childIds.push(node.id);
1043
+ return this.registerNode(node, parentId);
1044
+ }
1045
+ createNodeWithId(id, type, parentId, overrides = {}) {
1046
+ const node = createDefaultNode(() => id, type, overrides);
1047
+ node.id = id;
1048
+ const parent = parentId ? this.nodes.get(parentId) : void 0;
1049
+ if (parent && !parent.childIds.includes(id)) parent.childIds.push(id);
1050
+ return this.registerNode(node, parentId);
1051
+ }
1052
+ static TEXT_PICTURE_KEYS = TEXT_PICTURE_KEYS;
1053
+ static GLYPH_AFFECTING_KEYS = GLYPH_AFFECTING_KEYS;
1054
+ static LAYOUT_AFFECTING_KEYS = /* @__PURE__ */ new Set([
1055
+ "x",
1056
+ "y",
1057
+ "width",
1058
+ "height",
1059
+ "rotation",
1060
+ "flipX",
1061
+ "flipY",
1062
+ "layoutMode",
1063
+ "layoutDirection",
1064
+ "itemSpacing",
1065
+ "counterAxisSpacing",
1066
+ "paddingLeft",
1067
+ "paddingRight",
1068
+ "paddingTop",
1069
+ "paddingBottom",
1070
+ "primaryAxisAlign",
1071
+ "counterAxisAlign",
1072
+ "counterAxisAlignContent",
1073
+ "layoutWrap",
1074
+ "primaryAxisSizing",
1075
+ "counterAxisSizing",
1076
+ "layoutPositioning",
1077
+ "layoutGrow",
1078
+ "layoutAlignSelf",
1079
+ "strokesIncludedInLayout",
1080
+ "horizontalConstraint",
1081
+ "verticalConstraint",
1082
+ "gridTemplateColumns",
1083
+ "gridTemplateRows",
1084
+ "gridColumnGap",
1085
+ "gridRowGap",
1086
+ "gridPosition",
1087
+ "minWidth",
1088
+ "maxWidth",
1089
+ "minHeight",
1090
+ "maxHeight"
1091
+ ]);
1092
+ runPreviewUpdates(fn) {
1093
+ this.previewMutationDepth++;
1094
+ try {
1095
+ fn();
1096
+ } finally {
1097
+ this.previewMutationDepth--;
1098
+ }
1099
+ }
1100
+ preserveSourceMetadataDuring(fn) {
1101
+ this.sourceMetadataPreservationDepth++;
1102
+ try {
1103
+ fn();
1104
+ } finally {
1105
+ this.sourceMetadataPreservationDepth--;
1106
+ }
1107
+ }
1108
+ withLayoutMutations(fn) {
1109
+ this.layoutMutationDepth++;
1110
+ try {
1111
+ fn();
1112
+ } finally {
1113
+ this.layoutMutationDepth--;
1114
+ }
1115
+ }
1116
+ get isApplyingLayout() {
1117
+ return this.layoutMutationDepth > 0;
1118
+ }
1119
+ updateNodePositionPreview(id, x, y) {
1120
+ this.updateNodePreview(id, {
1121
+ x,
1122
+ y
1123
+ });
1124
+ }
1125
+ updateNodePreview(id, changes) {
1126
+ const appliedChanges = updateNodePreview(this, id, changes);
1127
+ if (appliedChanges) this.emitter.emit("node:previewUpdated", id, appliedChanges);
1128
+ }
1129
+ updateNode(id, changes) {
1130
+ if (this.previewMutationDepth > 0) {
1131
+ this.updateNodePreview(id, changes);
1132
+ return;
1133
+ }
1134
+ const node = this.nodes.get(id);
1135
+ if (!node) return;
1136
+ let entries = Object.entries(changes);
1137
+ changes = Object.fromEntries(entries.filter(([, value]) => value !== void 0));
1138
+ changes = styleDetachmentChanges(node, changes);
1139
+ entries = Object.entries(changes);
1140
+ changes = Object.fromEntries(entries.filter(([, value]) => value !== void 0));
1141
+ if (Object.keys(changes).some((k) => SceneGraph.LAYOUT_AFFECTING_KEYS.has(k))) this.absPosCache.clear();
1142
+ if (node.type === "INSTANCE" && "componentId" in changes && changes.componentId !== node.componentId) {
1143
+ if (node.componentId) this.instanceIndex.get(node.componentId)?.delete(id);
1144
+ if (changes.componentId) {
1145
+ let set = this.instanceIndex.get(changes.componentId);
1146
+ if (!set) {
1147
+ set = /* @__PURE__ */ new Set();
1148
+ this.instanceIndex.set(changes.componentId, set);
1149
+ }
1150
+ set.add(id);
1151
+ }
1152
+ }
1153
+ if (node.type === "TEXT") {
1154
+ const textChanged = Object.keys(changes).some((k) => TEXT_PICTURE_KEYS.has(k));
1155
+ if (node.textPicture && textChanged) node.textPicture = null;
1156
+ const glyphChanged = Object.keys(changes).some((k) => GLYPH_AFFECTING_KEYS.has(k));
1157
+ if (node.figmaDerivedTextGlyphs && glyphChanged) node.figmaDerivedTextGlyphs = null;
1158
+ }
1159
+ if (this.sourceMetadataPreservationDepth === 0) markSourceFieldsEdited(node, Object.keys(changes));
1160
+ if (changes.vectorNetwork) changes = {
1161
+ ...changes,
1162
+ vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork)
1163
+ };
1164
+ Object.assign(node, changes);
1165
+ if (changes.fills) removeStaleBindings(node, "fills", changes);
1166
+ if (changes.strokes) removeStaleBindings(node, "strokes", changes);
1167
+ this.emitter.emit("node:updated", id, changes);
1168
+ }
1169
+ reparentNode(nodeId, newParentId) {
1170
+ const node = this.nodes.get(nodeId);
1171
+ if (!node || nodeId === this.rootId) return;
1172
+ if (this.isDescendant(newParentId, nodeId)) return;
1173
+ const oldParent = node.parentId ? this.nodes.get(node.parentId) : void 0;
1174
+ const newParent = this.nodes.get(newParentId);
1175
+ if (!newParent) return;
1176
+ if (node.parentId === newParentId) return;
1177
+ const oldParentId = node.parentId;
1178
+ this.absPosCache.clear();
1179
+ const absPos = this.getAbsolutePosition(nodeId);
1180
+ const newParentNode = this.nodes.get(newParentId);
1181
+ const newParentAbs = newParentId === this.rootId || newParentNode?.type === "CANVAS" ? {
1182
+ x: 0,
1183
+ y: 0
1184
+ } : this.getAbsolutePosition(newParentId);
1185
+ if (oldParent) oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId);
1186
+ node.parentId = newParentId;
1187
+ newParent.childIds.push(nodeId);
1188
+ node.x = absPos.x - newParentAbs.x;
1189
+ node.y = absPos.y - newParentAbs.y;
1190
+ this.emitter.emit("node:reparented", nodeId, oldParentId, newParentId);
1191
+ }
1192
+ reorderChild(nodeId, parentId, insertIndex) {
1193
+ const node = this.nodes.get(nodeId);
1194
+ if (!node) return;
1195
+ const oldParent = node.parentId ? this.nodes.get(node.parentId) : void 0;
1196
+ const newParent = this.nodes.get(parentId);
1197
+ if (!newParent) return;
1198
+ if (oldParent) oldParent.childIds = oldParent.childIds.filter((cid) => cid !== nodeId);
1199
+ let idx = insertIndex;
1200
+ if (oldParent === newParent && idx > (!oldParent.childIds.includes(nodeId) ? idx : oldParent.childIds.length)) {}
1201
+ node.parentId = parentId;
1202
+ idx = Math.min(idx, newParent.childIds.length);
1203
+ newParent.childIds.splice(idx, 0, nodeId);
1204
+ this.emitter.emit("node:reordered", nodeId, parentId, idx);
1205
+ }
1206
+ insertChildAt(childId, parentId, index) {
1207
+ const oldParent = this.getNode(this.getNode(childId)?.parentId ?? "");
1208
+ if (oldParent) oldParent.childIds = oldParent.childIds.filter((id) => id !== childId);
1209
+ const newParent = this.getNode(parentId);
1210
+ if (!newParent) return;
1211
+ newParent.childIds = newParent.childIds.filter((id) => id !== childId);
1212
+ newParent.childIds.splice(index, 0, childId);
1213
+ const node = this.getNode(childId);
1214
+ if (node) node.parentId = parentId;
1215
+ this.clearAbsPosCache();
1216
+ this.emitter.emit("node:reordered", childId, parentId, index);
1217
+ }
1218
+ deleteNode(id) {
1219
+ const node = this.nodes.get(id);
1220
+ if (!node || id === this.rootId) return;
1221
+ if (node.parentId) {
1222
+ const parent = this.nodes.get(node.parentId);
1223
+ if (parent) parent.childIds = parent.childIds.filter((cid) => cid !== id);
1224
+ }
1225
+ for (const childId of Array.from(node.childIds)) this.deleteNode(childId);
1226
+ if (node.type === "INSTANCE" && node.componentId) this.instanceIndex.get(node.componentId)?.delete(id);
1227
+ this.nodes.delete(id);
1228
+ this.emitter.emit("node:deleted", id);
1229
+ }
1230
+ hitTest(px, py, scopeId) {
1231
+ return hitTest(this, px, py, scopeId);
1232
+ }
1233
+ hitTestDeep(px, py, scopeId) {
1234
+ return hitTestDeep(this, px, py, scopeId);
1235
+ }
1236
+ hitTestFrame(px, py, excludeIds, scopeId) {
1237
+ return hitTestFrame(this, px, py, excludeIds, scopeId);
1238
+ }
1239
+ cloneTree(sourceId, parentId, overrides = {}) {
1240
+ const src = this.nodes.get(sourceId);
1241
+ if (!src) return null;
1242
+ const props = cloneNodeProps(src, null);
1243
+ props.source = {
1244
+ ...props.source,
1245
+ id: null,
1246
+ orderKey: null
1247
+ };
1248
+ const clone = this.createNode(src.type, parentId, {
1249
+ ...props,
1250
+ ...overrides
1251
+ });
1252
+ for (const childId of src.childIds) this.cloneTree(childId, clone.id);
1253
+ return clone;
1254
+ }
1255
+ createInstance(componentId, parentId, overrides = {}) {
1256
+ return createInstance(this, componentId, parentId, overrides);
1257
+ }
1258
+ populateInstanceChildren(instanceId, componentId, mode = "deep") {
1259
+ populateInstanceChildren(this, instanceId, componentId, mode);
1260
+ }
1261
+ swapInstanceComponent(instanceId, componentId) {
1262
+ swapInstanceComponent(this, instanceId, componentId);
1263
+ }
1264
+ syncInstances(componentId) {
1265
+ syncInstances(this, componentId);
1266
+ }
1267
+ detachInstance(instanceId) {
1268
+ detachInstance(this, instanceId);
1269
+ }
1270
+ getMainComponent(instanceId) {
1271
+ return getMainComponent(this, instanceId);
1272
+ }
1273
+ getInstances(componentId) {
1274
+ return getInstances(this, componentId);
1275
+ }
1276
+ flattenTree(parentId, depth = 0) {
1277
+ const id = parentId ?? this.rootId;
1278
+ const parent = this.nodes.get(id);
1279
+ if (!parent) return [];
1280
+ const result = [];
1281
+ for (const childId of parent.childIds) {
1282
+ const child = this.nodes.get(childId);
1283
+ if (!child) continue;
1284
+ result.push({
1285
+ node: child,
1286
+ depth
1287
+ });
1288
+ if (child.childIds.length > 0) result.push(...this.flattenTree(childId, depth + 1));
1289
+ }
1290
+ return result;
1291
+ }
1292
+ };
1293
+ //#endregion
1294
+ export { GLYPH_AFFECTING_KEYS, SceneGraph, TEXT_PICTURE_KEYS, UndoManager, addCollection, addMode, addVariable, bindVariable, computeSelectionBounds, computeSnap, copyInstanceComponentProps, createCollection, createInstance, createVariable, detachInstance, generateId, getActiveModeId, getInstances, getMainComponent, getNodeVariableModeId, getSharedStyles, getVariablesByType, getVariablesForCollection, markSourceFieldsEdited, populateInstanceChildren, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveVariable, setActiveMode, setDefaultMode, sharedStyleRefKey, sharedStyleTypeForKind, styleDetachmentChanges, swapInstanceComponent, syncInstances, unbindVariable, updateNodePreview };
1295
+
1296
+ //# sourceMappingURL=types.js.map