@grida/svg-editor 1.0.0-alpha.2 → 1.0.0-alpha.21

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