@open-pencil/scene-graph 0.13.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/arrow-caps.d.ts +44 -0
  2. package/dist/arrow-caps.d.ts.map +1 -0
  3. package/dist/arrow-caps.js +131 -0
  4. package/dist/arrow-caps.js.map +1 -0
  5. package/dist/chunks/checkpoint.js +78 -0
  6. package/dist/chunks/checkpoint.js.map +1 -0
  7. package/dist/chunks/components/properties.js +1571 -0
  8. package/dist/chunks/components/properties.js.map +1 -0
  9. package/dist/chunks/coordinate.js +87 -33
  10. package/dist/chunks/coordinate.js.map +1 -1
  11. package/dist/chunks/font-style.js +2 -1
  12. package/dist/chunks/font-style.js.map +1 -1
  13. package/dist/chunks/index.js +1283 -0
  14. package/dist/chunks/index.js.map +1 -0
  15. package/dist/constants.js +1 -18
  16. package/dist/constants2.d.ts +0 -1
  17. package/dist/constants2.d.ts.map +1 -1
  18. package/dist/coordinate.d.ts +107 -11
  19. package/dist/coordinate.d.ts.map +1 -1
  20. package/dist/coordinate.js +2 -2
  21. package/dist/coordinate2.d.ts +2 -2
  22. package/dist/copy.d.ts +2 -2
  23. package/dist/copy.js +2 -2
  24. package/dist/geometry.d.ts +2 -2
  25. package/dist/geometry.js +2 -431
  26. package/dist/guides.d.ts +2 -0
  27. package/dist/guides.js +0 -0
  28. package/dist/guides2.d.ts +11 -0
  29. package/dist/guides2.d.ts.map +1 -0
  30. package/dist/hit-test.d.ts +1 -2
  31. package/dist/hit-test.d.ts.map +1 -1
  32. package/dist/hit-test.js +26 -14
  33. package/dist/hit-test.js.map +1 -1
  34. package/dist/images.js +0 -1
  35. package/dist/images.js.map +1 -1
  36. package/dist/images2.d.ts.map +1 -1
  37. package/dist/index.d.ts +5 -3
  38. package/dist/index.js +5 -6
  39. package/dist/instances.d.ts +2 -2
  40. package/dist/instances.js +2 -2
  41. package/dist/layout-guides.d.ts +2 -0
  42. package/dist/layout-guides.js +2 -0
  43. package/dist/layout-guides2.d.ts +16 -0
  44. package/dist/layout-guides2.d.ts.map +1 -0
  45. package/dist/matrix2.d.ts +0 -1
  46. package/dist/matrix2.d.ts.map +1 -1
  47. package/dist/node-defaults.d.ts +1 -2
  48. package/dist/node-defaults.d.ts.map +1 -1
  49. package/dist/node-defaults.js +1 -1
  50. package/dist/parse-path.d.ts +1 -2
  51. package/dist/parse-path.d.ts.map +1 -1
  52. package/dist/parse-path.js.map +1 -1
  53. package/dist/preview.d.ts +2 -12
  54. package/dist/preview.js +1 -1
  55. package/dist/preview2.d.ts +12 -0
  56. package/dist/preview2.d.ts.map +1 -0
  57. package/dist/primitives2.d.ts.map +1 -1
  58. package/dist/resize.d.ts +18 -4
  59. package/dist/resize.d.ts.map +1 -1
  60. package/dist/resize.js +70 -22
  61. package/dist/resize.js.map +1 -1
  62. package/dist/snap.js +1 -1
  63. package/dist/source-metadata.d.ts +1 -2
  64. package/dist/source-metadata.d.ts.map +1 -1
  65. package/dist/source-metadata.js +1 -1
  66. package/dist/text-picture.d.ts +13 -2
  67. package/dist/text-picture.d.ts.map +1 -1
  68. package/dist/text-picture.js +2 -2
  69. package/dist/types.d.ts +499 -2
  70. package/dist/types.d.ts.map +1 -0
  71. package/dist/types.js +1 -1296
  72. package/dist/types2.d.ts +2 -430
  73. package/dist/undo.js +1 -1
  74. package/dist/undo2.d.ts +5 -0
  75. package/dist/undo2.d.ts.map +1 -1
  76. package/dist/variables.d.ts +1 -2
  77. package/dist/variables.d.ts.map +1 -1
  78. package/dist/variables.js +1 -1
  79. package/dist/variant-name.d.ts.map +1 -1
  80. package/dist/variant-properties.d.ts +10 -0
  81. package/dist/variant-properties.d.ts.map +1 -0
  82. package/dist/variant-properties.js +39 -0
  83. package/dist/variant-properties.js.map +1 -0
  84. package/dist/vector-network.js +1 -1
  85. package/dist/vector-network2.d.ts +1 -2
  86. package/dist/vector-network2.d.ts.map +1 -1
  87. package/package.json +40 -15
  88. package/src/arrow-caps.ts +146 -0
  89. package/src/bindings.ts +20 -0
  90. package/src/checkpoint.ts +123 -0
  91. package/src/components/properties.ts +238 -0
  92. package/src/constants.ts +6 -0
  93. package/src/coordinate.ts +226 -0
  94. package/src/copy.ts +294 -0
  95. package/src/events.ts +21 -0
  96. package/src/export-scale.ts +16 -0
  97. package/src/font-style.ts +77 -0
  98. package/src/geometry.ts +530 -0
  99. package/src/guides.ts +8 -0
  100. package/src/hit-test.ts +205 -0
  101. package/src/images.ts +34 -0
  102. package/src/index.ts +686 -0
  103. package/src/instance-overrides.test.ts +67 -0
  104. package/src/instance-overrides.ts +152 -0
  105. package/src/instances.ts +480 -0
  106. package/src/layout-guides.ts +103 -0
  107. package/src/matrix.ts +116 -0
  108. package/src/mutation-impact.ts +70 -0
  109. package/src/node-defaults.ts +186 -0
  110. package/src/parse-path.ts +191 -0
  111. package/src/preview.ts +80 -0
  112. package/src/primitives.ts +42 -0
  113. package/src/resize.ts +302 -0
  114. package/src/shared-styles.ts +73 -0
  115. package/src/snap.ts +129 -0
  116. package/src/source-metadata.ts +8 -0
  117. package/src/text-picture.ts +65 -0
  118. package/src/types.ts +635 -0
  119. package/src/undo.ts +171 -0
  120. package/src/variables.ts +399 -0
  121. package/src/variant-name.ts +15 -0
  122. package/src/variant-properties.ts +48 -0
  123. package/src/vector-network.ts +293 -0
  124. package/dist/chunks/copy.js +0 -576
  125. package/dist/chunks/copy.js.map +0 -1
  126. package/dist/constants.js.map +0 -1
  127. package/dist/geometry.js.map +0 -1
  128. package/dist/preview.d.ts.map +0 -1
  129. package/dist/types.js.map +0 -1
  130. package/dist/types2.d.ts.map +0 -1
@@ -0,0 +1,1571 @@
1
+ import { arrowCapOverflow } from "../../arrow-caps.js";
2
+ import { isEqual } from "es-toolkit/predicate";
3
+ //#region src/instance-overrides.ts
4
+ function createInstanceOverrideState() {
5
+ return {
6
+ self: /* @__PURE__ */ new Map(),
7
+ descendants: /* @__PURE__ */ new Map()
8
+ };
9
+ }
10
+ function serializeOverrideValue(value) {
11
+ return value === void 0 ? { defined: false } : {
12
+ defined: true,
13
+ value
14
+ };
15
+ }
16
+ function deserializeOverrideValue(value) {
17
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {
18
+ valid: false,
19
+ value: void 0
20
+ };
21
+ if (!("defined" in value) || typeof value.defined !== "boolean") return {
22
+ valid: false,
23
+ value: void 0
24
+ };
25
+ if (value.defined) return "value" in value ? {
26
+ valid: true,
27
+ value: value["value"]
28
+ } : {
29
+ valid: false,
30
+ value: void 0
31
+ };
32
+ return {
33
+ valid: true,
34
+ value: void 0
35
+ };
36
+ }
37
+ function deserializeEntries(value) {
38
+ const result = /* @__PURE__ */ new Map();
39
+ if (!Array.isArray(value)) return result;
40
+ for (const entry of value) {
41
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string") continue;
42
+ const decoded = deserializeOverrideValue(entry[1]);
43
+ if (decoded.valid) result.set(entry[0], decoded.value);
44
+ }
45
+ return result;
46
+ }
47
+ function serializeInstanceOverrideState(state) {
48
+ return {
49
+ self: [...state.self].map(([field, value]) => [field, serializeOverrideValue(value)]),
50
+ descendants: [...state.descendants].map(([nodeId, fields]) => [nodeId, [...fields].map(([field, value]) => [field, serializeOverrideValue(value)])])
51
+ };
52
+ }
53
+ function deserializeInstanceOverrideState(state) {
54
+ if (!state || typeof state !== "object" || Array.isArray(state)) return createInstanceOverrideState();
55
+ const self = "self" in state ? deserializeEntries(state.self) : /* @__PURE__ */ new Map();
56
+ const descendants = /* @__PURE__ */ new Map();
57
+ if ("descendants" in state && Array.isArray(state.descendants)) for (const entry of state.descendants) {
58
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string") continue;
59
+ descendants.set(entry[0], deserializeEntries(entry[1]));
60
+ }
61
+ return {
62
+ self,
63
+ descendants
64
+ };
65
+ }
66
+ function cloneInstanceOverrideState(state) {
67
+ return {
68
+ self: new Map([...state.self].map(([field, value]) => [field, structuredClone(value)])),
69
+ descendants: new Map([...state.descendants].map(([id, fields]) => [id, new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))]))
70
+ };
71
+ }
72
+ function getInstanceOverride(state, instanceId, nodeId, field) {
73
+ return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field);
74
+ }
75
+ function hasInstanceOverride$1(state, instanceId, nodeId, field) {
76
+ return (nodeId === instanceId ? state.self : state.descendants.get(nodeId))?.has(field) ?? false;
77
+ }
78
+ function setInstanceOverride(state, instanceId, nodeId, field, value = true) {
79
+ if (nodeId === instanceId) {
80
+ state.self.set(field, value);
81
+ return;
82
+ }
83
+ const fields = state.descendants.get(nodeId) ?? /* @__PURE__ */ new Map();
84
+ fields.set(field, value);
85
+ state.descendants.set(nodeId, fields);
86
+ }
87
+ function deleteInstanceOverride(state, instanceId, nodeId, field) {
88
+ const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId);
89
+ if (!fields?.delete(field)) return false;
90
+ if (nodeId !== instanceId && fields.size === 0) state.descendants.delete(nodeId);
91
+ return true;
92
+ }
93
+ function clearInstanceOverrides(state) {
94
+ state.self.clear();
95
+ state.descendants.clear();
96
+ }
97
+ function forEachInstanceOverride(state, callback) {
98
+ for (const [field, value] of state.self) callback("", field, value);
99
+ for (const [nodeId, fields] of state.descendants) for (const [field, value] of fields) callback(nodeId, field, value);
100
+ }
101
+ //#endregion
102
+ //#region src/geometry.ts
103
+ function degToRad(degrees) {
104
+ return degrees * Math.PI / 180;
105
+ }
106
+ function radToDeg(radians) {
107
+ return radians * 180 / Math.PI;
108
+ }
109
+ function rotatePoint(px, py, cx, cy, rad) {
110
+ const cos = Math.cos(rad);
111
+ const sin = Math.sin(rad);
112
+ return {
113
+ x: cx + (px - cx) * cos - (py - cy) * sin,
114
+ y: cy + (px - cx) * sin + (py - cy) * cos
115
+ };
116
+ }
117
+ function rotatedCorners(cx, cy, hw, hh, rotationDeg) {
118
+ const rad = degToRad(rotationDeg);
119
+ const cos = Math.cos(rad);
120
+ const sin = Math.sin(rad);
121
+ return [
122
+ {
123
+ x: cx + -hw * cos - -hh * sin,
124
+ y: cy + -hw * sin + -hh * cos
125
+ },
126
+ {
127
+ x: cx + hw * cos - -hh * sin,
128
+ y: cy + hw * sin + -hh * cos
129
+ },
130
+ {
131
+ x: cx + hw * cos - hh * sin,
132
+ y: cy + hw * sin + hh * cos
133
+ },
134
+ {
135
+ x: cx + -hw * cos - hh * sin,
136
+ y: cy + -hw * sin + hh * cos
137
+ }
138
+ ];
139
+ }
140
+ function rotatedBBox(x, y, w, h, rotationDeg) {
141
+ if (rotationDeg === 0) return {
142
+ left: x,
143
+ right: x + w,
144
+ top: y,
145
+ bottom: y + h,
146
+ centerX: x + w / 2,
147
+ centerY: y + h / 2
148
+ };
149
+ const corners = rotatedCorners(x + w / 2, y + h / 2, w / 2, h / 2, rotationDeg);
150
+ let left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity;
151
+ for (const c of corners) {
152
+ left = Math.min(left, c.x);
153
+ right = Math.max(right, c.x);
154
+ top = Math.min(top, c.y);
155
+ bottom = Math.max(bottom, c.y);
156
+ }
157
+ return {
158
+ left,
159
+ right,
160
+ top,
161
+ bottom,
162
+ centerX: (left + right) / 2,
163
+ centerY: (top + bottom) / 2
164
+ };
165
+ }
166
+ function createBoundsAccumulator() {
167
+ return {
168
+ minX: Infinity,
169
+ minY: Infinity,
170
+ maxX: -Infinity,
171
+ maxY: -Infinity
172
+ };
173
+ }
174
+ function includePoint(bounds, x, y) {
175
+ bounds.minX = Math.min(bounds.minX, x);
176
+ bounds.minY = Math.min(bounds.minY, y);
177
+ bounds.maxX = Math.max(bounds.maxX, x);
178
+ bounds.maxY = Math.max(bounds.maxY, y);
179
+ }
180
+ function includeRect(bounds, rect) {
181
+ includePoint(bounds, rect.x, rect.y);
182
+ includePoint(bounds, rect.x + rect.width, rect.y + rect.height);
183
+ }
184
+ function boundsToRect(bounds) {
185
+ return bounds.minX === Infinity ? {
186
+ x: 0,
187
+ y: 0,
188
+ width: 0,
189
+ height: 0
190
+ } : {
191
+ x: bounds.minX,
192
+ y: bounds.minY,
193
+ width: bounds.maxX - bounds.minX,
194
+ height: bounds.maxY - bounds.minY
195
+ };
196
+ }
197
+ function computeBounds(items) {
198
+ const bounds = createBoundsAccumulator();
199
+ for (const item of items) includeRect(bounds, item);
200
+ return boundsToRect(bounds);
201
+ }
202
+ function polygonVertices(node) {
203
+ const cx = node.width / 2;
204
+ const cy = node.height / 2;
205
+ const rx = node.width / 2;
206
+ const ry = node.height / 2;
207
+ const pointCount = Math.max(3, node.pointCount);
208
+ const isStar = node.type === "STAR";
209
+ const innerRatio = isStar ? node.starInnerRadius : 1;
210
+ const totalPoints = isStar ? pointCount * 2 : pointCount;
211
+ const angleOffset = -Math.PI / 2;
212
+ return Array.from({ length: totalPoints }, (_, index) => {
213
+ const angle = angleOffset + 2 * Math.PI * index / totalPoints;
214
+ const radius = isStar && index % 2 === 1 ? innerRatio : 1;
215
+ return {
216
+ x: cx + rx * radius * Math.cos(angle),
217
+ y: cy + ry * radius * Math.sin(angle)
218
+ };
219
+ });
220
+ }
221
+ function strokeOverflow(strokes, fallbackCap, network) {
222
+ let overflow = 0;
223
+ for (const stroke of strokes ?? []) {
224
+ if (!stroke.visible) continue;
225
+ let extra = 0;
226
+ if (stroke.align === "OUTSIDE") extra = stroke.weight;
227
+ else if (stroke.align === "CENTER") extra = stroke.weight / 2;
228
+ overflow = Math.max(overflow, extra);
229
+ }
230
+ return Math.max(overflow, arrowCapOverflow(strokes, fallbackCap, network));
231
+ }
232
+ function effectOverflow(effects) {
233
+ let left = 0;
234
+ let right = 0;
235
+ let top = 0;
236
+ let bottom = 0;
237
+ for (const effect of effects ?? []) {
238
+ if (!effect.visible) continue;
239
+ if (effect.type !== "DROP_SHADOW" && effect.type !== "LAYER_BLUR" && effect.type !== "FOREGROUND_BLUR") continue;
240
+ const blurSpread = effect.radius + effect.spread;
241
+ left = Math.max(left, blurSpread + Math.max(0, -effect.offset.x));
242
+ right = Math.max(right, blurSpread + Math.max(0, effect.offset.x));
243
+ top = Math.max(top, blurSpread + Math.max(0, -effect.offset.y));
244
+ bottom = Math.max(bottom, blurSpread + Math.max(0, effect.offset.y));
245
+ }
246
+ return {
247
+ left,
248
+ right,
249
+ top,
250
+ bottom
251
+ };
252
+ }
253
+ function computeAbsoluteBounds(nodes, getAbsolutePosition) {
254
+ const bounds = createBoundsAccumulator();
255
+ for (const n of nodes) {
256
+ const abs = getAbsolutePosition(n.id);
257
+ includeRect(bounds, {
258
+ x: abs.x,
259
+ y: abs.y,
260
+ width: n.width,
261
+ height: n.height
262
+ });
263
+ }
264
+ return boundsToRect(bounds);
265
+ }
266
+ function computeVisualBounds(nodes, getAbsolutePosition) {
267
+ const bounds = createBoundsAccumulator();
268
+ for (const n of nodes) {
269
+ const abs = getAbsolutePosition(n.id);
270
+ const bbox = rotatedBBox(abs.x, abs.y, n.width, n.height, n.rotation ?? 0);
271
+ const stroke = strokeOverflow(n.strokes, n.strokeCap, n.vectorNetwork);
272
+ const effects = effectOverflow(n.effects);
273
+ includePoint(bounds, bbox.left - stroke - effects.left, bbox.top - stroke - effects.top);
274
+ includePoint(bounds, bbox.right + stroke + effects.right, bbox.bottom + stroke + effects.bottom);
275
+ }
276
+ return boundsToRect(bounds);
277
+ }
278
+ function unionVisualBounds(a, b) {
279
+ if (!a) return b;
280
+ if (!b) return a;
281
+ return {
282
+ minX: Math.min(a.minX, b.minX),
283
+ minY: Math.min(a.minY, b.minY),
284
+ maxX: Math.max(a.maxX, b.maxX),
285
+ maxY: Math.max(a.maxY, b.maxY)
286
+ };
287
+ }
288
+ function intersectVisualBounds(a, b) {
289
+ const minX = Math.max(a.minX, b.minX);
290
+ const minY = Math.max(a.minY, b.minY);
291
+ const maxX = Math.min(a.maxX, b.maxX);
292
+ const maxY = Math.min(a.maxY, b.maxY);
293
+ return minX < maxX && minY < maxY ? {
294
+ minX,
295
+ minY,
296
+ maxX,
297
+ maxY
298
+ } : null;
299
+ }
300
+ /**
301
+ * Coordinate pairs per path blob command: 0=close, 1=move, 2=line,
302
+ * 3=quad (glyph-derived blobs are quad-heavy), 4=cubic. Unknown → null so
303
+ * walkers stop instead of desyncing into coordinate bytes.
304
+ */
305
+ function geometryCommandCoordCount(command) {
306
+ if (command === 0) return 0;
307
+ if (command === 1 || command === 2) return 1;
308
+ if (command === 3) return 2;
309
+ if (command === 4) return 3;
310
+ return null;
311
+ }
312
+ function geometryBlobBounds(paths) {
313
+ const bounds = createBoundsAccumulator();
314
+ for (const path of paths) {
315
+ const blob = path.commandsBlob;
316
+ const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
317
+ let offset = 0;
318
+ while (offset < blob.length) {
319
+ const command = blob[offset++];
320
+ const coords = geometryCommandCoordCount(command);
321
+ if (coords == null) break;
322
+ for (let i = 0; i < coords; i++) {
323
+ if (offset + 8 > blob.length) break;
324
+ includePoint(bounds, dv.getFloat32(offset, true), dv.getFloat32(offset + 4, true));
325
+ offset += 8;
326
+ }
327
+ }
328
+ }
329
+ return bounds.minX === Infinity ? null : boundsToRect(bounds);
330
+ }
331
+ function transformLocalPoint(node, point) {
332
+ let x = node.flipX ? node.width - point.x : point.x;
333
+ let y = node.flipY ? node.height - point.y : point.y;
334
+ const rotation = node.rotation ?? 0;
335
+ if (rotation !== 0) {
336
+ const rotated = rotatePoint(x, y, node.width / 2, node.height / 2, degToRad(rotation));
337
+ x = rotated.x;
338
+ y = rotated.y;
339
+ }
340
+ return {
341
+ x,
342
+ y
343
+ };
344
+ }
345
+ function transformedLocalBounds(node, local, abs) {
346
+ const points = [
347
+ {
348
+ x: local.x,
349
+ y: local.y
350
+ },
351
+ {
352
+ x: local.x + local.width,
353
+ y: local.y
354
+ },
355
+ {
356
+ x: local.x + local.width,
357
+ y: local.y + local.height
358
+ },
359
+ {
360
+ x: local.x,
361
+ y: local.y + local.height
362
+ }
363
+ ].map((point) => transformLocalPoint(node, point));
364
+ return {
365
+ minX: abs.x + Math.min(...points.map((point) => point.x)),
366
+ minY: abs.y + Math.min(...points.map((point) => point.y)),
367
+ maxX: abs.x + Math.max(...points.map((point) => point.x)),
368
+ maxY: abs.y + Math.max(...points.map((point) => point.y))
369
+ };
370
+ }
371
+ function nodeVisualBounds(node, getAbsolutePosition) {
372
+ const abs = getAbsolutePosition(node.id);
373
+ const base = computeVisualBounds([node], getAbsolutePosition);
374
+ let bounds = {
375
+ minX: base.x,
376
+ minY: base.y,
377
+ maxX: base.x + base.width,
378
+ maxY: base.y + base.height
379
+ };
380
+ const hasNonInsideStroke = node.strokes?.some((stroke) => stroke.visible && stroke.align !== "INSIDE");
381
+ const localGeometry = geometryBlobBounds([...node.fillGeometry ?? [], ...hasNonInsideStroke ? node.strokeGeometry ?? [] : []]);
382
+ if (localGeometry) bounds = unionVisualBounds(bounds, transformedLocalBounds(node, localGeometry, abs)) ?? bounds;
383
+ if (node.type === "TEXT" && node.textDecoration && node.textDecoration !== "NONE") {
384
+ const fontSize = node.fontSize ?? 14;
385
+ const underlineOffset = node.textUnderlineOffset ?? fontSize * .18;
386
+ const thickness = node.textDecorationThickness ?? Math.max(1, fontSize / 16);
387
+ bounds.maxY += underlineOffset + thickness + fontSize * .35;
388
+ }
389
+ return bounds;
390
+ }
391
+ function collectDescendantVisualBounds(nodeId, getNode, getAbsolutePosition, clip = null) {
392
+ const node = getNode(nodeId);
393
+ if (!node?.visible) return null;
394
+ const own = nodeVisualBounds(node, getAbsolutePosition);
395
+ let bounds = clip ? intersectVisualBounds(own, clip) : own;
396
+ const isClippableContainer = node.type === "FRAME" || node.type === "COMPONENT" || node.type === "INSTANCE";
397
+ let childClip = clip;
398
+ if (isClippableContainer && node.clipsContent) {
399
+ const abs = getAbsolutePosition(node.id);
400
+ const nodeClip = {
401
+ minX: abs.x,
402
+ minY: abs.y,
403
+ maxX: abs.x + node.width,
404
+ maxY: abs.y + node.height
405
+ };
406
+ childClip = childClip ? intersectVisualBounds(childClip, nodeClip) : nodeClip;
407
+ if (!childClip) return bounds;
408
+ }
409
+ for (const childId of node.childIds ?? []) bounds = unionVisualBounds(bounds, collectDescendantVisualBounds(childId, getNode, getAbsolutePosition, childClip));
410
+ return bounds;
411
+ }
412
+ function computeDescendantVisualBounds(nodeIds, getNode, getAbsolutePosition) {
413
+ let bounds = null;
414
+ for (const nodeId of nodeIds) bounds = unionVisualBounds(bounds, collectDescendantVisualBounds(nodeId, getNode, getAbsolutePosition));
415
+ return bounds;
416
+ }
417
+ function crossProduct(a, b, p) {
418
+ return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
419
+ }
420
+ function lineSegmentIntersect(p1, p2, p3, p4) {
421
+ const dx1 = p2.x - p1.x;
422
+ const dy1 = p2.y - p1.y;
423
+ const dx2 = p4.x - p3.x;
424
+ const dy2 = p4.y - p3.y;
425
+ const denom = dx1 * dy2 - dy1 * dx2;
426
+ if (denom === 0) return p1;
427
+ const t = ((p3.x - p1.x) * dy2 - (p3.y - p1.y) * dx2) / denom;
428
+ return {
429
+ x: p1.x + t * dx1,
430
+ y: p1.y + t * dy1
431
+ };
432
+ }
433
+ function clipHalfPlane(polygon, a, b, wantPositive) {
434
+ const output = [];
435
+ const isInside = (p) => {
436
+ const cross = crossProduct(a, b, p);
437
+ return wantPositive ? cross >= 0 : cross <= 0;
438
+ };
439
+ for (let i = 0; i < polygon.length; i++) {
440
+ const curr = polygon[i];
441
+ const prev = polygon[i === 0 ? polygon.length - 1 : i - 1];
442
+ const currInside = isInside(curr);
443
+ const prevInside = isInside(prev);
444
+ if (currInside) {
445
+ if (!prevInside) output.push(lineSegmentIntersect(prev, curr, a, b));
446
+ output.push(curr);
447
+ } else if (prevInside) output.push(lineSegmentIntersect(prev, curr, a, b));
448
+ }
449
+ return output;
450
+ }
451
+ /**
452
+ * Clip a subject polygon against a convex polygon (e.g. the 4 canvas-space
453
+ * corners of a rotated clipping ancestor).
454
+ *
455
+ * Uses Sutherland–Hodgman polygon clipping with centroid-based interior
456
+ * detection, making it robust to either winding order of the clip polygon.
457
+ * Returns the clipped polygon, or null if the subject is fully outside the
458
+ * clip polygon. When `clipCorners` has fewer than 3 points the subject is
459
+ * returned unchanged (no clipping).
460
+ *
461
+ * Preserving the polygon (rather than collapsing to an AABB) lets callers
462
+ * chain multiple clips without reintroducing corners removed by an inner clip.
463
+ */
464
+ function clipPolygon(subject, clipCorners) {
465
+ if (clipCorners.length < 3) return subject;
466
+ let cx = 0;
467
+ let cy = 0;
468
+ for (const c of clipCorners) {
469
+ cx += c.x;
470
+ cy += c.y;
471
+ }
472
+ cx /= clipCorners.length;
473
+ cy /= clipCorners.length;
474
+ let polygon = subject;
475
+ for (let i = 0; i < clipCorners.length; i++) {
476
+ if (polygon.length === 0) return null;
477
+ const a = clipCorners[i];
478
+ const b = clipCorners[(i + 1) % clipCorners.length];
479
+ const centroidCross = crossProduct(a, b, {
480
+ x: cx,
481
+ y: cy
482
+ });
483
+ polygon = clipHalfPlane(polygon, a, b, centroidCross >= 0);
484
+ }
485
+ return polygon.length === 0 ? null : polygon;
486
+ }
487
+ /**
488
+ * Clip an axis-aligned VisualBounds rectangle against a convex polygon
489
+ * (e.g. the 4 canvas-space corners of a rotated clipping ancestor).
490
+ *
491
+ * Returns the AABB of the intersection, or null if the bounds are fully
492
+ * outside the clip polygon. Delegates to {@link clipPolygon}.
493
+ *
494
+ * For a non-rotated clip (axis-aligned corners) the result is identical
495
+ * to `intersectVisualBounds`.
496
+ */
497
+ function clipBoundsToPolygon(bounds, clipCorners) {
498
+ if (clipCorners.length < 3) return bounds;
499
+ const polygon = clipPolygon([
500
+ {
501
+ x: bounds.minX,
502
+ y: bounds.minY
503
+ },
504
+ {
505
+ x: bounds.maxX,
506
+ y: bounds.minY
507
+ },
508
+ {
509
+ x: bounds.maxX,
510
+ y: bounds.maxY
511
+ },
512
+ {
513
+ x: bounds.minX,
514
+ y: bounds.maxY
515
+ }
516
+ ], clipCorners);
517
+ if (!polygon) return null;
518
+ let minX = Infinity;
519
+ let minY = Infinity;
520
+ let maxX = -Infinity;
521
+ let maxY = -Infinity;
522
+ for (const p of polygon) {
523
+ if (p.x < minX) minX = p.x;
524
+ if (p.y < minY) minY = p.y;
525
+ if (p.x > maxX) maxX = p.x;
526
+ if (p.y > maxY) maxY = p.y;
527
+ }
528
+ return minX < maxX && minY < maxY ? {
529
+ minX,
530
+ minY,
531
+ maxX,
532
+ maxY
533
+ } : null;
534
+ }
535
+ //#endregion
536
+ //#region src/constants.ts
537
+ const BLACK = {
538
+ r: 0,
539
+ g: 0,
540
+ b: 0,
541
+ a: 1
542
+ };
543
+ const TRANSPARENT = {
544
+ r: 0,
545
+ g: 0,
546
+ b: 0,
547
+ a: 0
548
+ };
549
+ const DEFAULT_FONT_FAMILY = "Inter";
550
+ const DEFAULT_STROKE_MITER_LIMIT = 4;
551
+ //#endregion
552
+ //#region src/node-defaults.ts
553
+ function createDefaultSourceMetadata() {
554
+ return {
555
+ format: null,
556
+ id: null,
557
+ orderKey: null,
558
+ editedFields: [],
559
+ fig: {
560
+ rawSize: null,
561
+ rawTransform: null,
562
+ rawNodeFields: {},
563
+ layout: null,
564
+ symbolOverrides: [],
565
+ componentPropAssignments: [],
566
+ derivedSymbolData: [],
567
+ derivedSymbolDataLayoutVersion: null,
568
+ uniformScaleFactor: null
569
+ }
570
+ };
571
+ }
572
+ function createDefaultNode(generateId, type, overrides = {}) {
573
+ return {
574
+ id: generateId(),
575
+ type,
576
+ name: type.charAt(0) + type.slice(1).toLowerCase(),
577
+ parentId: null,
578
+ childIds: [],
579
+ x: 0,
580
+ y: 0,
581
+ width: 100,
582
+ height: 100,
583
+ rotation: 0,
584
+ source: createDefaultSourceMetadata(),
585
+ derivedLayout: null,
586
+ fills: type === "TEXT" ? [{
587
+ type: "SOLID",
588
+ color: BLACK,
589
+ opacity: 1,
590
+ visible: true
591
+ }] : [],
592
+ strokes: [],
593
+ effects: [],
594
+ layoutGrids: [],
595
+ guides: [],
596
+ fillStyleId: null,
597
+ strokeStyleId: null,
598
+ textStyleId: null,
599
+ effectStyleId: null,
600
+ gridStyleId: null,
601
+ sharedStyleType: null,
602
+ opacity: 1,
603
+ cornerRadius: 0,
604
+ topLeftRadius: 0,
605
+ topRightRadius: 0,
606
+ bottomRightRadius: 0,
607
+ bottomLeftRadius: 0,
608
+ independentCorners: false,
609
+ cornerSmoothing: 0,
610
+ visible: true,
611
+ locked: false,
612
+ clipsContent: false,
613
+ text: "",
614
+ fontSize: 14,
615
+ fontFamily: DEFAULT_FONT_FAMILY,
616
+ fontWeight: 400,
617
+ italic: false,
618
+ textAlignHorizontal: "LEFT",
619
+ textDirection: "AUTO",
620
+ textLanguage: null,
621
+ leadingTrim: "NONE",
622
+ lineHeight: null,
623
+ letterSpacing: 0,
624
+ layoutMode: "NONE",
625
+ layoutDirection: "AUTO",
626
+ layoutWrap: "NO_WRAP",
627
+ primaryAxisAlign: "MIN",
628
+ counterAxisAlign: "MIN",
629
+ primaryAxisSizing: "FIXED",
630
+ counterAxisSizing: "FIXED",
631
+ itemSpacing: 0,
632
+ counterAxisSpacing: 0,
633
+ paddingTop: 0,
634
+ paddingRight: 0,
635
+ paddingBottom: 0,
636
+ paddingLeft: 0,
637
+ blendMode: "PASS_THROUGH",
638
+ layoutPositioning: "AUTO",
639
+ layoutGrow: 0,
640
+ layoutAlignSelf: "AUTO",
641
+ vectorNetwork: null,
642
+ handleMirroring: "NONE",
643
+ fillGeometry: [],
644
+ strokeGeometry: [],
645
+ arcData: null,
646
+ textAlignVertical: "TOP",
647
+ textAutoResize: "NONE",
648
+ textCase: "ORIGINAL",
649
+ textDecoration: "NONE",
650
+ textDecorationStyle: "SOLID",
651
+ textDecorationThickness: null,
652
+ textDecorationFills: [],
653
+ textDecorationSkipInk: true,
654
+ textUnderlineOffset: null,
655
+ maxLines: null,
656
+ styleRuns: [],
657
+ fontVariations: [],
658
+ fontFeatures: [],
659
+ horizontalConstraint: "MIN",
660
+ verticalConstraint: "MIN",
661
+ strokeCap: "NONE",
662
+ strokeJoin: "MITER",
663
+ dashPattern: [],
664
+ borderTopWeight: 0,
665
+ borderRightWeight: 0,
666
+ borderBottomWeight: 0,
667
+ borderLeftWeight: 0,
668
+ independentStrokeWeights: false,
669
+ strokeMiterLimit: 4,
670
+ minWidth: null,
671
+ maxWidth: null,
672
+ minHeight: null,
673
+ maxHeight: null,
674
+ isMask: false,
675
+ maskType: "ALPHA",
676
+ maskIsOutline: false,
677
+ gridTemplateColumns: [],
678
+ gridTemplateRows: [],
679
+ gridColumnGap: 0,
680
+ gridRowGap: 0,
681
+ gridPosition: null,
682
+ counterAxisAlignContent: "AUTO",
683
+ itemReverseZIndex: false,
684
+ strokesIncludedInLayout: false,
685
+ expanded: true,
686
+ textTruncation: "DISABLED",
687
+ autoRename: true,
688
+ pointCount: 5,
689
+ starInnerRadius: .38,
690
+ componentId: null,
691
+ instanceOverrides: createInstanceOverrideState(),
692
+ componentPropertyDefinitions: [],
693
+ componentPropertyReferences: [],
694
+ componentPropertyAssignments: {},
695
+ componentPropertyValues: {},
696
+ componentKey: null,
697
+ sourceLibraryKey: null,
698
+ publishId: null,
699
+ overrideKey: null,
700
+ sharedSymbolVersion: null,
701
+ publishedVersion: null,
702
+ librarySource: null,
703
+ isPublishable: false,
704
+ isSymbolPublishable: false,
705
+ symbolDescription: "",
706
+ symbolLinks: [],
707
+ variantPropSpecs: [],
708
+ boundVariables: {},
709
+ variableModes: {},
710
+ exportSettings: [],
711
+ pluginData: [],
712
+ pluginRelaunchData: [],
713
+ internalOnly: false,
714
+ flipX: false,
715
+ flipY: false,
716
+ textPicture: null,
717
+ derivedTextGlyphs: null,
718
+ textPathData: null,
719
+ textPathBox: null,
720
+ ...overrides
721
+ };
722
+ }
723
+ const CONTAINER_TYPES = /* @__PURE__ */ new Set([
724
+ "CANVAS",
725
+ "FRAME",
726
+ "GROUP",
727
+ "BOOLEAN_OPERATION",
728
+ "SECTION",
729
+ "COMPONENT",
730
+ "COMPONENT_SET",
731
+ "INSTANCE"
732
+ ]);
733
+ //#endregion
734
+ //#region src/vector-network.ts
735
+ /** Concatenate vector networks while preserving independent geometry. */
736
+ function mergeVectorNetworks(networks) {
737
+ const vertices = [];
738
+ const segments = [];
739
+ const regions = [];
740
+ let vertexOffset = 0;
741
+ let segmentOffset = 0;
742
+ for (const network of networks) {
743
+ for (const vertex of network.vertices) vertices.push({ ...vertex });
744
+ for (const segment of network.segments) segments.push({
745
+ ...segment,
746
+ start: segment.start + vertexOffset,
747
+ end: segment.end + vertexOffset,
748
+ tangentStart: { ...segment.tangentStart },
749
+ tangentEnd: { ...segment.tangentEnd }
750
+ });
751
+ for (const region of network.regions) {
752
+ const loops = [];
753
+ for (const loop of region.loops) {
754
+ const shifted = [];
755
+ for (const segmentIndex of loop) shifted.push(segmentIndex + segmentOffset);
756
+ loops.push(shifted);
757
+ }
758
+ regions.push({
759
+ windingRule: region.windingRule,
760
+ loops
761
+ });
762
+ }
763
+ vertexOffset += network.vertices.length;
764
+ segmentOffset += network.segments.length;
765
+ }
766
+ return {
767
+ vertices,
768
+ segments,
769
+ regions
770
+ };
771
+ }
772
+ /**
773
+ * Map a VectorNetwork through an affine matrix: vertices as points,
774
+ * tangents as direction vectors (linear part only, no translation).
775
+ * Returns a deep copy; the input is not mutated.
776
+ */
777
+ function transformVectorNetwork(m, vn) {
778
+ const mapVector = (v) => ({
779
+ x: m[0] * v.x + m[1] * v.y,
780
+ y: m[3] * v.x + m[4] * v.y
781
+ });
782
+ return {
783
+ vertices: vn.vertices.map((v) => ({
784
+ ...v,
785
+ x: m[0] * v.x + m[1] * v.y + m[2],
786
+ y: m[3] * v.x + m[4] * v.y + m[5]
787
+ })),
788
+ segments: vn.segments.map((s) => ({
789
+ ...s,
790
+ tangentStart: mapVector(s.tangentStart),
791
+ tangentEnd: mapVector(s.tangentEnd)
792
+ })),
793
+ regions: vn.regions.map((r) => ({
794
+ windingRule: r.windingRule,
795
+ loops: r.loops.map((l) => [...l])
796
+ }))
797
+ };
798
+ }
799
+ /** Structural equality of two VectorNetworks (order-sensitive, exact values). */
800
+ function vectorNetworksEqual(a, b) {
801
+ return isEqual(a.vertices, b.vertices) && isEqual(a.segments, b.segments) && isEqual(a.regions, b.regions);
802
+ }
803
+ /** Deep-copy a VectorNetwork, stripping any Vue Proxy wrappers. */
804
+ function cloneVectorNetwork(vn) {
805
+ return {
806
+ vertices: vn.vertices.map((v) => ({ ...v })),
807
+ segments: vn.segments.map((s) => ({
808
+ ...s,
809
+ tangentStart: { ...s.tangentStart },
810
+ tangentEnd: { ...s.tangentEnd }
811
+ })),
812
+ regions: vn.regions.map((r) => ({
813
+ windingRule: r.windingRule,
814
+ loops: r.loops.map((l) => [...l])
815
+ }))
816
+ };
817
+ }
818
+ /**
819
+ * Validate a VectorNetwork structure, returning an array of error messages.
820
+ * Empty array means the network is valid.
821
+ */
822
+ function validateVectorNetwork(value) {
823
+ if (!isRecord(value)) return ["network must be an object"];
824
+ if (!Array.isArray(value.vertices)) return ["vertices must be an array"];
825
+ if (!Array.isArray(value.segments)) return ["segments must be an array"];
826
+ const errors = [];
827
+ validateVertices(value.vertices, errors);
828
+ validateSegments(value.segments, value.vertices.length, errors);
829
+ const typedSegments = value.segments.filter(isSegmentRecord);
830
+ if (value.regions !== void 0) {
831
+ if (Array.isArray(value.regions)) validateRegions(value.regions, value.segments.length, typedSegments.length === value.segments.length ? typedSegments : null, errors);
832
+ else errors.push("regions must be an array when provided");
833
+ }
834
+ return errors;
835
+ }
836
+ function validateVertices(vertices, errors) {
837
+ for (let index = 0; index < vertices.length; index++) if (!isFiniteVector(vertices[index])) errors.push(`vertex[${index}]: x and y must be finite numbers`);
838
+ }
839
+ function validateSegments(segments, vertexCount, errors) {
840
+ for (let index = 0; index < segments.length; index++) {
841
+ const segment = segments[index];
842
+ if (!isRecord(segment)) {
843
+ errors.push(`segment[${index}] must be an object`);
844
+ continue;
845
+ }
846
+ if (!isInteger(segment.start) || !isInteger(segment.end)) {
847
+ errors.push(`segment[${index}]: start and end must be integers`);
848
+ continue;
849
+ }
850
+ if (segment.start < 0 || segment.start >= vertexCount) errors.push(`segment[${index}]: start index ${segment.start} out of range`);
851
+ if (segment.end < 0 || segment.end >= vertexCount) errors.push(`segment[${index}]: end index ${segment.end} out of range`);
852
+ validateSegmentTangents(segment, index, errors);
853
+ }
854
+ }
855
+ function validateSegmentTangents(segment, index, errors) {
856
+ for (const tangentKey of ["tangentStart", "tangentEnd"]) {
857
+ const tangent = segment[tangentKey];
858
+ if (tangent !== void 0 && !isFiniteVector(tangent)) errors.push(`segment[${index}]: ${tangentKey} must contain finite x and y numbers`);
859
+ }
860
+ }
861
+ function validateRegions(regions, segmentCount, segments, errors) {
862
+ for (let regionIndex = 0; regionIndex < regions.length; regionIndex++) {
863
+ const region = regions[regionIndex];
864
+ if (!isRecord(region) || !Array.isArray(region.loops)) {
865
+ errors.push(`region[${regionIndex}]: loops must be an array`);
866
+ continue;
867
+ }
868
+ if (region.windingRule !== "NONZERO" && region.windingRule !== "EVENODD") errors.push(`region[${regionIndex}]: windingRule must be NONZERO or EVENODD`);
869
+ if (region.loops.length === 0) errors.push(`region[${regionIndex}]: loops must contain at least one loop`);
870
+ validateRegionLoops(region.loops, regionIndex, segmentCount, segments, errors);
871
+ }
872
+ }
873
+ function validateRegionLoops(loops, regionIndex, segmentCount, segments, errors) {
874
+ for (let loopIndex = 0; loopIndex < loops.length; loopIndex++) {
875
+ const loop = loops[loopIndex];
876
+ if (!Array.isArray(loop)) {
877
+ errors.push(`region[${regionIndex}].loop[${loopIndex}] must be an array`);
878
+ continue;
879
+ }
880
+ if (loop.length === 0) {
881
+ errors.push(`region[${regionIndex}].loop[${loopIndex}] must contain at least one segment`);
882
+ continue;
883
+ }
884
+ const segmentIndices = [];
885
+ for (const segmentIndex of loop) if (!isInteger(segmentIndex) || segmentIndex < 0 || segmentIndex >= segmentCount) errors.push(`region[${regionIndex}].loop[${loopIndex}]: segment index ${String(segmentIndex)} out of range`);
886
+ else segmentIndices.push(segmentIndex);
887
+ if (segmentIndices.length !== loop.length) continue;
888
+ if (new Set(segmentIndices).size !== segmentIndices.length) {
889
+ errors.push(`region[${regionIndex}].loop[${loopIndex}] must not repeat segments`);
890
+ continue;
891
+ }
892
+ if (segments && !formsContinuousChain(segmentIndices, segments)) errors.push(`region[${regionIndex}].loop[${loopIndex}] segments must form a continuous chain`);
893
+ }
894
+ }
895
+ function formsContinuousChain(indices, segments) {
896
+ if (indices.length <= 1) return true;
897
+ const first = segments[indices[0]];
898
+ return followsChain(indices, segments, first.end) || followsChain(indices, segments, first.start);
899
+ }
900
+ function followsChain(indices, segments, initialEnd) {
901
+ let current = initialEnd;
902
+ for (let index = 1; index < indices.length; index++) {
903
+ const segment = segments[indices[index]];
904
+ if (segment.start === current) current = segment.end;
905
+ else if (segment.end === current) current = segment.start;
906
+ else return false;
907
+ }
908
+ return true;
909
+ }
910
+ function isSegmentRecord(value) {
911
+ return isRecord(value) && isInteger(value.start) && isInteger(value.end);
912
+ }
913
+ function isFiniteVector(value) {
914
+ return isRecord(value) && typeof value.x === "number" && Number.isFinite(value.x) && typeof value.y === "number" && Number.isFinite(value.y);
915
+ }
916
+ function isInteger(value) {
917
+ return typeof value === "number" && Number.isInteger(value);
918
+ }
919
+ function isRecord(value) {
920
+ return typeof value === "object" && value !== null;
921
+ }
922
+ /**
923
+ * Ensure every segment has tangentStart/tangentEnd and a regions array.
924
+ * Missing tangents default to {x:0, y:0} (straight line segments).
925
+ * Use at system boundaries where input may come from JSON/MCP.
926
+ */
927
+ function normalizeVectorNetwork(vn) {
928
+ const ZERO = {
929
+ x: 0,
930
+ y: 0
931
+ };
932
+ return {
933
+ vertices: vn.vertices,
934
+ segments: vn.segments.map((s) => ({
935
+ start: s.start,
936
+ end: s.end,
937
+ tangentStart: s.tangentStart ?? { ...ZERO },
938
+ tangentEnd: s.tangentEnd ?? { ...ZERO }
939
+ })),
940
+ regions: vn.regions ?? []
941
+ };
942
+ }
943
+ //#endregion
944
+ //#region src/copy.ts
945
+ function copyFill(f) {
946
+ const copy = {
947
+ ...f,
948
+ color: { ...f.color }
949
+ };
950
+ if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop);
951
+ if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform };
952
+ if (f.imageTransform) copy.imageTransform = { ...f.imageTransform };
953
+ if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing };
954
+ if (f.noiseSize) copy.noiseSize = { ...f.noiseSize };
955
+ return copy;
956
+ }
957
+ function copyStroke(s) {
958
+ const copy = {
959
+ ...s,
960
+ color: { ...s.color }
961
+ };
962
+ if (s.dashPattern) copy.dashPattern = [...s.dashPattern];
963
+ return copy;
964
+ }
965
+ function copyEffect(e) {
966
+ return {
967
+ ...e,
968
+ color: { ...e.color },
969
+ offset: { ...e.offset }
970
+ };
971
+ }
972
+ function copyStyleRun(r) {
973
+ return {
974
+ ...r,
975
+ style: {
976
+ ...r.style,
977
+ fills: r.style.fills ? r.style.fills.map(copyFill) : void 0,
978
+ textDecorationFills: r.style.textDecorationFills ? r.style.textDecorationFills.map(copyFill) : void 0,
979
+ fontVariations: r.style.fontVariations ? r.style.fontVariations.map((v) => ({ ...v })) : void 0,
980
+ fontFeatures: r.style.fontFeatures ? r.style.fontFeatures.map((v) => ({ ...v })) : void 0
981
+ }
982
+ };
983
+ }
984
+ const internalCopySources = /* @__PURE__ */ new WeakMap();
985
+ /** Record immutable lineage for an internal deep copy without sharing mutable values. */
986
+ function markCopySource(source, copy) {
987
+ internalCopySources.set(copy, internalCopySources.get(source) ?? source);
988
+ return copy;
989
+ }
990
+ /** Compare internal deep copies in O(1) without traversing large paint or text payloads. */
991
+ function hasSameCopySource(left, right) {
992
+ if (left === right) return true;
993
+ return (internalCopySources.get(left) ?? left) === (internalCopySources.get(right) ?? right);
994
+ }
995
+ function copyFills(fills) {
996
+ return fills.map(copyFill);
997
+ }
998
+ function copyStrokes(strokes) {
999
+ return strokes.map(copyStroke);
1000
+ }
1001
+ function copyEffects(effects) {
1002
+ return effects.map(copyEffect);
1003
+ }
1004
+ function copyLayoutGrids(grids) {
1005
+ return grids.map((grid) => ({
1006
+ ...grid,
1007
+ color: grid.color ? { ...grid.color } : void 0
1008
+ }));
1009
+ }
1010
+ function copyStyleRuns(runs) {
1011
+ return runs.map(copyStyleRun);
1012
+ }
1013
+ /** Keep path-level fills across copy/scale/transform (resize snapshots). */
1014
+ function withPathPaintMeta(path, commandsBlob) {
1015
+ return {
1016
+ windingRule: path.windingRule,
1017
+ commandsBlob,
1018
+ ...path.fills ? { fills: copyFills(path.fills) } : {}
1019
+ };
1020
+ }
1021
+ function copyGeometryPaths(paths) {
1022
+ return paths.map((p) => withPathPaintMeta(p, p.commandsBlob.slice()));
1023
+ }
1024
+ /**
1025
+ * Affine-transform every coordinate pair in a path command blob (returns a
1026
+ * copy): (x, y) → (m00·x + m01·y + tx, m10·x + m11·y + ty).
1027
+ * Command layout: 1=move/2=line (1 pair), 3=quad (2 pairs), 4=cubic (3 pairs)
1028
+ * — font-glyph blobs are quad-heavy, so skipping command 3 desyncs the walk.
1029
+ */
1030
+ function transformGeometryBlob(blob, m00, m01, m10, m11, tx = 0, ty = 0) {
1031
+ const out = blob.slice();
1032
+ const dv = new DataView(out.buffer, out.byteOffset, out.byteLength);
1033
+ let offset = 0;
1034
+ while (offset < out.length) {
1035
+ const command = out[offset++];
1036
+ const coords = geometryCommandCoordCount(command);
1037
+ if (coords == null) break;
1038
+ for (let i = 0; i < coords; i++) {
1039
+ if (offset + 8 > out.length) break;
1040
+ const x = dv.getFloat32(offset, true);
1041
+ const y = dv.getFloat32(offset + 4, true);
1042
+ dv.setFloat32(offset, m00 * x + m01 * y + tx, true);
1043
+ dv.setFloat32(offset + 4, m10 * x + m11 * y + ty, true);
1044
+ offset += 8;
1045
+ }
1046
+ }
1047
+ return out;
1048
+ }
1049
+ function transformGeometryPaths(paths, m00, m01, m10, m11, tx = 0, ty = 0) {
1050
+ return paths.map((g) => withPathPaintMeta(g, transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty)));
1051
+ }
1052
+ /**
1053
+ * Scale path command blob coordinates by (sx, sy).
1054
+ * Identity scale returns a deep copy (same as copyGeometryPaths).
1055
+ */
1056
+ function scaleGeometryPaths(paths, sx, sy) {
1057
+ if (sx === 1 && sy === 1) return copyGeometryPaths(paths);
1058
+ return transformGeometryPaths(paths, sx, 0, 0, sy);
1059
+ }
1060
+ /** Copy an optional array: non-empty → mapped, empty → [], undefined → undefined. */
1061
+ function copyOpt(arr, fn) {
1062
+ if (arr === void 0) return void 0;
1063
+ return arr.length > 0 ? fn(arr) : [];
1064
+ }
1065
+ function copyGradientStop(gs) {
1066
+ return {
1067
+ color: { ...gs.color },
1068
+ position: gs.position
1069
+ };
1070
+ }
1071
+ function copySpread(arr) {
1072
+ return arr?.map((item) => ({ ...item })) ?? [];
1073
+ }
1074
+ function copyPropertyDefs(defs) {
1075
+ return defs?.map((d) => ({
1076
+ ...d,
1077
+ variantOptions: d.variantOptions ? [...d.variantOptions] : void 0,
1078
+ preferredValues: d.preferredValues ? [...d.preferredValues] : void 0
1079
+ })) ?? [];
1080
+ }
1081
+ /** Deep-copy path-text glyphs (fresh commandsBlob buffers). */
1082
+ function copyDerivedGlyphs(glyphs) {
1083
+ return glyphs ? glyphs.map((g) => ({
1084
+ ...g,
1085
+ commandsBlob: new Uint8Array(g.commandsBlob)
1086
+ })) : null;
1087
+ }
1088
+ function copyArcData(a) {
1089
+ return {
1090
+ startingAngle: a.startingAngle,
1091
+ endingAngle: a.endingAngle,
1092
+ innerRadius: a.innerRadius
1093
+ };
1094
+ }
1095
+ function cloneNodeProps(src, componentId, mode = "deep") {
1096
+ const { id: _, parentId: _p, childIds: _c, ...rest } = src;
1097
+ if (mode === "fig-import") return {
1098
+ ...rest,
1099
+ ...componentId !== null ? { componentId } : {},
1100
+ source: createDefaultSourceMetadata(),
1101
+ boundVariables: { ...src.boundVariables },
1102
+ variableModes: { ...src.variableModes },
1103
+ instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
1104
+ componentPropertyAssignments: { ...src.componentPropertyAssignments },
1105
+ componentPropertyValues: { ...src.componentPropertyValues }
1106
+ };
1107
+ return {
1108
+ ...rest,
1109
+ ...componentId !== null ? { componentId } : {},
1110
+ boundVariables: { ...src.boundVariables },
1111
+ variableModes: { ...src.variableModes },
1112
+ instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
1113
+ fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),
1114
+ strokes: copyOpt(src.strokes, (value) => markCopySource(value, copyStrokes(value))),
1115
+ effects: copyOpt(src.effects, (value) => markCopySource(value, copyEffects(value))),
1116
+ layoutGrids: copyOpt(src.layoutGrids, copyLayoutGrids),
1117
+ guides: copyOpt(src.guides, (guides) => guides.map((guide) => ({ ...guide }))),
1118
+ styleRuns: copyOpt(src.styleRuns, (value) => markCopySource(value, copyStyleRuns(value))),
1119
+ source: componentId === null ? structuredClone(src.source) : createDefaultSourceMetadata(),
1120
+ dashPattern: copyOpt(src.dashPattern, (a) => [...a]),
1121
+ fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),
1122
+ fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),
1123
+ textDecorationFills: copyOpt(src.textDecorationFills, copyFills),
1124
+ fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),
1125
+ strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),
1126
+ gridTemplateColumns: copySpread(src.gridTemplateColumns),
1127
+ gridTemplateRows: copySpread(src.gridTemplateRows),
1128
+ componentPropertyDefinitions: copyPropertyDefs(src.componentPropertyDefinitions),
1129
+ componentPropertyReferences: copySpread(src.componentPropertyReferences),
1130
+ componentPropertyAssignments: { ...src.componentPropertyAssignments },
1131
+ symbolLinks: copySpread(src.symbolLinks),
1132
+ variantPropSpecs: copySpread(src.variantPropSpecs),
1133
+ pluginData: copySpread(src.pluginData),
1134
+ pluginRelaunchData: copySpread(src.pluginRelaunchData),
1135
+ exportSettings: copySpread(src.exportSettings),
1136
+ componentPropertyValues: { ...src.componentPropertyValues },
1137
+ derivedLayout: src.derivedLayout ? { ...src.derivedLayout } : null,
1138
+ arcData: src.arcData ? copyArcData(src.arcData) : null,
1139
+ vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,
1140
+ textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,
1141
+ derivedTextGlyphs: src.derivedTextGlyphs ? markCopySource(src.derivedTextGlyphs, copyDerivedGlyphs(src.derivedTextGlyphs) ?? []) : null,
1142
+ textPathData: src.textPathData ? structuredClone(src.textPathData) : null,
1143
+ textPathBox: src.textPathBox ? { ...src.textPathBox } : null,
1144
+ gridPosition: src.gridPosition ? { ...src.gridPosition } : null
1145
+ };
1146
+ }
1147
+ //#endregion
1148
+ //#region src/instances.ts
1149
+ const INSTANCE_SYNC_TEXT_PROPS = [
1150
+ "name",
1151
+ "text",
1152
+ "fontSize",
1153
+ "fontWeight",
1154
+ "fontFamily",
1155
+ "textDirection"
1156
+ ];
1157
+ const INSTANCE_SYNC_PROPS = [
1158
+ "width",
1159
+ "height",
1160
+ "minWidth",
1161
+ "maxWidth",
1162
+ "minHeight",
1163
+ "maxHeight",
1164
+ "fills",
1165
+ "strokes",
1166
+ "effects",
1167
+ "opacity",
1168
+ "cornerRadius",
1169
+ "topLeftRadius",
1170
+ "topRightRadius",
1171
+ "bottomRightRadius",
1172
+ "bottomLeftRadius",
1173
+ "independentCorners",
1174
+ "layoutMode",
1175
+ "layoutDirection",
1176
+ "layoutWrap",
1177
+ "primaryAxisAlign",
1178
+ "counterAxisAlign",
1179
+ "primaryAxisSizing",
1180
+ "counterAxisSizing",
1181
+ "itemSpacing",
1182
+ "counterAxisSpacing",
1183
+ "paddingTop",
1184
+ "paddingRight",
1185
+ "paddingBottom",
1186
+ "paddingLeft",
1187
+ "gridTemplateColumns",
1188
+ "gridTemplateRows",
1189
+ "gridColumnGap",
1190
+ "gridRowGap",
1191
+ "gridPosition",
1192
+ "clipsContent",
1193
+ "independentStrokeWeights",
1194
+ "borderTopWeight",
1195
+ "borderRightWeight",
1196
+ "borderBottomWeight",
1197
+ "borderLeftWeight",
1198
+ "boundVariables",
1199
+ "variableModes"
1200
+ ];
1201
+ const INSTANCE_SYNC_FIELDS = [...INSTANCE_SYNC_PROPS, ...INSTANCE_SYNC_TEXT_PROPS];
1202
+ function setSceneProp(target, key, value) {
1203
+ target[key] = value;
1204
+ }
1205
+ function copyProp(target, source, key) {
1206
+ if (key === "fills") setSceneProp(target, key, copyFills(source.fills));
1207
+ else if (key === "strokes") setSceneProp(target, key, copyStrokes(source.strokes));
1208
+ else if (key === "effects") setSceneProp(target, key, copyEffects(source.effects));
1209
+ else if (key === "styleRuns") setSceneProp(target, key, copyStyleRuns(source.styleRuns));
1210
+ else if (key === "boundVariables") setSceneProp(target, key, { ...source.boundVariables });
1211
+ else if (key === "variableModes") setSceneProp(target, key, { ...source.variableModes });
1212
+ else if (key === "gridPosition") setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null);
1213
+ else {
1214
+ const value = source[key];
1215
+ setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value);
1216
+ }
1217
+ }
1218
+ function cloneChildrenWithMapping(graph, sourceParentId, destParentId, mode = "deep") {
1219
+ if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return;
1220
+ const sourceParent = graph.nodes.get(sourceParentId);
1221
+ if (!sourceParent) return;
1222
+ for (const childId of sourceParent.childIds) {
1223
+ const src = graph.nodes.get(childId);
1224
+ if (!src) continue;
1225
+ const clone = graph.createNode(src.type, destParentId, cloneNodeProps(src, childId, mode));
1226
+ if (src.childIds.length > 0) cloneChildrenWithMapping(graph, childId, clone.id, mode);
1227
+ }
1228
+ }
1229
+ function linkMatchedChild(overrides, instParentId, instChild, compChildId) {
1230
+ if (instChild.type === "INSTANCE") setInstanceOverride(overrides, instParentId, instChild.id, "sourceComponentId", compChildId);
1231
+ else instChild.componentId = compChildId;
1232
+ }
1233
+ function matchFallbackChildren(graph, compParent, instParent, instParentId, overrides, instChildMap, usedInstChildIds) {
1234
+ const fallbackByType = /* @__PURE__ */ new Map();
1235
+ const remainingCandidateCount = /* @__PURE__ */ new Map();
1236
+ const unmatchedComponentCount = /* @__PURE__ */ new Map();
1237
+ for (const compChildId of compParent.childIds) {
1238
+ if (instChildMap.has(compChildId)) continue;
1239
+ const child = graph.nodes.get(compChildId);
1240
+ if (child) unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1);
1241
+ }
1242
+ for (const childId of instParent.childIds) {
1243
+ const child = graph.nodes.get(childId);
1244
+ if (!child || usedInstChildIds.has(child.id)) continue;
1245
+ remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1);
1246
+ let byName = fallbackByType.get(child.type);
1247
+ if (!byName) {
1248
+ byName = /* @__PURE__ */ new Map();
1249
+ fallbackByType.set(child.type, byName);
1250
+ }
1251
+ const queue = byName.get(child.name);
1252
+ if (queue) queue.push(child);
1253
+ else byName.set(child.name, [child]);
1254
+ }
1255
+ for (const compChildId of compParent.childIds) {
1256
+ if (instChildMap.has(compChildId)) continue;
1257
+ const compChild = graph.nodes.get(compChildId);
1258
+ if (!compChild) continue;
1259
+ const candidatesByName = fallbackByType.get(compChild.type);
1260
+ const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0;
1261
+ if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue;
1262
+ const match = candidatesByName?.get(compChild.name)?.shift();
1263
+ if (!match) continue;
1264
+ remainingCandidateCount.set(compChild.type, candidateCount - 1);
1265
+ instChildMap.set(compChildId, match);
1266
+ usedInstChildIds.add(match.id);
1267
+ linkMatchedChild(overrides, instParentId, match, compChildId);
1268
+ }
1269
+ }
1270
+ function sortInstanceChildren(graph, instParent, instParentId, compChildOrder, overrides) {
1271
+ const orderMap = /* @__PURE__ */ new Map();
1272
+ for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i);
1273
+ const ranks = /* @__PURE__ */ new Map();
1274
+ for (let index = 0; index < instParent.childIds.length; index++) {
1275
+ const childId = instParent.childIds[index];
1276
+ const node = graph.nodes.get(childId);
1277
+ const source = node ? getInstanceOverride(overrides, instParentId, node.id, "sourceComponentId") : void 0;
1278
+ const mapped = typeof source === "string" ? source : node?.componentId;
1279
+ const componentIndex = mapped ? orderMap.get(mapped) : void 0;
1280
+ ranks.set(childId, componentIndex ?? compChildOrder.length + index);
1281
+ }
1282
+ instParent.childIds.sort((left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0));
1283
+ }
1284
+ /** True when syncing `compParentId` into `instParentId` would form a cycle. */
1285
+ function isCyclicSync(graph, compParentId, instParentId) {
1286
+ return compParentId === instParentId || graph.isDescendant(instParentId, compParentId);
1287
+ }
1288
+ function syncChildren(graph, compParentId, instParentId, overrides) {
1289
+ if (isCyclicSync(graph, compParentId, instParentId)) return;
1290
+ const compParent = graph.nodes.get(compParentId);
1291
+ const instParent = graph.nodes.get(instParentId);
1292
+ if (!compParent || !instParent) return;
1293
+ const instChildMap = /* @__PURE__ */ new Map();
1294
+ const usedInstChildIds = /* @__PURE__ */ new Set();
1295
+ const compChildIdSet = new Set(compParent.childIds);
1296
+ for (const childId of instParent.childIds) {
1297
+ const child = graph.nodes.get(childId);
1298
+ if (!child) continue;
1299
+ const sourceComponentId = getInstanceOverride(overrides, instParentId, child.id, "sourceComponentId");
1300
+ const mappedComponentId = typeof sourceComponentId === "string" ? sourceComponentId : child.componentId;
1301
+ if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {
1302
+ instChildMap.set(mappedComponentId, child);
1303
+ usedInstChildIds.add(child.id);
1304
+ }
1305
+ }
1306
+ matchFallbackChildren(graph, compParent, instParent, instParentId, overrides, instChildMap, usedInstChildIds);
1307
+ for (const compChildId of compParent.childIds) if (!instChildMap.has(compChildId)) {
1308
+ const src = graph.nodes.get(compChildId);
1309
+ if (!src) continue;
1310
+ const clone = graph.createNode(src.type, instParentId, cloneNodeProps(src, compChildId));
1311
+ if (src.childIds.length > 0) cloneChildrenWithMapping(graph, compChildId, clone.id);
1312
+ instChildMap.set(compChildId, clone);
1313
+ usedInstChildIds.add(clone.id);
1314
+ }
1315
+ for (const compChildId of compParent.childIds) {
1316
+ const compChild = graph.nodes.get(compChildId);
1317
+ const instChild = instChildMap.get(compChildId);
1318
+ if (!compChild || !instChild) continue;
1319
+ for (const key of INSTANCE_SYNC_FIELDS) {
1320
+ if (hasInstanceOverride$1(overrides, instParentId, instChild.id, key)) continue;
1321
+ copyProp(instChild, compChild, key);
1322
+ }
1323
+ if (compChild.childIds.length > 0 && !hasInstanceOverride$1(overrides, instParentId, instChild.id, "componentId")) syncChildren(graph, compChildId, instChild.id, overrides);
1324
+ }
1325
+ sortInstanceChildren(graph, instParent, instParentId, compParent.childIds, overrides);
1326
+ }
1327
+ function copyInstanceComponentProps(component) {
1328
+ const props = {};
1329
+ for (const key of INSTANCE_SYNC_PROPS) copyProp(props, component, key);
1330
+ return props;
1331
+ }
1332
+ function createInstance(graph, componentId, parentId, overrides = {}) {
1333
+ const component = graph.nodes.get(componentId);
1334
+ if (component?.type !== "COMPONENT") return null;
1335
+ const props = {
1336
+ ...copyInstanceComponentProps(component),
1337
+ name: component.name,
1338
+ componentId
1339
+ };
1340
+ const instance = graph.createNode("INSTANCE", parentId, {
1341
+ ...props,
1342
+ ...overrides
1343
+ });
1344
+ cloneChildrenWithMapping(graph, component.id, instance.id);
1345
+ return instance;
1346
+ }
1347
+ function populateInstanceChildren(graph, instanceId, componentId, mode = "deep") {
1348
+ const instance = graph.nodes.get(instanceId);
1349
+ const component = graph.nodes.get(componentId);
1350
+ if (!instance || !component || instance.type !== "INSTANCE") return;
1351
+ cloneChildrenWithMapping(graph, componentId, instanceId, mode);
1352
+ }
1353
+ function swapInstanceComponent(graph, instanceId, componentId) {
1354
+ const instance = graph.nodes.get(instanceId);
1355
+ const component = graph.nodes.get(componentId);
1356
+ if (!instance || component?.type !== "COMPONENT" || instance.type !== "INSTANCE") return;
1357
+ const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : void 0;
1358
+ const updates = { componentId };
1359
+ for (const key of INSTANCE_SYNC_PROPS) {
1360
+ if (hasInstanceOverride$1(instance.instanceOverrides, instance.id, instance.id, key)) continue;
1361
+ copyProp(updates, component, key);
1362
+ }
1363
+ if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name;
1364
+ const childIds = Array.from(instance.childIds);
1365
+ for (const childId of childIds) graph.deleteNode(childId);
1366
+ graph.updateNode(instanceId, updates);
1367
+ cloneChildrenWithMapping(graph, componentId, instanceId);
1368
+ }
1369
+ const syncingComponentsByGraph = /* @__PURE__ */ new WeakMap();
1370
+ function syncInstances(graph, componentId) {
1371
+ const component = graph.nodes.get(componentId);
1372
+ if (component?.type !== "COMPONENT") return;
1373
+ let syncing = syncingComponentsByGraph.get(graph);
1374
+ if (!syncing) {
1375
+ syncing = /* @__PURE__ */ new Set();
1376
+ syncingComponentsByGraph.set(graph, syncing);
1377
+ }
1378
+ if (syncing.has(componentId)) return;
1379
+ syncing.add(componentId);
1380
+ try {
1381
+ for (const instance of getInstances(graph, componentId)) {
1382
+ for (const key of INSTANCE_SYNC_PROPS) {
1383
+ if (hasInstanceOverride$1(instance.instanceOverrides, instance.id, instance.id, key)) continue;
1384
+ copyProp(instance, component, key);
1385
+ }
1386
+ syncChildren(graph, component.id, instance.id, instance.instanceOverrides);
1387
+ }
1388
+ } finally {
1389
+ syncing.delete(componentId);
1390
+ }
1391
+ }
1392
+ function detachInstance(graph, instanceId) {
1393
+ const node = graph.nodes.get(instanceId);
1394
+ if (node?.type !== "INSTANCE") return;
1395
+ if (node.componentId) graph.instanceIndex.get(node.componentId)?.delete(instanceId);
1396
+ node.type = "FRAME";
1397
+ node.componentId = null;
1398
+ clearInstanceOverrides(node.instanceOverrides);
1399
+ }
1400
+ function getMainComponent(graph, instanceId) {
1401
+ const node = graph.nodes.get(instanceId);
1402
+ if (!node?.componentId) return void 0;
1403
+ return graph.nodes.get(node.componentId);
1404
+ }
1405
+ function getInstances(graph, componentId) {
1406
+ const ids = graph.instanceIndex.get(componentId);
1407
+ if (!ids) return [];
1408
+ const instances = [];
1409
+ for (const id of ids) {
1410
+ const node = graph.nodes.get(id);
1411
+ if (node) instances.push(node);
1412
+ }
1413
+ return instances;
1414
+ }
1415
+ /** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */
1416
+ function findInstanceAncestor(graph, nodeId) {
1417
+ let current = graph.nodes.get(nodeId);
1418
+ while (current) {
1419
+ if (current.type === "INSTANCE") return current;
1420
+ current = current.parentId ? graph.nodes.get(current.parentId) : void 0;
1421
+ }
1422
+ }
1423
+ /**
1424
+ * True when a node field is protected from instance synchronization.
1425
+ */
1426
+ function hasInstanceOverride(graph, nodeId, field) {
1427
+ const instance = findInstanceAncestor(graph, nodeId);
1428
+ if (!instance) return false;
1429
+ return hasInstanceOverride$1(instance.instanceOverrides, instance.id, nodeId, field);
1430
+ }
1431
+ function recordInstanceOverrideValue(graph, nodeId, field, value) {
1432
+ const instance = findInstanceAncestor(graph, nodeId);
1433
+ if (!instance) return;
1434
+ setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field, value);
1435
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides });
1436
+ }
1437
+ function recordInstanceOverride(graph, nodeId, fields) {
1438
+ const instance = findInstanceAncestor(graph, nodeId);
1439
+ if (!instance) return;
1440
+ const relevant = [...fields].filter((field) => INSTANCE_SYNC_FIELDS.includes(field));
1441
+ if (relevant.length === 0) return;
1442
+ for (const field of relevant) setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field);
1443
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides });
1444
+ }
1445
+ //#endregion
1446
+ //#region src/components/properties.ts
1447
+ function componentPropertyOwners(graph, instance) {
1448
+ if (instance.type !== "INSTANCE" || !instance.componentId) return [];
1449
+ const component = graph.getNode(instance.componentId);
1450
+ if (!component) return [];
1451
+ const parent = component.parentId ? graph.getNode(component.parentId) : null;
1452
+ return parent?.type === "COMPONENT_SET" ? [parent, component] : [component];
1453
+ }
1454
+ function componentPropertyDefinitions(graph, instance) {
1455
+ const definitions = /* @__PURE__ */ new Map();
1456
+ for (const owner of componentPropertyOwners(graph, instance)) for (const definition of owner.componentPropertyDefinitions) if (!definitions.has(definition.id)) definitions.set(definition.id, definition);
1457
+ return [...definitions.values()];
1458
+ }
1459
+ function resolveComponentPropertyValue(graph, value) {
1460
+ const direct = graph.getNode(value);
1461
+ if (direct?.type === "COMPONENT") return direct;
1462
+ if (direct?.type === "COMPONENT_SET") {
1463
+ const componentId = direct.childIds.find((id) => graph.getNode(id)?.type === "COMPONENT");
1464
+ return componentId ? graph.getNode(componentId) ?? null : null;
1465
+ }
1466
+ for (const node of graph.getAllNodes()) if (node.type === "COMPONENT" && (node.componentKey === value || node.sourceLibraryKey === value || node.source.id === value)) return node;
1467
+ return null;
1468
+ }
1469
+ function findComponentPropertyTarget(graph, instance, propertyId) {
1470
+ return findComponentPropertyTargets(graph, instance, propertyId)[0] ?? null;
1471
+ }
1472
+ function findComponentPropertyTargets(graph, instance, propertyId) {
1473
+ if (instance.type !== "INSTANCE" || !instance.componentId) return [];
1474
+ const component = graph.getNode(instance.componentId);
1475
+ if (!component) return [];
1476
+ const targets = [];
1477
+ const visit = (sourceParent, instanceParent) => {
1478
+ for (const [index, childId] of sourceParent.childIds.entries()) {
1479
+ const source = graph.getNode(childId);
1480
+ const targetId = instanceParent.childIds[index];
1481
+ const target = targetId ? graph.getNode(targetId) : void 0;
1482
+ if (!source || !target) continue;
1483
+ const reference = source.componentPropertyReferences.find((candidate) => candidate.propertyId === propertyId);
1484
+ if (reference) targets.push({
1485
+ node: target,
1486
+ field: reference.field,
1487
+ source
1488
+ });
1489
+ visit(source, target);
1490
+ }
1491
+ };
1492
+ visit(component, instance);
1493
+ return targets;
1494
+ }
1495
+ function applyTextProperty(graph, owner, targets, value) {
1496
+ for (const item of targets) {
1497
+ if (item.field !== "TEXT" || item.node.type !== "TEXT") continue;
1498
+ graph.updateNode(item.node.id, { text: value });
1499
+ if (findInstanceAncestor(graph, item.node.id)) setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "text", value);
1500
+ }
1501
+ }
1502
+ function applyBooleanProperty(graph, owner, targets, value) {
1503
+ for (const item of targets) {
1504
+ if (item.field !== "VISIBLE") continue;
1505
+ const instance = findInstanceAncestor(graph, item.node.id);
1506
+ graph.updateNode(item.node.id, { visible: value === "true" });
1507
+ if (instance) setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "visible", value === "true");
1508
+ }
1509
+ }
1510
+ function applyInstanceSwapProperty(graph, owner, targets, target) {
1511
+ for (const item of targets) {
1512
+ if (item.field !== "INSTANCE_SWAP" || item.node.type !== "INSTANCE") continue;
1513
+ graph.swapInstanceComponent(item.node.id, target.id);
1514
+ setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "name", target.name);
1515
+ setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "componentId", target.id);
1516
+ setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "sourceComponentId", item.source.id);
1517
+ graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides });
1518
+ }
1519
+ }
1520
+ function applyComponentPropertyValue(graph, instanceId, definition, value) {
1521
+ const instance = graph.getNode(instanceId);
1522
+ if (instance?.type !== "INSTANCE") return null;
1523
+ if (definition.type === "VARIANT") return null;
1524
+ const targets = findComponentPropertyTargets(graph, instance, definition.id);
1525
+ const target = definition.type === "INSTANCE_SWAP" ? resolveComponentPropertyValue(graph, value) : null;
1526
+ if (definition.type === "INSTANCE_SWAP" && !target) return null;
1527
+ if (definition.type === "TEXT") applyTextProperty(graph, instance, targets, value);
1528
+ else if (definition.type === "BOOLEAN") applyBooleanProperty(graph, instance, targets, value);
1529
+ else if (target) applyInstanceSwapProperty(graph, instance, targets, target);
1530
+ graph.updateNode(instance.id, { componentPropertyAssignments: {
1531
+ ...instance.componentPropertyAssignments,
1532
+ [definition.id]: definition.type === "INSTANCE_SWAP" && target ? target.id : value
1533
+ } });
1534
+ return definition.type === "INSTANCE_SWAP" ? target : instance;
1535
+ }
1536
+ function componentSubtree(graph, componentId) {
1537
+ const component = graph.getNode(componentId);
1538
+ if (!component) return [];
1539
+ const nodes = [component];
1540
+ const visit = (node) => {
1541
+ for (const child of graph.getChildren(node.id)) {
1542
+ nodes.push(child);
1543
+ visit(child);
1544
+ }
1545
+ };
1546
+ visit(component);
1547
+ return nodes;
1548
+ }
1549
+ function componentInstances(graph, componentId) {
1550
+ return [...graph.getAllNodes()].filter((node) => node.type === "INSTANCE" && node.componentId === componentId);
1551
+ }
1552
+ function removePropertyFromNode(graph, node, propertyId) {
1553
+ if (node.componentPropertyReferences.some((reference) => reference.propertyId === propertyId)) graph.updateNode(node.id, { componentPropertyReferences: node.componentPropertyReferences.filter((reference) => reference.propertyId !== propertyId) });
1554
+ if (node.type === "INSTANCE" && propertyId in node.componentPropertyAssignments) graph.updateNode(node.id, { componentPropertyAssignments: Object.fromEntries(Object.entries(node.componentPropertyAssignments).filter(([id]) => id !== propertyId)) });
1555
+ }
1556
+ function removeComponentProperty(graph, ownerId, propertyId) {
1557
+ const owner = graph.getNode(ownerId);
1558
+ if (!owner || owner.type !== "COMPONENT" && owner.type !== "COMPONENT_SET") return false;
1559
+ graph.updateNode(owner.id, { componentPropertyDefinitions: owner.componentPropertyDefinitions.filter((definition) => definition.id !== propertyId) });
1560
+ const nodes = [
1561
+ ...componentSubtree(graph, owner.id),
1562
+ ...componentInstances(graph, owner.id),
1563
+ ...owner.type === "COMPONENT_SET" ? owner.childIds.flatMap((id) => [...componentSubtree(graph, id), ...componentInstances(graph, id)]) : []
1564
+ ];
1565
+ for (const node of nodes) removePropertyFromNode(graph, node, propertyId);
1566
+ return true;
1567
+ }
1568
+ //#endregion
1569
+ export { BLACK, CONTAINER_TYPES, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS, TRANSPARENT, applyComponentPropertyValue, clearInstanceOverrides, clipBoundsToPolygon, clipPolygon, cloneInstanceOverrideState, cloneNodeProps, cloneVectorNetwork, componentPropertyDefinitions, componentPropertyOwners, computeAbsoluteBounds, computeBounds, computeDescendantVisualBounds, computeVisualBounds, copyDerivedGlyphs, copyEffect, copyEffects, copyFill, copyFills, copyGeometryPaths, copyInstanceComponentProps, copyLayoutGrids, copyStroke, copyStrokes, copyStyleRun, copyStyleRuns, createDefaultNode, createDefaultSourceMetadata, createInstance, createInstanceOverrideState, degToRad, deleteInstanceOverride, deserializeInstanceOverrideState, detachInstance, effectOverflow, findComponentPropertyTarget, findComponentPropertyTargets, findInstanceAncestor, forEachInstanceOverride, geometryBlobBounds, geometryCommandCoordCount, getInstanceOverride, getInstances, getMainComponent, hasInstanceOverride, hasSameCopySource, intersectVisualBounds, markCopySource, mergeVectorNetworks, nodeVisualBounds, normalizeVectorNetwork, polygonVertices, populateInstanceChildren, radToDeg, recordInstanceOverride, recordInstanceOverrideValue, removeComponentProperty, resolveComponentPropertyValue, rotatePoint, rotatedBBox, rotatedCorners, scaleGeometryPaths, serializeInstanceOverrideState, setInstanceOverride, strokeOverflow, swapInstanceComponent, syncInstances, transformGeometryBlob, transformGeometryPaths, transformVectorNetwork, unionVisualBounds, validateVectorNetwork, vectorNetworksEqual };
1570
+
1571
+ //# sourceMappingURL=properties.js.map