@grida/svg-editor 1.0.0-alpha.1

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,1833 @@
1
+ require("./dom-CfP_ZURh.js");
2
+ const require_paint = require("./paint-DHq_3iwU.js");
3
+ let _grida_history = require("@grida/history");
4
+ let _grida_keybinding = require("@grida/keybinding");
5
+ //#region src/commands/registry.ts
6
+ var CommandRegistry = class {
7
+ constructor() {
8
+ this.map = /* @__PURE__ */ new Map();
9
+ }
10
+ /**
11
+ * Register a command. Returns an unregister function. Re-registering
12
+ * the same id replaces the previous handler (last writer wins).
13
+ */
14
+ register(id, handler) {
15
+ this.map.set(id, handler);
16
+ return () => {
17
+ if (this.map.get(id) === handler) this.map.delete(id);
18
+ };
19
+ }
20
+ /**
21
+ * Invoke a command by id. Returns `true` if the handler consumed,
22
+ * `false` otherwise (including unknown ids and handlers that returned
23
+ * `false`/`undefined`).
24
+ */
25
+ invoke(id, args) {
26
+ const handler = this.map.get(id);
27
+ if (!handler) return false;
28
+ return handler(args) === true;
29
+ }
30
+ has(id) {
31
+ return this.map.has(id);
32
+ }
33
+ /** All registered ids, for debugging / introspection. */
34
+ ids() {
35
+ return Array.from(this.map.keys());
36
+ }
37
+ };
38
+ //#endregion
39
+ //#region src/commands/defaults.ts
40
+ function registerDefaultCommands(reg, editor) {
41
+ reg.register("history.undo", () => {
42
+ if (!editor.state.can_undo) return false;
43
+ editor.commands.undo();
44
+ return true;
45
+ });
46
+ reg.register("history.redo", () => {
47
+ if (!editor.state.can_redo) return false;
48
+ editor.commands.redo();
49
+ return true;
50
+ });
51
+ reg.register("selection.deselect", () => {
52
+ if (editor.state.selection.length === 0) return false;
53
+ editor.commands.deselect();
54
+ return true;
55
+ });
56
+ reg.register("selection.remove", () => {
57
+ if (editor.state.selection.length === 0) return false;
58
+ editor.commands.remove();
59
+ return true;
60
+ });
61
+ reg.register("hierarchy.enter", () => {
62
+ if (editor.state.selection.length !== 1) return false;
63
+ const id = editor.state.selection[0];
64
+ const node = editor.tree().nodes.get(id);
65
+ if (!node || node.children.length === 0) return false;
66
+ editor.commands.select(node.children[0]);
67
+ return true;
68
+ });
69
+ reg.register("hierarchy.exit", () => {
70
+ if (editor.state.selection.length !== 1) return false;
71
+ const id = editor.state.selection[0];
72
+ const tree = editor.tree();
73
+ const node = tree.nodes.get(id);
74
+ if (!node || node.parent === null || node.parent === tree.root) return false;
75
+ editor.commands.select(node.parent);
76
+ return true;
77
+ });
78
+ reg.register("transform.nudge", (args) => {
79
+ if (editor.state.selection.length === 0) return false;
80
+ const { dx, dy } = args;
81
+ editor.commands.translate({
82
+ dx,
83
+ dy
84
+ });
85
+ return true;
86
+ });
87
+ reg.register("reorder", (args) => {
88
+ if (editor.state.selection.length !== 1) return false;
89
+ editor.commands.reorder(args);
90
+ return true;
91
+ });
92
+ }
93
+ //#endregion
94
+ //#region src/keymap/keymap.ts
95
+ /**
96
+ * Keymap — bindings of declarative `Keybinding`s (from `@grida/keybinding`)
97
+ * to command ids.
98
+ *
99
+ * Dispatch is ProseMirror-`chainCommands`-shaped: multiple bindings on
100
+ * the same key are tried in priority order; the first whose handler
101
+ * returns `true` wins, the rest are skipped. This keeps "one key, many
102
+ * meanings" expressible without a `when:` DSL — handlers self-guard on
103
+ * editor state and return `false` when not applicable.
104
+ *
105
+ * The keymap does NOT see modifier-as-signal (e.g. Alt-held for
106
+ * measurement). That stays on the HUD modifiers channel. The keymap
107
+ * only sees Mod+D-shape chords.
108
+ */
109
+ /** Modifiers that, when held, allow a binding to fire even inside a text input. */
110
+ const TEXT_INPUT_SAFE_MODS = new Set([
111
+ _grida_keybinding.KeyCode.Meta,
112
+ _grida_keybinding.KeyCode.Ctrl,
113
+ _grida_keybinding.KeyCode.Alt
114
+ ]);
115
+ function is_text_input_focused() {
116
+ if (typeof document === "undefined") return false;
117
+ const el = document.activeElement;
118
+ if (!el) return false;
119
+ const tag = el.tagName;
120
+ if (tag === "INPUT" || tag === "TEXTAREA") return true;
121
+ if (el.isContentEditable) return true;
122
+ return false;
123
+ }
124
+ var Keymap = class {
125
+ constructor(commands, platformGetter = _grida_keybinding.getKeyboardOS) {
126
+ this.commands = commands;
127
+ this.platformGetter = platformGetter;
128
+ this.buckets = /* @__PURE__ */ new Map();
129
+ this.seq = 0;
130
+ }
131
+ /**
132
+ * Bind a key combination to a command. Returns an unbind function.
133
+ * The same `Keybinding` can be bound to multiple commands — they will
134
+ * all be tried in chain order on dispatch.
135
+ */
136
+ bind(binding) {
137
+ const entry = {
138
+ binding,
139
+ seq: ++this.seq
140
+ };
141
+ for (const hash of this.chunkKeysFor(binding.keybinding)) {
142
+ const list = this.buckets.get(hash);
143
+ if (list) {
144
+ list.push(entry);
145
+ list.sort(compareEntries);
146
+ } else this.buckets.set(hash, [entry]);
147
+ }
148
+ return () => {
149
+ for (const hash of this.chunkKeysFor(binding.keybinding)) {
150
+ const list = this.buckets.get(hash);
151
+ if (!list) continue;
152
+ const idx = list.findIndex((e) => e === entry);
153
+ if (idx >= 0) list.splice(idx, 1);
154
+ if (list.length === 0) this.buckets.delete(hash);
155
+ }
156
+ };
157
+ }
158
+ /**
159
+ * Remove bindings matching the spec. If both filters are passed, only
160
+ * bindings that match BOTH are removed.
161
+ */
162
+ unbind(spec) {
163
+ const hashFilter = spec.keybinding ? new Set(this.chunkKeysFor(spec.keybinding)) : null;
164
+ for (const [hash, list] of this.buckets) {
165
+ if (hashFilter && !hashFilter.has(hash)) continue;
166
+ const next = list.filter((e) => {
167
+ if (spec.command && e.binding.command !== spec.command) return true;
168
+ return false;
169
+ });
170
+ if (next.length === 0) this.buckets.delete(hash);
171
+ else if (next.length !== list.length) this.buckets.set(hash, next);
172
+ }
173
+ }
174
+ /** All registered bindings, for introspection. Order is not guaranteed. */
175
+ bindings() {
176
+ const seen = /* @__PURE__ */ new Set();
177
+ for (const list of this.buckets.values()) for (const e of list) seen.add(e.binding);
178
+ return Array.from(seen);
179
+ }
180
+ /**
181
+ * Match the event against bound chunks, then run candidates in chain
182
+ * order. Returns `true` and calls `preventDefault()` on the first
183
+ * handler that consumes; returns `false` if nothing matched or all
184
+ * matches fell through.
185
+ */
186
+ dispatch(event) {
187
+ const chunk = (0, _grida_keybinding.eventToChunk)(event);
188
+ if (chunk.keys.length === 0) return false;
189
+ const hash = (0, _grida_keybinding.chunkKey)(chunk);
190
+ const list = this.buckets.get(hash);
191
+ if (!list || list.length === 0) return false;
192
+ const text_focused = is_text_input_focused();
193
+ for (const { binding } of list) {
194
+ if (text_focused && !this.has_safe_mod(chunk.mods)) continue;
195
+ if (this.commands.invoke(binding.command, binding.args)) {
196
+ event.preventDefault();
197
+ return true;
198
+ }
199
+ }
200
+ return false;
201
+ }
202
+ /**
203
+ * Compute the set of canonical hashes a `Keybinding` lights up. A
204
+ * binding with aliases (multiple sequences) contributes one hash per
205
+ * single-chunk alias; multi-chunk sequences (chords) are skipped in
206
+ * V1.
207
+ */
208
+ chunkKeysFor(binding) {
209
+ const sequences = (0, _grida_keybinding.keybindingsToKeyCodes)(binding, this.platformGetter());
210
+ const out = [];
211
+ for (const seq of sequences) {
212
+ if (seq.length !== 1) continue;
213
+ out.push((0, _grida_keybinding.chunkKey)(seq[0]));
214
+ }
215
+ return out;
216
+ }
217
+ has_safe_mod(mods) {
218
+ for (const m of mods) if (TEXT_INPUT_SAFE_MODS.has(m)) return true;
219
+ return false;
220
+ }
221
+ };
222
+ function compareEntries(a, b) {
223
+ const pa = a.binding.priority ?? 0;
224
+ const pb = b.binding.priority ?? 0;
225
+ if (pa !== pb) return pb - pa;
226
+ return a.seq - b.seq;
227
+ }
228
+ //#endregion
229
+ //#region src/keymap/defaults.ts
230
+ /**
231
+ * Default keybindings shipped with `@grida/svg-editor`.
232
+ *
233
+ * THIS IS THE ONLY FILE where built-in shortcuts are declared. Adding
234
+ * a new shortcut = one new row here (plus, if the target command is
235
+ * new, one new handler in `src/commands/defaults.ts`). That is the
236
+ * V1 design contract.
237
+ *
238
+ * Same key, multiple meanings? Add multiple rows. The chain semantics
239
+ * (handler returns `false` when not applicable) handle the rest.
240
+ */
241
+ const DEFAULT_BINDINGS = [
242
+ {
243
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.KeyZ, _grida_keybinding.M.CtrlCmd),
244
+ command: "history.undo"
245
+ },
246
+ {
247
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.KeyZ, _grida_keybinding.M.CtrlCmd | _grida_keybinding.M.Shift),
248
+ command: "history.redo"
249
+ },
250
+ {
251
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.KeyY, _grida_keybinding.M.CtrlCmd),
252
+ command: "history.redo"
253
+ },
254
+ {
255
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.Escape),
256
+ command: "selection.deselect"
257
+ },
258
+ {
259
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.Backspace),
260
+ command: "selection.remove"
261
+ },
262
+ {
263
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.Delete),
264
+ command: "selection.remove"
265
+ },
266
+ {
267
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.Enter),
268
+ command: "hierarchy.enter"
269
+ },
270
+ {
271
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.Enter, _grida_keybinding.M.Shift),
272
+ command: "hierarchy.exit"
273
+ },
274
+ {
275
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.LeftArrow),
276
+ command: "transform.nudge",
277
+ args: {
278
+ dx: -1,
279
+ dy: 0
280
+ }
281
+ },
282
+ {
283
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.RightArrow),
284
+ command: "transform.nudge",
285
+ args: {
286
+ dx: 1,
287
+ dy: 0
288
+ }
289
+ },
290
+ {
291
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.UpArrow),
292
+ command: "transform.nudge",
293
+ args: {
294
+ dx: 0,
295
+ dy: -1
296
+ }
297
+ },
298
+ {
299
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.DownArrow),
300
+ command: "transform.nudge",
301
+ args: {
302
+ dx: 0,
303
+ dy: 1
304
+ }
305
+ },
306
+ {
307
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.LeftArrow, _grida_keybinding.M.Shift),
308
+ command: "transform.nudge",
309
+ args: {
310
+ dx: -10,
311
+ dy: 0
312
+ }
313
+ },
314
+ {
315
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.RightArrow, _grida_keybinding.M.Shift),
316
+ command: "transform.nudge",
317
+ args: {
318
+ dx: 10,
319
+ dy: 0
320
+ }
321
+ },
322
+ {
323
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.UpArrow, _grida_keybinding.M.Shift),
324
+ command: "transform.nudge",
325
+ args: {
326
+ dx: 0,
327
+ dy: -10
328
+ }
329
+ },
330
+ {
331
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.DownArrow, _grida_keybinding.M.Shift),
332
+ command: "transform.nudge",
333
+ args: {
334
+ dx: 0,
335
+ dy: 10
336
+ }
337
+ },
338
+ {
339
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.BracketRight),
340
+ command: "reorder",
341
+ args: "bring_to_front"
342
+ },
343
+ {
344
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.BracketLeft),
345
+ command: "reorder",
346
+ args: "send_to_back"
347
+ },
348
+ {
349
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.BracketRight, _grida_keybinding.M.CtrlCmd),
350
+ command: "reorder",
351
+ args: "bring_forward"
352
+ },
353
+ {
354
+ keybinding: (0, _grida_keybinding.kb)(_grida_keybinding.KeyCode.BracketLeft, _grida_keybinding.M.CtrlCmd),
355
+ command: "reorder",
356
+ args: "send_backward"
357
+ }
358
+ ];
359
+ /** Register every default binding into a keymap. */
360
+ function applyDefaultBindings(keymap) {
361
+ for (const b of DEFAULT_BINDINGS) keymap.bind(b);
362
+ }
363
+ //#endregion
364
+ //#region src/core/defs.ts
365
+ var GradientsRegistry = class {
366
+ constructor(doc) {
367
+ this.doc = doc;
368
+ this.listeners = /* @__PURE__ */ new Set();
369
+ this.counter = 0;
370
+ doc.on_change(() => this.emit());
371
+ }
372
+ list() {
373
+ const out = [];
374
+ const defs = this.find_defs_elements();
375
+ for (const def_id of defs) for (const child of this.doc.element_children_of(def_id)) {
376
+ const tag = this.doc.tag_of(child);
377
+ if (tag === "linearGradient" || tag === "radialGradient") {
378
+ const id = this.doc.get_attr(child, "id");
379
+ if (!id) continue;
380
+ const definition = this.read_gradient(child, tag);
381
+ if (!definition) continue;
382
+ out.push({
383
+ id,
384
+ definition,
385
+ ref_count: this.count_refs(id)
386
+ });
387
+ }
388
+ }
389
+ return out;
390
+ }
391
+ get(id) {
392
+ return this.list().find((g) => g.id === id) ?? null;
393
+ }
394
+ upsert(definition, opts) {
395
+ const existing_id = opts?.id;
396
+ if (existing_id) {
397
+ const node = this.find_gradient_node(existing_id);
398
+ if (node !== null) {
399
+ this.write_gradient(node, definition);
400
+ return existing_id;
401
+ }
402
+ }
403
+ const id = existing_id ?? this.fresh_id();
404
+ const defs_id = this.ensure_defs();
405
+ const tag = definition.kind === "linear" ? "linearGradient" : "radialGradient";
406
+ const new_id = this.doc.create_element(tag, { ns: "http://www.w3.org/2000/svg" });
407
+ this.doc.set_attr(new_id, "id", id);
408
+ this.doc.insert(new_id, defs_id, null);
409
+ this.write_gradient(new_id, definition);
410
+ this.emit();
411
+ return id;
412
+ }
413
+ remove(id) {
414
+ const refs = this.count_refs(id);
415
+ if (refs > 0) throw new Error(`[svg-editor] cannot remove gradient "${id}": ${refs} node(s) still reference it`);
416
+ const node = this.find_gradient_node(id);
417
+ if (node !== null) {
418
+ this.doc.remove(node);
419
+ this.emit();
420
+ }
421
+ }
422
+ subscribe(fn) {
423
+ this.listeners.add(fn);
424
+ return () => {
425
+ this.listeners.delete(fn);
426
+ };
427
+ }
428
+ emit() {
429
+ const snap = this.list();
430
+ for (const fn of this.listeners) fn(snap);
431
+ }
432
+ fresh_id() {
433
+ let id;
434
+ do
435
+ id = `g${++this.counter}`;
436
+ while (this.find_gradient_node(id) !== null);
437
+ return id;
438
+ }
439
+ find_defs_elements() {
440
+ return this.doc.find_by_tag(this.doc.root, "defs");
441
+ }
442
+ ensure_defs() {
443
+ const existing = this.find_defs_elements();
444
+ if (existing.length > 0) return existing[0];
445
+ const defs = this.doc.create_element("defs", { ns: "http://www.w3.org/2000/svg" });
446
+ const first = this.doc.children_of(this.doc.root)[0] ?? null;
447
+ this.doc.insert(defs, this.doc.root, first);
448
+ return defs;
449
+ }
450
+ find_gradient_node(id) {
451
+ 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) {
452
+ const tag = this.doc.tag_of(child);
453
+ if (tag === "linearGradient" || tag === "radialGradient") return child;
454
+ }
455
+ return null;
456
+ }
457
+ read_gradient(id, tag) {
458
+ const stops = [];
459
+ for (const child of this.doc.element_children_of(id)) {
460
+ if (this.doc.tag_of(child) !== "stop") continue;
461
+ const offset = parseFloat(this.doc.get_attr(child, "offset") ?? "0");
462
+ const color = this.doc.get_attr(child, "stop-color") ?? this.doc.get_style(child, "stop-color") ?? "#000000";
463
+ const opacity_str = this.doc.get_attr(child, "stop-opacity") ?? this.doc.get_style(child, "stop-opacity");
464
+ const opacity = opacity_str !== null ? parseFloat(opacity_str) : void 0;
465
+ stops.push({
466
+ offset,
467
+ color,
468
+ ...opacity !== void 0 ? { opacity } : {}
469
+ });
470
+ }
471
+ const gu = this.doc.get_attr(id, "gradientUnits");
472
+ const gradient_units = gu === "userSpaceOnUse" ? "user_space_on_use" : gu === "objectBoundingBox" ? "object_bounding_box" : void 0;
473
+ const sm = this.doc.get_attr(id, "spreadMethod");
474
+ const spread_method = sm === "pad" || sm === "reflect" || sm === "repeat" ? sm : void 0;
475
+ const num = (n) => {
476
+ const v = this.doc.get_attr(id, n);
477
+ return v !== null ? parseFloat(v) : void 0;
478
+ };
479
+ if (tag === "linearGradient") return {
480
+ kind: "linear",
481
+ stops,
482
+ x1: num("x1"),
483
+ y1: num("y1"),
484
+ x2: num("x2"),
485
+ y2: num("y2"),
486
+ gradient_units,
487
+ spread_method
488
+ };
489
+ return {
490
+ kind: "radial",
491
+ stops,
492
+ cx: num("cx"),
493
+ cy: num("cy"),
494
+ r: num("r"),
495
+ fx: num("fx"),
496
+ fy: num("fy"),
497
+ gradient_units,
498
+ spread_method
499
+ };
500
+ }
501
+ write_gradient(node, def) {
502
+ for (const c of [...this.doc.children_of(node)]) this.doc.remove(c);
503
+ const set_num = (name, v) => {
504
+ this.doc.set_attr(node, name, v === void 0 ? null : String(v));
505
+ };
506
+ if (def.kind === "linear") {
507
+ set_num("x1", def.x1);
508
+ set_num("y1", def.y1);
509
+ set_num("x2", def.x2);
510
+ set_num("y2", def.y2);
511
+ } else {
512
+ set_num("cx", def.cx);
513
+ set_num("cy", def.cy);
514
+ set_num("r", def.r);
515
+ set_num("fx", def.fx);
516
+ set_num("fy", def.fy);
517
+ }
518
+ if (def.gradient_units) this.doc.set_attr(node, "gradientUnits", def.gradient_units === "user_space_on_use" ? "userSpaceOnUse" : "objectBoundingBox");
519
+ if (def.spread_method) this.doc.set_attr(node, "spreadMethod", def.spread_method);
520
+ for (const stop of def.stops) {
521
+ const stop_id = this.doc.create_element("stop", { ns: "http://www.w3.org/2000/svg" });
522
+ this.doc.set_attr(stop_id, "offset", String(stop.offset));
523
+ this.doc.set_attr(stop_id, "stop-color", stop.color);
524
+ if (stop.opacity !== void 0) this.doc.set_attr(stop_id, "stop-opacity", String(stop.opacity));
525
+ this.doc.insert(stop_id, node, null);
526
+ }
527
+ }
528
+ count_refs(id) {
529
+ let count = 0;
530
+ const pattern = new RegExp(`url\\(\\s*["']?#${escape_regex(id)}["']?\\s*\\)`);
531
+ for (const node of this.doc.all_elements()) {
532
+ const fill = this.doc.get_attr(node, "fill");
533
+ const stroke = this.doc.get_attr(node, "stroke");
534
+ const style_fill = this.doc.get_style(node, "fill");
535
+ const style_stroke = this.doc.get_style(node, "stroke");
536
+ for (const v of [
537
+ fill,
538
+ stroke,
539
+ style_fill,
540
+ style_stroke
541
+ ]) if (v && pattern.test(v)) count++;
542
+ }
543
+ return count;
544
+ }
545
+ };
546
+ function escape_regex(s) {
547
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
548
+ }
549
+ function create_defs(doc) {
550
+ return { gradients: new GradientsRegistry(doc) };
551
+ }
552
+ const XML_NS = "http://www.w3.org/XML/1998/namespace";
553
+ const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
554
+ let id_counter = 0;
555
+ function fresh_id() {
556
+ return `n${id_counter++}`;
557
+ }
558
+ function reset_id_counter() {
559
+ id_counter = 0;
560
+ }
561
+ function parse_svg(src) {
562
+ reset_id_counter();
563
+ const nodes = /* @__PURE__ */ new Map();
564
+ const prolog = [];
565
+ const epilog = [];
566
+ let i = 0;
567
+ const n = src.length;
568
+ let root = null;
569
+ const open_stack = [];
570
+ /** ns prefix → uri, per ancestor scope (top of stack). */
571
+ const ns_stack = [new Map([["xml", XML_NS], ["xmlns", XMLNS_NS]])];
572
+ /** default ns per ancestor scope (top of stack). */
573
+ const default_ns_stack = [null];
574
+ function push_to_parent(node) {
575
+ nodes.set(node.id, node);
576
+ if (open_stack.length === 0) {
577
+ if (node.kind === "element" && root === null) return;
578
+ if (root === null) prolog.push(node);
579
+ else epilog.push(node);
580
+ return;
581
+ }
582
+ const parent = open_stack[open_stack.length - 1];
583
+ node.parent = parent.id;
584
+ parent.children.push(node.id);
585
+ }
586
+ while (i < n) {
587
+ if (src[i] === "<") {
588
+ if (src.startsWith("<!--", i)) {
589
+ const end = src.indexOf("-->", i + 4);
590
+ if (end === -1) throw new Error("unterminated comment");
591
+ const value = src.slice(i + 4, end);
592
+ push_to_parent({
593
+ kind: "comment",
594
+ id: fresh_id(),
595
+ parent: null,
596
+ value
597
+ });
598
+ i = end + 3;
599
+ continue;
600
+ }
601
+ if (src.startsWith("<![CDATA[", i)) {
602
+ const end = src.indexOf("]]>", i + 9);
603
+ if (end === -1) throw new Error("unterminated CDATA");
604
+ const value = src.slice(i + 9, end);
605
+ push_to_parent({
606
+ kind: "cdata",
607
+ id: fresh_id(),
608
+ parent: null,
609
+ value
610
+ });
611
+ i = end + 3;
612
+ continue;
613
+ }
614
+ if (src.startsWith("<!DOCTYPE", i) || src.startsWith("<!doctype", i)) {
615
+ let depth = 1;
616
+ let j = i + 9;
617
+ while (j < n && depth > 0) {
618
+ const c = src[j];
619
+ if (c === "<") depth++;
620
+ else if (c === ">") depth--;
621
+ if (depth === 0) break;
622
+ j++;
623
+ }
624
+ if (j >= n) throw new Error("unterminated doctype");
625
+ push_to_parent({
626
+ kind: "doctype",
627
+ id: fresh_id(),
628
+ parent: null,
629
+ value: src.slice(i + 9, j)
630
+ });
631
+ i = j + 1;
632
+ continue;
633
+ }
634
+ if (src.startsWith("<?", i)) {
635
+ const end = src.indexOf("?>", i + 2);
636
+ if (end === -1) throw new Error("unterminated PI");
637
+ const body = src.slice(i + 2, end);
638
+ const space = body.search(/\s/);
639
+ const target = space === -1 ? body : body.slice(0, space);
640
+ const value = space === -1 ? "" : body.slice(space + 1);
641
+ push_to_parent({
642
+ kind: "pi",
643
+ id: fresh_id(),
644
+ parent: null,
645
+ target,
646
+ value
647
+ });
648
+ i = end + 2;
649
+ continue;
650
+ }
651
+ if (src[i + 1] === "/") {
652
+ const end = src.indexOf(">", i + 2);
653
+ if (end === -1) throw new Error("unterminated end tag");
654
+ const open = open_stack.pop();
655
+ if (!open) throw new Error("unexpected end tag at " + i);
656
+ ns_stack.pop();
657
+ default_ns_stack.pop();
658
+ const m = src.slice(i + 2, end).match(/^(\s*)([^\s]+)(\s*)$/);
659
+ if (m) {
660
+ open.close_tag_leading = m[1];
661
+ open.close_tag_trailing = m[3];
662
+ }
663
+ i = end + 1;
664
+ continue;
665
+ }
666
+ const start = i + 1;
667
+ let j = start;
668
+ while (j < n && !/[\s/>]/.test(src[j])) j++;
669
+ const raw_tag = src.slice(start, j);
670
+ const [prefix, local] = split_qname(raw_tag);
671
+ const { attrs, end_index, self_closing, trailing } = parse_attrs(src, j);
672
+ const new_ns_map = new Map(ns_stack[ns_stack.length - 1]);
673
+ let new_default_ns = default_ns_stack[default_ns_stack.length - 1];
674
+ for (const a of attrs) if (a.prefix === "xmlns") new_ns_map.set(a.local, a.value);
675
+ else if (a.prefix === null && a.local === "xmlns") new_default_ns = a.value;
676
+ for (const a of attrs) if (a.prefix === "xmlns" || a.prefix === null && a.local === "xmlns") a.ns = XMLNS_NS;
677
+ else if (a.prefix) a.ns = new_ns_map.get(a.prefix) ?? null;
678
+ else a.ns = null;
679
+ const element_ns = prefix ? new_ns_map.get(prefix) ?? null : new_default_ns;
680
+ const elem = {
681
+ kind: "element",
682
+ id: fresh_id(),
683
+ parent: null,
684
+ raw_tag,
685
+ prefix,
686
+ local,
687
+ ns: element_ns,
688
+ attrs,
689
+ children: [],
690
+ self_closing,
691
+ open_tag_trailing: trailing,
692
+ close_tag_leading: "",
693
+ close_tag_trailing: ""
694
+ };
695
+ push_to_parent(elem);
696
+ if (root === null) root = elem.id;
697
+ if (!self_closing) {
698
+ open_stack.push(elem);
699
+ ns_stack.push(new_ns_map);
700
+ default_ns_stack.push(new_default_ns);
701
+ }
702
+ i = end_index;
703
+ continue;
704
+ }
705
+ const next = src.indexOf("<", i);
706
+ const end = next === -1 ? n : next;
707
+ const value = decode_entities(src.slice(i, end));
708
+ push_to_parent({
709
+ kind: "text",
710
+ id: fresh_id(),
711
+ parent: null,
712
+ value
713
+ });
714
+ i = end;
715
+ }
716
+ if (open_stack.length > 0) throw new Error(`unclosed element <${open_stack[open_stack.length - 1].raw_tag}>`);
717
+ if (root === null) throw new Error("no root element");
718
+ return {
719
+ prolog,
720
+ root,
721
+ epilog,
722
+ nodes
723
+ };
724
+ }
725
+ function split_qname(qname) {
726
+ const idx = qname.indexOf(":");
727
+ if (idx === -1) return [null, qname];
728
+ return [qname.slice(0, idx), qname.slice(idx + 1)];
729
+ }
730
+ function parse_attrs(src, from) {
731
+ const attrs = [];
732
+ let i = from;
733
+ let pre = "";
734
+ const n = src.length;
735
+ while (i < n) {
736
+ const ws_start = i;
737
+ while (i < n && /\s/.test(src[i])) i++;
738
+ pre += src.slice(ws_start, i);
739
+ if (i >= n) throw new Error("unterminated start tag");
740
+ const c = src[i];
741
+ if (c === "/") {
742
+ if (src[i + 1] !== ">") throw new Error("expected '/>' at " + i);
743
+ pre + "";
744
+ return {
745
+ attrs,
746
+ end_index: i + 2,
747
+ self_closing: true,
748
+ trailing: pre
749
+ };
750
+ }
751
+ if (c === ">") return {
752
+ attrs,
753
+ end_index: i + 1,
754
+ self_closing: false,
755
+ trailing: pre
756
+ };
757
+ const name_start = i;
758
+ while (i < n && !/[\s=/>]/.test(src[i])) i++;
759
+ const raw_name = src.slice(name_start, i);
760
+ let eq_trivia = "";
761
+ while (i < n && /\s/.test(src[i])) {
762
+ eq_trivia += src[i];
763
+ i++;
764
+ }
765
+ if (src[i] !== "=") {
766
+ const [prefix, local] = split_qname(raw_name);
767
+ attrs.push({
768
+ raw_name,
769
+ prefix,
770
+ local,
771
+ ns: null,
772
+ value: "",
773
+ pre,
774
+ eq_trivia,
775
+ quote: "\""
776
+ });
777
+ pre = "";
778
+ continue;
779
+ }
780
+ i++;
781
+ while (i < n && /\s/.test(src[i])) i++;
782
+ const quote = src[i];
783
+ if (quote !== "\"" && quote !== "'") throw new Error("expected attribute quote at " + i);
784
+ i++;
785
+ const val_start = i;
786
+ while (i < n && src[i] !== quote) i++;
787
+ if (i >= n) throw new Error("unterminated attribute value");
788
+ const raw_value = src.slice(val_start, i);
789
+ i++;
790
+ const [prefix, local] = split_qname(raw_name);
791
+ attrs.push({
792
+ raw_name,
793
+ prefix,
794
+ local,
795
+ ns: null,
796
+ value: decode_entities(raw_value),
797
+ pre,
798
+ eq_trivia,
799
+ quote
800
+ });
801
+ pre = "";
802
+ }
803
+ throw new Error("unterminated start tag");
804
+ }
805
+ const NAMED_ENTITIES = {
806
+ amp: "&",
807
+ lt: "<",
808
+ gt: ">",
809
+ quot: "\"",
810
+ apos: "'"
811
+ };
812
+ function decode_entities(s) {
813
+ return s.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g, (_, ent) => {
814
+ if (ent.startsWith("#x") || ent.startsWith("#X")) return String.fromCodePoint(parseInt(ent.slice(2), 16));
815
+ if (ent.startsWith("#")) return String.fromCodePoint(parseInt(ent.slice(1), 10));
816
+ return NAMED_ENTITIES[ent] ?? `&${ent};`;
817
+ });
818
+ }
819
+ function encode_attr_value(value, quote) {
820
+ let out = value.replace(/&/g, "&amp;").replace(/</g, "&lt;");
821
+ out = quote === "\"" ? out.replace(/"/g, "&quot;") : out.replace(/'/g, "&apos;");
822
+ return out;
823
+ }
824
+ function encode_text(value) {
825
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;");
826
+ }
827
+ //#endregion
828
+ //#region src/core/document.ts
829
+ var SvgDocument = class SvgDocument {
830
+ constructor(svg) {
831
+ this.listeners = /* @__PURE__ */ new Set();
832
+ this._structure_version = 0;
833
+ this.source = svg;
834
+ const parsed = parse_svg(svg);
835
+ this.original = parsed;
836
+ this.nodes = parsed.nodes;
837
+ this.prolog = parsed.prolog;
838
+ this.epilog = parsed.epilog;
839
+ this.root = parsed.root;
840
+ }
841
+ static parse(svg) {
842
+ return new SvgDocument(svg);
843
+ }
844
+ /** Reload from the original parse, discarding all edits. */
845
+ reset_to_original() {
846
+ const parsed = parse_svg(this.source);
847
+ this.original = parsed;
848
+ this.nodes = parsed.nodes;
849
+ this.prolog = parsed.prolog;
850
+ this.epilog = parsed.epilog;
851
+ this.root = parsed.root;
852
+ this._structure_version++;
853
+ this.emit();
854
+ }
855
+ /** Replace document with new svg source (clears edits + history-owned state). */
856
+ load(svg) {
857
+ this.source = svg;
858
+ const parsed = parse_svg(svg);
859
+ this.original = parsed;
860
+ this.nodes = parsed.nodes;
861
+ this.prolog = parsed.prolog;
862
+ this.epilog = parsed.epilog;
863
+ this.root = parsed.root;
864
+ this._structure_version++;
865
+ this.emit();
866
+ }
867
+ on_change(fn) {
868
+ this.listeners.add(fn);
869
+ return () => this.listeners.delete(fn);
870
+ }
871
+ /** See `_structure_version` for what this counter signals. */
872
+ get structure_version() {
873
+ return this._structure_version;
874
+ }
875
+ emit() {
876
+ for (const fn of this.listeners) fn();
877
+ }
878
+ /** Notify subscribers — for callers that mutate directly via setAttr/etc. */
879
+ notify() {
880
+ this.emit();
881
+ }
882
+ get(id) {
883
+ return this.nodes.get(id) ?? null;
884
+ }
885
+ is_element(id) {
886
+ return this.nodes.get(id)?.kind === "element";
887
+ }
888
+ parent_of(id) {
889
+ return this.nodes.get(id)?.parent ?? null;
890
+ }
891
+ children_of(id) {
892
+ const n = this.nodes.get(id);
893
+ if (!n || n.kind !== "element") return [];
894
+ return n.children;
895
+ }
896
+ /** Element children only — text/comment/cdata filtered out. */
897
+ element_children_of(id) {
898
+ return this.children_of(id).filter((c) => this.is_element(c));
899
+ }
900
+ next_sibling_of(id) {
901
+ const parent = this.parent_of(id);
902
+ if (parent === null) return null;
903
+ const siblings = this.children_of(parent);
904
+ const i = siblings.indexOf(id);
905
+ return i >= 0 && i + 1 < siblings.length ? siblings[i + 1] : null;
906
+ }
907
+ next_element_sibling_of(id) {
908
+ const parent = this.parent_of(id);
909
+ if (parent === null) return null;
910
+ const siblings = this.element_children_of(parent);
911
+ const i = siblings.indexOf(id);
912
+ return i >= 0 && i + 1 < siblings.length ? siblings[i + 1] : null;
913
+ }
914
+ tag_of(id) {
915
+ const n = this.nodes.get(id);
916
+ return n && n.kind === "element" ? n.local : "";
917
+ }
918
+ contains(ancestor, descendant) {
919
+ if (ancestor === descendant) return true;
920
+ let cur = this.parent_of(descendant);
921
+ while (cur !== null) {
922
+ if (cur === ancestor) return true;
923
+ cur = this.parent_of(cur);
924
+ }
925
+ return false;
926
+ }
927
+ all_nodes() {
928
+ const out = [];
929
+ const walk = (id) => {
930
+ out.push(id);
931
+ const c = this.children_of(id);
932
+ for (const ch of c) walk(ch);
933
+ };
934
+ walk(this.root);
935
+ return out;
936
+ }
937
+ all_elements() {
938
+ return this.all_nodes().filter((id) => this.is_element(id));
939
+ }
940
+ find_by_tag(ancestor, tag) {
941
+ const out = [];
942
+ const walk = (id) => {
943
+ if (id !== ancestor && this.is_element(id) && this.tag_of(id) === tag) out.push(id);
944
+ for (const c of this.children_of(id)) walk(c);
945
+ };
946
+ walk(ancestor);
947
+ return out;
948
+ }
949
+ /** Read attribute by local name, optionally namespace-filtered. */
950
+ get_attr(id, name, ns = null) {
951
+ const n = this.nodes.get(id);
952
+ if (!n || n.kind !== "element") return null;
953
+ for (const a of n.attrs) if (a.local === name && (ns === null || a.ns === ns)) return a.value;
954
+ return null;
955
+ }
956
+ /**
957
+ * Set / remove an attribute. If the attribute exists, it is mutated in place
958
+ * (preserving source position). If it doesn't, it's appended.
959
+ */
960
+ set_attr(id, name, value, ns = null) {
961
+ const n = this.nodes.get(id);
962
+ if (!n || n.kind !== "element") return;
963
+ const structural = name === "id";
964
+ for (let i = 0; i < n.attrs.length; i++) {
965
+ const a = n.attrs[i];
966
+ if (a.local === name && (ns === null || a.ns === ns)) {
967
+ if (value === null) n.attrs.splice(i, 1);
968
+ else a.value = value;
969
+ if (structural) this._structure_version++;
970
+ this.emit();
971
+ return;
972
+ }
973
+ }
974
+ if (value !== null) {
975
+ const prefix = ns === "http://www.w3.org/1999/xlink" ? "xlink" : null;
976
+ n.attrs.push({
977
+ raw_name: prefix ? `${prefix}:${name}` : name,
978
+ prefix,
979
+ local: name,
980
+ ns,
981
+ value,
982
+ pre: " ",
983
+ eq_trivia: "",
984
+ quote: "\""
985
+ });
986
+ if (structural) this._structure_version++;
987
+ this.emit();
988
+ }
989
+ }
990
+ attributes_of(id) {
991
+ const n = this.nodes.get(id);
992
+ if (!n || n.kind !== "element") return [];
993
+ return n.attrs.map((a) => ({
994
+ name: a.local,
995
+ ns: a.ns,
996
+ value: a.value
997
+ }));
998
+ }
999
+ get_style(id, property) {
1000
+ const style = this.get_attr(id, "style");
1001
+ if (!style) return null;
1002
+ const decls = parse_inline_style(style);
1003
+ for (const d of decls) if (d.property === property) return d.value;
1004
+ return null;
1005
+ }
1006
+ set_style(id, property, value) {
1007
+ const decls = parse_inline_style(this.get_attr(id, "style") ?? "");
1008
+ const idx = decls.findIndex((d) => d.property === property);
1009
+ if (value === null) {
1010
+ if (idx === -1) return;
1011
+ decls.splice(idx, 1);
1012
+ } else if (idx === -1) decls.push({
1013
+ property,
1014
+ value
1015
+ });
1016
+ else decls[idx].value = value;
1017
+ const next = decls.map((d) => `${d.property}: ${d.value}`).join("; ");
1018
+ this.set_attr(id, "style", next === "" ? null : next);
1019
+ }
1020
+ get_all_styles(id) {
1021
+ const style = this.get_attr(id, "style");
1022
+ if (!style) return [];
1023
+ return parse_inline_style(style);
1024
+ }
1025
+ text_of(id) {
1026
+ const n = this.nodes.get(id);
1027
+ if (!n || n.kind !== "element") return "";
1028
+ let out = "";
1029
+ for (const c of n.children) {
1030
+ const cn = this.nodes.get(c);
1031
+ if (cn?.kind === "text") out += cn.value;
1032
+ }
1033
+ return out;
1034
+ }
1035
+ /** Replace all direct text children with a single text node carrying `value`. */
1036
+ set_text(id, value) {
1037
+ const n = this.nodes.get(id);
1038
+ if (!n || n.kind !== "element") return;
1039
+ n.children = n.children.filter((c) => this.nodes.get(c)?.kind !== "text");
1040
+ if (value !== "") {
1041
+ const text_id = `t${Math.random().toString(36).slice(2, 10)}`;
1042
+ const text_node = {
1043
+ kind: "text",
1044
+ id: text_id,
1045
+ parent: id,
1046
+ value
1047
+ };
1048
+ this.nodes.set(text_id, text_node);
1049
+ n.children.push(text_id);
1050
+ }
1051
+ this._structure_version++;
1052
+ this.emit();
1053
+ }
1054
+ insert(id, parent, before) {
1055
+ const node = this.nodes.get(id);
1056
+ const parent_node = this.nodes.get(parent);
1057
+ if (!node || !parent_node || parent_node.kind !== "element") return;
1058
+ if (node.parent !== null) {
1059
+ const old_parent = this.nodes.get(node.parent);
1060
+ if (old_parent && old_parent.kind === "element") {
1061
+ const i = old_parent.children.indexOf(id);
1062
+ if (i >= 0) old_parent.children.splice(i, 1);
1063
+ }
1064
+ }
1065
+ const ix = before === null ? -1 : parent_node.children.indexOf(before);
1066
+ if (ix < 0) parent_node.children.push(id);
1067
+ else parent_node.children.splice(ix, 0, id);
1068
+ node.parent = parent;
1069
+ this._structure_version++;
1070
+ this.emit();
1071
+ }
1072
+ remove(id) {
1073
+ const n = this.nodes.get(id);
1074
+ if (!n || n.parent === null) return;
1075
+ const parent = this.nodes.get(n.parent);
1076
+ if (!parent || parent.kind !== "element") return;
1077
+ const i = parent.children.indexOf(id);
1078
+ if (i >= 0) parent.children.splice(i, 1);
1079
+ n.parent = null;
1080
+ this._structure_version++;
1081
+ this.emit();
1082
+ }
1083
+ /** Create a new element node and register it (not yet inserted). */
1084
+ create_element(local, opts) {
1085
+ const id = `e${Math.random().toString(36).slice(2, 10)}`;
1086
+ const prefix = opts?.prefix ?? null;
1087
+ const ns = opts?.ns ?? null;
1088
+ const node = {
1089
+ kind: "element",
1090
+ id,
1091
+ parent: null,
1092
+ raw_tag: prefix ? `${prefix}:${local}` : local,
1093
+ prefix,
1094
+ local,
1095
+ ns,
1096
+ attrs: [],
1097
+ children: [],
1098
+ self_closing: false,
1099
+ open_tag_trailing: "",
1100
+ close_tag_leading: "",
1101
+ close_tag_trailing: ""
1102
+ };
1103
+ this.nodes.set(id, node);
1104
+ return id;
1105
+ }
1106
+ serialize() {
1107
+ let out = "";
1108
+ for (const p of this.prolog) out += this.emit_node(p);
1109
+ out += this.emit_node(this.nodes.get(this.root));
1110
+ for (const e of this.epilog) out += this.emit_node(e);
1111
+ return out;
1112
+ }
1113
+ emit_node(n) {
1114
+ switch (n.kind) {
1115
+ case "text": return encode_text(n.value);
1116
+ case "comment": return `<!--${n.value}-->`;
1117
+ case "cdata": return `<![CDATA[${n.value}]]>`;
1118
+ case "pi": {
1119
+ const pi = n;
1120
+ return `<?${pi.target}${pi.value ? " " + pi.value : ""}?>`;
1121
+ }
1122
+ case "doctype": return `<!DOCTYPE${n.value}>`;
1123
+ case "element": {
1124
+ const e = n;
1125
+ let s = `<${e.raw_tag}`;
1126
+ for (const a of e.attrs) s += this.emit_attr(a);
1127
+ if (e.children.length === 0 && e.self_closing) {
1128
+ s += `${e.open_tag_trailing}/>`;
1129
+ return s;
1130
+ }
1131
+ s += `${e.open_tag_trailing}>`;
1132
+ for (const cid of e.children) {
1133
+ const cn = this.nodes.get(cid);
1134
+ if (cn) s += this.emit_node(cn);
1135
+ }
1136
+ s += `</${e.close_tag_leading}${e.raw_tag}${e.close_tag_trailing}>`;
1137
+ return s;
1138
+ }
1139
+ }
1140
+ }
1141
+ emit_attr(a) {
1142
+ return `${a.pre}${a.raw_name}${a.eq_trivia}=${a.quote}${encode_attr_value(a.value, a.quote)}${a.quote}`;
1143
+ }
1144
+ };
1145
+ function parse_inline_style(s) {
1146
+ const out = [];
1147
+ const decls = s.split(";");
1148
+ for (const decl of decls) {
1149
+ const colon = decl.indexOf(":");
1150
+ if (colon === -1) continue;
1151
+ const property = decl.slice(0, colon).trim();
1152
+ const value = decl.slice(colon + 1).trim();
1153
+ if (property) out.push({
1154
+ property,
1155
+ value
1156
+ });
1157
+ }
1158
+ return out;
1159
+ }
1160
+ //#endregion
1161
+ //#region src/core/properties.ts
1162
+ /** SVG properties that inherit per SVG 2 §6 (subset; the common ones). */
1163
+ const INHERITED = new Set([
1164
+ "color",
1165
+ "cursor",
1166
+ "direction",
1167
+ "fill",
1168
+ "fill-opacity",
1169
+ "fill-rule",
1170
+ "font",
1171
+ "font-family",
1172
+ "font-size",
1173
+ "font-style",
1174
+ "font-variant",
1175
+ "font-weight",
1176
+ "letter-spacing",
1177
+ "marker",
1178
+ "marker-end",
1179
+ "marker-mid",
1180
+ "marker-start",
1181
+ "paint-order",
1182
+ "pointer-events",
1183
+ "shape-rendering",
1184
+ "stroke",
1185
+ "stroke-dasharray",
1186
+ "stroke-dashoffset",
1187
+ "stroke-linecap",
1188
+ "stroke-linejoin",
1189
+ "stroke-miterlimit",
1190
+ "stroke-opacity",
1191
+ "stroke-width",
1192
+ "text-anchor",
1193
+ "text-rendering",
1194
+ "visibility",
1195
+ "word-spacing",
1196
+ "writing-mode"
1197
+ ]);
1198
+ /** Initial values for known properties (subset). */
1199
+ const INITIAL = {
1200
+ fill: "black",
1201
+ stroke: "none",
1202
+ "fill-opacity": "1",
1203
+ "stroke-opacity": "1",
1204
+ "stroke-width": "1",
1205
+ opacity: "1",
1206
+ visibility: "visible",
1207
+ display: "inline"
1208
+ };
1209
+ /**
1210
+ * Resolve a property's declared value and its provenance for a single node.
1211
+ *
1212
+ * The cascade engine here covers what the README says is in scope:
1213
+ * presentation attributes + inline style + parent inheritance + initial.
1214
+ * `<style>` block matching is deferred.
1215
+ */
1216
+ function resolve_declared(doc, id, property) {
1217
+ const inline = doc.get_style(id, property);
1218
+ if (inline !== null && inline !== "") return {
1219
+ declared: inline,
1220
+ provenance: {
1221
+ origin: "author",
1222
+ carrier: "inline_style"
1223
+ }
1224
+ };
1225
+ const attr = doc.get_attr(id, property);
1226
+ if (attr !== null && attr !== "") return {
1227
+ declared: attr,
1228
+ provenance: {
1229
+ origin: "author",
1230
+ carrier: "presentation_attribute"
1231
+ }
1232
+ };
1233
+ if (INHERITED.has(property)) {
1234
+ const parent = doc.parent_of(id);
1235
+ if (parent !== null && doc.is_element(parent)) {
1236
+ const r = resolve_declared(doc, parent, property);
1237
+ if (r.declared !== null) return {
1238
+ declared: r.declared,
1239
+ provenance: {
1240
+ origin: "author",
1241
+ carrier: "inherited"
1242
+ }
1243
+ };
1244
+ }
1245
+ }
1246
+ return {
1247
+ declared: INITIAL[property] ?? null,
1248
+ provenance: {
1249
+ origin: "user_agent",
1250
+ carrier: "defaulted"
1251
+ }
1252
+ };
1253
+ }
1254
+ /**
1255
+ * Type-parsed computed value for known properties. Unknown property names
1256
+ * return the declared string as-is.
1257
+ */
1258
+ function compute_known(property, declared) {
1259
+ if (declared === null) return null;
1260
+ const trimmed = declared.trim();
1261
+ if (trimmed === "inherit" || trimmed === "initial" || trimmed === "unset" || trimmed === "revert" || trimmed === "revert-layer") return null;
1262
+ if (/^var\s*\(/i.test(trimmed)) return {
1263
+ error: "invalid_at_computed_value_time",
1264
+ reason: `var() substitution requires a cascade engine (not implemented)`
1265
+ };
1266
+ switch (property) {
1267
+ case "opacity":
1268
+ case "fill-opacity":
1269
+ case "stroke-opacity":
1270
+ case "stroke-width":
1271
+ case "x":
1272
+ case "y":
1273
+ case "width":
1274
+ case "height":
1275
+ case "cx":
1276
+ case "cy":
1277
+ case "r":
1278
+ case "rx":
1279
+ case "ry":
1280
+ case "font-size": {
1281
+ const n = parseFloat(trimmed);
1282
+ return Number.isFinite(n) ? n : trimmed;
1283
+ }
1284
+ default: return trimmed;
1285
+ }
1286
+ }
1287
+ function read_property(doc, id, property) {
1288
+ const { declared, provenance } = resolve_declared(doc, id, property);
1289
+ return {
1290
+ declared,
1291
+ computed: compute_known(property, declared),
1292
+ provenance
1293
+ };
1294
+ }
1295
+ /** Which carrier should a `set_property` write to? Per the README (P1):
1296
+ * whichever carrier currently wins the cascade. If nothing wins (defaulted /
1297
+ * inherited), write a presentation attribute by default. */
1298
+ function choose_write_carrier(doc, id, property) {
1299
+ const inline = doc.get_style(id, property);
1300
+ if (inline !== null && inline !== "") return "inline_style";
1301
+ return "presentation_attribute";
1302
+ }
1303
+ //#endregion
1304
+ //#region src/types.ts
1305
+ const DEFAULT_STYLE = {
1306
+ chrome_color: "#2563eb",
1307
+ handle_size: 8,
1308
+ handle_fill: "#ffffff",
1309
+ handle_stroke: "#2563eb",
1310
+ endpoint_dot_radius: 5,
1311
+ selection_outline_width: 2,
1312
+ measurement_color: "#ff3a30"
1313
+ };
1314
+ //#endregion
1315
+ //#region src/core/editor.ts
1316
+ const PROVIDER_ID = "svg-editor";
1317
+ /** Max characters in a synthesized display label before truncation. */
1318
+ const DISPLAY_LABEL_MAX_LEN = 40;
1319
+ function createSvgEditor(opts) {
1320
+ const doc = new SvgDocument(opts.svg);
1321
+ const history = new _grida_history.HistoryImpl();
1322
+ const defs = create_defs(doc);
1323
+ let selection = [];
1324
+ let scope = null;
1325
+ let mode = "select";
1326
+ let version = 0;
1327
+ /** Document-edit counter — only bumps on actual mutations, not selection. */
1328
+ let doc_version = 0;
1329
+ /** doc_version at the last load()/serialize(); compared to derive `dirty`. */
1330
+ let baseline_doc_version = 0;
1331
+ let style = {
1332
+ ...DEFAULT_STYLE,
1333
+ ...opts.style ?? {}
1334
+ };
1335
+ const providers = opts.providers ?? {};
1336
+ const listeners = /* @__PURE__ */ new Set();
1337
+ let attached_surface = null;
1338
+ const modes = ["select", "edit-content"];
1339
+ function snapshot() {
1340
+ return Object.freeze({
1341
+ selection,
1342
+ scope,
1343
+ mode,
1344
+ dirty: doc_version !== baseline_doc_version,
1345
+ can_undo: history.stack.canUndo,
1346
+ can_redo: history.stack.canRedo,
1347
+ version,
1348
+ structure_version: doc.structure_version
1349
+ });
1350
+ }
1351
+ function emit() {
1352
+ version++;
1353
+ const s = snapshot();
1354
+ for (const fn of listeners) fn(s);
1355
+ }
1356
+ history.on("onChange", () => emit());
1357
+ history.on("onUndo", () => emit());
1358
+ history.on("onRedo", () => emit());
1359
+ doc.on_change(() => {
1360
+ doc_version++;
1361
+ });
1362
+ function subscribe(fn) {
1363
+ listeners.add(fn);
1364
+ return () => {
1365
+ listeners.delete(fn);
1366
+ };
1367
+ }
1368
+ function subscribe_with_selector(selector, fn, equals = Object.is) {
1369
+ let prev = selector(snapshot());
1370
+ return subscribe((state) => {
1371
+ const next = selector(state);
1372
+ if (!equals(prev, next)) {
1373
+ const p = prev;
1374
+ prev = next;
1375
+ fn(next, p);
1376
+ }
1377
+ });
1378
+ }
1379
+ function set_selection(next) {
1380
+ selection = Object.freeze([...next]);
1381
+ emit();
1382
+ }
1383
+ function select(target, opts) {
1384
+ const ids = typeof target === "string" ? [target] : [...target];
1385
+ if (opts?.additive) {
1386
+ const merged = new Set(selection);
1387
+ for (const id of ids) merged.add(id);
1388
+ set_selection([...merged]);
1389
+ } else set_selection(ids);
1390
+ }
1391
+ function deselect() {
1392
+ set_selection([]);
1393
+ }
1394
+ function enter_scope(group) {
1395
+ scope = group;
1396
+ emit();
1397
+ }
1398
+ function exit_scope() {
1399
+ if (scope === null) return;
1400
+ const parent = doc.parent_of(scope);
1401
+ scope = parent && parent !== doc.root ? parent : null;
1402
+ emit();
1403
+ }
1404
+ function set_mode(next) {
1405
+ if (mode === next) return;
1406
+ mode = next;
1407
+ emit();
1408
+ }
1409
+ function node_properties(id, names) {
1410
+ const out = {};
1411
+ for (const name of names) out[name] = read_property(doc, id, name);
1412
+ return out;
1413
+ }
1414
+ function node_paint(id, channel) {
1415
+ const { declared, provenance } = resolve_declared(doc, id, channel);
1416
+ return {
1417
+ declared,
1418
+ computed: require_paint.parse_paint(declared),
1419
+ provenance
1420
+ };
1421
+ }
1422
+ function write_property(id, name, value) {
1423
+ if (choose_write_carrier(doc, id, name) === "inline_style") doc.set_style(id, name, value);
1424
+ else doc.set_attr(id, name, value);
1425
+ }
1426
+ function set_property(name, value) {
1427
+ if (selection.length === 0) return;
1428
+ const before = [];
1429
+ for (const id of selection) before.push({
1430
+ id,
1431
+ attr: doc.get_attr(id, name),
1432
+ style: doc.get_style(id, name)
1433
+ });
1434
+ const targets = [...selection];
1435
+ const apply = () => {
1436
+ for (const id of targets) write_property(id, name, value);
1437
+ emit();
1438
+ };
1439
+ const revert = () => {
1440
+ for (const b of before) {
1441
+ if (b.style !== null) doc.set_style(b.id, name, b.style);
1442
+ else doc.set_style(b.id, name, null);
1443
+ doc.set_attr(b.id, name, b.attr);
1444
+ }
1445
+ emit();
1446
+ };
1447
+ apply();
1448
+ history.atomic(`set ${name}`, (tx) => {
1449
+ tx.push({
1450
+ providerId: PROVIDER_ID,
1451
+ apply,
1452
+ revert
1453
+ });
1454
+ });
1455
+ }
1456
+ function preview_property(name) {
1457
+ const before = [];
1458
+ for (const id of selection) before.push({
1459
+ id,
1460
+ attr: doc.get_attr(id, name),
1461
+ style: doc.get_style(id, name)
1462
+ });
1463
+ const preview = history.preview(`change ${name}`);
1464
+ return {
1465
+ update(value) {
1466
+ preview.set({
1467
+ providerId: PROVIDER_ID,
1468
+ apply: () => {
1469
+ for (const id of selection) write_property(id, name, value);
1470
+ emit();
1471
+ },
1472
+ revert: () => {
1473
+ for (const b of before) {
1474
+ if (b.style !== null) doc.set_style(b.id, name, b.style);
1475
+ else doc.set_style(b.id, name, null);
1476
+ doc.set_attr(b.id, name, b.attr);
1477
+ }
1478
+ emit();
1479
+ }
1480
+ });
1481
+ },
1482
+ commit: () => preview.commit(),
1483
+ discard: () => preview.discard()
1484
+ };
1485
+ }
1486
+ function set_paint(channel, paint) {
1487
+ if (selection.length === 0) return;
1488
+ set_property(channel, require_paint.serialize_paint(paint));
1489
+ }
1490
+ function preview_paint(channel) {
1491
+ const session = preview_property(channel);
1492
+ return {
1493
+ update: (paint) => session.update(require_paint.serialize_paint(paint)),
1494
+ commit: () => session.commit(),
1495
+ discard: () => session.discard()
1496
+ };
1497
+ }
1498
+ function set_paint_from_gradient(channel, definition, _opts) {
1499
+ const gradient_id = defs.gradients.upsert(definition);
1500
+ set_paint(channel, {
1501
+ kind: "ref",
1502
+ id: gradient_id
1503
+ });
1504
+ return { gradient_id };
1505
+ }
1506
+ function translate(delta) {
1507
+ if (selection.length === 0) return;
1508
+ if (delta.dx === 0 && delta.dy === 0) return;
1509
+ const baselines = selection.map((id) => ({
1510
+ id,
1511
+ baseline: require_paint.capture_translate_baseline(doc, id)
1512
+ }));
1513
+ const apply = () => {
1514
+ for (const { id, baseline } of baselines) require_paint.apply_translate(doc, id, baseline, delta.dx, delta.dy);
1515
+ emit();
1516
+ };
1517
+ const revert = () => {
1518
+ for (const { id, baseline } of baselines) require_paint.apply_translate(doc, id, baseline, 0, 0);
1519
+ emit();
1520
+ };
1521
+ apply();
1522
+ history.atomic("translate", (tx) => {
1523
+ tx.push({
1524
+ providerId: PROVIDER_ID,
1525
+ apply,
1526
+ revert
1527
+ });
1528
+ });
1529
+ }
1530
+ function reorder(direction) {
1531
+ if (selection.length !== 1) return;
1532
+ const target = selection[0];
1533
+ const parent = doc.parent_of(target);
1534
+ if (parent === null) return;
1535
+ const siblings = doc.element_children_of(parent);
1536
+ const i = siblings.indexOf(target);
1537
+ if (i < 0) return;
1538
+ const original_before = siblings[i + 1] ?? null;
1539
+ let new_before;
1540
+ switch (direction) {
1541
+ case "bring_forward":
1542
+ if (i >= siblings.length - 1) return;
1543
+ new_before = siblings[i + 2] ?? null;
1544
+ break;
1545
+ case "send_backward":
1546
+ if (i <= 0) return;
1547
+ new_before = siblings[i - 1];
1548
+ break;
1549
+ case "bring_to_front":
1550
+ if (i === siblings.length - 1) return;
1551
+ new_before = null;
1552
+ break;
1553
+ case "send_to_back":
1554
+ if (i === 0) return;
1555
+ new_before = siblings[0];
1556
+ break;
1557
+ }
1558
+ const apply = () => {
1559
+ doc.insert(target, parent, new_before);
1560
+ emit();
1561
+ };
1562
+ const revert = () => {
1563
+ doc.insert(target, parent, original_before);
1564
+ emit();
1565
+ };
1566
+ apply();
1567
+ history.atomic(`reorder: ${direction}`, (tx) => {
1568
+ tx.push({
1569
+ providerId: PROVIDER_ID,
1570
+ apply,
1571
+ revert
1572
+ });
1573
+ });
1574
+ }
1575
+ function remove() {
1576
+ if (selection.length !== 1) return;
1577
+ const target = selection[0];
1578
+ const parent = doc.parent_of(target);
1579
+ if (parent === null) return;
1580
+ const next_sibling = doc.next_element_sibling_of(target);
1581
+ const old_selection = selection;
1582
+ const apply = () => {
1583
+ doc.remove(target);
1584
+ set_selection([]);
1585
+ };
1586
+ const revert = () => {
1587
+ doc.insert(target, parent, next_sibling);
1588
+ set_selection(old_selection);
1589
+ };
1590
+ apply();
1591
+ history.atomic("remove", (tx) => {
1592
+ tx.push({
1593
+ providerId: PROVIDER_ID,
1594
+ apply,
1595
+ revert
1596
+ });
1597
+ });
1598
+ }
1599
+ function set_text(value) {
1600
+ if (selection.length !== 1) return;
1601
+ const target = selection[0];
1602
+ if (doc.tag_of(target) !== "text") return;
1603
+ const original = doc.text_of(target);
1604
+ if (original === value) return;
1605
+ const apply = () => {
1606
+ doc.set_text(target, value);
1607
+ emit();
1608
+ };
1609
+ const revert = () => {
1610
+ doc.set_text(target, original);
1611
+ emit();
1612
+ };
1613
+ apply();
1614
+ history.atomic("edit text", (tx) => {
1615
+ tx.push({
1616
+ providerId: PROVIDER_ID,
1617
+ apply,
1618
+ revert
1619
+ });
1620
+ });
1621
+ }
1622
+ let content_edit_driver = null;
1623
+ let computed_resolver = null;
1624
+ function dom_computed_property(id, name) {
1625
+ return computed_resolver?.computed_property(id, name) ?? null;
1626
+ }
1627
+ function dom_computed_paint(id, channel) {
1628
+ return computed_resolver?.computed_paint(id, channel) ?? null;
1629
+ }
1630
+ let current_surface_hover = null;
1631
+ let surface_hover_override = null;
1632
+ const surface_hover_listeners = /* @__PURE__ */ new Set();
1633
+ let surface_hover_override_driver = null;
1634
+ function notify_surface_hover() {
1635
+ for (const cb of surface_hover_listeners) cb();
1636
+ }
1637
+ function _set_current_surface_hover(id) {
1638
+ if (current_surface_hover === id) return;
1639
+ current_surface_hover = id;
1640
+ notify_surface_hover();
1641
+ }
1642
+ function enter_content_edit(target) {
1643
+ const id = target ?? (selection.length === 1 ? selection[0] : null);
1644
+ if (!id) return false;
1645
+ if (doc.tag_of(id) !== "text") return false;
1646
+ if (!content_edit_driver) return false;
1647
+ return content_edit_driver(id);
1648
+ }
1649
+ function load_svg(svg) {
1650
+ doc.load(svg);
1651
+ selection = [];
1652
+ scope = null;
1653
+ mode = "select";
1654
+ history.clear();
1655
+ baseline_doc_version = doc_version;
1656
+ emit();
1657
+ }
1658
+ function serialize_svg() {
1659
+ return doc.serialize();
1660
+ }
1661
+ function undo() {
1662
+ history.undo();
1663
+ }
1664
+ function redo() {
1665
+ history.redo();
1666
+ }
1667
+ const registry = new CommandRegistry();
1668
+ const keymap = new Keymap(registry);
1669
+ const commands = {
1670
+ select,
1671
+ deselect,
1672
+ enter_scope,
1673
+ exit_scope,
1674
+ set_mode,
1675
+ set_property,
1676
+ preview_property,
1677
+ set_paint,
1678
+ preview_paint,
1679
+ set_paint_from_gradient,
1680
+ translate,
1681
+ reorder,
1682
+ remove,
1683
+ set_text,
1684
+ load_svg,
1685
+ serialize_svg,
1686
+ undo,
1687
+ redo,
1688
+ register: (id, handler) => registry.register(id, handler),
1689
+ invoke: (id, args) => registry.invoke(id, args),
1690
+ has: (id) => registry.has(id)
1691
+ };
1692
+ function load(svg) {
1693
+ load_svg(svg);
1694
+ }
1695
+ function serialize() {
1696
+ return doc.serialize();
1697
+ }
1698
+ function reset() {
1699
+ history.clear();
1700
+ doc.reset_to_original();
1701
+ selection = [];
1702
+ scope = null;
1703
+ mode = "select";
1704
+ baseline_doc_version = doc_version;
1705
+ emit();
1706
+ }
1707
+ function attach(surface) {
1708
+ if (attached_surface) attached_surface.dispose();
1709
+ attached_surface = surface;
1710
+ return { detach() {
1711
+ if (attached_surface === surface) {
1712
+ attached_surface.dispose();
1713
+ attached_surface = null;
1714
+ }
1715
+ } };
1716
+ }
1717
+ function detach() {
1718
+ if (attached_surface) {
1719
+ attached_surface.dispose();
1720
+ attached_surface = null;
1721
+ }
1722
+ }
1723
+ function dispose() {
1724
+ detach();
1725
+ listeners.clear();
1726
+ }
1727
+ function set_style(partial) {
1728
+ style = {
1729
+ ...style,
1730
+ ...partial
1731
+ };
1732
+ emit();
1733
+ }
1734
+ const public_editor = {
1735
+ document: doc,
1736
+ get state() {
1737
+ return snapshot();
1738
+ },
1739
+ subscribe,
1740
+ subscribe_with_selector,
1741
+ node_properties,
1742
+ node_paint,
1743
+ dom_computed_property,
1744
+ dom_computed_paint,
1745
+ enter_content_edit,
1746
+ defs,
1747
+ commands,
1748
+ display_label(id, opts) {
1749
+ const tag = doc.tag_of(id);
1750
+ if (tag === "text") {
1751
+ const collapsed = doc.text_of(id).replace(/\s+/g, " ").trim();
1752
+ if (collapsed.length === 0) return "text";
1753
+ return collapsed.length > DISPLAY_LABEL_MAX_LEN ? `${collapsed.slice(0, DISPLAY_LABEL_MAX_LEN)}…` : collapsed;
1754
+ }
1755
+ const elem_id = doc.get_attr(id, "id");
1756
+ const head = opts?.tagLabel ? opts.tagLabel(tag) : tag;
1757
+ return elem_id && elem_id.length > 0 ? `${head} #${elem_id}` : head;
1758
+ },
1759
+ tree() {
1760
+ const map = /* @__PURE__ */ new Map();
1761
+ for (const id of doc.all_elements()) map.set(id, {
1762
+ id,
1763
+ tag: doc.tag_of(id),
1764
+ name: doc.get_attr(id, "id") ?? void 0,
1765
+ parent: doc.parent_of(id),
1766
+ children: doc.element_children_of(id)
1767
+ });
1768
+ return {
1769
+ root: doc.root,
1770
+ nodes: map
1771
+ };
1772
+ },
1773
+ surface_hover() {
1774
+ return current_surface_hover;
1775
+ },
1776
+ set_surface_hover_override(id) {
1777
+ if (surface_hover_override === id) return;
1778
+ surface_hover_override = id;
1779
+ if (surface_hover_override_driver) surface_hover_override_driver(id);
1780
+ },
1781
+ subscribe_surface_hover(cb) {
1782
+ surface_hover_listeners.add(cb);
1783
+ return () => {
1784
+ surface_hover_listeners.delete(cb);
1785
+ };
1786
+ },
1787
+ modes,
1788
+ get style() {
1789
+ return style;
1790
+ },
1791
+ set_style,
1792
+ load,
1793
+ serialize,
1794
+ reset,
1795
+ attach,
1796
+ detach,
1797
+ dispose,
1798
+ providers,
1799
+ _internal: {
1800
+ doc,
1801
+ set_content_edit_driver(fn) {
1802
+ content_edit_driver = fn;
1803
+ },
1804
+ set_surface_hover_override_driver(fn) {
1805
+ surface_hover_override_driver = fn;
1806
+ if (fn) fn(surface_hover_override);
1807
+ },
1808
+ push_surface_hover(id) {
1809
+ _set_current_surface_hover(id);
1810
+ },
1811
+ set_computed_resolver(fn) {
1812
+ computed_resolver = fn;
1813
+ }
1814
+ },
1815
+ keymap
1816
+ };
1817
+ registerDefaultCommands(registry, public_editor);
1818
+ applyDefaultBindings(keymap);
1819
+ return public_editor;
1820
+ }
1821
+ //#endregion
1822
+ Object.defineProperty(exports, "DEFAULT_STYLE", {
1823
+ enumerable: true,
1824
+ get: function() {
1825
+ return DEFAULT_STYLE;
1826
+ }
1827
+ });
1828
+ Object.defineProperty(exports, "createSvgEditor", {
1829
+ enumerable: true,
1830
+ get: function() {
1831
+ return createSvgEditor;
1832
+ }
1833
+ });