@grida/svg-editor 1.0.0-alpha.4 → 1.0.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 (41) hide show
  1. package/README.md +365 -384
  2. package/dist/dom-BEjG2bSw.d.mts +320 -0
  3. package/dist/dom-DYD1BHTo.js +6050 -0
  4. package/dist/dom-Y2QR7QSi.d.ts +318 -0
  5. package/dist/dom-tM3Dr1EK.mjs +5971 -0
  6. package/dist/dom.d.mts +3 -2
  7. package/dist/dom.d.ts +3 -2
  8. package/dist/dom.js +13 -1
  9. package/dist/dom.mjs +2 -2
  10. package/dist/editor-CWNtt1vu.mjs +2998 -0
  11. package/dist/editor-CZgwg8BK.d.mts +2537 -0
  12. package/dist/editor-CesShk9o.js +3004 -0
  13. package/dist/editor-kFTYSb_8.d.ts +2537 -0
  14. package/dist/index.d.mts +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +5 -2
  17. package/dist/index.mjs +3 -2
  18. package/dist/model-D0iEDcg3.mjs +5451 -0
  19. package/dist/model-tywvTGZv.js +5640 -0
  20. package/dist/presets.d.mts +17 -2
  21. package/dist/presets.d.ts +17 -2
  22. package/dist/presets.js +20 -15
  23. package/dist/presets.mjs +19 -15
  24. package/dist/react.d.mts +88 -10
  25. package/dist/react.d.ts +88 -10
  26. package/dist/react.js +169 -14
  27. package/dist/react.mjs +159 -16
  28. package/package.json +35 -9
  29. package/dist/dom-CmOu0HvI.mjs +0 -1623
  30. package/dist/dom-Cn-RtjRL.d.ts +0 -48
  31. package/dist/dom-CoVZzFqy.js +0 -1672
  32. package/dist/dom-DJnZhtOd.d.mts +0 -48
  33. package/dist/editor-CjK56cgb.mjs +0 -1823
  34. package/dist/editor-D2l_CDr0.d.ts +0 -818
  35. package/dist/editor-D2zZAyny.js +0 -1835
  36. package/dist/editor-Uu6dZX4y.d.mts +0 -818
  37. package/dist/index-CHiXYO9-.d.ts +0 -1
  38. package/dist/index-ThDLM4Am.d.mts +0 -1
  39. package/dist/paint-Cfiw4g_J.mjs +0 -477
  40. package/dist/paint-dDV-Trt9.js +0 -531
  41. /package/dist/{chunk-CfYAbeIz.mjs → chunk-D7D4PA-g.mjs} +0 -0
@@ -0,0 +1,2998 @@
1
+ import { C as is_text_input_focused, E as registerDefaultCommands, S as array_shallow_equal, _ as subtree, a as paint, b as WELL_KNOWN_NS_PREFIXES, d as rotate_pipeline, g as transform, h as group, i as TOOL_CURSOR, m as translate_pipeline, n as insertions, r as DEFAULT_STYLE, s as resize_pipeline, v as SVG_NS, w as TOOL_SET, x as XMLNS_NS, y as SvgDocument } from "./model-D0iEDcg3.mjs";
2
+ import { HistoryImpl } from "@grida/history";
3
+ import { KeyCode, M, chunkKey, eventToChunk, getKeyboardOS, kb, keybindingsToKeyCodes } from "@grida/keybinding";
4
+ import cmath from "@grida/cmath";
5
+ import { encode_attr_value } from "@grida/svg/parser";
6
+ //#region src/commands/registry.ts
7
+ var CommandRegistry = class {
8
+ constructor() {
9
+ this.map = /* @__PURE__ */ new Map();
10
+ }
11
+ /**
12
+ * Register a command. Returns an unregister function. Re-registering
13
+ * the same id replaces the previous handler (last writer wins).
14
+ */
15
+ register(id, handler) {
16
+ this.map.set(id, handler);
17
+ return () => {
18
+ if (this.map.get(id) === handler) this.map.delete(id);
19
+ };
20
+ }
21
+ /**
22
+ * Invoke a command by id. Returns `true` if the handler consumed,
23
+ * `false` otherwise (including unknown ids and handlers that returned
24
+ * `false`/`undefined`).
25
+ */
26
+ invoke(id, args) {
27
+ const handler = this.map.get(id);
28
+ if (!handler) return false;
29
+ return handler(args) === true;
30
+ }
31
+ has(id) {
32
+ return this.map.has(id);
33
+ }
34
+ /** All registered ids, for debugging / introspection. */
35
+ ids() {
36
+ return Array.from(this.map.keys());
37
+ }
38
+ };
39
+ //#endregion
40
+ //#region src/keymap/keymap.ts
41
+ /**
42
+ * Keymap — bindings of declarative `Keybinding`s (from `@grida/keybinding`)
43
+ * to command ids.
44
+ *
45
+ * Dispatch is ProseMirror-`chainCommands`-shaped: multiple bindings on
46
+ * the same key are tried in priority order; the first whose handler
47
+ * returns `true` wins, the rest are skipped. This keeps "one key, many
48
+ * meanings" expressible without a `when:` DSL — handlers self-guard on
49
+ * editor state and return `false` when not applicable.
50
+ *
51
+ * The keymap does NOT see modifier-as-signal (e.g. Alt-held for
52
+ * measurement). That stays on the HUD modifiers channel. The keymap
53
+ * only sees Mod+D-shape chords.
54
+ */
55
+ var Keymap = class {
56
+ constructor(commands, platformGetter = getKeyboardOS) {
57
+ this.commands = commands;
58
+ this.platformGetter = platformGetter;
59
+ this.buckets = /* @__PURE__ */ new Map();
60
+ this.seq = 0;
61
+ }
62
+ /**
63
+ * Bind a key combination to a command. Returns an unbind function.
64
+ * The same `Keybinding` can be bound to multiple commands — they will
65
+ * all be tried in chain order on dispatch.
66
+ */
67
+ bind(binding) {
68
+ const entry = {
69
+ binding,
70
+ seq: ++this.seq
71
+ };
72
+ for (const hash of this.chunkKeysFor(binding.keybinding)) {
73
+ const list = this.buckets.get(hash);
74
+ if (list) {
75
+ list.push(entry);
76
+ list.sort(compareEntries);
77
+ } else this.buckets.set(hash, [entry]);
78
+ }
79
+ return () => {
80
+ for (const hash of this.chunkKeysFor(binding.keybinding)) {
81
+ const list = this.buckets.get(hash);
82
+ if (!list) continue;
83
+ const idx = list.findIndex((e) => e === entry);
84
+ if (idx >= 0) list.splice(idx, 1);
85
+ if (list.length === 0) this.buckets.delete(hash);
86
+ }
87
+ };
88
+ }
89
+ /**
90
+ * Remove bindings matching the spec. If both filters are passed, only
91
+ * bindings that match BOTH are removed.
92
+ */
93
+ unbind(spec) {
94
+ const hashFilter = spec.keybinding ? new Set(this.chunkKeysFor(spec.keybinding)) : null;
95
+ for (const [hash, list] of this.buckets) {
96
+ if (hashFilter && !hashFilter.has(hash)) continue;
97
+ const next = list.filter((e) => {
98
+ if (spec.command && e.binding.command !== spec.command) return true;
99
+ return false;
100
+ });
101
+ if (next.length === 0) this.buckets.delete(hash);
102
+ else if (next.length !== list.length) this.buckets.set(hash, next);
103
+ }
104
+ }
105
+ /** All registered bindings, for introspection. Order is not guaranteed. */
106
+ bindings() {
107
+ const seen = /* @__PURE__ */ new Set();
108
+ for (const list of this.buckets.values()) for (const e of list) seen.add(e.binding);
109
+ return Array.from(seen);
110
+ }
111
+ /**
112
+ * Does the keymap have a binding that matches this event's chord —
113
+ * regardless of whether any handler would consume it? Hosts use this
114
+ * to decide whether to swallow the platform's default action (e.g.
115
+ * `event.preventDefault()` in the browser), so that an advertised
116
+ * shortcut like `Cmd+G` doesn't fall through to the browser's find
117
+ * bar even when the binding's handler rejects.
118
+ *
119
+ * Pure read; runs no handlers, no side effects. Honors the same
120
+ * form-element focus guard `dispatch` uses, so a typing user's
121
+ * keystroke isn't "claimed" — and the browser's native text-editing
122
+ * default (Cmd+A select all, Cmd+Z undo, etc.) wins.
123
+ */
124
+ claims(event) {
125
+ const chunk = eventToChunk(event);
126
+ if (chunk.keys.length === 0) return false;
127
+ const list = this.buckets.get(chunkKey(chunk));
128
+ if (!list || list.length === 0) return false;
129
+ if (is_text_input_focused()) return list.some(({ binding }) => binding.allowInFormElement === true);
130
+ return true;
131
+ }
132
+ /**
133
+ * Match the event against bound chunks, then run candidates in chain
134
+ * order. Returns `true` on the first handler that consumes; returns
135
+ * `false` if nothing matched or all matches fell through.
136
+ *
137
+ * **Form-element focus guard.** When a text input is focused
138
+ * (`<input>`, `<textarea>`, contentEditable), bindings are suppressed
139
+ * by default so the platform's native shortcuts (Cmd+A, Cmd+Z, Cmd+C,
140
+ * arrow nav, …) are preserved. A binding can opt out of this guard
141
+ * with `allowInFormElement: true` — see `KeymapBinding`.
142
+ *
143
+ * `dispatch` is browser-agnostic: it does NOT call `preventDefault()`
144
+ * or touch the event in any way. The host decides what to do with the
145
+ * platform default — typically `if (keymap.claims(e)) e.preventDefault()`,
146
+ * which prevents the platform default for advertised shortcuts even
147
+ * when the chain rejects. See README → `editor.keymap`.
148
+ */
149
+ dispatch(event) {
150
+ const chunk = eventToChunk(event);
151
+ if (chunk.keys.length === 0) return false;
152
+ const hash = chunkKey(chunk);
153
+ const list = this.buckets.get(hash);
154
+ if (!list || list.length === 0) return false;
155
+ const text_focused = is_text_input_focused();
156
+ for (const { binding } of list) {
157
+ if (text_focused && binding.allowInFormElement !== true) continue;
158
+ if (this.commands.invoke(binding.command, binding.args)) return true;
159
+ }
160
+ return false;
161
+ }
162
+ /**
163
+ * Compute the set of canonical hashes a `Keybinding` lights up. A
164
+ * binding with aliases (multiple sequences) contributes one hash per
165
+ * single-chunk alias; multi-chunk sequences (chords) are skipped in
166
+ * V1.
167
+ */
168
+ chunkKeysFor(binding) {
169
+ const sequences = keybindingsToKeyCodes(binding, this.platformGetter());
170
+ const out = [];
171
+ for (const seq of sequences) {
172
+ if (seq.length !== 1) continue;
173
+ out.push(chunkKey(seq[0]));
174
+ }
175
+ return out;
176
+ }
177
+ };
178
+ function compareEntries(a, b) {
179
+ const pa = a.binding.priority ?? 0;
180
+ const pb = b.binding.priority ?? 0;
181
+ if (pa !== pb) return pb - pa;
182
+ return a.seq - b.seq;
183
+ }
184
+ //#endregion
185
+ //#region src/keymap/defaults.ts
186
+ /**
187
+ * Default keybindings shipped with `@grida/svg-editor`.
188
+ *
189
+ * THIS IS THE ONLY FILE where built-in shortcuts are declared. Adding
190
+ * a new shortcut = one new row here (plus, if the target command is
191
+ * new, one new handler in `src/commands/defaults.ts`). That is the
192
+ * V1 design contract.
193
+ *
194
+ * Same key, multiple meanings? Add multiple rows. The chain semantics
195
+ * (handler returns `false` when not applicable) handle the rest.
196
+ */
197
+ const NUDGE_MEANINGFUL = M.Shift | M.Ctrl;
198
+ const RESIZE_MEANINGFUL = M.Shift | M.Ctrl | M.Alt;
199
+ const DEFAULT_BINDINGS = [
200
+ {
201
+ keybinding: kb(KeyCode.KeyZ, M.CtrlCmd),
202
+ command: "history.undo"
203
+ },
204
+ {
205
+ keybinding: kb(KeyCode.KeyZ, M.CtrlCmd | M.Shift),
206
+ command: "history.redo"
207
+ },
208
+ {
209
+ keybinding: kb(KeyCode.KeyY, M.CtrlCmd),
210
+ command: "history.redo"
211
+ },
212
+ {
213
+ keybinding: kb(KeyCode.Escape),
214
+ command: "selection.deselect"
215
+ },
216
+ {
217
+ keybinding: kb(KeyCode.Backspace),
218
+ command: "vector.delete-vertex"
219
+ },
220
+ {
221
+ keybinding: kb(KeyCode.Backspace),
222
+ command: "selection.remove"
223
+ },
224
+ {
225
+ keybinding: kb(KeyCode.Delete),
226
+ command: "vector.delete-vertex"
227
+ },
228
+ {
229
+ keybinding: kb(KeyCode.Delete),
230
+ command: "selection.remove"
231
+ },
232
+ {
233
+ keybinding: kb(KeyCode.KeyG, M.CtrlCmd),
234
+ command: "selection.group"
235
+ },
236
+ {
237
+ keybinding: kb(KeyCode.KeyG, M.CtrlCmd | M.Shift),
238
+ command: "selection.ungroup"
239
+ },
240
+ {
241
+ keybinding: kb(KeyCode.KeyD, M.CtrlCmd),
242
+ command: "selection.duplicate"
243
+ },
244
+ {
245
+ keybinding: kb(KeyCode.KeyA, M.CtrlCmd),
246
+ command: "selection.all"
247
+ },
248
+ {
249
+ keybinding: kb(KeyCode.Tab),
250
+ command: "selection.sibling",
251
+ args: "next"
252
+ },
253
+ {
254
+ keybinding: kb(KeyCode.Tab, M.Shift),
255
+ command: "selection.sibling",
256
+ args: "prev"
257
+ },
258
+ {
259
+ keybinding: kb(KeyCode.KeyA, M.Alt),
260
+ command: "selection.align",
261
+ args: "left"
262
+ },
263
+ {
264
+ keybinding: kb(KeyCode.KeyD, M.Alt),
265
+ command: "selection.align",
266
+ args: "right"
267
+ },
268
+ {
269
+ keybinding: kb(KeyCode.KeyW, M.Alt),
270
+ command: "selection.align",
271
+ args: "top"
272
+ },
273
+ {
274
+ keybinding: kb(KeyCode.KeyS, M.Alt),
275
+ command: "selection.align",
276
+ args: "bottom"
277
+ },
278
+ {
279
+ keybinding: kb(KeyCode.KeyH, M.Alt),
280
+ command: "selection.align",
281
+ args: "horizontal_centers"
282
+ },
283
+ {
284
+ keybinding: kb(KeyCode.KeyV, M.Alt),
285
+ command: "selection.align",
286
+ args: "vertical_centers"
287
+ },
288
+ {
289
+ keybinding: kb(KeyCode.Enter),
290
+ command: "content.enter"
291
+ },
292
+ {
293
+ keybinding: kb(KeyCode.Enter),
294
+ command: "hierarchy.enter"
295
+ },
296
+ {
297
+ keybinding: kb(KeyCode.Enter, M.Shift),
298
+ command: "hierarchy.exit"
299
+ },
300
+ {
301
+ keybinding: kb(KeyCode.LeftArrow, 0, NUDGE_MEANINGFUL),
302
+ command: "transform.nudge",
303
+ args: {
304
+ dx: -1,
305
+ dy: 0
306
+ }
307
+ },
308
+ {
309
+ keybinding: kb(KeyCode.RightArrow, 0, NUDGE_MEANINGFUL),
310
+ command: "transform.nudge",
311
+ args: {
312
+ dx: 1,
313
+ dy: 0
314
+ }
315
+ },
316
+ {
317
+ keybinding: kb(KeyCode.UpArrow, 0, NUDGE_MEANINGFUL),
318
+ command: "transform.nudge",
319
+ args: {
320
+ dx: 0,
321
+ dy: -1
322
+ }
323
+ },
324
+ {
325
+ keybinding: kb(KeyCode.DownArrow, 0, NUDGE_MEANINGFUL),
326
+ command: "transform.nudge",
327
+ args: {
328
+ dx: 0,
329
+ dy: 1
330
+ }
331
+ },
332
+ {
333
+ keybinding: kb(KeyCode.LeftArrow, M.Shift, NUDGE_MEANINGFUL),
334
+ command: "transform.nudge",
335
+ args: {
336
+ dx: -10,
337
+ dy: 0
338
+ }
339
+ },
340
+ {
341
+ keybinding: kb(KeyCode.RightArrow, M.Shift, NUDGE_MEANINGFUL),
342
+ command: "transform.nudge",
343
+ args: {
344
+ dx: 10,
345
+ dy: 0
346
+ }
347
+ },
348
+ {
349
+ keybinding: kb(KeyCode.UpArrow, M.Shift, NUDGE_MEANINGFUL),
350
+ command: "transform.nudge",
351
+ args: {
352
+ dx: 0,
353
+ dy: -10
354
+ }
355
+ },
356
+ {
357
+ keybinding: kb(KeyCode.DownArrow, M.Shift, NUDGE_MEANINGFUL),
358
+ command: "transform.nudge",
359
+ args: {
360
+ dx: 0,
361
+ dy: 10
362
+ }
363
+ },
364
+ {
365
+ keybinding: kb(KeyCode.RightArrow, M.Ctrl | M.Alt, RESIZE_MEANINGFUL),
366
+ command: "selection.nudge_resize",
367
+ args: {
368
+ dw: 1,
369
+ dh: 0
370
+ }
371
+ },
372
+ {
373
+ keybinding: kb(KeyCode.LeftArrow, M.Ctrl | M.Alt, RESIZE_MEANINGFUL),
374
+ command: "selection.nudge_resize",
375
+ args: {
376
+ dw: -1,
377
+ dh: 0
378
+ }
379
+ },
380
+ {
381
+ keybinding: kb(KeyCode.DownArrow, M.Ctrl | M.Alt, RESIZE_MEANINGFUL),
382
+ command: "selection.nudge_resize",
383
+ args: {
384
+ dw: 0,
385
+ dh: 1
386
+ }
387
+ },
388
+ {
389
+ keybinding: kb(KeyCode.UpArrow, M.Ctrl | M.Alt, RESIZE_MEANINGFUL),
390
+ command: "selection.nudge_resize",
391
+ args: {
392
+ dw: 0,
393
+ dh: -1
394
+ }
395
+ },
396
+ {
397
+ keybinding: kb(KeyCode.RightArrow, M.Ctrl | M.Alt | M.Shift, RESIZE_MEANINGFUL),
398
+ command: "selection.nudge_resize",
399
+ args: {
400
+ dw: 10,
401
+ dh: 0
402
+ }
403
+ },
404
+ {
405
+ keybinding: kb(KeyCode.LeftArrow, M.Ctrl | M.Alt | M.Shift, RESIZE_MEANINGFUL),
406
+ command: "selection.nudge_resize",
407
+ args: {
408
+ dw: -10,
409
+ dh: 0
410
+ }
411
+ },
412
+ {
413
+ keybinding: kb(KeyCode.DownArrow, M.Ctrl | M.Alt | M.Shift, RESIZE_MEANINGFUL),
414
+ command: "selection.nudge_resize",
415
+ args: {
416
+ dw: 0,
417
+ dh: 10
418
+ }
419
+ },
420
+ {
421
+ keybinding: kb(KeyCode.UpArrow, M.Ctrl | M.Alt | M.Shift, RESIZE_MEANINGFUL),
422
+ command: "selection.nudge_resize",
423
+ args: {
424
+ dw: 0,
425
+ dh: -10
426
+ }
427
+ },
428
+ {
429
+ keybinding: kb(KeyCode.KeyV),
430
+ command: TOOL_SET,
431
+ args: { type: "cursor" }
432
+ },
433
+ {
434
+ keybinding: kb(KeyCode.KeyR),
435
+ command: TOOL_SET,
436
+ args: {
437
+ type: "insert",
438
+ tag: "rect"
439
+ }
440
+ },
441
+ {
442
+ keybinding: kb(KeyCode.KeyO),
443
+ command: TOOL_SET,
444
+ args: {
445
+ type: "insert",
446
+ tag: "ellipse"
447
+ }
448
+ },
449
+ {
450
+ keybinding: kb(KeyCode.KeyL),
451
+ command: TOOL_SET,
452
+ args: {
453
+ type: "insert",
454
+ tag: "line"
455
+ }
456
+ },
457
+ {
458
+ keybinding: kb(KeyCode.KeyT),
459
+ command: TOOL_SET,
460
+ args: { type: "insert-text" }
461
+ },
462
+ {
463
+ keybinding: kb(KeyCode.KeyQ),
464
+ command: TOOL_SET,
465
+ args: { type: "lasso" }
466
+ },
467
+ {
468
+ keybinding: kb(KeyCode.BracketRight),
469
+ command: "reorder",
470
+ args: "bring_to_front"
471
+ },
472
+ {
473
+ keybinding: kb(KeyCode.BracketLeft),
474
+ command: "reorder",
475
+ args: "send_to_back"
476
+ },
477
+ {
478
+ keybinding: kb(KeyCode.BracketRight, M.CtrlCmd),
479
+ command: "reorder",
480
+ args: "bring_forward"
481
+ },
482
+ {
483
+ keybinding: kb(KeyCode.BracketLeft, M.CtrlCmd),
484
+ command: "reorder",
485
+ args: "send_backward"
486
+ }
487
+ ];
488
+ /** Register every default binding into a keymap. */
489
+ function applyDefaultBindings(keymap) {
490
+ for (const b of DEFAULT_BINDINGS) keymap.bind(b);
491
+ }
492
+ //#endregion
493
+ //#region src/core/defs.ts
494
+ var GradientsRegistry = class {
495
+ constructor(doc) {
496
+ this.doc = doc;
497
+ this.listeners = /* @__PURE__ */ new Set();
498
+ this.counter = 0;
499
+ this._cached = null;
500
+ this._cached_by_id = /* @__PURE__ */ new Map();
501
+ this._dirty = true;
502
+ doc.on_change(() => {
503
+ this._dirty = true;
504
+ this.emit();
505
+ });
506
+ }
507
+ list() {
508
+ if (!this._dirty && this._cached) return this._cached;
509
+ const out = [];
510
+ let any_change = !this._cached;
511
+ const seen = /* @__PURE__ */ new Set();
512
+ const defs = this.find_defs_elements();
513
+ for (const def_id of defs) for (const child of this.doc.element_children_of(def_id)) {
514
+ const tag = this.doc.tag_of(child);
515
+ if (tag === "linearGradient" || tag === "radialGradient") {
516
+ const id = this.doc.get_attr(child, "id");
517
+ if (!id) continue;
518
+ const definition = this.read_gradient(child, tag);
519
+ if (!definition) continue;
520
+ const ref_count = this.count_refs(id);
521
+ const prev = this._cached_by_id.get(id);
522
+ if (prev && prev.ref_count === ref_count && gradient_definition_equals(prev.definition, definition)) out.push(prev);
523
+ else {
524
+ const entry = {
525
+ id,
526
+ definition,
527
+ ref_count
528
+ };
529
+ this._cached_by_id.set(id, entry);
530
+ out.push(entry);
531
+ any_change = true;
532
+ }
533
+ seen.add(id);
534
+ }
535
+ }
536
+ for (const id of this._cached_by_id.keys()) if (!seen.has(id)) {
537
+ this._cached_by_id.delete(id);
538
+ any_change = true;
539
+ }
540
+ if (!any_change && this._cached && array_shallow_equal(this._cached, out)) {
541
+ this._dirty = false;
542
+ return this._cached;
543
+ }
544
+ const frozen = Object.freeze(out);
545
+ this._cached = frozen;
546
+ this._dirty = false;
547
+ return frozen;
548
+ }
549
+ get(id) {
550
+ return this.list().find((g) => g.id === id) ?? null;
551
+ }
552
+ upsert(definition, opts) {
553
+ const existing_id = opts?.id;
554
+ if (existing_id) {
555
+ const node = this.find_gradient_node(existing_id);
556
+ if (node !== null) {
557
+ this.write_gradient(node, definition);
558
+ return existing_id;
559
+ }
560
+ }
561
+ const id = existing_id ?? this.fresh_id();
562
+ const defs_id = this.ensure_defs();
563
+ const tag = definition.kind === "linear" ? "linearGradient" : "radialGradient";
564
+ const new_id = this.doc.create_element(tag, { ns: "http://www.w3.org/2000/svg" });
565
+ this.doc.set_attr(new_id, "id", id);
566
+ this.doc.insert(new_id, defs_id, null);
567
+ this.write_gradient(new_id, definition);
568
+ this.emit();
569
+ return id;
570
+ }
571
+ remove(id) {
572
+ const refs = this.count_refs(id);
573
+ if (refs > 0) throw new Error(`[svg-editor] cannot remove gradient "${id}": ${refs} node(s) still reference it`);
574
+ const node = this.find_gradient_node(id);
575
+ if (node !== null) {
576
+ this.doc.remove(node);
577
+ this.emit();
578
+ }
579
+ }
580
+ subscribe(fn) {
581
+ this.listeners.add(fn);
582
+ return () => {
583
+ this.listeners.delete(fn);
584
+ };
585
+ }
586
+ emit() {
587
+ const snap = this.list();
588
+ for (const fn of this.listeners) fn(snap);
589
+ }
590
+ fresh_id() {
591
+ let id;
592
+ do
593
+ id = `g${++this.counter}`;
594
+ while (this.find_gradient_node(id) !== null);
595
+ return id;
596
+ }
597
+ find_defs_elements() {
598
+ return this.doc.find_by_tag(this.doc.root, "defs");
599
+ }
600
+ ensure_defs() {
601
+ const existing = this.find_defs_elements();
602
+ if (existing.length > 0) return existing[0];
603
+ const defs = this.doc.create_element("defs", { ns: "http://www.w3.org/2000/svg" });
604
+ const first = this.doc.children_of(this.doc.root)[0] ?? null;
605
+ this.doc.insert(defs, this.doc.root, first);
606
+ return defs;
607
+ }
608
+ find_gradient_node(id) {
609
+ for (const def of this.find_defs_elements()) for (const child of this.doc.element_children_of(def)) if (this.doc.get_attr(child, "id") === id) {
610
+ const tag = this.doc.tag_of(child);
611
+ if (tag === "linearGradient" || tag === "radialGradient") return child;
612
+ }
613
+ return null;
614
+ }
615
+ read_gradient(id, tag) {
616
+ const stops = [];
617
+ for (const child of this.doc.element_children_of(id)) {
618
+ if (this.doc.tag_of(child) !== "stop") continue;
619
+ const offset = parseFloat(this.doc.get_attr(child, "offset") ?? "0");
620
+ const color = this.doc.get_attr(child, "stop-color") ?? this.doc.get_style(child, "stop-color") ?? "#000000";
621
+ const opacity_str = this.doc.get_attr(child, "stop-opacity") ?? this.doc.get_style(child, "stop-opacity");
622
+ const opacity = opacity_str !== null ? parseFloat(opacity_str) : void 0;
623
+ stops.push({
624
+ offset,
625
+ color,
626
+ ...opacity !== void 0 ? { opacity } : {}
627
+ });
628
+ }
629
+ const gu = this.doc.get_attr(id, "gradientUnits");
630
+ const gradient_units = gu === "userSpaceOnUse" ? "user_space_on_use" : gu === "objectBoundingBox" ? "object_bounding_box" : void 0;
631
+ const sm = this.doc.get_attr(id, "spreadMethod");
632
+ const spread_method = sm === "pad" || sm === "reflect" || sm === "repeat" ? sm : void 0;
633
+ const num = (n) => {
634
+ const v = this.doc.get_attr(id, n);
635
+ return v !== null ? parseFloat(v) : void 0;
636
+ };
637
+ if (tag === "linearGradient") return {
638
+ kind: "linear",
639
+ stops,
640
+ x1: num("x1"),
641
+ y1: num("y1"),
642
+ x2: num("x2"),
643
+ y2: num("y2"),
644
+ gradient_units,
645
+ spread_method
646
+ };
647
+ return {
648
+ kind: "radial",
649
+ stops,
650
+ cx: num("cx"),
651
+ cy: num("cy"),
652
+ r: num("r"),
653
+ fx: num("fx"),
654
+ fy: num("fy"),
655
+ gradient_units,
656
+ spread_method
657
+ };
658
+ }
659
+ write_gradient(node, def) {
660
+ for (const c of this.doc.children_of(node).slice()) this.doc.remove(c);
661
+ const set_num = (name, v) => {
662
+ this.doc.set_attr(node, name, v === void 0 ? null : String(v));
663
+ };
664
+ if (def.kind === "linear") {
665
+ set_num("x1", def.x1);
666
+ set_num("y1", def.y1);
667
+ set_num("x2", def.x2);
668
+ set_num("y2", def.y2);
669
+ } else {
670
+ set_num("cx", def.cx);
671
+ set_num("cy", def.cy);
672
+ set_num("r", def.r);
673
+ set_num("fx", def.fx);
674
+ set_num("fy", def.fy);
675
+ }
676
+ if (def.gradient_units) this.doc.set_attr(node, "gradientUnits", def.gradient_units === "user_space_on_use" ? "userSpaceOnUse" : "objectBoundingBox");
677
+ if (def.spread_method) this.doc.set_attr(node, "spreadMethod", def.spread_method);
678
+ for (const stop of def.stops) {
679
+ const stop_id = this.doc.create_element("stop", { ns: "http://www.w3.org/2000/svg" });
680
+ this.doc.set_attr(stop_id, "offset", String(stop.offset));
681
+ this.doc.set_attr(stop_id, "stop-color", stop.color);
682
+ if (stop.opacity !== void 0) this.doc.set_attr(stop_id, "stop-opacity", String(stop.opacity));
683
+ this.doc.insert(stop_id, node, null);
684
+ }
685
+ }
686
+ count_refs(id) {
687
+ let count = 0;
688
+ const pattern = new RegExp(`url\\(\\s*["']?#${escape_regex(id)}["']?\\s*\\)`);
689
+ for (const node of this.doc.all_elements()) {
690
+ const fill = this.doc.get_attr(node, "fill");
691
+ const stroke = this.doc.get_attr(node, "stroke");
692
+ const style_fill = this.doc.get_style(node, "fill");
693
+ const style_stroke = this.doc.get_style(node, "stroke");
694
+ for (const v of [
695
+ fill,
696
+ stroke,
697
+ style_fill,
698
+ style_stroke
699
+ ]) if (v && pattern.test(v)) count++;
700
+ }
701
+ return count;
702
+ }
703
+ };
704
+ function escape_regex(s) {
705
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
706
+ }
707
+ function gradient_definition_equals(a, b) {
708
+ if (a === b) return true;
709
+ if (a.kind !== b.kind) return false;
710
+ if (a.stops.length !== b.stops.length) return false;
711
+ for (let i = 0; i < a.stops.length; i++) {
712
+ const sa = a.stops[i];
713
+ const sb = b.stops[i];
714
+ if (sa.offset !== sb.offset || sa.color !== sb.color || sa.opacity !== sb.opacity) return false;
715
+ }
716
+ if (a.kind === "linear" && b.kind === "linear") return a.x1 === b.x1 && a.y1 === b.y1 && a.x2 === b.x2 && a.y2 === b.y2 && a.gradient_units === b.gradient_units && a.spread_method === b.spread_method;
717
+ if (a.kind === "radial" && b.kind === "radial") return a.cx === b.cx && a.cy === b.cy && a.r === b.r && a.fx === b.fx && a.fy === b.fy && a.gradient_units === b.gradient_units && a.spread_method === b.spread_method;
718
+ return false;
719
+ }
720
+ function create_defs(doc) {
721
+ return { gradients: new GradientsRegistry(doc) };
722
+ }
723
+ //#endregion
724
+ //#region src/core/clipboard.ts
725
+ /**
726
+ * Clipboard payload extraction — selection → standalone SVG document.
727
+ *
728
+ * Implements the copy side of the clipboard FRD
729
+ * ([docs/wg/feat-svg-editor/clipboard.md](../../../../docs/wg/feat-svg-editor/clipboard.md)):
730
+ * the payload is a standalone, namespace-well-formed SVG document — not a
731
+ * private envelope. Assembly is a pure function of (document, selection):
732
+ * no geometry, no environment, no randomness (FRD R6 — the same selection
733
+ * yields the same bytes headless or surface-attached).
734
+ *
735
+ * What the payload carries, and what it deliberately does not
736
+ * (FRD §Extraction — five context kinds):
737
+ *
738
+ * 1. Referenced resources — CARRIED. The outbound `url(#…)` / `href`
739
+ * closure is walked from the closed carrier list below and emitted
740
+ * verbatim in one `<defs>` block.
741
+ * 2. Namespace declarations — CARRIED. Prefixes a subtree borrows from
742
+ * ancestor scope are declared on the payload shell (an undeclared
743
+ * prefix is a well-formedness error, so this includes the deliberate
744
+ * well-known-table repair for e.g. `xlink`).
745
+ * 3. Ancestor transforms — NOT carried (verbatim policy).
746
+ * 4. Inherited presentation / cascade — NOT carried (verbatim policy).
747
+ * 5. Viewport — NOT carried (no `viewBox`, no sizing on the shell).
748
+ *
749
+ * This module is the **payload extraction** operation only. The sibling
750
+ * operation the FRD names — in-document subtree CLONE (duplicate /
751
+ * clone-drag), which must NOT carry the closure — lives in `./subtree`.
752
+ * The two share exactly selection normalization (`subtree.normalize_roots`)
753
+ * and verbatim subtree serialization (`doc.serialize_node`).
754
+ */
755
+ let clipboard;
756
+ (function(_clipboard) {
757
+ /**
758
+ * Presentation carriers that may hold `url(#…)` references, read both as
759
+ * a presentation attribute and as an inline `style=""` declaration.
760
+ *
761
+ * CLOSED LIST — extending it is a spec change to the FRD's §Extraction 1
762
+ * carrier list, not a bug fix. Deliberately NOT walked in v1 (documented
763
+ * degradations): `<style>` element rules (CSS parsing is the deferred
764
+ * cascade capability), SMIL timing/value references, `cursor`, SVG 2
765
+ * text-layout properties.
766
+ */
767
+ const URL_REF_PROPS = [
768
+ "fill",
769
+ "stroke",
770
+ "filter",
771
+ "clip-path",
772
+ "mask",
773
+ "marker-start",
774
+ "marker-mid",
775
+ "marker-end",
776
+ "marker"
777
+ ];
778
+ /** Set view of {@link URL_REF_PROPS} for membership tests over parsed
779
+ * style declarations. */
780
+ const URL_REF_PROP_SET = new Set(URL_REF_PROPS);
781
+ /**
782
+ * Elements whose `href` / `xlink:href` is a same-document resource
783
+ * reference the closure follows. CLOSED LIST — `<a href>` is navigation,
784
+ * `<image href>` is content, SMIL `href` is an animation target; none of
785
+ * them are walked.
786
+ */
787
+ const HREF_TAGS = new Set([
788
+ "use",
789
+ "textPath",
790
+ "mpath",
791
+ "feImage",
792
+ "pattern",
793
+ "linearGradient",
794
+ "radialGradient",
795
+ "filter"
796
+ ]);
797
+ /**
798
+ * `url(#id)` extractor. Global — a single value can carry several
799
+ * references (`filter: url(#a) blur(2px) url(#b)` is a legal filter
800
+ * function list). Same quoting tolerance as the defs registry's
801
+ * ref-counting pattern.
802
+ */
803
+ const URL_REF_RE = /url\(\s*["']?#([^"')\s]+)["']?\s*\)/g;
804
+ function extract_payload(doc, selection) {
805
+ const order = subtree.by_document_order(doc);
806
+ const roots = subtree.normalize_roots(doc, selection, order);
807
+ if (roots.length === 0) return null;
808
+ const closure = collect_reference_closure(doc, roots);
809
+ const shell_ns = /* @__PURE__ */ new Map();
810
+ for (const member of [...closure, ...roots].sort(order)) for (const prefix of doc.undeclared_ns_prefixes(member)) {
811
+ if (shell_ns.has(prefix)) continue;
812
+ const uri = resolve_prefix(doc, member, prefix);
813
+ if (uri !== null) shell_ns.set(prefix, uri);
814
+ }
815
+ let shell = `<svg xmlns="${SVG_NS}"`;
816
+ for (const [prefix, uri] of shell_ns) shell += ` xmlns:${prefix}="${encode_attr_value(uri, "\"")}"`;
817
+ shell += ">";
818
+ const defs_block = closure.length > 0 ? `<defs>${closure.map((id) => doc.serialize_node(id)).join("")}</defs>` : "";
819
+ const content = roots.map((id) => doc.serialize_node(id)).join("");
820
+ return `${shell}${defs_block}${content}</svg>`;
821
+ }
822
+ _clipboard.extract_payload = extract_payload;
823
+ function collect_reference_closure(doc, roots) {
824
+ const id_map = /* @__PURE__ */ new Map();
825
+ for (const el of doc.all_elements()) {
826
+ const id_attr = doc.get_attr(el, "id");
827
+ if (id_attr !== null && !id_map.has(id_attr)) id_map.set(id_attr, el);
828
+ }
829
+ const in_forest = (target) => roots.some((r) => doc.contains(r, target));
830
+ const collected = /* @__PURE__ */ new Set();
831
+ const pending = [...roots];
832
+ while (pending.length > 0) {
833
+ const subtree = pending.pop();
834
+ for (const el of elements_of_subtree(doc, subtree)) for (const ref of refs_of(doc, el)) {
835
+ const target = id_map.get(ref);
836
+ if (target === void 0) continue;
837
+ if (in_forest(target)) continue;
838
+ if (collected.has(target)) continue;
839
+ collected.add(target);
840
+ pending.push(target);
841
+ }
842
+ }
843
+ return doc.prune_nested_nodes([...collected]).sort(subtree.by_document_order(doc));
844
+ }
845
+ _clipboard.collect_reference_closure = collect_reference_closure;
846
+ /** Preorder element walk of `root`'s subtree, root included. */
847
+ function elements_of_subtree(doc, root) {
848
+ const out = [];
849
+ const walk = (id) => {
850
+ if (!doc.is_element(id)) return;
851
+ out.push(id);
852
+ for (const c of doc.children_of(id)) walk(c);
853
+ };
854
+ walk(root);
855
+ return out;
856
+ }
857
+ /** Same-document reference ids carried by one element, per the closed
858
+ * carrier list. */
859
+ function refs_of(doc, id) {
860
+ const out = [];
861
+ for (const prop of URL_REF_PROPS) {
862
+ const value = doc.get_attr(id, prop);
863
+ if (!value) continue;
864
+ for (const m of value.matchAll(URL_REF_RE)) out.push(m[1]);
865
+ }
866
+ for (const { property, value } of doc.get_all_styles(id)) {
867
+ if (!URL_REF_PROP_SET.has(property)) continue;
868
+ for (const m of value.matchAll(URL_REF_RE)) out.push(m[1]);
869
+ }
870
+ if (HREF_TAGS.has(doc.tag_of(id))) {
871
+ const href = doc.get_attr(id, "href");
872
+ if (href !== null && href.startsWith("#") && href.length > 1) out.push(href.slice(1));
873
+ }
874
+ return out;
875
+ }
876
+ /**
877
+ * Resolve a prefix a member's subtree borrows from ancestor scope:
878
+ * nearest ancestor `xmlns:<prefix>` declaration wins (correct XML
879
+ * scoping), falling back to the well-known table — the deliberate
880
+ * repair that keeps the payload namespace-well-formed even when the
881
+ * source never declared the prefix (FRD §Extraction 2).
882
+ */
883
+ function resolve_prefix(doc, member, prefix) {
884
+ let cur = doc.parent_of(member);
885
+ while (cur !== null) {
886
+ const uri = doc.get_attr(cur, prefix, XMLNS_NS);
887
+ if (uri !== null) return uri;
888
+ cur = doc.parent_of(cur);
889
+ }
890
+ return WELL_KNOWN_NS_PREFIXES.get(prefix) ?? null;
891
+ }
892
+ })(clipboard || (clipboard = {}));
893
+ //#endregion
894
+ //#region src/core/align.ts
895
+ /**
896
+ * Compute per-member translation deltas to align `members` against `target`.
897
+ *
898
+ * Convention (matches Figma menu labels and `cmath.rect.alignA`):
899
+ * - `left` / `right` → shift X so each left/right edge matches target's
900
+ * - `top` / `bottom` → shift Y so each top/bottom edge matches target's
901
+ * - `horizontal_centers` → shift X so each center-X matches target's center-X
902
+ * - `vertical_centers` → shift Y so each center-Y matches target's center-Y
903
+ *
904
+ * Members already at the target position are omitted from the returned map —
905
+ * callers iterate non-zero deltas only.
906
+ */
907
+ function compute_align_deltas(members, target, direction) {
908
+ const out = /* @__PURE__ */ new Map();
909
+ for (const m of members) {
910
+ const d = delta_for(m.bbox, target, direction);
911
+ if (d.x !== 0 || d.y !== 0) out.set(m.id, d);
912
+ }
913
+ return out;
914
+ }
915
+ function delta_for(bbox, target, direction) {
916
+ switch (direction) {
917
+ case "left": return {
918
+ x: target.x - bbox.x,
919
+ y: 0
920
+ };
921
+ case "right": return {
922
+ x: target.x + target.width - (bbox.x + bbox.width),
923
+ y: 0
924
+ };
925
+ case "top": return {
926
+ x: 0,
927
+ y: target.y - bbox.y
928
+ };
929
+ case "bottom": return {
930
+ x: 0,
931
+ y: target.y + target.height - (bbox.y + bbox.height)
932
+ };
933
+ case "horizontal_centers": return {
934
+ x: target.x + target.width / 2 - (bbox.x + bbox.width / 2),
935
+ y: 0
936
+ };
937
+ case "vertical_centers": return {
938
+ x: 0,
939
+ y: target.y + target.height / 2 - (bbox.y + bbox.height / 2)
940
+ };
941
+ }
942
+ }
943
+ //#endregion
944
+ //#region src/core/properties.ts
945
+ let properties;
946
+ (function(_properties) {
947
+ /** SVG properties that inherit per SVG 2 §6 (subset; the common ones). */
948
+ const INHERITED = new Set([
949
+ "color",
950
+ "cursor",
951
+ "direction",
952
+ "fill",
953
+ "fill-opacity",
954
+ "fill-rule",
955
+ "font",
956
+ "font-family",
957
+ "font-size",
958
+ "font-style",
959
+ "font-variant",
960
+ "font-weight",
961
+ "letter-spacing",
962
+ "marker",
963
+ "marker-end",
964
+ "marker-mid",
965
+ "marker-start",
966
+ "paint-order",
967
+ "pointer-events",
968
+ "shape-rendering",
969
+ "stroke",
970
+ "stroke-dasharray",
971
+ "stroke-dashoffset",
972
+ "stroke-linecap",
973
+ "stroke-linejoin",
974
+ "stroke-miterlimit",
975
+ "stroke-opacity",
976
+ "stroke-width",
977
+ "text-anchor",
978
+ "text-rendering",
979
+ "visibility",
980
+ "word-spacing",
981
+ "writing-mode"
982
+ ]);
983
+ /** Initial values for known properties (subset). */
984
+ const INITIAL = {
985
+ fill: "black",
986
+ stroke: "none",
987
+ "fill-opacity": "1",
988
+ "stroke-opacity": "1",
989
+ "stroke-width": "1",
990
+ opacity: "1",
991
+ visibility: "visible",
992
+ display: "inline"
993
+ };
994
+ function resolve_declared(doc, id, property) {
995
+ const inline = doc.get_style(id, property);
996
+ if (inline !== null && inline !== "") return {
997
+ declared: inline,
998
+ provenance: {
999
+ origin: "author",
1000
+ carrier: "inline_style"
1001
+ }
1002
+ };
1003
+ const attr = doc.get_attr(id, property);
1004
+ if (attr !== null && attr !== "") return {
1005
+ declared: attr,
1006
+ provenance: {
1007
+ origin: "author",
1008
+ carrier: "presentation_attribute"
1009
+ }
1010
+ };
1011
+ if (INHERITED.has(property)) {
1012
+ const parent = doc.parent_of(id);
1013
+ if (parent !== null && doc.is_element(parent)) {
1014
+ const r = resolve_declared(doc, parent, property);
1015
+ if (r.declared !== null) return {
1016
+ declared: r.declared,
1017
+ provenance: {
1018
+ origin: "author",
1019
+ carrier: "inherited"
1020
+ }
1021
+ };
1022
+ }
1023
+ }
1024
+ return {
1025
+ declared: INITIAL[property] ?? null,
1026
+ provenance: {
1027
+ origin: "user_agent",
1028
+ carrier: "defaulted"
1029
+ }
1030
+ };
1031
+ }
1032
+ _properties.resolve_declared = resolve_declared;
1033
+ function compute_known(property, declared) {
1034
+ if (declared === null) return null;
1035
+ const trimmed = declared.trim();
1036
+ if (trimmed === "inherit" || trimmed === "initial" || trimmed === "unset" || trimmed === "revert" || trimmed === "revert-layer") return null;
1037
+ if (/^var\s*\(/i.test(trimmed)) return {
1038
+ error: "invalid_at_computed_value_time",
1039
+ reason: `var() substitution requires a cascade engine (not implemented)`
1040
+ };
1041
+ switch (property) {
1042
+ case "opacity":
1043
+ case "fill-opacity":
1044
+ case "stroke-opacity":
1045
+ case "stroke-width":
1046
+ case "x":
1047
+ case "y":
1048
+ case "width":
1049
+ case "height":
1050
+ case "cx":
1051
+ case "cy":
1052
+ case "r":
1053
+ case "rx":
1054
+ case "ry":
1055
+ case "font-size": {
1056
+ const n = parseFloat(trimmed);
1057
+ return Number.isFinite(n) ? n : trimmed;
1058
+ }
1059
+ default: return trimmed;
1060
+ }
1061
+ }
1062
+ _properties.compute_known = compute_known;
1063
+ function read(doc, id, property) {
1064
+ const { declared, provenance } = resolve_declared(doc, id, property);
1065
+ return {
1066
+ declared,
1067
+ computed: compute_known(property, declared),
1068
+ provenance
1069
+ };
1070
+ }
1071
+ _properties.read = read;
1072
+ function choose_write_carrier(doc, id, property) {
1073
+ const inline = doc.get_style(id, property);
1074
+ if (inline !== null && inline !== "") return "inline_style";
1075
+ return "presentation_attribute";
1076
+ }
1077
+ _properties.choose_write_carrier = choose_write_carrier;
1078
+ function value_equals(a, b) {
1079
+ if (a === b) return true;
1080
+ if (a.declared !== b.declared) return false;
1081
+ if (a.provenance.carrier !== b.provenance.carrier) return false;
1082
+ if (a.provenance.origin !== b.provenance.origin) return false;
1083
+ if (a.computed === b.computed) return true;
1084
+ if (a.computed && b.computed && typeof a.computed === "object" && typeof b.computed === "object" && "error" in a.computed && "error" in b.computed) return a.computed.error === b.computed.error && a.computed.reason === b.computed.reason;
1085
+ return false;
1086
+ }
1087
+ _properties.value_equals = value_equals;
1088
+ })(properties || (properties = {}));
1089
+ //#endregion
1090
+ //#region src/core/editor.ts
1091
+ const PROVIDER_ID = "svg-editor";
1092
+ /** Max characters in a synthesized display label before truncation. */
1093
+ const DISPLAY_LABEL_MAX_LEN = 40;
1094
+ /**
1095
+ * Wide internal factory — returns the full object including the
1096
+ * `_internal` / `keymap` surfaces in its inferred type. Stays private.
1097
+ * The public `createSvgEditor` below wraps this and narrows the return
1098
+ * to `SvgEditor` so the published `.d.ts` doesn't advertise internals.
1099
+ */
1100
+ function _create_svg_editor_internal(opts) {
1101
+ const doc = new SvgDocument(opts.svg);
1102
+ const history = new HistoryImpl();
1103
+ const defs = create_defs(doc);
1104
+ let selection = [];
1105
+ let scope = null;
1106
+ let mode = "select";
1107
+ let tool = TOOL_CURSOR;
1108
+ let version = 0;
1109
+ /** `doc.revision` at the last load()/reset(); compared to derive `dirty`.
1110
+ * The doc's own total mutation counter is the single edit-version
1111
+ * source — `content_version`, `dirty`, and the typed-read memo caches
1112
+ * all derive from it (no editor-side shadow counter to drift). */
1113
+ let baseline_revision = doc.revision;
1114
+ /**
1115
+ * Bumps once per `editor.load(svg)` call. The constructor's initial parse
1116
+ * does NOT count — it's the "factory" state. Hosts subscribe via
1117
+ * `subscribe_with_selector(s => s.load_version, ...)` to react to fresh
1118
+ * document loads without firing on every edit.
1119
+ */
1120
+ let load_version = 0;
1121
+ let style = {
1122
+ ...DEFAULT_STYLE,
1123
+ ...opts.style
1124
+ };
1125
+ const providers = opts.providers ?? {};
1126
+ /**
1127
+ * In-memory clipboard buffer — the transport floor (FRD R1: the buffer
1128
+ * write cannot fail; external channels are best-effort on top). NOT part
1129
+ * of `EditorState` and NOT history-managed: it survives `load()` /
1130
+ * `reset()` / undo, like the OS clipboard it mirrors.
1131
+ */
1132
+ let clipboard_buffer = null;
1133
+ /**
1134
+ * The last committed duplication — read by the NEXT `duplicate()` to
1135
+ * repeat the user's translate delta (gridaco/grida#825; spec
1136
+ * §Repeating offset). Session state like `clipboard_buffer`: not in
1137
+ * `EditorState`, not history-managed (undo/redo replay never re-arms
1138
+ * it — only a user-initiated ⌘D or cloned-drag commit does). Staleness
1139
+ * is caught at use by `subtree.repeat_delta`; the only eager clears are
1140
+ * `load()` / `reset()`, where every NodeId dies wholesale.
1141
+ */
1142
+ let active_duplication = null;
1143
+ const listeners = /* @__PURE__ */ new Set();
1144
+ let attached_surface = null;
1145
+ /**
1146
+ * World-space geometry query provider. Set by the DOM surface on
1147
+ * attach (`editor._internal.set_geometry`); cleared on detach. Null
1148
+ * means no renderer is attached — bounds queries cannot be answered.
1149
+ */
1150
+ let geometry_provider = null;
1151
+ const modes = ["select", "edit-content"];
1152
+ function snapshot() {
1153
+ return Object.freeze({
1154
+ selection,
1155
+ scope,
1156
+ mode,
1157
+ tool,
1158
+ dirty: doc.revision !== baseline_revision,
1159
+ can_undo: history.stack.canUndo,
1160
+ can_redo: history.stack.canRedo,
1161
+ version,
1162
+ content_version: doc.revision,
1163
+ structure_version: doc.structure_version,
1164
+ geometry_version: doc.geometry_version,
1165
+ load_version
1166
+ });
1167
+ }
1168
+ function emit() {
1169
+ version++;
1170
+ const s = snapshot();
1171
+ for (const fn of listeners) fn(s);
1172
+ }
1173
+ history.on("onChange", () => emit());
1174
+ history.on("onUndo", () => emit());
1175
+ history.on("onRedo", () => emit());
1176
+ let last_emitted_geometry_version = doc.geometry_version;
1177
+ const geometry_listeners = /* @__PURE__ */ new Set();
1178
+ const translate_commit_listeners = /* @__PURE__ */ new Set();
1179
+ const notify_translate_commit = () => {
1180
+ for (const cb of translate_commit_listeners) cb();
1181
+ };
1182
+ /**
1183
+ * Fan out the geometry channel iff the doc's `geometry_version` has
1184
+ * moved since we last fired. Shared by the `doc.on_change` handler
1185
+ * (mutation-driven bumps) and the surface-driven `bump_geometry` seam
1186
+ * (font-load reflow). Idempotent against a stale version — never
1187
+ * double-fires for the same value.
1188
+ */
1189
+ function fire_geometry_listeners_if_advanced() {
1190
+ if (doc.geometry_version !== last_emitted_geometry_version) {
1191
+ last_emitted_geometry_version = doc.geometry_version;
1192
+ for (const cb of geometry_listeners) cb();
1193
+ }
1194
+ }
1195
+ doc.on_change(() => {
1196
+ fire_geometry_listeners_if_advanced();
1197
+ });
1198
+ function subscribe(fn) {
1199
+ listeners.add(fn);
1200
+ return () => {
1201
+ listeners.delete(fn);
1202
+ };
1203
+ }
1204
+ function subscribe_with_selector(selector, fn, equals = Object.is) {
1205
+ let prev = selector(snapshot());
1206
+ return subscribe((state) => {
1207
+ const next = selector(state);
1208
+ if (!equals(prev, next)) {
1209
+ const p = prev;
1210
+ prev = next;
1211
+ fn(next, p);
1212
+ }
1213
+ });
1214
+ }
1215
+ function set_selection(next) {
1216
+ const pruned = doc.prune_nested_nodes(next);
1217
+ if (pruned.length === selection.length) {
1218
+ let same = true;
1219
+ for (let i = 0; i < pruned.length; i++) if (pruned[i] !== selection[i]) {
1220
+ same = false;
1221
+ break;
1222
+ }
1223
+ if (same) return;
1224
+ }
1225
+ selection = Object.freeze([...pruned]);
1226
+ emit();
1227
+ }
1228
+ function select(target, opts) {
1229
+ const ids = typeof target === "string" ? [target] : [...target];
1230
+ const mode = opts?.mode ?? "replace";
1231
+ if (mode === "replace") {
1232
+ set_selection(ids);
1233
+ return;
1234
+ }
1235
+ const next = new Set(selection);
1236
+ if (mode === "add") for (const id of ids) next.add(id);
1237
+ else for (const id of ids) if (next.has(id)) next.delete(id);
1238
+ else next.add(id);
1239
+ set_selection([...next]);
1240
+ }
1241
+ function deselect() {
1242
+ set_selection([]);
1243
+ }
1244
+ function enter_scope(group) {
1245
+ scope = group;
1246
+ emit();
1247
+ }
1248
+ function exit_scope() {
1249
+ if (scope === null) return;
1250
+ const parent = doc.parent_of(scope);
1251
+ scope = parent && parent !== doc.root ? parent : null;
1252
+ emit();
1253
+ }
1254
+ function set_mode(next) {
1255
+ if (mode === next) return;
1256
+ mode = next;
1257
+ emit();
1258
+ }
1259
+ function tools_equal(a, b) {
1260
+ if (a.type !== b.type) return false;
1261
+ if (a.type === "cursor" || a.type === "lasso" || a.type === "bend" || a.type === "insert-text") return true;
1262
+ return b.type === "insert" && a.tag === b.tag;
1263
+ }
1264
+ function set_tool(next) {
1265
+ if (tools_equal(tool, next)) return;
1266
+ tool = next;
1267
+ emit();
1268
+ }
1269
+ const paint_cache = /* @__PURE__ */ new Map();
1270
+ const property_cache = /* @__PURE__ */ new Map();
1271
+ const properties_cache = /* @__PURE__ */ new Map();
1272
+ let tree_cache = null;
1273
+ const tree_node_pool = /* @__PURE__ */ new Map();
1274
+ function tree_snapshot() {
1275
+ const sv = doc.structure_version;
1276
+ if (tree_cache && tree_cache.structure_version === sv) return tree_cache.value;
1277
+ const map = /* @__PURE__ */ new Map();
1278
+ let any_change = !tree_cache;
1279
+ for (const id of doc.all_elements()) {
1280
+ const tag = doc.tag_of(id);
1281
+ const name = doc.get_attr(id, "id") ?? void 0;
1282
+ const parent = doc.parent_of(id);
1283
+ const children = doc.element_children_of(id);
1284
+ const pooled = tree_node_pool.get(id);
1285
+ if (pooled && pooled.tag === tag && pooled.name === name && pooled.parent === parent && array_shallow_equal(pooled.children, children)) {
1286
+ map.set(id, pooled);
1287
+ continue;
1288
+ }
1289
+ const node = {
1290
+ id,
1291
+ tag,
1292
+ name,
1293
+ parent,
1294
+ children
1295
+ };
1296
+ tree_node_pool.set(id, node);
1297
+ map.set(id, node);
1298
+ any_change = true;
1299
+ }
1300
+ for (const id of tree_node_pool.keys()) if (!map.has(id)) {
1301
+ tree_node_pool.delete(id);
1302
+ any_change = true;
1303
+ }
1304
+ if (!any_change && tree_cache) {
1305
+ tree_cache.structure_version = sv;
1306
+ return tree_cache.value;
1307
+ }
1308
+ const snap = {
1309
+ root: doc.root,
1310
+ nodes: map
1311
+ };
1312
+ tree_cache = {
1313
+ structure_version: sv,
1314
+ value: snap
1315
+ };
1316
+ return snap;
1317
+ }
1318
+ function node_property_cached(id, name) {
1319
+ const key = `${id}${name}`;
1320
+ const cached = property_cache.get(key);
1321
+ if (cached && cached.revision === doc.revision) return cached.value;
1322
+ const next = properties.read(doc, id, name);
1323
+ if (cached && properties.value_equals(cached.value, next)) {
1324
+ cached.revision = doc.revision;
1325
+ return cached.value;
1326
+ }
1327
+ property_cache.set(key, {
1328
+ revision: doc.revision,
1329
+ value: next
1330
+ });
1331
+ return next;
1332
+ }
1333
+ function node_properties(id, names) {
1334
+ const key = `${id}${names.join("")}`;
1335
+ const cached = properties_cache.get(key);
1336
+ if (cached && cached.revision === doc.revision) return cached.value;
1337
+ const next = {};
1338
+ let changed = !cached;
1339
+ for (const name of names) {
1340
+ const v = node_property_cached(id, name);
1341
+ next[name] = v;
1342
+ if (cached && cached.value[name] !== v) changed = true;
1343
+ }
1344
+ if (cached && !changed) {
1345
+ cached.revision = doc.revision;
1346
+ return cached.value;
1347
+ }
1348
+ const frozen = Object.freeze(next);
1349
+ properties_cache.set(key, {
1350
+ revision: doc.revision,
1351
+ value: frozen
1352
+ });
1353
+ return frozen;
1354
+ }
1355
+ function node_paint(id, channel) {
1356
+ const key = `${id}${channel}`;
1357
+ const cached = paint_cache.get(key);
1358
+ if (cached && cached.revision === doc.revision) return cached.value;
1359
+ const { declared, provenance } = properties.resolve_declared(doc, id, channel);
1360
+ const next = {
1361
+ declared,
1362
+ computed: paint.parse(declared),
1363
+ provenance
1364
+ };
1365
+ if (cached && paint.value_equals(cached.value, next)) {
1366
+ cached.revision = doc.revision;
1367
+ return cached.value;
1368
+ }
1369
+ paint_cache.set(key, {
1370
+ revision: doc.revision,
1371
+ value: next
1372
+ });
1373
+ return next;
1374
+ }
1375
+ function write_property(id, name, value) {
1376
+ if (properties.choose_write_carrier(doc, id, name) === "inline_style") doc.set_style(id, name, value);
1377
+ else doc.set_attr(id, name, value);
1378
+ }
1379
+ /** Open `preview_property` sessions, keyed by property name. A discrete
1380
+ * write to the same name supersedes the in-flight gesture: the session
1381
+ * is silently discarded so a later host-side `commit()` cannot replay
1382
+ * the stale previewed value over the discrete write. The stored
1383
+ * function reverts the previewed value and unregisters itself. */
1384
+ const open_property_previews = /* @__PURE__ */ new Map();
1385
+ function supersede_property_preview(name) {
1386
+ open_property_previews.get(name)?.();
1387
+ }
1388
+ /** End EVERY open preview session. Called by operations that detach
1389
+ * nodes (remove / cut, ungroup) or replace the document (load,
1390
+ * reset): the sessions' deltas target nodes that are about to die,
1391
+ * so a later close-time `commit()` would push a dead history step.
1392
+ * Must run BEFORE the destructive mutation — each discard reverts
1393
+ * its in-flight delta against the still-intact document. (Live
1394
+ * iteration is safe: each discard deletes only its own map entry.) */
1395
+ function discard_open_property_previews() {
1396
+ for (const discard of open_property_previews.values()) discard();
1397
+ }
1398
+ function set_property(name, value) {
1399
+ if (selection.length === 0) return;
1400
+ supersede_property_preview(name);
1401
+ const before = [];
1402
+ for (const id of selection) before.push({
1403
+ id,
1404
+ attr: doc.get_attr(id, name),
1405
+ style: doc.get_style(id, name)
1406
+ });
1407
+ const targets = [...selection];
1408
+ const apply = () => {
1409
+ for (const id of targets) write_property(id, name, value);
1410
+ emit();
1411
+ };
1412
+ const revert = () => {
1413
+ for (const b of before) {
1414
+ if (b.style !== null) doc.set_style(b.id, name, b.style);
1415
+ else doc.set_style(b.id, name, null);
1416
+ doc.set_attr(b.id, name, b.attr);
1417
+ }
1418
+ emit();
1419
+ };
1420
+ apply();
1421
+ history.atomic(`set ${name}`, (tx) => {
1422
+ tx.push({
1423
+ providerId: PROVIDER_ID,
1424
+ apply,
1425
+ revert
1426
+ });
1427
+ });
1428
+ }
1429
+ function preview_property(name) {
1430
+ supersede_property_preview(name);
1431
+ const targets = [...selection];
1432
+ const before = [];
1433
+ for (const id of targets) before.push({
1434
+ id,
1435
+ attr: doc.get_attr(id, name),
1436
+ style: doc.get_style(id, name)
1437
+ });
1438
+ const preview = history.preview(`change ${name}`);
1439
+ const live = () => preview.state === "active";
1440
+ const close = () => {
1441
+ if (open_property_previews.get(name) === discard) open_property_previews.delete(name);
1442
+ };
1443
+ const discard = () => {
1444
+ close();
1445
+ if (live()) preview.discard();
1446
+ };
1447
+ open_property_previews.set(name, discard);
1448
+ return {
1449
+ get live() {
1450
+ return live();
1451
+ },
1452
+ update(value) {
1453
+ if (!live()) return;
1454
+ preview.set({
1455
+ providerId: PROVIDER_ID,
1456
+ apply: () => {
1457
+ for (const id of targets) write_property(id, name, value);
1458
+ emit();
1459
+ },
1460
+ revert: () => {
1461
+ for (const b of before) {
1462
+ if (b.style !== null) doc.set_style(b.id, name, b.style);
1463
+ else doc.set_style(b.id, name, null);
1464
+ doc.set_attr(b.id, name, b.attr);
1465
+ }
1466
+ emit();
1467
+ }
1468
+ });
1469
+ },
1470
+ commit: () => {
1471
+ close();
1472
+ if (live()) preview.commit();
1473
+ },
1474
+ discard
1475
+ };
1476
+ }
1477
+ function set_paint(channel, p) {
1478
+ if (selection.length === 0) return;
1479
+ set_property(channel, paint.serialize(p));
1480
+ }
1481
+ function preview_paint(channel) {
1482
+ const session = preview_property(channel);
1483
+ return {
1484
+ get live() {
1485
+ return session.live;
1486
+ },
1487
+ update: (p) => session.update(paint.serialize(p)),
1488
+ commit: () => session.commit(),
1489
+ discard: () => session.discard()
1490
+ };
1491
+ }
1492
+ function set_paint_from_gradient(channel, definition, _opts) {
1493
+ const gradient_id = defs.gradients.upsert(definition);
1494
+ set_paint(channel, {
1495
+ kind: "ref",
1496
+ id: gradient_id
1497
+ });
1498
+ return { gradient_id };
1499
+ }
1500
+ function set_opacity(value) {
1501
+ if (!Number.isFinite(value)) return;
1502
+ const clamped = cmath.clamp01(value);
1503
+ set_property("opacity", String(clamped));
1504
+ }
1505
+ /** World→local delta projection shared by every one-shot translate
1506
+ * writer (translate / nudge via `prepare_rpc`, align). Re-expresses a
1507
+ * world-space delta in the frame the target's position attributes are
1508
+ * written in — nested-viewport / transformed-ancestor correctness.
1509
+ * Identity for flat docs and DOM-less hosts (no provider, or a
1510
+ * provider without a layout engine). */
1511
+ const project_world_delta = (id, d) => geometry_provider?.world_delta_to_local?.(id, d) ?? d;
1512
+ /** Shared one-shot translate runner. `stages` selects semantics — see
1513
+ * `core/translate-pipeline/README.md`'s "Stage lists per entry point". */
1514
+ function do_translate_oneshot(delta, stages, label) {
1515
+ if (selection.length === 0) return false;
1516
+ if (delta.dx === 0 && delta.dy === 0) return false;
1517
+ const { apply, revert } = translate_pipeline.prepare_rpc({
1518
+ doc,
1519
+ ids: selection,
1520
+ delta: {
1521
+ x: delta.dx,
1522
+ y: delta.dy
1523
+ },
1524
+ options: {
1525
+ pixel_grid_quantum: style.snap_to_pixel_grid ? style.pixel_grid_size : null,
1526
+ snap_enabled: style.snap_enabled,
1527
+ snap_threshold_px: style.snap_threshold_px
1528
+ },
1529
+ emit,
1530
+ stages,
1531
+ project: project_world_delta
1532
+ });
1533
+ apply();
1534
+ history.atomic(label, (tx) => {
1535
+ tx.push({
1536
+ providerId: PROVIDER_ID,
1537
+ apply,
1538
+ revert
1539
+ });
1540
+ });
1541
+ return true;
1542
+ }
1543
+ function translate(delta) {
1544
+ if (do_translate_oneshot(delta, void 0, "translate")) notify_translate_commit();
1545
+ }
1546
+ function nudge(delta) {
1547
+ if (do_translate_oneshot(delta, translate_pipeline.stages.NUDGE, "nudge")) notify_translate_commit();
1548
+ }
1549
+ /**
1550
+ * Gate + capture for a resize gesture. Returns the resizable members (with
1551
+ * captured baseline / pre-transform / bbox), or `null` if the gesture can't
1552
+ * run: no geometry provider, empty selection, or — in `all_or_nothing` mode
1553
+ * — any member fails the gate.
1554
+ *
1555
+ * `mode`:
1556
+ * - `"skip"` — drop members failing the `is_resizable_node` gate
1557
+ * (tag + transform class) or lacking a bbox; resize the rest. Used by the
1558
+ * inspector `resize_to` (set-bbox) path.
1559
+ * - `"all_or_nothing"` — refuse the WHOLE gesture (return `null`) if ANY
1560
+ * member fails. Used by keyboard `resize_by` (nudge), matching the resize
1561
+ * HUD, whose handle-drag is rejected when any member is unsafe.
1562
+ */
1563
+ function collect_resize_members(ids, mode) {
1564
+ if (ids.length === 0) return null;
1565
+ if (!geometry_provider) return null;
1566
+ const members = [];
1567
+ for (const id of ids) {
1568
+ if (!resize_pipeline.intent.is_resizable_node(doc, id)) {
1569
+ if (mode === "all_or_nothing") return null;
1570
+ continue;
1571
+ }
1572
+ const bbox = geometry_provider.bounds_of(id);
1573
+ if (!bbox) {
1574
+ if (mode === "all_or_nothing") return null;
1575
+ continue;
1576
+ }
1577
+ members.push({
1578
+ id,
1579
+ rz: resize_pipeline.intent.capture_baseline(doc, id, bbox),
1580
+ bbox
1581
+ });
1582
+ }
1583
+ return members.length === 0 ? null : members;
1584
+ }
1585
+ /**
1586
+ * Apply a resize to each member, optionally followed by a uniform group
1587
+ * translate, as ONE atomic history step. `op` resolves each member's scale
1588
+ * factors + scale origin; `group_translate` is the post-scale envelope shift
1589
+ * (group resize only — `null` for per-element). Callers guarantee `members`
1590
+ * is non-empty. Returns `true` when a history step was pushed; `false` when
1591
+ * the gesture is geometrically identity (no member scales and no group
1592
+ * translate) so undo isn't polluted with an empty step. NOTE: a per-tag
1593
+ * constraint that collapses a non-1 factor to identity *inside* the handler
1594
+ * (e.g. `<circle>` uniform `min` on a single-axis nudge) is not detected
1595
+ * here — the op-level factor is still ≠ 1, so that case still pushes a step.
1596
+ */
1597
+ function commit_resize(members, op, group_translate, label) {
1598
+ const ops = members.map((m) => ({
1599
+ m,
1600
+ ...op(m)
1601
+ }));
1602
+ const scales = ops.some(({ sx, sy }) => sx !== 1 || sy !== 1);
1603
+ const translates = !!group_translate && (group_translate.dx !== 0 || group_translate.dy !== 0);
1604
+ if (!scales && !translates) return false;
1605
+ const apply = () => {
1606
+ for (const { m, sx, sy, origin } of ops) resize_pipeline.intent.apply(doc, m.id, m.rz, sx, sy, origin);
1607
+ if (group_translate && (group_translate.dx !== 0 || group_translate.dy !== 0)) for (const m of members) {
1608
+ const tx_after = translate_pipeline.intent.capture_baseline(doc, m.id);
1609
+ translate_pipeline.intent.apply(doc, m.id, tx_after, group_translate.dx, group_translate.dy);
1610
+ }
1611
+ emit();
1612
+ };
1613
+ const revert = () => {
1614
+ for (const { m } of ops) resize_pipeline.intent.restore(doc, m.id, m.rz);
1615
+ emit();
1616
+ };
1617
+ apply();
1618
+ history.atomic(label, (tx) => {
1619
+ tx.push({
1620
+ providerId: PROVIDER_ID,
1621
+ apply,
1622
+ revert
1623
+ });
1624
+ });
1625
+ return true;
1626
+ }
1627
+ /**
1628
+ * One-shot multi-member resize to an explicit target rect. Mirrors a
1629
+ * drag-resize gesture in mechanics — capture per-member baselines,
1630
+ * scale around the union's NW corner, translate the result so the
1631
+ * union NW lands at the requested position — but as a single
1632
+ * atomic step rather than a preview session. This is the GROUP path:
1633
+ * the whole selection is treated as one envelope.
1634
+ *
1635
+ * The function does its own geometry lookup via the
1636
+ * `geometry_provider` registered by the DOM surface. When no surface
1637
+ * is attached, the call is a no-op (returns `false`). Members that fail
1638
+ * the `is_resizable_node` gate — an unresizable tag (e.g. `<g>`) OR a
1639
+ * non-trivially-transformed element — are silently skipped (see
1640
+ * `collect_resize_members`).
1641
+ *
1642
+ * Revert restores the captured `transform` attribute and all
1643
+ * geometry attrs the apply step wrote — so a `<rect>` with an
1644
+ * existing `transform` round-trips cleanly. See `apply_translate`'s
1645
+ * `viaTransform` arm for why this matters.
1646
+ */
1647
+ function resize_to(target, opts) {
1648
+ const members = collect_resize_members(opts?.ids ?? selection, "skip");
1649
+ if (!members) return false;
1650
+ const union = cmath.rect.union(members.map((m) => m.bbox));
1651
+ const sx = union.width === 0 ? 1 : target.width / union.width;
1652
+ const sy = union.height === 0 ? 1 : target.height / union.height;
1653
+ const origin = {
1654
+ x: union.x,
1655
+ y: union.y
1656
+ };
1657
+ return commit_resize(members, () => ({
1658
+ sx,
1659
+ sy,
1660
+ origin
1661
+ }), {
1662
+ dx: target.x - union.x,
1663
+ dy: target.y - union.y
1664
+ }, opts?.label ?? "resize-to");
1665
+ }
1666
+ /**
1667
+ * Resize by a `{dw, dh}` delta — the core verb behind keyboard nudge-resize
1668
+ * (`Ctrl+Alt+Arrow`). This is the PER-ELEMENT path: each selected member
1669
+ * grows/shrinks by the delta around ITS OWN NW corner, so members keep their
1670
+ * positions relative to one another. This deliberately differs from
1671
+ * {@link resize_to} (the group/envelope path): a HUD group-resize scales the
1672
+ * whole selection around the shared union origin, translating off-origin
1673
+ * members — correct for a drag handle, wrong for a keyboard nudge, whose UX
1674
+ * is "apply the delta to each".
1675
+ *
1676
+ * ALL-OR-NOTHING gate (`collect_resize_members("all_or_nothing")`): refuses
1677
+ * (returns `false`, no history step) on empty selection, no geometry
1678
+ * provider, or any member failing the `is_resizable_node` gate — matching
1679
+ * the resize HUD rather than `resize_to`'s per-member skip.
1680
+ */
1681
+ function resize_by(delta, opts) {
1682
+ const members = collect_resize_members(opts?.ids ?? selection, "all_or_nothing");
1683
+ if (!members) return false;
1684
+ const axis = (size, d) => size === 0 ? 1 : Math.max(0, size + d) / size;
1685
+ return commit_resize(members, (m) => ({
1686
+ sx: axis(m.bbox.width, delta.dw),
1687
+ sy: axis(m.bbox.height, delta.dh),
1688
+ origin: {
1689
+ x: m.bbox.x,
1690
+ y: m.bbox.y
1691
+ }
1692
+ }), null, "nudge-resize");
1693
+ }
1694
+ /** Shared helper: compute a default rotation pivot from the live
1695
+ * geometry_provider when the caller omitted one. Falls back to (0,0)
1696
+ * if no surface is attached. */
1697
+ function default_rotate_pivot(ids) {
1698
+ if (!geometry_provider || ids.length === 0) return {
1699
+ x: 0,
1700
+ y: 0
1701
+ };
1702
+ const rects = [];
1703
+ for (const id of ids) {
1704
+ const b = geometry_provider.bounds_of(id);
1705
+ if (b) rects.push(b);
1706
+ }
1707
+ if (rects.length === 0) return {
1708
+ x: 0,
1709
+ y: 0
1710
+ };
1711
+ const u = cmath.rect.union(rects);
1712
+ return {
1713
+ x: u.x + u.width / 2,
1714
+ y: u.y + u.height / 2
1715
+ };
1716
+ }
1717
+ function rotate(angle, opts) {
1718
+ const ids = opts?.ids ?? selection;
1719
+ if (ids.length === 0) return false;
1720
+ const pivot = opts?.pivot ?? default_rotate_pivot(ids);
1721
+ const prepared = rotate_pipeline.prepare_rpc({
1722
+ doc,
1723
+ ids,
1724
+ pivot,
1725
+ angle_radians: angle,
1726
+ options: { angle_snap_step_radians: style.angle_snap_step_radians },
1727
+ emit
1728
+ });
1729
+ for (const v of prepared.verdicts.values()) if (v.kind === "refuse") return false;
1730
+ prepared.apply();
1731
+ history.atomic("rotate", (tx) => {
1732
+ tx.push({
1733
+ providerId: PROVIDER_ID,
1734
+ apply: prepared.apply,
1735
+ revert: prepared.revert
1736
+ });
1737
+ });
1738
+ return true;
1739
+ }
1740
+ function rotate_to(angle, opts) {
1741
+ const ids = opts?.ids ?? selection;
1742
+ if (ids.length === 0) return false;
1743
+ const pivot = opts?.pivot ?? default_rotate_pivot(ids);
1744
+ const probe = rotate_pipeline.prepare_rpc({
1745
+ doc,
1746
+ ids,
1747
+ pivot,
1748
+ angle_radians: 0,
1749
+ options: { angle_snap_step_radians: style.angle_snap_step_radians },
1750
+ emit: () => {}
1751
+ });
1752
+ for (const v of probe.verdicts.values()) if (v.kind === "refuse") return false;
1753
+ const DEG_TO_RAD = Math.PI / 180;
1754
+ const apply = () => {
1755
+ for (const m of probe.plan.members) {
1756
+ const delta = angle - m.baseline.current_rotation_deg * DEG_TO_RAD;
1757
+ rotate_pipeline.intent.apply(doc, m.id, m.baseline, delta);
1758
+ }
1759
+ emit();
1760
+ };
1761
+ const revert = () => {
1762
+ for (const m of probe.plan.members) rotate_pipeline.intent.apply(doc, m.id, m.baseline, 0);
1763
+ emit();
1764
+ };
1765
+ apply();
1766
+ history.atomic("rotate-to", (tx) => {
1767
+ tx.push({
1768
+ providerId: PROVIDER_ID,
1769
+ apply,
1770
+ revert
1771
+ });
1772
+ });
1773
+ return true;
1774
+ }
1775
+ /**
1776
+ * Relative affine compose about a pivot. See the `Commands.transform`
1777
+ * doc for the full contract. This function owns ONLY the pivot/effective-
1778
+ * matrix computation (which needs `geometry_provider`); the parse→fold→
1779
+ * emit round-trip is delegated per-member to the pure
1780
+ * `transform.apply_affine` helper.
1781
+ */
1782
+ function apply_transform(matrix, opts) {
1783
+ const ids = opts?.ids ?? selection;
1784
+ if (ids.length === 0) return false;
1785
+ if (!geometry_provider) return false;
1786
+ for (const id of ids) if (rotate_pipeline.intent.is_transformable(doc, id).kind === "refuse") return false;
1787
+ const pivot = opts?.pivot ?? default_rotate_pivot(ids);
1788
+ const [a, b, c, d, e, f] = matrix;
1789
+ const requested = [[
1790
+ a,
1791
+ c,
1792
+ e
1793
+ ], [
1794
+ b,
1795
+ d,
1796
+ f
1797
+ ]];
1798
+ const t_pivot = [[
1799
+ 1,
1800
+ 0,
1801
+ pivot.x
1802
+ ], [
1803
+ 0,
1804
+ 1,
1805
+ pivot.y
1806
+ ]];
1807
+ const t_neg_pivot = [[
1808
+ 1,
1809
+ 0,
1810
+ -pivot.x
1811
+ ], [
1812
+ 0,
1813
+ 1,
1814
+ -pivot.y
1815
+ ]];
1816
+ const effective = cmath.transform.multiply(cmath.transform.multiply(t_pivot, requested), t_neg_pivot);
1817
+ const members = ids.map((id) => ({
1818
+ id,
1819
+ transform_pre: doc.get_attr(id, "transform")
1820
+ }));
1821
+ const apply = () => {
1822
+ for (const m of members) doc.set_attr(m.id, "transform", transform.apply_affine(m.transform_pre, effective));
1823
+ emit();
1824
+ };
1825
+ const revert = () => {
1826
+ for (const m of members) doc.set_attr(m.id, "transform", m.transform_pre);
1827
+ emit();
1828
+ };
1829
+ apply();
1830
+ history.atomic("transform", (tx) => {
1831
+ tx.push({
1832
+ providerId: PROVIDER_ID,
1833
+ apply,
1834
+ revert
1835
+ });
1836
+ });
1837
+ return true;
1838
+ }
1839
+ function flatten_transform(opts) {
1840
+ const ids = opts?.ids ?? selection;
1841
+ if (ids.length === 0) return false;
1842
+ const members = [];
1843
+ for (const id of ids) {
1844
+ const pre = doc.get_attr(id, "transform");
1845
+ if (pre === null) continue;
1846
+ const ops = transform.parse(pre);
1847
+ if (ops === null) continue;
1848
+ if (ops.length === 1 && ops[0].type === "matrix") continue;
1849
+ members.push({
1850
+ id,
1851
+ transform_pre: pre,
1852
+ ops
1853
+ });
1854
+ }
1855
+ if (members.length === 0) return false;
1856
+ const apply = () => {
1857
+ for (const m of members) {
1858
+ let mat = FLATTEN_IDENT;
1859
+ for (const op of m.ops) mat = flatten_mul(mat, flatten_op_to_mat(op));
1860
+ doc.set_attr(m.id, "transform", transform.emit([{
1861
+ type: "matrix",
1862
+ a: mat[0],
1863
+ b: mat[1],
1864
+ c: mat[2],
1865
+ d: mat[3],
1866
+ e: mat[4],
1867
+ f: mat[5]
1868
+ }]));
1869
+ }
1870
+ emit();
1871
+ };
1872
+ const revert = () => {
1873
+ for (const m of members) doc.set_attr(m.id, "transform", m.transform_pre);
1874
+ emit();
1875
+ };
1876
+ apply();
1877
+ history.atomic("flatten-transform", (tx) => {
1878
+ tx.push({
1879
+ providerId: PROVIDER_ID,
1880
+ apply,
1881
+ revert
1882
+ });
1883
+ });
1884
+ return true;
1885
+ }
1886
+ /**
1887
+ * Translate selected members so they line up along the requested edge or
1888
+ * center of a reference rect. Same mechanics as `resize_to`: per-member
1889
+ * translate baselines (so `<g>`, transformed, and natively-attributed
1890
+ * nodes all write the cleanest in-place representation), one atomic
1891
+ * history step. Deltas are computed in world space and re-expressed in
1892
+ * each member's local frame before writing (`world_delta_to_local`),
1893
+ * so members under scaled/rotated ancestors land exactly and a repeat
1894
+ * invocation is a no-op.
1895
+ *
1896
+ * Reference rect is selection-size dependent:
1897
+ * - multi-selection: union of member bboxes
1898
+ * - single selection: the parent's bbox (root → `<svg>` viewport,
1899
+ * inside a `<g>` → that group's bbox). Refuses when the selected
1900
+ * node IS the root (no container to align against).
1901
+ *
1902
+ * Refuses when `geometry_provider` is null (no surface attached) or when
1903
+ * no member has a resolvable bbox.
1904
+ */
1905
+ function align(direction, opts) {
1906
+ const ids = opts?.ids ?? selection;
1907
+ if (ids.length === 0) return false;
1908
+ if (!geometry_provider) return false;
1909
+ const members = [];
1910
+ for (const id of ids) {
1911
+ const bbox = geometry_provider.bounds_of(id);
1912
+ if (!bbox) continue;
1913
+ const baseline = translate_pipeline.intent.capture_baseline(doc, id);
1914
+ if (baseline.type === "unsupported") continue;
1915
+ members.push({
1916
+ id,
1917
+ bbox,
1918
+ baseline
1919
+ });
1920
+ }
1921
+ if (members.length === 0) return false;
1922
+ let target;
1923
+ if (members.length === 1) {
1924
+ const parent_id = doc.parent_of(members[0].id);
1925
+ if (parent_id === null) return false;
1926
+ const parent_bbox = geometry_provider.bounds_of(parent_id);
1927
+ if (!parent_bbox) return false;
1928
+ target = parent_bbox;
1929
+ } else target = cmath.rect.union(members.map((m) => m.bbox));
1930
+ const world_deltas = compute_align_deltas(members, target, direction);
1931
+ if (world_deltas.size === 0) return false;
1932
+ const deltas = /* @__PURE__ */ new Map();
1933
+ for (const [id, d] of world_deltas) deltas.set(id, project_world_delta(id, d));
1934
+ const apply = () => {
1935
+ for (const m of members) {
1936
+ const d = deltas.get(m.id);
1937
+ if (d) translate_pipeline.intent.apply(doc, m.id, m.baseline, d.x, d.y);
1938
+ }
1939
+ emit();
1940
+ };
1941
+ const revert = () => {
1942
+ for (const m of members) if (deltas.has(m.id)) translate_pipeline.intent.apply(doc, m.id, m.baseline, 0, 0);
1943
+ emit();
1944
+ };
1945
+ apply();
1946
+ history.atomic(`align ${direction}`, (tx) => {
1947
+ tx.push({
1948
+ providerId: PROVIDER_ID,
1949
+ apply,
1950
+ revert
1951
+ });
1952
+ });
1953
+ return true;
1954
+ }
1955
+ function select_all() {
1956
+ const parent = scope ?? doc.root;
1957
+ const children = doc.element_children_of(parent);
1958
+ if (children.length === 0) return false;
1959
+ set_selection(children);
1960
+ return true;
1961
+ }
1962
+ /**
1963
+ * Cycle the selection to the next / previous sibling. Single-selection
1964
+ * path uses the selected node's parent; empty / multi-selection falls
1965
+ * back to the current scope's first / last child. Wraps at edges.
1966
+ */
1967
+ function select_sibling(direction) {
1968
+ let parent;
1969
+ let anchor_index;
1970
+ let siblings;
1971
+ if (selection.length === 1) {
1972
+ const current = selection[0];
1973
+ parent = doc.parent_of(current);
1974
+ if (parent === null) return false;
1975
+ siblings = doc.element_children_of(parent);
1976
+ anchor_index = siblings.indexOf(current);
1977
+ if (anchor_index < 0) return false;
1978
+ } else {
1979
+ parent = scope ?? doc.root;
1980
+ siblings = doc.element_children_of(parent);
1981
+ if (siblings.length === 0) return false;
1982
+ anchor_index = direction === "next" ? -1 : siblings.length;
1983
+ }
1984
+ const n = siblings.length;
1985
+ const next = direction === "next" ? (anchor_index + 1) % n : (anchor_index - 1 + n) % n;
1986
+ set_selection([siblings[next]]);
1987
+ return true;
1988
+ }
1989
+ function reorder(direction) {
1990
+ if (selection.length !== 1) return;
1991
+ const target = selection[0];
1992
+ const parent = doc.parent_of(target);
1993
+ if (parent === null) return;
1994
+ const siblings = doc.element_children_of(parent);
1995
+ const i = siblings.indexOf(target);
1996
+ if (i < 0) return;
1997
+ const original_before = siblings[i + 1] ?? null;
1998
+ let new_before;
1999
+ switch (direction) {
2000
+ case "bring_forward":
2001
+ if (i >= siblings.length - 1) return;
2002
+ new_before = siblings[i + 2] ?? null;
2003
+ break;
2004
+ case "send_backward":
2005
+ if (i <= 0) return;
2006
+ new_before = siblings[i - 1];
2007
+ break;
2008
+ case "bring_to_front":
2009
+ if (i === siblings.length - 1) return;
2010
+ new_before = null;
2011
+ break;
2012
+ case "send_to_back":
2013
+ if (i === 0) return;
2014
+ new_before = siblings[0];
2015
+ break;
2016
+ }
2017
+ const apply = () => {
2018
+ doc.insert(target, parent, new_before);
2019
+ emit();
2020
+ };
2021
+ const revert = () => {
2022
+ doc.insert(target, parent, original_before);
2023
+ emit();
2024
+ };
2025
+ apply();
2026
+ history.atomic(`reorder: ${direction}`, (tx) => {
2027
+ tx.push({
2028
+ providerId: PROVIDER_ID,
2029
+ apply,
2030
+ revert
2031
+ });
2032
+ });
2033
+ }
2034
+ function remove() {
2035
+ remove_selection("remove");
2036
+ }
2037
+ /**
2038
+ * Shared deletion body for `remove` and `cut` — identical
2039
+ * capture/revert semantics, differing only in the history label
2040
+ * (`verb`), so undo attribution names the gesture that caused the
2041
+ * deletion.
2042
+ */
2043
+ function remove_selection(verb) {
2044
+ if (selection.length === 0) return;
2045
+ const filtered = doc.prune_nested_nodes(selection).filter((id) => doc.parent_of(id) !== null);
2046
+ if (filtered.length === 0) return;
2047
+ discard_open_property_previews();
2048
+ const captures = [...filtered].sort(subtree.by_document_order(doc)).map((id) => ({
2049
+ id,
2050
+ parent: doc.parent_of(id),
2051
+ next_sibling: doc.next_element_sibling_of(id)
2052
+ }));
2053
+ const old_selection = selection;
2054
+ const apply = () => {
2055
+ for (const c of captures) doc.remove(c.id);
2056
+ set_selection([]);
2057
+ };
2058
+ const revert = () => {
2059
+ for (let i = captures.length - 1; i >= 0; i--) {
2060
+ const c = captures[i];
2061
+ doc.insert(c.id, c.parent, c.next_sibling);
2062
+ }
2063
+ set_selection(old_selection);
2064
+ };
2065
+ apply();
2066
+ history.atomic(captures.length === 1 ? verb : `${verb} ${captures.length}`, (tx) => {
2067
+ tx.push({
2068
+ providerId: PROVIDER_ID,
2069
+ apply,
2070
+ revert
2071
+ });
2072
+ });
2073
+ }
2074
+ function group$1() {
2075
+ const plan = group.plan(doc, selection);
2076
+ if (!plan) return false;
2077
+ const group_id = doc.create_element("g");
2078
+ const original_selection = selection;
2079
+ const apply = () => {
2080
+ doc.insert(group_id, plan.parent, plan.insert_before);
2081
+ for (const child of plan.children) doc.insert(child, group_id, null);
2082
+ set_selection([group_id]);
2083
+ };
2084
+ const revert = () => {
2085
+ for (let i = plan.children.length - 1; i >= 0; i--) {
2086
+ const child = plan.children[i];
2087
+ doc.insert(child, plan.parent, plan.original_positions.get(child) ?? null);
2088
+ }
2089
+ doc.remove(group_id);
2090
+ set_selection(original_selection);
2091
+ };
2092
+ apply();
2093
+ history.atomic("group", (tx) => {
2094
+ tx.push({
2095
+ providerId: PROVIDER_ID,
2096
+ apply,
2097
+ revert
2098
+ });
2099
+ });
2100
+ return true;
2101
+ }
2102
+ function ungroup(opts) {
2103
+ let target;
2104
+ if (opts?.id !== void 0) target = opts.id;
2105
+ else {
2106
+ if (selection.length !== 1) return false;
2107
+ target = selection[0];
2108
+ }
2109
+ discard_open_property_previews();
2110
+ const plan = group.plan_ungroup(doc, target);
2111
+ if (!plan) return false;
2112
+ const group_id = plan.group_id;
2113
+ const group_next_sibling = doc.next_element_sibling_of(group_id);
2114
+ const original_child_transforms = /* @__PURE__ */ new Map();
2115
+ for (const child of plan.children) original_child_transforms.set(child, doc.get_attr(child, "transform"));
2116
+ const group_ops = plan.group_transform === null ? [] : transform.parse(plan.group_transform) ?? [];
2117
+ const original_selection = selection;
2118
+ const apply = () => {
2119
+ if (group_ops.length > 0) for (const child of plan.children) {
2120
+ const child_ops = transform.parse(doc.get_attr(child, "transform")) ?? [];
2121
+ const next = transform.emit([...group_ops, ...child_ops]);
2122
+ doc.set_attr(child, "transform", next === "" ? null : next);
2123
+ }
2124
+ for (const child of plan.children) doc.insert(child, plan.parent, group_id);
2125
+ doc.remove(group_id);
2126
+ set_selection(plan.children);
2127
+ };
2128
+ const revert = () => {
2129
+ doc.insert(group_id, plan.parent, group_next_sibling);
2130
+ for (const child of plan.children) doc.insert(child, group_id, null);
2131
+ if (group_ops.length > 0) for (const child of plan.children) doc.set_attr(child, "transform", original_child_transforms.get(child) ?? null);
2132
+ set_selection(original_selection);
2133
+ };
2134
+ apply();
2135
+ history.atomic("ungroup", (tx) => {
2136
+ tx.push({
2137
+ providerId: PROVIDER_ID,
2138
+ apply,
2139
+ revert
2140
+ });
2141
+ });
2142
+ return true;
2143
+ }
2144
+ /**
2145
+ * Atomic one-shot insertion. Used by paste, programmatic RPC, and the
2146
+ * click-no-drag commit path inside the insertion gesture driver. One
2147
+ * undo step. Returns the new node id.
2148
+ *
2149
+ * `attrs` are merged on top of `default_paint_attrs(tag)` — caller attrs
2150
+ * win. `opts.parent` defaults to root; `opts.index` (insert-before
2151
+ * sibling index) defaults to append; `opts.select` defaults to `true`.
2152
+ */
2153
+ /**
2154
+ * Resolve an optional `index` (position in `parent`'s element-children
2155
+ * list to insert AT — anything at or after it shifts; out-of-range or
2156
+ * `undefined` appends) to an insert-before anchor. Shared by `insert`,
2157
+ * `insert_fragment`, and `insert_preview`.
2158
+ */
2159
+ function resolve_insert_before(parent, index) {
2160
+ if (index === void 0) return null;
2161
+ return doc.element_children_of(parent)[index] ?? null;
2162
+ }
2163
+ function insert(tag, attrs, opts) {
2164
+ const parent = opts?.parent ?? doc.root;
2165
+ const select_after = opts?.select !== false;
2166
+ const insert_before = resolve_insert_before(parent, opts?.index);
2167
+ const id = doc.create_element(tag);
2168
+ const merged_attrs = {
2169
+ ...default_paint_attrs_for(tag),
2170
+ ...attrs
2171
+ };
2172
+ const attr_pairs = Object.entries(merged_attrs);
2173
+ const previous_selection = selection;
2174
+ const apply = () => {
2175
+ for (const [name, value] of attr_pairs) doc.set_attr(id, name, value);
2176
+ doc.insert(id, parent, insert_before);
2177
+ if (select_after) set_selection([id]);
2178
+ };
2179
+ const revert = () => {
2180
+ doc.remove(id);
2181
+ if (select_after) set_selection(previous_selection);
2182
+ };
2183
+ apply();
2184
+ history.atomic(`insert ${tag}`, (tx) => {
2185
+ tx.push({
2186
+ providerId: PROVIDER_ID,
2187
+ apply,
2188
+ revert
2189
+ });
2190
+ });
2191
+ return id;
2192
+ }
2193
+ /**
2194
+ * Atomic fragment insertion — contract in {@link Commands.insert_fragment}.
2195
+ * Parses + adopts via `doc.create_fragment` (subtrees registered but
2196
+ * detached, like `create_element` — history.redo finds them via
2197
+ * closure), computes the namespace hoist plan, then brackets inserts +
2198
+ * hoisted declarations + selection in ONE history step.
2199
+ */
2200
+ function insert_fragment(svg, opts) {
2201
+ return insert_fragment_impl(svg, opts, "insert fragment");
2202
+ }
2203
+ /**
2204
+ * Label-bearing body shared by `insert_fragment` and `paste` — same
2205
+ * atomic insertion, differing only in history attribution (undo for a
2206
+ * paste gesture should read "paste", not "insert fragment").
2207
+ */
2208
+ function insert_fragment_impl(svg, opts, label) {
2209
+ const parent = opts?.parent ?? doc.root;
2210
+ if (!doc.is_element(parent) || !doc.contains(doc.root, parent)) throw new Error(`insert_fragment: parent ${JSON.stringify(parent)} is not an element in the current document`);
2211
+ const select_after = opts?.select !== false;
2212
+ const { roots, xmlns } = doc.create_fragment(svg);
2213
+ if (roots.length === 0) return [];
2214
+ const known_uri = new Map(WELL_KNOWN_NS_PREFIXES);
2215
+ for (const d of xmlns) known_uri.set(d.prefix, d.uri);
2216
+ const hoist = [];
2217
+ const considered = /* @__PURE__ */ new Set();
2218
+ for (const id of roots) for (const prefix of doc.undeclared_ns_prefixes(id)) {
2219
+ if (considered.has(prefix)) continue;
2220
+ considered.add(prefix);
2221
+ if (doc.get_attr(doc.root, prefix, XMLNS_NS) !== null) continue;
2222
+ const uri = known_uri.get(prefix);
2223
+ if (uri === void 0) continue;
2224
+ hoist.push({
2225
+ prefix,
2226
+ uri
2227
+ });
2228
+ }
2229
+ const insert_before = resolve_insert_before(parent, opts?.index);
2230
+ const previous_selection = selection;
2231
+ const apply = () => {
2232
+ for (const { prefix, uri } of hoist) doc.declare_xmlns(prefix, uri);
2233
+ for (const id of roots) doc.insert(id, parent, insert_before);
2234
+ if (select_after) set_selection(roots);
2235
+ };
2236
+ const revert = () => {
2237
+ for (let i = roots.length - 1; i >= 0; i--) doc.remove(roots[i]);
2238
+ for (const { prefix } of hoist) doc.set_attr(doc.root, prefix, null, XMLNS_NS);
2239
+ if (select_after) set_selection(previous_selection);
2240
+ };
2241
+ apply();
2242
+ history.atomic(label, (tx) => {
2243
+ tx.push({
2244
+ providerId: PROVIDER_ID,
2245
+ apply,
2246
+ revert
2247
+ });
2248
+ });
2249
+ return roots;
2250
+ }
2251
+ function copy_impl(deliver_external) {
2252
+ const payload = clipboard.extract_payload(doc, selection);
2253
+ if (payload === null) return null;
2254
+ clipboard_buffer = payload;
2255
+ if (deliver_external && providers.clipboard) providers.clipboard.write(payload).catch((err) => {
2256
+ console.warn("[svg-editor] clipboard provider write failed:", err);
2257
+ });
2258
+ return payload;
2259
+ }
2260
+ function copy() {
2261
+ return copy_impl(true);
2262
+ }
2263
+ function cut_impl(deliver_external) {
2264
+ if (selection.length === 0) return null;
2265
+ discard_open_property_previews();
2266
+ const payload = copy_impl(deliver_external);
2267
+ if (payload === null) return null;
2268
+ remove_selection("cut");
2269
+ return payload;
2270
+ }
2271
+ function cut() {
2272
+ return cut_impl(true);
2273
+ }
2274
+ function paste(text) {
2275
+ if (text !== void 0 && typeof text !== "string") throw new TypeError(`paste(text) requires a string when provided, got ${text === null ? "null" : typeof text}`);
2276
+ const source = text ?? clipboard_buffer;
2277
+ if (source === null) return [];
2278
+ try {
2279
+ return insert_fragment_impl(source, void 0, "paste");
2280
+ } catch (err) {
2281
+ if (err instanceof TypeError) throw err;
2282
+ return [];
2283
+ }
2284
+ }
2285
+ /**
2286
+ * Duplicate over `subtree.clone_plan` — see the `Commands` doc. Same
2287
+ * atomic shape as `insert_fragment_impl`: closures own the
2288
+ * insert/remove pair so redo re-inserts the same NodeIds.
2289
+ *
2290
+ * Repeating offset (gridaco/grida#825, spec §Repeating offset): when
2291
+ * the targets are exactly the previous duplication's clones and
2292
+ * geometry witnesses a rigid translate between that record's origins
2293
+ * and clones, the fresh clones land displaced by the same delta. The
2294
+ * offset rides the translate pipeline INSIDE the same atomic step —
2295
+ * one undo removes copy + offset together. Clone baselines are
2296
+ * key-swapped from the origins (a clone is a verbatim copy at rest —
2297
+ * the orchestrator's `enter_clone` trick), so nothing reads the
2298
+ * detached clones. Any failed precondition degrades to plain
2299
+ * duplicate-in-place; never an error.
2300
+ */
2301
+ function duplicate() {
2302
+ const plan = subtree.clone_plan(doc, selection);
2303
+ if (plan.length === 0) return [];
2304
+ const clones = plan.map((p) => p.clone);
2305
+ const origins = plan.map((p) => p.origin);
2306
+ const previous_selection = selection;
2307
+ const delta = subtree.repeat_delta(active_duplication, origins, (id) => geometry_provider ? geometry_provider.bounds_of(id) : null);
2308
+ let offset_plan = null;
2309
+ if (delta) {
2310
+ const baselines = /* @__PURE__ */ new Map();
2311
+ for (const p of plan) baselines.set(p.clone, translate_pipeline.intent.capture_baseline(doc, p.origin));
2312
+ offset_plan = {
2313
+ ids: clones,
2314
+ baselines,
2315
+ delta
2316
+ };
2317
+ }
2318
+ const apply = () => {
2319
+ subtree.insert_plan(doc, plan);
2320
+ if (offset_plan) translate_pipeline.apply(doc, offset_plan, project_world_delta);
2321
+ set_selection(clones);
2322
+ };
2323
+ const revert = () => {
2324
+ if (offset_plan) translate_pipeline.revert(doc, offset_plan);
2325
+ subtree.remove_plan(doc, plan);
2326
+ set_selection(previous_selection);
2327
+ };
2328
+ apply();
2329
+ history.atomic("duplicate", (tx) => {
2330
+ tx.push({
2331
+ providerId: PROVIDER_ID,
2332
+ apply,
2333
+ revert
2334
+ });
2335
+ });
2336
+ active_duplication = {
2337
+ origins,
2338
+ clones
2339
+ };
2340
+ return clones;
2341
+ }
2342
+ /**
2343
+ * Preview-bracketed insertion. Used by the pointer-driven drag gesture
2344
+ * in the DOM surface. Per-frame attr writes call `update(attrs)`; one
2345
+ * undo step on `commit()`; clean rollback on `discard()`.
2346
+ *
2347
+ * The node is created and inserted on open so the HUD selection chrome
2348
+ * can render the in-progress shape immediately. On `discard()` the
2349
+ * preview's revert removes the node entirely.
2350
+ */
2351
+ function insert_preview(tag, initial, opts) {
2352
+ const parent = opts?.parent ?? doc.root;
2353
+ const insert_before = resolve_insert_before(parent, opts?.index);
2354
+ const id = doc.create_element(tag);
2355
+ const previous_selection = selection;
2356
+ const live_attrs = {
2357
+ ...default_paint_attrs_for(tag),
2358
+ ...initial
2359
+ };
2360
+ for (const name in live_attrs) doc.set_attr(id, name, live_attrs[name]);
2361
+ doc.insert(id, parent, insert_before);
2362
+ set_selection([id]);
2363
+ const preview = history.preview(`insert ${tag}`);
2364
+ const live = () => preview.state === "active";
2365
+ const apply = () => {
2366
+ for (const name in live_attrs) doc.set_attr(id, name, live_attrs[name]);
2367
+ if (doc.parent_of(id) === null) doc.insert(id, parent, insert_before);
2368
+ set_selection([id]);
2369
+ };
2370
+ const revert = () => {
2371
+ doc.remove(id);
2372
+ set_selection(previous_selection);
2373
+ };
2374
+ const entry = {
2375
+ providerId: PROVIDER_ID,
2376
+ apply,
2377
+ revert
2378
+ };
2379
+ preview.set(entry);
2380
+ return {
2381
+ id,
2382
+ update(attrs) {
2383
+ if (!live()) return;
2384
+ for (const name in attrs) {
2385
+ live_attrs[name] = attrs[name];
2386
+ doc.set_attr(id, name, attrs[name]);
2387
+ }
2388
+ preview.set(entry);
2389
+ },
2390
+ commit() {
2391
+ if (!live()) return;
2392
+ preview.commit();
2393
+ },
2394
+ discard() {
2395
+ if (!live()) return;
2396
+ preview.discard();
2397
+ }
2398
+ };
2399
+ }
2400
+ /**
2401
+ * Text-creation bracket for the click-to-place text tool. Creates an
2402
+ * empty `<text>` with `initial` attrs, opens a single history preview,
2403
+ * and selects it — the DOM surface then mounts inline content-edit on
2404
+ * it. The surface finalizes the returned session when content-edit
2405
+ * exits:
2406
+ *
2407
+ * - `commit()` — snapshots the live text content into the delta and
2408
+ * commits ONE undo step (create + text together). Redo replays both,
2409
+ * so a redone text insert keeps its content (a plain `insert_preview`
2410
+ * would lose it — text is not an attribute).
2411
+ * - `discard()` — rolls the creation back entirely: no node, no
2412
+ * committed history entry. This is the empty-equals-delete rule for a
2413
+ * freshly-placed node (design:
2414
+ * `docs/wg/feat-svg-editor/text-tool.md`).
2415
+ *
2416
+ * The node is inserted empty on open (so the caret has somewhere to
2417
+ * live); live edits mutate its text in place, and `commit()` reads the
2418
+ * final text back off the document.
2419
+ */
2420
+ function insert_text_preview(initial, opts) {
2421
+ const parent = opts?.parent ?? doc.root;
2422
+ const id = doc.create_element("text");
2423
+ const previous_selection = selection;
2424
+ const attrs = { ...initial };
2425
+ let committed_text = "";
2426
+ const apply = () => {
2427
+ for (const name in attrs) doc.set_attr(id, name, attrs[name]);
2428
+ if (doc.parent_of(id) === null) doc.insert(id, parent, null);
2429
+ doc.set_text(id, committed_text);
2430
+ set_selection([id]);
2431
+ };
2432
+ const revert = () => {
2433
+ doc.remove(id);
2434
+ set_selection(previous_selection);
2435
+ };
2436
+ const preview = history.preview("insert text");
2437
+ const live = () => preview.state === "active";
2438
+ preview.set({
2439
+ providerId: PROVIDER_ID,
2440
+ apply,
2441
+ revert
2442
+ });
2443
+ return {
2444
+ id,
2445
+ commit() {
2446
+ if (!live()) return;
2447
+ committed_text = doc.text_of(id);
2448
+ preview.commit();
2449
+ },
2450
+ discard() {
2451
+ if (!live()) return;
2452
+ preview.discard();
2453
+ }
2454
+ };
2455
+ }
2456
+ /** Per-tag default paint attrs. Wrapped so callers don't need to depend
2457
+ * on the InsertableTag type — `insert()` accepts arbitrary string tags
2458
+ * (so `commands.insert("path", ...)` works for paste / RPC) but only
2459
+ * the closed insertable set gets default paint. */
2460
+ function default_paint_attrs_for(tag) {
2461
+ if (tag === "rect" || tag === "ellipse" || tag === "line") return insertions.default_paint_attrs(tag);
2462
+ return {};
2463
+ }
2464
+ function set_text(value) {
2465
+ if (selection.length !== 1) return;
2466
+ const target = selection[0];
2467
+ if (!doc.is_text_edit_target(target)) return;
2468
+ const original = doc.text_of(target);
2469
+ if (original === value) return;
2470
+ const apply = () => {
2471
+ doc.set_text(target, value);
2472
+ emit();
2473
+ };
2474
+ const revert = () => {
2475
+ doc.set_text(target, original);
2476
+ emit();
2477
+ };
2478
+ apply();
2479
+ history.atomic("edit text", (tx) => {
2480
+ tx.push({
2481
+ providerId: PROVIDER_ID,
2482
+ apply,
2483
+ revert
2484
+ });
2485
+ });
2486
+ }
2487
+ let content_edit_driver = null;
2488
+ let vector_subselect_driver = null;
2489
+ let vector_delete_driver = null;
2490
+ let computed_resolver = null;
2491
+ function dom_computed_property(id, name) {
2492
+ return computed_resolver?.computed_property(id, name) ?? null;
2493
+ }
2494
+ function dom_computed_paint(id, channel) {
2495
+ return computed_resolver?.computed_paint(id, channel) ?? null;
2496
+ }
2497
+ let current_surface_hover = null;
2498
+ let surface_hover_override = null;
2499
+ const surface_hover_listeners = /* @__PURE__ */ new Set();
2500
+ let surface_hover_override_driver = null;
2501
+ function notify_surface_hover() {
2502
+ for (const cb of surface_hover_listeners) cb();
2503
+ }
2504
+ function _set_current_surface_hover(id) {
2505
+ if (current_surface_hover === id) return;
2506
+ current_surface_hover = id;
2507
+ notify_surface_hover();
2508
+ }
2509
+ const pick_listeners = /* @__PURE__ */ new Set();
2510
+ function notify_pick(e) {
2511
+ for (const cb of pick_listeners) cb(e);
2512
+ }
2513
+ let current_vector_subselection = null;
2514
+ const vector_subselection_listeners = /* @__PURE__ */ new Set();
2515
+ function notify_vector_subselection() {
2516
+ for (const cb of vector_subselection_listeners) cb(current_vector_subselection);
2517
+ }
2518
+ function _set_current_vector_subselection(sel) {
2519
+ current_vector_subselection = sel;
2520
+ notify_vector_subselection();
2521
+ }
2522
+ function enter_content_edit(target, opts) {
2523
+ const id = target ?? (selection.length === 1 ? selection[0] : null);
2524
+ if (!id) return false;
2525
+ if (!doc.is_text_edit_target(id) && doc.is_vector_edit_target(id) === null) return false;
2526
+ if (!content_edit_driver) return false;
2527
+ return content_edit_driver(id, opts);
2528
+ }
2529
+ function set_vector_selection(input, mode) {
2530
+ if (!vector_subselect_driver) return false;
2531
+ return vector_subselect_driver(input, mode);
2532
+ }
2533
+ function delete_vector_selection() {
2534
+ if (!vector_delete_driver) return false;
2535
+ return vector_delete_driver();
2536
+ }
2537
+ function load_svg(svg) {
2538
+ discard_open_property_previews();
2539
+ history.clear();
2540
+ doc.load(svg);
2541
+ selection = [];
2542
+ scope = null;
2543
+ mode = "select";
2544
+ tool = TOOL_CURSOR;
2545
+ active_duplication = null;
2546
+ baseline_revision = doc.revision;
2547
+ load_version++;
2548
+ emit();
2549
+ }
2550
+ function serialize_svg() {
2551
+ return doc.serialize();
2552
+ }
2553
+ function undo() {
2554
+ history.undo();
2555
+ }
2556
+ function redo() {
2557
+ history.redo();
2558
+ }
2559
+ const registry = new CommandRegistry();
2560
+ const keymap = new Keymap(registry);
2561
+ const commands = {
2562
+ select,
2563
+ deselect,
2564
+ select_all,
2565
+ select_sibling,
2566
+ enter_scope,
2567
+ exit_scope,
2568
+ set_mode,
2569
+ set_property,
2570
+ preview_property,
2571
+ set_paint,
2572
+ preview_paint,
2573
+ set_paint_from_gradient,
2574
+ set_opacity,
2575
+ translate,
2576
+ nudge,
2577
+ resize_to,
2578
+ resize_by,
2579
+ rotate,
2580
+ rotate_to,
2581
+ transform: apply_transform,
2582
+ flatten_transform,
2583
+ align,
2584
+ reorder,
2585
+ remove,
2586
+ copy,
2587
+ cut,
2588
+ paste,
2589
+ duplicate,
2590
+ group: group$1,
2591
+ ungroup,
2592
+ insert,
2593
+ insert_fragment,
2594
+ insert_preview,
2595
+ set_text,
2596
+ set_vector_selection,
2597
+ delete_vector_selection,
2598
+ load_svg,
2599
+ serialize_svg,
2600
+ undo,
2601
+ redo,
2602
+ register: (id, handler) => registry.register(id, handler),
2603
+ invoke: (id, args) => registry.invoke(id, args),
2604
+ has: (id) => registry.has(id)
2605
+ };
2606
+ function load(svg) {
2607
+ load_svg(svg);
2608
+ }
2609
+ function serialize() {
2610
+ return doc.serialize();
2611
+ }
2612
+ function reset() {
2613
+ discard_open_property_previews();
2614
+ history.clear();
2615
+ doc.reset_to_original();
2616
+ selection = [];
2617
+ scope = null;
2618
+ mode = "select";
2619
+ tool = TOOL_CURSOR;
2620
+ active_duplication = null;
2621
+ baseline_revision = doc.revision;
2622
+ emit();
2623
+ }
2624
+ function attach(surface) {
2625
+ if (attached_surface) attached_surface.dispose();
2626
+ attached_surface = surface;
2627
+ return { detach() {
2628
+ if (attached_surface === surface) {
2629
+ attached_surface.dispose();
2630
+ attached_surface = null;
2631
+ }
2632
+ } };
2633
+ }
2634
+ function detach() {
2635
+ if (attached_surface) {
2636
+ attached_surface.dispose();
2637
+ attached_surface = null;
2638
+ }
2639
+ }
2640
+ function dispose() {
2641
+ detach();
2642
+ listeners.clear();
2643
+ surface_hover_listeners.clear();
2644
+ geometry_listeners.clear();
2645
+ translate_commit_listeners.clear();
2646
+ pick_listeners.clear();
2647
+ vector_subselection_listeners.clear();
2648
+ }
2649
+ function set_style(partial) {
2650
+ style = {
2651
+ ...style,
2652
+ ...partial
2653
+ };
2654
+ emit();
2655
+ }
2656
+ const public_editor = {
2657
+ /**
2658
+ * Low-level IR handle. Mutating directly bypasses history; prefer
2659
+ * `editor.commands` for app code.
2660
+ */
2661
+ document: doc,
2662
+ get state() {
2663
+ return snapshot();
2664
+ },
2665
+ subscribe,
2666
+ subscribe_with_selector,
2667
+ node_properties,
2668
+ node_paint,
2669
+ dom_computed_property,
2670
+ dom_computed_paint,
2671
+ /**
2672
+ * Enter content-edit mode on a `<text>` node. Returns `false` (no-op)
2673
+ * when no DOM surface is attached.
2674
+ */
2675
+ enter_content_edit,
2676
+ defs,
2677
+ commands,
2678
+ /**
2679
+ * Human-readable label for hierarchy panels. SVG has no native "name";
2680
+ * this is the package's single source of truth so panels don't reinvent
2681
+ * the rule.
2682
+ *
2683
+ * Rule:
2684
+ * - `<text>` → text content, whitespace-collapsed and truncated at
2685
+ * ~40 chars (falls back to `"text"` for empty content).
2686
+ * - Otherwise → tag name, suffixed with `#id` when the `id` attribute
2687
+ * is present (e.g. `"rect #sun"`).
2688
+ *
2689
+ * `opts.tagLabel` lets callers substitute a friendlier or localized
2690
+ * term for the raw tag (e.g. `"rect"` → `"Rectangle"`). Only invoked
2691
+ * on the non-text branch.
2692
+ */
2693
+ display_label(id, opts) {
2694
+ const tag = doc.tag_of(id);
2695
+ if (tag === "text") {
2696
+ const collapsed = doc.text_of(id).replace(/\s+/g, " ").trim();
2697
+ if (collapsed.length === 0) return "text";
2698
+ return collapsed.length > DISPLAY_LABEL_MAX_LEN ? `${collapsed.slice(0, DISPLAY_LABEL_MAX_LEN)}…` : collapsed;
2699
+ }
2700
+ const elem_id = doc.get_attr(id, "id");
2701
+ const head = opts?.tagLabel ? opts.tagLabel(tag) : tag;
2702
+ return elem_id && elem_id.length > 0 ? `${head} #${elem_id}` : head;
2703
+ },
2704
+ tree() {
2705
+ return tree_snapshot();
2706
+ },
2707
+ /**
2708
+ * The effective hover from the attached HUD surface — what's under the
2709
+ * pointer, OR whatever `set_surface_hover_override` last pushed. Used
2710
+ * by out-of-canvas UI (layers panel, breadcrumbs) to mirror the canvas
2711
+ * highlight. Returns `null` when nothing is hovered.
2712
+ */
2713
+ surface_hover() {
2714
+ return current_surface_hover;
2715
+ },
2716
+ /**
2717
+ * Push a hover override into the HUD surface — e.g. when the user
2718
+ * hovers a row in a layers panel. The HUD will render the override's
2719
+ * outline and (when applicable) drive measurement to that node.
2720
+ * Pass `null` to clear and let the pointer pick take over again.
2721
+ */
2722
+ set_surface_hover_override(id) {
2723
+ if (surface_hover_override === id) return;
2724
+ surface_hover_override = id;
2725
+ if (surface_hover_override_driver) surface_hover_override_driver(id);
2726
+ },
2727
+ /**
2728
+ * Subscribe to changes in the effective surface hover. Fires when the
2729
+ * HUD reports a new pointer pick AND when an override is set/cleared.
2730
+ * Cheap channel — does NOT bump `state.version`.
2731
+ */
2732
+ subscribe_surface_hover(cb) {
2733
+ surface_hover_listeners.add(cb);
2734
+ return () => {
2735
+ surface_hover_listeners.delete(cb);
2736
+ };
2737
+ },
2738
+ /**
2739
+ * Subscribe to pick (tap) outcomes — a discrete click on the canvas,
2740
+ * reporting the document-space point and the node under it (`null` for
2741
+ * empty canvas), plus the button and modifier snapshot. Fires once per
2742
+ * tap, after the editor's own selection handling. Observe-only: a pick
2743
+ * cannot alter selection, and the channel does NOT bump `state.version`.
2744
+ * See {@link PickEvent}.
2745
+ *
2746
+ * @unstable
2747
+ */
2748
+ subscribe_pick(cb) {
2749
+ pick_listeners.add(cb);
2750
+ return () => {
2751
+ pick_listeners.delete(cb);
2752
+ };
2753
+ },
2754
+ /**
2755
+ * The current vector sub-selection (vertices / segments / tangents) inside
2756
+ * an open vector content-edit session, or `null` when no such session is
2757
+ * active (gridaco/grida#790). The read counterpart to
2758
+ * `commands.set_vector_selection`. See {@link VectorSubSelection}.
2759
+ */
2760
+ vector_subselection() {
2761
+ return current_vector_subselection;
2762
+ },
2763
+ /**
2764
+ * Subscribe to vector sub-selection changes — fires whenever the live
2765
+ * vertex / segment / tangent selection changes (click, marquee, lasso,
2766
+ * programmatic `set_vector_selection`, undo/redo) and on session
2767
+ * enter/exit (`null` on exit). The callback receives the new value, also
2768
+ * readable via {@link vector_subselection}. Cheap channel — does NOT bump
2769
+ * `state.version`.
2770
+ */
2771
+ subscribe_vector_subselection(cb) {
2772
+ vector_subselection_listeners.add(cb);
2773
+ return () => {
2774
+ vector_subselection_listeners.delete(cb);
2775
+ };
2776
+ },
2777
+ /**
2778
+ * Subscribe to bounds-affecting changes. Fires when any document
2779
+ * mutation advances `state.geometry_version` — drag, resize, text
2780
+ * edit, structural insert/remove. Skips presentation-only writes
2781
+ * (fill, opacity, stroke-color).
2782
+ */
2783
+ subscribe_geometry(cb) {
2784
+ geometry_listeners.add(cb);
2785
+ return () => {
2786
+ geometry_listeners.delete(cb);
2787
+ };
2788
+ },
2789
+ /**
2790
+ * World-space geometry queries. Non-null when a DOM surface is
2791
+ * attached; null otherwise (queries need a renderer to read bbox
2792
+ * from). Read-only — never mutates document state.
2793
+ */
2794
+ get geometry() {
2795
+ return geometry_provider;
2796
+ },
2797
+ modes,
2798
+ /** Switch the active tool. No history entry; bumps `state.version`. */
2799
+ set_tool,
2800
+ get style() {
2801
+ return style;
2802
+ },
2803
+ set_style,
2804
+ load,
2805
+ serialize,
2806
+ /**
2807
+ * Serialize a single element's subtree as an SVG **fragment**, using the
2808
+ * same trivia-preserving rules as {@link serialize} — for handing "the
2809
+ * markup of the element the user selected" to a downstream consumer
2810
+ * (e.g. an AI agent) without re-serializing the whole document.
2811
+ *
2812
+ * Fragment, not document (see `SvgDocument.serialize_node`): it does NOT
2813
+ * carry `serialize()`'s whole-document round-trip guarantee. Namespace
2814
+ * declarations on an ancestor (`xmlns:xlink`, normally on the root
2815
+ * `<svg>`) are NOT inlined — a node using `xlink:href` serializes without
2816
+ * `xmlns:xlink`. Throws on an unknown id or a non-element node.
2817
+ */
2818
+ serialize_node(id) {
2819
+ return doc.serialize_node(id);
2820
+ },
2821
+ reset,
2822
+ attach,
2823
+ detach,
2824
+ dispose,
2825
+ providers,
2826
+ _internal: {
2827
+ doc,
2828
+ history: {
2829
+ preview: (label) => history.preview(label),
2830
+ undo_label: () => history.stack.undoLabel
2831
+ },
2832
+ clipboard: {
2833
+ copy: () => copy_impl(false),
2834
+ cut: () => cut_impl(false)
2835
+ },
2836
+ insert_text_preview,
2837
+ emit,
2838
+ subscribe_translate_commit(cb) {
2839
+ translate_commit_listeners.add(cb);
2840
+ return () => {
2841
+ translate_commit_listeners.delete(cb);
2842
+ };
2843
+ },
2844
+ notify_translate_commit,
2845
+ seed_duplication(record) {
2846
+ active_duplication = record;
2847
+ },
2848
+ set_content_edit_driver(fn) {
2849
+ content_edit_driver = fn;
2850
+ },
2851
+ set_vector_subselect_driver(fn) {
2852
+ vector_subselect_driver = fn;
2853
+ },
2854
+ set_vector_delete_driver(fn) {
2855
+ vector_delete_driver = fn;
2856
+ },
2857
+ push_vector_subselection(sel) {
2858
+ _set_current_vector_subselection(sel);
2859
+ },
2860
+ set_surface_hover_override_driver(fn) {
2861
+ surface_hover_override_driver = fn;
2862
+ if (fn) fn(surface_hover_override);
2863
+ },
2864
+ push_surface_hover(id) {
2865
+ _set_current_surface_hover(id);
2866
+ },
2867
+ push_pick(e) {
2868
+ notify_pick(e);
2869
+ },
2870
+ set_computed_resolver(fn) {
2871
+ computed_resolver = fn;
2872
+ },
2873
+ set_geometry(p) {
2874
+ geometry_provider = p;
2875
+ },
2876
+ register_command(id, handler) {
2877
+ return registry.register(id, handler);
2878
+ },
2879
+ bump_geometry() {
2880
+ doc.bump_geometry();
2881
+ fire_geometry_listeners_if_advanced();
2882
+ }
2883
+ },
2884
+ keymap
2885
+ };
2886
+ registerDefaultCommands(registry, public_editor);
2887
+ applyDefaultBindings(keymap);
2888
+ return public_editor;
2889
+ }
2890
+ /**
2891
+ * Construct a headless SVG editor. The returned object is the public
2892
+ * editor surface — observation (`state`, `subscribe`), commands
2893
+ * (`commands.*`), lifecycle (`attach` / `dispose`), and the typed-read
2894
+ * caches (`node_paint`, `node_properties`). Surfaces (DOM, headless)
2895
+ * attach later via `editor.attach(surface)`.
2896
+ */
2897
+ function createSvgEditor(opts) {
2898
+ if (opts == null || typeof opts.svg !== "string") {
2899
+ const got = opts == null ? String(opts) : opts.svg === null ? "null" : typeof opts.svg;
2900
+ throw new TypeError(`createSvgEditor({ svg }) requires { svg: string }, got svg=${got}`);
2901
+ }
2902
+ return _create_svg_editor_internal(opts);
2903
+ }
2904
+ const FLATTEN_IDENT = [
2905
+ 1,
2906
+ 0,
2907
+ 0,
2908
+ 1,
2909
+ 0,
2910
+ 0
2911
+ ];
2912
+ function flatten_mul(m1, m2) {
2913
+ const [a1, b1, c1, d1, e1, f1] = m1;
2914
+ const [a2, b2, c2, d2, e2, f2] = m2;
2915
+ return [
2916
+ a1 * a2 + c1 * b2,
2917
+ b1 * a2 + d1 * b2,
2918
+ a1 * c2 + c1 * d2,
2919
+ b1 * c2 + d1 * d2,
2920
+ a1 * e2 + c1 * f2 + e1,
2921
+ b1 * e2 + d1 * f2 + f1
2922
+ ];
2923
+ }
2924
+ function flatten_op_to_mat(op) {
2925
+ switch (op.type) {
2926
+ case "matrix": return [
2927
+ op.a,
2928
+ op.b,
2929
+ op.c,
2930
+ op.d,
2931
+ op.e,
2932
+ op.f
2933
+ ];
2934
+ case "translate": return [
2935
+ 1,
2936
+ 0,
2937
+ 0,
2938
+ 1,
2939
+ op.tx,
2940
+ op.ty
2941
+ ];
2942
+ case "rotate": {
2943
+ const rad = op.angle * Math.PI / 180;
2944
+ const c = Math.cos(rad);
2945
+ const s = Math.sin(rad);
2946
+ if (op.cx === 0 && op.cy === 0) return [
2947
+ c,
2948
+ s,
2949
+ -s,
2950
+ c,
2951
+ 0,
2952
+ 0
2953
+ ];
2954
+ const e = op.cx - c * op.cx + s * op.cy;
2955
+ const f = op.cy - s * op.cx - c * op.cy;
2956
+ return [
2957
+ c,
2958
+ s,
2959
+ -s,
2960
+ c,
2961
+ e,
2962
+ f
2963
+ ];
2964
+ }
2965
+ case "scale": return [
2966
+ op.sx,
2967
+ 0,
2968
+ 0,
2969
+ op.sy,
2970
+ 0,
2971
+ 0
2972
+ ];
2973
+ case "skewX": {
2974
+ const rad = op.angle * Math.PI / 180;
2975
+ return [
2976
+ 1,
2977
+ 0,
2978
+ Math.tan(rad),
2979
+ 1,
2980
+ 0,
2981
+ 0
2982
+ ];
2983
+ }
2984
+ case "skewY": {
2985
+ const rad = op.angle * Math.PI / 180;
2986
+ return [
2987
+ 1,
2988
+ Math.tan(rad),
2989
+ 0,
2990
+ 1,
2991
+ 0,
2992
+ 0
2993
+ ];
2994
+ }
2995
+ }
2996
+ }
2997
+ //#endregion
2998
+ export { createSvgEditor as t };