@grida/svg-editor 1.0.0-alpha.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +365 -384
  2. package/dist/dom-BEjG2bSw.d.mts +320 -0
  3. package/dist/dom-DYD1BHTo.js +6050 -0
  4. package/dist/dom-Y2QR7QSi.d.ts +318 -0
  5. package/dist/dom-tM3Dr1EK.mjs +5971 -0
  6. package/dist/dom.d.mts +3 -2
  7. package/dist/dom.d.ts +3 -2
  8. package/dist/dom.js +13 -1
  9. package/dist/dom.mjs +2 -2
  10. package/dist/editor-CWNtt1vu.mjs +2998 -0
  11. package/dist/editor-CZgwg8BK.d.mts +2537 -0
  12. package/dist/editor-CesShk9o.js +3004 -0
  13. package/dist/editor-kFTYSb_8.d.ts +2537 -0
  14. package/dist/index.d.mts +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +5 -2
  17. package/dist/index.mjs +3 -2
  18. package/dist/model-D0iEDcg3.mjs +5451 -0
  19. package/dist/model-tywvTGZv.js +5640 -0
  20. package/dist/presets.d.mts +17 -2
  21. package/dist/presets.d.ts +17 -2
  22. package/dist/presets.js +20 -15
  23. package/dist/presets.mjs +19 -15
  24. package/dist/react.d.mts +88 -10
  25. package/dist/react.d.ts +88 -10
  26. package/dist/react.js +169 -14
  27. package/dist/react.mjs +159 -16
  28. package/package.json +35 -9
  29. package/dist/dom-CmOu0HvI.mjs +0 -1623
  30. package/dist/dom-Cn-RtjRL.d.ts +0 -48
  31. package/dist/dom-CoVZzFqy.js +0 -1672
  32. package/dist/dom-DJnZhtOd.d.mts +0 -48
  33. package/dist/editor-CjK56cgb.mjs +0 -1823
  34. package/dist/editor-D2l_CDr0.d.ts +0 -818
  35. package/dist/editor-D2zZAyny.js +0 -1835
  36. package/dist/editor-Uu6dZX4y.d.mts +0 -818
  37. package/dist/index-CHiXYO9-.d.ts +0 -1
  38. package/dist/index-ThDLM4Am.d.mts +0 -1
  39. package/dist/paint-Cfiw4g_J.mjs +0 -477
  40. package/dist/paint-dDV-Trt9.js +0 -531
  41. /package/dist/{chunk-CfYAbeIz.mjs → chunk-D7D4PA-g.mjs} +0 -0
@@ -1,1623 +0,0 @@
1
- import { a as capture_resize_baseline, c as is_resizable, i as apply_translate, l as is_text_input_focused, o as capture_translate_baseline, r as apply_resize, s as compute_resize_factors, t as parse_paint } from "./paint-Cfiw4g_J.mjs";
2
- import { createTextEditor } from "@grida/text-editor/dom";
3
- import { NO_MODS, Surface, measurementToHUDDraw } from "@grida/hud";
4
- import { measure } from "@grida/cmath/_measurement";
5
- import cmath from "@grida/cmath";
6
- //#region src/core/camera.ts
7
- /**
8
- * Surface-scoped pan/zoom state.
9
- *
10
- * The public shape leads with the peer convention (`center` / `zoom` /
11
- * `bounds`) and keeps the matrix as an advanced read. Methods mirror
12
- * Figma/Penpot where they overlap.
13
- */
14
- var Camera = class {
15
- constructor(opts) {
16
- this.viewport_w = 0;
17
- this.viewport_h = 0;
18
- this.listeners = /* @__PURE__ */ new Set();
19
- this._constraints = null;
20
- this._transform = opts.initial ?? cmath.transform.identity;
21
- this.resolve_bounds = opts.resolve_bounds;
22
- }
23
- /**
24
- * Current viewport constraint, or `null` for free pan/zoom. Set with
25
- * `camera.constraints = { type: 'cover', bounds: '<root>', padding: 80 }`
26
- * to clamp zoom + pan; assign `null` to clear.
27
- *
28
- * Constraints are applied synchronously inside `set_transform` (and
29
- * `_set_viewport_size`), so every public mutation respects them
30
- * automatically — the host never needs to subscribe-and-clamp itself.
31
- */
32
- get constraints() {
33
- return this._constraints;
34
- }
35
- set constraints(c) {
36
- this._constraints = c;
37
- if (c) this.reenforce();
38
- }
39
- /** Underlying 2D affine. World→screen. */
40
- get transform() {
41
- return this._transform;
42
- }
43
- /** Uniform scale factor. 1 = 100 %. */
44
- get zoom() {
45
- return this._transform[0][0];
46
- }
47
- /** World-space point currently at viewport center. */
48
- get center() {
49
- return this.screen_to_world({
50
- x: this.viewport_w / 2,
51
- y: this.viewport_h / 2
52
- });
53
- }
54
- /** World-space rectangle visible in the viewport. */
55
- get bounds() {
56
- const tl = this.screen_to_world({
57
- x: 0,
58
- y: 0
59
- });
60
- const br = this.screen_to_world({
61
- x: this.viewport_w,
62
- y: this.viewport_h
63
- });
64
- return {
65
- x: tl.x,
66
- y: tl.y,
67
- width: br.x - tl.x,
68
- height: br.y - tl.y
69
- };
70
- }
71
- /** Translate the camera by a screen-space delta. */
72
- pan(delta_screen) {
73
- const t = this._transform;
74
- this.set_transform([[
75
- t[0][0],
76
- t[0][1],
77
- t[0][2] + delta_screen.x
78
- ], [
79
- t[1][0],
80
- t[1][1],
81
- t[1][2] + delta_screen.y
82
- ]]);
83
- }
84
- /**
85
- * Multiply zoom by `factor` keeping `origin_screen` fixed in world space.
86
- * Used by wheel-zoom-at-cursor and pinch-zoom.
87
- */
88
- zoom_at(factor, origin_screen) {
89
- const t = this._transform;
90
- const s2 = t[0][0] * factor;
91
- const tx2 = origin_screen.x * (1 - factor) + factor * t[0][2];
92
- const ty2 = origin_screen.y * (1 - factor) + factor * t[1][2];
93
- this.set_transform([[
94
- s2,
95
- 0,
96
- tx2
97
- ], [
98
- 0,
99
- s2,
100
- ty2
101
- ]]);
102
- }
103
- /** Pan so `c` lands at the viewport center. Zoom unchanged. */
104
- set_center(c) {
105
- const s = this._transform[0][0];
106
- const tx = this.viewport_w / 2 - s * c.x;
107
- const ty = this.viewport_h / 2 - s * c.y;
108
- this.set_transform([[
109
- s,
110
- 0,
111
- tx
112
- ], [
113
- 0,
114
- s,
115
- ty
116
- ]]);
117
- }
118
- /** Set zoom directly; pivot defaults to viewport center. */
119
- set_zoom(z, pivot_screen) {
120
- const current = this._transform[0][0];
121
- if (current === 0) return;
122
- const factor = z / current;
123
- const pivot = pivot_screen ?? {
124
- x: this.viewport_w / 2,
125
- y: this.viewport_h / 2
126
- };
127
- this.zoom_at(factor, pivot);
128
- }
129
- /**
130
- * Replace the entire transform.
131
- *
132
- * Idempotent: when the new transform is element-wise equal to the current
133
- * one, this is a no-op (no notification fires). This is the seam that
134
- * makes external constraint loops (e.g. "subscribe → compute clamped →
135
- * set_transform") terminate: the clamp re-emits the same transform on
136
- * the second pass, set_transform short-circuits, no recursion.
137
- *
138
- * When `camera.constraints` is non-null, the input transform is clamped
139
- * synchronously before being stored — every public mutation respects the
140
- * constraint automatically.
141
- */
142
- set_transform(t) {
143
- const next = this.apply_constraints(t);
144
- if (transform_equal(this._transform, next)) return;
145
- this._transform = next;
146
- this.notify();
147
- }
148
- /** Viewport size in screen pixels. Read by host code computing constraints. */
149
- get viewport_size() {
150
- return {
151
- width: this.viewport_w,
152
- height: this.viewport_h
153
- };
154
- }
155
- /**
156
- * Fit a target into the viewport.
157
- *
158
- * - `"<root>"` — the document root's content bounds (host-resolved).
159
- * - `"<selection>"` — current editor.state.selection's union bounds.
160
- * - `NodeId` — that node's content bounds.
161
- * - `Rect` — an explicit world-space rectangle.
162
- *
163
- * No-ops if the target resolves to `null` (e.g. empty selection) or if
164
- * the viewport size is 0 (no container).
165
- */
166
- fit(target, opts) {
167
- if (this.viewport_w <= 0 || this.viewport_h <= 0) return;
168
- const rect = typeof target === "string" ? this.resolve_bounds(target) : target;
169
- if (!rect || rect.width <= 0 || rect.height <= 0) return;
170
- const margin = opts?.margin ?? 64;
171
- const viewport = {
172
- x: 0,
173
- y: 0,
174
- width: this.viewport_w,
175
- height: this.viewport_h
176
- };
177
- this.set_transform(cmath.ext.viewport.transformToFit(viewport, rect, margin));
178
- }
179
- /** Snap back to identity. */
180
- reset() {
181
- this.set_transform(cmath.transform.identity);
182
- }
183
- /**
184
- * Subscribe to camera changes. Fires on every mutation. Cheap channel —
185
- * does NOT bump `editor.state.version`. Same pattern as
186
- * `editor.subscribe_surface_hover`.
187
- */
188
- subscribe(cb) {
189
- this.listeners.add(cb);
190
- return () => {
191
- this.listeners.delete(cb);
192
- };
193
- }
194
- /** @internal Surface drives this on container resize. */
195
- _set_viewport_size(w, h) {
196
- if (w === this.viewport_w && h === this.viewport_h) return;
197
- this.viewport_w = w;
198
- this.viewport_h = h;
199
- if (this._constraints) {
200
- const next = this.apply_constraints(this._transform);
201
- if (!transform_equal(this._transform, next)) this._transform = next;
202
- }
203
- this.notify();
204
- }
205
- /** Convert a screen-space point to world-space. */
206
- screen_to_world(p) {
207
- const inv = cmath.transform.invert(this._transform);
208
- const [wx, wy] = cmath.vector2.transform([p.x, p.y], inv);
209
- return {
210
- x: wx,
211
- y: wy
212
- };
213
- }
214
- /** Convert a world-space point to screen-space. */
215
- world_to_screen(p) {
216
- const [sx, sy] = cmath.vector2.transform([p.x, p.y], this._transform);
217
- return {
218
- x: sx,
219
- y: sy
220
- };
221
- }
222
- /**
223
- * Apply the current constraint (if any) to a candidate transform.
224
- * Pure: returns the clamped result, never mutates state. Returns the
225
- * input unchanged when constraints are null / bounds are unresolvable /
226
- * viewport is 0.
227
- */
228
- apply_constraints(t) {
229
- if (!this._constraints) return t;
230
- if (this.viewport_w <= 0 || this.viewport_h <= 0) return t;
231
- switch (this._constraints.type) {
232
- case "cover": return clamp_cover(t, this._constraints, this.viewport_w, this.viewport_h, this.resolve_bounds);
233
- }
234
- }
235
- /**
236
- * Re-clamp the stored transform against the current constraint. Called
237
- * from the `constraints` setter; `_set_viewport_size` has its own
238
- * notify-inclusive path.
239
- */
240
- reenforce() {
241
- if (!this._constraints) return;
242
- const next = this.apply_constraints(this._transform);
243
- if (transform_equal(this._transform, next)) return;
244
- this._transform = next;
245
- this.notify();
246
- }
247
- notify() {
248
- for (const cb of this.listeners) cb();
249
- }
250
- };
251
- /**
252
- * Clamp a transform under a `'cover'` constraint:
253
- * - Zoom lower-bounded at fit-with-padding (the slide always fills the
254
- * viewport edge-to-edge).
255
- * - When at min-zoom the slide is locked centered (bounds smaller than
256
- * viewport on the constrained axis is impossible above min_zoom; below
257
- * is impossible because zoom is clamped up).
258
- * - When zoomed in, pan is clamped so the slide always covers the viewport
259
- * (no black bars).
260
- *
261
- * Returns the input transform unchanged when bounds can't be resolved or
262
- * are degenerate.
263
- */
264
- function clamp_cover(t, c, vp_w, vp_h, resolve) {
265
- const bounds = typeof c.bounds === "string" ? resolve(c.bounds) : c.bounds;
266
- if (!bounds || bounds.width <= 0 || bounds.height <= 0) return t;
267
- const padding = c.padding ?? 0;
268
- const eff_w = vp_w - 2 * padding;
269
- const eff_h = vp_h - 2 * padding;
270
- if (eff_w <= 0 || eff_h <= 0) return t;
271
- const min_zoom = Math.min(eff_w / bounds.width, eff_h / bounds.height);
272
- const s = Math.max(t[0][0], min_zoom);
273
- const sw = s * bounds.width;
274
- const sh = s * bounds.height;
275
- const tx = sw > vp_w ? cmath.clamp(t[0][2], vp_w - s * (bounds.x + bounds.width), -s * bounds.x) : (vp_w - sw) / 2 - s * bounds.x;
276
- const ty = sh > vp_h ? cmath.clamp(t[1][2], vp_h - s * (bounds.y + bounds.height), -s * bounds.y) : (vp_h - sh) / 2 - s * bounds.y;
277
- return [[
278
- s,
279
- 0,
280
- tx
281
- ], [
282
- 0,
283
- s,
284
- ty
285
- ]];
286
- }
287
- function transform_equal(a, b) {
288
- return a[0][0] === b[0][0] && a[0][1] === b[0][1] && a[0][2] === b[0][2] && a[1][0] === b[1][0] && a[1][1] === b[1][1] && a[1][2] === b[1][2];
289
- }
290
- //#endregion
291
- //#region src/gestures/gestures.ts
292
- /**
293
- * Sibling to `Keymap`. Owns a list of installed gesture bindings; each
294
- * binding's `install(ctx)` is called eagerly when bound and uninstalled
295
- * on `unbind` or surface detach.
296
- */
297
- var Gestures = class {
298
- constructor(ctx) {
299
- this.ctx = ctx;
300
- this.entries = [];
301
- }
302
- /**
303
- * Install a gesture binding. Returns an unbind function.
304
- * Re-binding the same `id` does NOT replace — both will be active.
305
- * Use `unbind({ id })` first if you want a clean swap.
306
- */
307
- bind(binding) {
308
- const uninstall = binding.install(this.ctx);
309
- const entry = {
310
- binding,
311
- uninstall
312
- };
313
- this.entries.push(entry);
314
- return () => {
315
- const i = this.entries.indexOf(entry);
316
- if (i < 0) return;
317
- this.entries.splice(i, 1);
318
- uninstall();
319
- };
320
- }
321
- /**
322
- * Remove bindings matching the spec. With `{ id }`, all bindings with
323
- * that id are uninstalled. With no spec, this is a no-op (use
324
- * `dispose()` to nuke everything).
325
- */
326
- unbind(spec) {
327
- if (spec.id === void 0) return;
328
- const remaining = [];
329
- for (const entry of this.entries) if (entry.binding.id === spec.id) entry.uninstall();
330
- else remaining.push(entry);
331
- this.entries = remaining;
332
- }
333
- /** All currently installed bindings. Order is registration order. */
334
- bindings() {
335
- return this.entries.map((e) => e.binding);
336
- }
337
- /** @internal Uninstall every binding. Surface calls on detach. */
338
- _dispose() {
339
- for (const entry of this.entries) entry.uninstall();
340
- this.entries = [];
341
- }
342
- };
343
- //#endregion
344
- //#region src/gestures/defaults.ts
345
- /** Default margin for `camera.fit` from keyboard shortcuts. */
346
- const KEYBOARD_FIT_MARGIN = 64;
347
- /** Default zoom step for `Cmd/Ctrl+=` / `Cmd/Ctrl+-`. */
348
- const ZOOM_STEP = 1.2;
349
- /** Per-wheel-unit zoom sensitivity for Cmd/Ctrl+wheel + pinch. */
350
- const WHEEL_ZOOM_SENSITIVITY = .01;
351
- /** Min/max zoom clamps. Generous; hosts that want tighter limits can
352
- * unbind these defaults and bind their own. */
353
- const MIN_ZOOM = .02;
354
- const MAX_ZOOM = 256;
355
- function clamp_zoom(z) {
356
- return cmath.clamp(z, MIN_ZOOM, MAX_ZOOM);
357
- }
358
- /** wheel-pan-zoom: plain wheel = pan, Cmd/Ctrl+wheel + pinch = zoom-at-cursor. */
359
- const WHEEL_PAN_ZOOM = {
360
- id: "wheel-pan-zoom",
361
- install({ container, camera }) {
362
- const on_wheel = (e) => {
363
- e.preventDefault();
364
- if (e.ctrlKey || e.metaKey) {
365
- const factor = 1 - e.deltaY * WHEEL_ZOOM_SENSITIVITY;
366
- const eff = clamp_zoom(camera.zoom * factor) / camera.zoom;
367
- if (eff === 1) return;
368
- const rect = container.getBoundingClientRect();
369
- camera.zoom_at(eff, {
370
- x: e.clientX - rect.left,
371
- y: e.clientY - rect.top
372
- });
373
- } else camera.pan({
374
- x: -e.deltaX,
375
- y: -e.deltaY
376
- });
377
- };
378
- container.addEventListener("wheel", on_wheel, { passive: false });
379
- return () => container.removeEventListener("wheel", on_wheel);
380
- }
381
- };
382
- /**
383
- * Begin a drag-pan from a pointerdown. Attaches `pointermove` / `pointerup`
384
- * listeners scoped to the gesture lifetime, then detaches them on release.
385
- * This is the d3-drag pattern: global listeners only exist while a drag is
386
- * in flight, not for the surface's whole lifetime.
387
- */
388
- function begin_drag_pan(e, container, camera, on_release) {
389
- let last_x = e.clientX;
390
- let last_y = e.clientY;
391
- try {
392
- container.setPointerCapture(e.pointerId);
393
- } catch {}
394
- e.preventDefault();
395
- e.stopPropagation();
396
- const win = container.ownerDocument.defaultView ?? window;
397
- const on_pointermove = (ev) => {
398
- const dx = ev.clientX - last_x;
399
- const dy = ev.clientY - last_y;
400
- last_x = ev.clientX;
401
- last_y = ev.clientY;
402
- camera.pan({
403
- x: dx,
404
- y: dy
405
- });
406
- ev.preventDefault();
407
- ev.stopPropagation();
408
- };
409
- const cleanup = () => {
410
- win.removeEventListener("pointermove", on_pointermove, true);
411
- win.removeEventListener("pointerup", on_pointerup, true);
412
- win.removeEventListener("pointercancel", on_pointerup, true);
413
- on_release?.();
414
- };
415
- const on_pointerup = () => cleanup();
416
- win.addEventListener("pointermove", on_pointermove, true);
417
- win.addEventListener("pointerup", on_pointerup, true);
418
- win.addEventListener("pointercancel", on_pointerup, true);
419
- }
420
- /** The data-driven default set. Order = install order. */
421
- const DEFAULT_GESTURE_BINDINGS = [
422
- WHEEL_PAN_ZOOM,
423
- {
424
- id: "space-drag-pan",
425
- install({ container, camera }) {
426
- let space_held = false;
427
- let prev_cursor = null;
428
- const set_cursor = (next) => {
429
- if (prev_cursor === null) prev_cursor = container.style.cursor;
430
- container.style.cursor = next ?? prev_cursor ?? "";
431
- if (next === null) prev_cursor = null;
432
- };
433
- const on_keydown = (e) => {
434
- if (e.code !== "Space" || e.repeat) return;
435
- if (is_text_input_focused()) return;
436
- space_held = true;
437
- set_cursor("grab");
438
- e.preventDefault();
439
- };
440
- const on_keyup = (e) => {
441
- if (e.code !== "Space") return;
442
- space_held = false;
443
- set_cursor(null);
444
- };
445
- const on_pointerdown = (e) => {
446
- if (!space_held || e.button !== 0) return;
447
- set_cursor("grabbing");
448
- begin_drag_pan(e, container, camera, () => set_cursor(space_held ? "grab" : null));
449
- };
450
- const on_blur = () => {
451
- space_held = false;
452
- set_cursor(null);
453
- };
454
- const win = container.ownerDocument.defaultView ?? window;
455
- win.addEventListener("keydown", on_keydown);
456
- win.addEventListener("keyup", on_keyup);
457
- container.addEventListener("pointerdown", on_pointerdown, true);
458
- win.addEventListener("blur", on_blur);
459
- return () => {
460
- win.removeEventListener("keydown", on_keydown);
461
- win.removeEventListener("keyup", on_keyup);
462
- container.removeEventListener("pointerdown", on_pointerdown, true);
463
- win.removeEventListener("blur", on_blur);
464
- if (prev_cursor !== null) container.style.cursor = prev_cursor;
465
- };
466
- }
467
- },
468
- {
469
- id: "middle-mouse-pan",
470
- install({ container, camera }) {
471
- const on_pointerdown = (e) => {
472
- if (e.button !== 1) return;
473
- begin_drag_pan(e, container, camera);
474
- };
475
- const on_auxclick = (e) => {
476
- if (e.button === 1) e.preventDefault();
477
- };
478
- container.addEventListener("pointerdown", on_pointerdown, true);
479
- container.addEventListener("auxclick", on_auxclick);
480
- return () => {
481
- container.removeEventListener("pointerdown", on_pointerdown, true);
482
- container.removeEventListener("auxclick", on_auxclick);
483
- };
484
- }
485
- },
486
- {
487
- id: "keyboard-zoom",
488
- install({ container, camera }) {
489
- const owner_doc = container.ownerDocument;
490
- const on_keydown = (e) => {
491
- const active = owner_doc.activeElement;
492
- if (active && active !== owner_doc.body && !container.contains(active)) return;
493
- if (is_text_input_focused()) return;
494
- const mod = e.metaKey || e.ctrlKey;
495
- if (e.shiftKey && !mod && (e.code === "Digit0" || e.code === "Numpad0")) {
496
- camera.reset();
497
- e.preventDefault();
498
- } else if (e.shiftKey && !mod && (e.code === "Digit1" || e.code === "Digit9" || e.code === "Numpad1" || e.code === "Numpad9")) {
499
- camera.fit("<root>", { margin: KEYBOARD_FIT_MARGIN });
500
- e.preventDefault();
501
- } else if (e.shiftKey && !mod && (e.code === "Digit2" || e.code === "Numpad2")) {
502
- camera.fit("<selection>", { margin: KEYBOARD_FIT_MARGIN });
503
- e.preventDefault();
504
- } else if (mod && (e.code === "Equal" || e.code === "NumpadAdd")) {
505
- camera.set_zoom(clamp_zoom(camera.zoom * ZOOM_STEP));
506
- e.preventDefault();
507
- } else if (mod && (e.code === "Minus" || e.code === "NumpadSubtract")) {
508
- camera.set_zoom(clamp_zoom(camera.zoom / ZOOM_STEP));
509
- e.preventDefault();
510
- }
511
- };
512
- owner_doc.addEventListener("keydown", on_keydown);
513
- return () => owner_doc.removeEventListener("keydown", on_keydown);
514
- }
515
- }
516
- ];
517
- /** Install every default binding into the gesture layer. */
518
- function applyDefaultGestures(gestures) {
519
- for (const b of DEFAULT_GESTURE_BINDINGS) gestures.bind(b);
520
- }
521
- //#endregion
522
- //#region src/text-surface.ts
523
- const SVG_NS = "http://www.w3.org/2000/svg";
524
- const XML_NS = "http://www.w3.org/XML/1998/namespace";
525
- var SvgTextSurface = class {
526
- constructor(textEl) {
527
- this.prevXmlSpace = void 0;
528
- this.prevPointerEvents = void 0;
529
- this.last_caret_idx = -1;
530
- this.last_caret_visible = false;
531
- this.last_sel_start = -1;
532
- this.last_sel_end = -1;
533
- this.textEl = textEl;
534
- const ownerDoc = textEl.ownerDocument;
535
- const parent = textEl.parentNode;
536
- if (!parent) throw new Error("text element has no parent");
537
- const computedWhitespace = ownerDoc.defaultView?.getComputedStyle(textEl).whiteSpace;
538
- if (!(computedWhitespace === "pre" || computedWhitespace === "pre-wrap" || computedWhitespace === "break-spaces")) {
539
- this.prevXmlSpace = textEl.getAttributeNS(XML_NS, "space");
540
- textEl.setAttributeNS(XML_NS, "xml:space", "preserve");
541
- }
542
- this.prevPointerEvents = textEl.getAttribute("pointer-events");
543
- textEl.setAttribute("pointer-events", "bounding-box");
544
- const selection = ownerDoc.createElementNS(SVG_NS, "rect");
545
- selection.setAttribute("fill", "#2563eb");
546
- selection.setAttribute("fill-opacity", "0.25");
547
- selection.setAttribute("pointer-events", "none");
548
- selection.setAttribute("data-svg-text-edit-selection", "");
549
- selection.style.display = "none";
550
- parent.insertBefore(selection, textEl);
551
- this.selectionRect = selection;
552
- const caret = ownerDoc.createElementNS(SVG_NS, "rect");
553
- caret.setAttribute("fill", "#2563eb");
554
- caret.setAttribute("pointer-events", "none");
555
- caret.setAttribute("data-svg-text-edit-caret", "");
556
- caret.style.display = "none";
557
- parent.insertBefore(caret, textEl.nextSibling);
558
- this.caretRect = caret;
559
- }
560
- setText(text) {
561
- if (this.textEl.textContent !== text) this.textEl.textContent = text;
562
- }
563
- setCaret(index, visible) {
564
- if (index === this.last_caret_idx && visible === this.last_caret_visible) return;
565
- this.last_caret_idx = index;
566
- this.last_caret_visible = visible;
567
- if (!visible) {
568
- this.caretRect.style.display = "none";
569
- return;
570
- }
571
- const m = this.metrics();
572
- const x = this.charX(index);
573
- this.caretRect.setAttribute("x", String(x - .75));
574
- this.caretRect.setAttribute("y", String(m.top));
575
- this.caretRect.setAttribute("width", "1.5");
576
- this.caretRect.setAttribute("height", String(m.height));
577
- this.caretRect.style.display = "block";
578
- }
579
- setSelection(start, end) {
580
- if (start === this.last_sel_start && end === this.last_sel_end) return;
581
- this.last_sel_start = start;
582
- this.last_sel_end = end;
583
- if (start === end) {
584
- this.selectionRect.style.display = "none";
585
- return;
586
- }
587
- const m = this.metrics();
588
- const x1 = this.charX(start);
589
- const x2 = this.charX(end);
590
- this.selectionRect.setAttribute("x", String(Math.min(x1, x2)));
591
- this.selectionRect.setAttribute("y", String(m.top));
592
- this.selectionRect.setAttribute("width", String(Math.abs(x2 - x1)));
593
- this.selectionRect.setAttribute("height", String(m.height));
594
- this.selectionRect.style.display = "block";
595
- }
596
- dispose(keepEditMutations = false) {
597
- this.caretRect.remove();
598
- this.selectionRect.remove();
599
- if (this.prevXmlSpace !== void 0 && !keepEditMutations) if (this.prevXmlSpace === null) this.textEl.removeAttributeNS(XML_NS, "space");
600
- else this.textEl.setAttributeNS(XML_NS, "xml:space", this.prevXmlSpace);
601
- if (this.prevPointerEvents !== void 0) if (this.prevPointerEvents === null) this.textEl.removeAttribute("pointer-events");
602
- else this.textEl.setAttribute("pointer-events", this.prevPointerEvents);
603
- this.prevXmlSpace = void 0;
604
- this.prevPointerEvents = void 0;
605
- }
606
- positionAtPoint(clientX, clientY) {
607
- const ctm = this.textEl.getScreenCTM();
608
- const svg = this.textEl.ownerSVGElement;
609
- if (!ctm || !svg) return 0;
610
- const pt = svg.createSVGPoint();
611
- pt.x = clientX;
612
- pt.y = clientY;
613
- const local = pt.matrixTransform(ctm.inverse());
614
- return this.localXToCharIndex(local.x);
615
- }
616
- /**
617
- * Single-line `<text>` element: there's no "previous visual line" to move
618
- * to. Cocoa single-line convention: Up/PageUp/line_start → doc start;
619
- * Down/PageDown/line_end → doc end.
620
- */
621
- positionForNavigation(_index, direction) {
622
- const text = this.textEl.textContent ?? "";
623
- switch (direction) {
624
- case "up":
625
- case "page_up":
626
- case "line_start": return 0;
627
- case "down":
628
- case "page_down":
629
- case "line_end": return text.length;
630
- }
631
- }
632
- metrics() {
633
- try {
634
- const b = this.textEl.getBBox();
635
- if (b.height > 0) return {
636
- top: b.y,
637
- height: b.height
638
- };
639
- } catch {}
640
- const fontSize = parseFloat(this.textEl.ownerDocument.defaultView?.getComputedStyle(this.textEl).fontSize ?? "16") || 16;
641
- return {
642
- top: parseFloat(this.textEl.getAttribute("y") ?? "0") - fontSize * .85,
643
- height: fontSize
644
- };
645
- }
646
- charX(i) {
647
- const text = this.textEl.textContent ?? "";
648
- const baseX = parseFloat(this.textEl.getAttribute("x") ?? "0");
649
- if (text.length === 0) return baseX;
650
- if (i <= 0) try {
651
- return this.textEl.getStartPositionOfChar(0).x;
652
- } catch {
653
- return baseX;
654
- }
655
- if (i >= text.length) try {
656
- return this.textEl.getEndPositionOfChar(text.length - 1).x;
657
- } catch {
658
- return baseX;
659
- }
660
- try {
661
- return this.textEl.getStartPositionOfChar(i).x;
662
- } catch {
663
- return baseX;
664
- }
665
- }
666
- localXToCharIndex(localX) {
667
- const text = this.textEl.textContent ?? "";
668
- if (!text) return 0;
669
- for (let i = 0; i < text.length; i++) try {
670
- const ext = this.textEl.getExtentOfChar(i);
671
- if (localX < ext.x + ext.width / 2) return i;
672
- } catch {
673
- break;
674
- }
675
- return text.length;
676
- }
677
- };
678
- //#endregion
679
- //#region src/dom.ts
680
- const ID_ATTR = "data-grida-id";
681
- /** KeyboardEvent.key values for the modifiers the surface tracks. Used to
682
- * short-circuit window-level `keydown`/`keyup` for non-modifier keystrokes. */
683
- const IS_MODIFIER_KEY = {
684
- Shift: true,
685
- Alt: true,
686
- Meta: true,
687
- Control: true
688
- };
689
- /** Sentinel placed in `text_edit` before `createTextEditor` returns, so the
690
- * surface skips render() during the in-flight mount and doesn't yank the
691
- * live `<text>` element out from under the about-to-mount text surface. */
692
- const TEXT_EDIT_PENDING = { __pending: true };
693
- /**
694
- * Attach a DOM surface to a headless editor. Returns a `DomSurfaceHandle`
695
- * whose `detach()` is the inverse — DOM cleared, listeners removed,
696
- * gestures uninstalled.
697
- *
698
- * Usage is one-shot per container: the surface owns the container's children
699
- * for its lifetime, and `detach()` restores it to empty.
700
- */
701
- function attach_dom_surface(editor, options) {
702
- const surface = new DomSurface(editor, options);
703
- const inner = editor.attach(surface);
704
- return {
705
- detach: () => {
706
- surface.detach_gestures();
707
- inner.detach();
708
- },
709
- camera: surface.camera,
710
- gestures: surface.gestures
711
- };
712
- }
713
- var DomSurface = class {
714
- constructor(editor, options) {
715
- this.editor = editor;
716
- this.svg_root = null;
717
- this.teardown = [];
718
- this.element_index = /* @__PURE__ */ new Map();
719
- this.resize_observer = null;
720
- this.active_preview = null;
721
- this.text_edit = null;
722
- this.text_edit_target = null;
723
- this.text_edit_original = "";
724
- this.editor_hover_internal = null;
725
- this.container = options.container;
726
- const container = this.container;
727
- this.fit_on_attach = options.fit === true;
728
- if (getComputedStyle(container).position === "static") container.style.position = "relative";
729
- container.style.userSelect = "none";
730
- container.style.webkitUserSelect = "none";
731
- this.hud_canvas = container.ownerDocument.createElement("canvas");
732
- Object.assign(this.hud_canvas.style, {
733
- position: "absolute",
734
- left: "0",
735
- top: "0",
736
- pointerEvents: "none"
737
- });
738
- container.appendChild(this.hud_canvas);
739
- this.hud = new Surface(this.hud_canvas, {
740
- pick: (p) => this.hit_test(p[0], p[1]),
741
- shapeOf: (id) => this.shape_of(id),
742
- onIntent: (i) => this.commit_intent(i),
743
- style: { chromeColor: editor.style.chrome_color }
744
- });
745
- this.camera = new Camera({
746
- resolve_bounds: (target) => this.resolve_world_bounds(target),
747
- initial: options.initial_camera
748
- });
749
- this.teardown.push(this.camera.subscribe(() => {
750
- this.apply_camera_transform();
751
- this.redraw();
752
- }));
753
- this.render();
754
- this.sync_canvas_size();
755
- this.sync_surface_selection();
756
- this.redraw();
757
- const win = container.ownerDocument.defaultView ?? window;
758
- const raf = win.requestAnimationFrame(() => {
759
- this.sync_canvas_size();
760
- this.honor_initial_fit();
761
- this.redraw();
762
- });
763
- this.teardown.push(() => win.cancelAnimationFrame(raf));
764
- this.gestures = new Gestures({
765
- container,
766
- svg_root: () => this.svg_root,
767
- hud_canvas: this.hud_canvas,
768
- camera: this.camera,
769
- editor,
770
- handle: { detach: () => {} }
771
- });
772
- if (options.gestures !== false) applyDefaultGestures(this.gestures);
773
- const unsub = editor.subscribe(() => {
774
- this.render();
775
- this.sync_surface_selection();
776
- this.sync_canvas_size();
777
- });
778
- this.teardown.push(unsub);
779
- if (typeof ResizeObserver !== "undefined") {
780
- this.resize_observer = new ResizeObserver(() => this.sync_canvas_size());
781
- this.resize_observer.observe(container);
782
- this.teardown.push(() => this.resize_observer?.disconnect());
783
- } else {
784
- const win = container.ownerDocument.defaultView ?? window;
785
- const fn = () => this.sync_canvas_size();
786
- win.addEventListener("resize", fn);
787
- this.teardown.push(() => win.removeEventListener("resize", fn));
788
- }
789
- this.wire_events();
790
- const internal = editor._internal;
791
- this.editor_hover_internal = internal;
792
- internal.set_content_edit_driver((id) => this.enter_content_edit(id));
793
- this.teardown.push(() => internal.set_content_edit_driver(null));
794
- internal.set_computed_resolver({
795
- computed_property: (id, name) => {
796
- const el = this.element_index.get(id);
797
- if (!el) return null;
798
- const value = getComputedStyle(el).getPropertyValue(name);
799
- return value === "" ? null : value;
800
- },
801
- computed_paint: (id, channel) => {
802
- const el = this.element_index.get(id);
803
- if (!el) return null;
804
- const computed = getComputedStyle(el).getPropertyValue(channel);
805
- if (computed === "") return null;
806
- return {
807
- computed,
808
- resolved_paint: parse_paint(computed)
809
- };
810
- }
811
- });
812
- this.teardown.push(() => internal.set_computed_resolver(null));
813
- internal.set_surface_hover_override_driver((id) => {
814
- const response = this.hud.setHoverOverride(id);
815
- if (response.hoverChanged) internal.push_surface_hover(this.hud.hover());
816
- if (response.needsRedraw) this.redraw();
817
- });
818
- this.teardown.push(() => internal.set_surface_hover_override_driver(null));
819
- }
820
- paint(_snapshot) {}
821
- hit_test(x, y) {
822
- const owner_doc = this.container.ownerDocument;
823
- const cr = this.container.getBoundingClientRect();
824
- const target = owner_doc.elementFromPoint(cr.left + x, cr.top + y);
825
- if (!(target instanceof SVGElement)) return null;
826
- const root_id = this.editor.tree().root;
827
- let cur = target;
828
- while (cur instanceof Element) {
829
- const id = cur.getAttribute(ID_ATTR);
830
- if (id) return id === root_id ? null : id;
831
- cur = cur.parentElement;
832
- }
833
- return null;
834
- }
835
- on_input(_listener) {
836
- return () => {};
837
- }
838
- dispose() {
839
- if (this.text_edit) {
840
- this.text_edit.cancel();
841
- this.text_edit = null;
842
- this.text_edit_target = null;
843
- }
844
- this.gestures._dispose();
845
- for (const fn of this.teardown) fn();
846
- this.teardown = [];
847
- this.hud.dispose();
848
- this.hud_canvas.remove();
849
- if (this.svg_root) this.svg_root.remove();
850
- this.svg_root = null;
851
- this.element_index.clear();
852
- this.active_preview = null;
853
- }
854
- /** Public — invoked by the `DomSurfaceHandle` wrapper before `detach()`. */
855
- detach_gestures() {
856
- this.gestures._dispose();
857
- }
858
- render() {
859
- if (this.text_edit) return;
860
- const owner_doc = this.container.ownerDocument;
861
- const doc = this.editor._internal.doc;
862
- const svg_text = this.editor.serialize();
863
- const wrapper = owner_doc.createElement("div");
864
- wrapper.innerHTML = svg_text;
865
- const new_svg = wrapper.querySelector("svg");
866
- if (!(new_svg instanceof SVGSVGElement)) return;
867
- if (this.svg_root) this.svg_root.replaceWith(new_svg);
868
- else this.container.insertBefore(new_svg, this.hud_canvas);
869
- this.svg_root = new_svg;
870
- this.apply_svg_layout();
871
- this.apply_camera_transform();
872
- this.element_index.clear();
873
- const ids = doc.all_elements();
874
- let i = 0;
875
- const tag_walk = (el) => {
876
- if (i < ids.length) {
877
- const id = ids[i++];
878
- el.setAttribute(ID_ATTR, id);
879
- this.element_index.set(id, el);
880
- }
881
- for (let c = el.firstElementChild; c; c = c.nextElementSibling) if (c instanceof SVGElement) tag_walk(c);
882
- };
883
- tag_walk(new_svg);
884
- }
885
- sync_canvas_size() {
886
- const cr = this.container.getBoundingClientRect();
887
- this.hud.setSize(cr.width, cr.height);
888
- this.camera._set_viewport_size(cr.width, cr.height);
889
- this.redraw();
890
- }
891
- /**
892
- * Apply absolute positioning + transform-origin to the SVG so the camera's
893
- * CSS matrix maps SVG-coord (0,0) cleanly to container-screen (tx, ty).
894
- * Called after every render() that may have replaced the root element.
895
- */
896
- apply_svg_layout() {
897
- if (!this.svg_root) return;
898
- const style = this.svg_root.style;
899
- style.position = "absolute";
900
- style.left = "0";
901
- style.top = "0";
902
- style.transformOrigin = "0 0";
903
- }
904
- /**
905
- * Push the current camera transform to the SVG as a CSS `matrix(...)`.
906
- * The HUD canvas stays at identity — selection chrome reads node bounds
907
- * via `getScreenCTM()`, which already includes the CSS transform, so
908
- * chrome aligns automatically and stays 1px sharp at any zoom.
909
- */
910
- apply_camera_transform() {
911
- if (!this.svg_root) return;
912
- const t = this.camera.transform;
913
- this.svg_root.style.transform = `matrix(${t[0][0]}, ${t[1][0]}, ${t[0][1]}, ${t[1][1]}, ${t[0][2]}, ${t[1][2]})`;
914
- }
915
- /** One-shot fit-on-attach. Runs after layout has settled. */
916
- honor_initial_fit() {
917
- if (!this.fit_on_attach) return;
918
- this.fit_on_attach = false;
919
- this.camera.fit("<root>");
920
- }
921
- /**
922
- * BoundsResolver for `Camera.fit(target)`. The Camera class handles Rect
923
- * passthrough itself; this resolver only sees string targets — sentinels
924
- * ("<root>", "<selection>") and NodeIds.
925
- */
926
- resolve_world_bounds(target) {
927
- if (target === "<root>") return this.root_world_bounds();
928
- if (target === "<selection>") {
929
- const sel = this.editor.state.selection;
930
- if (sel.length === 0) return null;
931
- const rects = [];
932
- for (const id of sel) {
933
- const r = this.node_world_bounds(id);
934
- if (r) rects.push(r);
935
- }
936
- if (rects.length === 0) return null;
937
- return cmath.rect.union(rects);
938
- }
939
- return this.node_world_bounds(target);
940
- }
941
- /**
942
- * World-space bounds of the root document. Prefer `viewBox` (the SVG's
943
- * declared world rect), fall back to `width`/`height` attrs, then the
944
- * SVG root's `getBBox()` as a last resort.
945
- */
946
- root_world_bounds() {
947
- const root_id = this.editor.tree().root;
948
- const doc = this.editor.document;
949
- const view_box = doc.get_attr(root_id, "viewBox");
950
- if (view_box) {
951
- const parts = view_box.trim().split(/[\s,]+/).map(Number);
952
- if (parts.length === 4 && parts.every((n) => Number.isFinite(n))) return {
953
- x: parts[0],
954
- y: parts[1],
955
- width: parts[2],
956
- height: parts[3]
957
- };
958
- }
959
- const w = parseFloat(doc.get_attr(root_id, "width") ?? "");
960
- const h = parseFloat(doc.get_attr(root_id, "height") ?? "");
961
- if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) return {
962
- x: 0,
963
- y: 0,
964
- width: w,
965
- height: h
966
- };
967
- if (this.svg_root) try {
968
- const b = this.svg_root.getBBox();
969
- if (b.width > 0 && b.height > 0) return {
970
- x: b.x,
971
- y: b.y,
972
- width: b.width,
973
- height: b.height
974
- };
975
- } catch {}
976
- return null;
977
- }
978
- /**
979
- * World-space bounds of a single node. Uses `getBBox()` (element-local)
980
- * and projects through `getCTM()` (local → nearest viewport = SVG root).
981
- */
982
- node_world_bounds(id) {
983
- const el = this.element_index.get(id);
984
- if (!el) return null;
985
- const ge = el;
986
- if (typeof ge.getBBox !== "function" || typeof ge.getCTM !== "function") return null;
987
- let bbox;
988
- try {
989
- const b = ge.getBBox();
990
- bbox = {
991
- x: b.x,
992
- y: b.y,
993
- width: b.width,
994
- height: b.height
995
- };
996
- } catch {
997
- return null;
998
- }
999
- const ctm = ge.getCTM();
1000
- if (!ctm) return bbox;
1001
- const project = (px, py) => ({
1002
- x: ctm.a * px + ctm.c * py + ctm.e,
1003
- y: ctm.b * px + ctm.d * py + ctm.f
1004
- });
1005
- const corners = [
1006
- project(bbox.x, bbox.y),
1007
- project(bbox.x + bbox.width, bbox.y),
1008
- project(bbox.x + bbox.width, bbox.y + bbox.height),
1009
- project(bbox.x, bbox.y + bbox.height)
1010
- ];
1011
- const xs = corners.map((c) => c.x);
1012
- const ys = corners.map((c) => c.y);
1013
- const left = Math.min(...xs);
1014
- const top = Math.min(...ys);
1015
- const right = Math.max(...xs);
1016
- const bottom = Math.max(...ys);
1017
- return {
1018
- x: left,
1019
- y: top,
1020
- width: right - left,
1021
- height: bottom - top
1022
- };
1023
- }
1024
- /** Single per-frame draw entry — merges host-fed extras with surface chrome. */
1025
- redraw() {
1026
- this.hud.draw(this.compute_measurement_extra());
1027
- }
1028
- /**
1029
- * Build the host-fed measurement guide for the current frame, or
1030
- * `undefined` if no guide should be drawn.
1031
- *
1032
- * Master signal: Alt held (read from `surface.modifiers()`). Each
1033
- * additional condition is a derivation, not a separate flag — this keeps
1034
- * a single source of truth and lets future Alt-consumers (constrained
1035
- * resize, axis-lock, …) live next to this one without re-tracking the key.
1036
- */
1037
- compute_measurement_extra() {
1038
- if (!this.hud.modifiers().alt) return void 0;
1039
- if (this.hud.gesture().kind !== "idle") return void 0;
1040
- const sel = this.editor.state.selection;
1041
- if (sel.length === 0) return void 0;
1042
- const hover = this.hud.hover();
1043
- if (!hover) return void 0;
1044
- if (sel.includes(hover)) return void 0;
1045
- const a_rects = sel.map((id) => this.container_box(id)).filter((r) => r !== null);
1046
- if (a_rects.length === 0) return void 0;
1047
- const b_rect = this.container_box(hover);
1048
- if (!b_rect) return void 0;
1049
- const m = measure(cmath.rect.union(a_rects), b_rect);
1050
- if (!m) return void 0;
1051
- return measurementToHUDDraw(m, this.editor.style.measurement_color);
1052
- }
1053
- sync_surface_selection() {
1054
- const state = this.editor.state;
1055
- if (state.mode === "edit-content") {
1056
- this.hud.setSelection([]);
1057
- return;
1058
- }
1059
- this.hud.setSelection(state.selection);
1060
- }
1061
- /**
1062
- * Return the selection shape for a node. Vector `<line>` nodes return
1063
- * `{ kind: "line", p1, p2 }` so the HUD lays out endpoint knobs; all
1064
- * other nodes return `{ kind: "rect", rect }` using the container-space
1065
- * bounding box.
1066
- */
1067
- shape_of(id) {
1068
- if (this.tag_of(id) === "line") {
1069
- const line = this.line_endpoints_in_container(id);
1070
- if (line) return {
1071
- kind: "line",
1072
- p1: line.p1,
1073
- p2: line.p2
1074
- };
1075
- }
1076
- const rect = this.container_box(id);
1077
- if (!rect) return null;
1078
- return {
1079
- kind: "rect",
1080
- rect
1081
- };
1082
- }
1083
- /**
1084
- * Project an SVG `<line>`'s `x1,y1,x2,y2` from its own coordinate space
1085
- * to the container's coordinate space, where the HUD operates.
1086
- */
1087
- line_endpoints_in_container(id) {
1088
- const el = this.element_index.get(id);
1089
- if (!(el instanceof SVGGraphicsElement)) return null;
1090
- if (typeof el.getScreenCTM !== "function") return null;
1091
- const ctm = el.getScreenCTM();
1092
- if (!ctm || !this.svg_root) return null;
1093
- const x1 = parseFloat(el.getAttribute("x1") ?? "0");
1094
- const y1 = parseFloat(el.getAttribute("y1") ?? "0");
1095
- const x2 = parseFloat(el.getAttribute("x2") ?? "0");
1096
- const y2 = parseFloat(el.getAttribute("y2") ?? "0");
1097
- if (!Number.isFinite(x1) || !Number.isFinite(y1)) return null;
1098
- if (!Number.isFinite(x2) || !Number.isFinite(y2)) return null;
1099
- const project = (px, py) => {
1100
- return [ctm.a * px + ctm.c * py + ctm.e, ctm.b * px + ctm.d * py + ctm.f];
1101
- };
1102
- const cr = this.container.getBoundingClientRect();
1103
- const [s1x, s1y] = project(x1, y1);
1104
- const [s2x, s2y] = project(x2, y2);
1105
- return {
1106
- p1: [s1x - cr.left + this.container.scrollLeft, s1y - cr.top + this.container.scrollTop],
1107
- p2: [s2x - cr.left + this.container.scrollLeft, s2y - cr.top + this.container.scrollTop]
1108
- };
1109
- }
1110
- container_box(id) {
1111
- const el = this.element_index.get(id);
1112
- if (!el) return null;
1113
- const ge = el;
1114
- if (typeof ge.getBBox !== "function" || typeof ge.getScreenCTM !== "function") return null;
1115
- let bbox;
1116
- try {
1117
- const b = ge.getBBox();
1118
- bbox = {
1119
- x: b.x,
1120
- y: b.y,
1121
- width: b.width,
1122
- height: b.height
1123
- };
1124
- } catch {
1125
- return null;
1126
- }
1127
- const ctm = ge.getScreenCTM();
1128
- if (!ctm) return null;
1129
- const project = (px, py) => ({
1130
- x: ctm.a * px + ctm.c * py + ctm.e,
1131
- y: ctm.b * px + ctm.d * py + ctm.f
1132
- });
1133
- const corners = [
1134
- project(bbox.x, bbox.y),
1135
- project(bbox.x + bbox.width, bbox.y),
1136
- project(bbox.x + bbox.width, bbox.y + bbox.height),
1137
- project(bbox.x, bbox.y + bbox.height)
1138
- ];
1139
- const xs = corners.map((c) => c.x);
1140
- const ys = corners.map((c) => c.y);
1141
- const left = Math.min(...xs);
1142
- const top = Math.min(...ys);
1143
- const right = Math.max(...xs);
1144
- const bottom = Math.max(...ys);
1145
- const cr = this.container.getBoundingClientRect();
1146
- return {
1147
- x: left - cr.left + this.container.scrollLeft,
1148
- y: top - cr.top + this.container.scrollTop,
1149
- width: right - left,
1150
- height: bottom - top
1151
- };
1152
- }
1153
- screen_delta_in_own_frame(id, dx, dy) {
1154
- const el = this.element_index.get(id);
1155
- if (!el) return {
1156
- x: dx,
1157
- y: dy
1158
- };
1159
- return this.unproject_delta(el, dx, dy);
1160
- }
1161
- screen_delta_in_parent_frame(id, dx, dy) {
1162
- const el = this.element_index.get(id);
1163
- if (!el) return {
1164
- x: dx,
1165
- y: dy
1166
- };
1167
- const parent = el.parentNode ?? el;
1168
- return this.unproject_delta(parent, dx, dy);
1169
- }
1170
- unproject_delta(frame, dx, dy) {
1171
- const ctm = typeof frame.getScreenCTM === "function" ? frame.getScreenCTM() : null;
1172
- if (!ctm || !this.svg_root) return {
1173
- x: dx,
1174
- y: dy
1175
- };
1176
- const inv = ctm.inverse();
1177
- const p0 = this.svg_root.createSVGPoint();
1178
- p0.x = 0;
1179
- p0.y = 0;
1180
- const p1 = this.svg_root.createSVGPoint();
1181
- p1.x = dx;
1182
- p1.y = dy;
1183
- const tp0 = p0.matrixTransform(inv);
1184
- const tp1 = p1.matrixTransform(inv);
1185
- return {
1186
- x: tp1.x - tp0.x,
1187
- y: tp1.y - tp0.y
1188
- };
1189
- }
1190
- wire_events() {
1191
- const owner_doc = this.container.ownerDocument;
1192
- const win = owner_doc.defaultView ?? window;
1193
- const on = (target, event, handler) => {
1194
- target.addEventListener(event, handler);
1195
- this.teardown.push(() => target.removeEventListener(event, handler));
1196
- };
1197
- on(this.container, "pointerdown", (e) => this.dispatch_pointer(e, "pointer_down"));
1198
- on(win, "pointermove", (e) => this.dispatch_pointer(e, "pointer_move"));
1199
- on(win, "pointerup", (e) => this.dispatch_pointer(e, "pointer_up"));
1200
- on(owner_doc, "keydown", (e) => this.on_keydown(e));
1201
- on(win, "keydown", (e) => {
1202
- if (e.repeat || !IS_MODIFIER_KEY[e.key]) return;
1203
- this.sync_modifiers(e);
1204
- });
1205
- on(win, "keyup", (e) => {
1206
- if (!IS_MODIFIER_KEY[e.key]) return;
1207
- this.sync_modifiers(e);
1208
- });
1209
- on(win, "blur", () => this.sync_modifiers(null));
1210
- on(this.container, "contextmenu", (e) => e.preventDefault());
1211
- }
1212
- /**
1213
- * Master signal for modifier-driven UX consumers (measurement, future
1214
- * constrained-resize, …). Modifier changes aren't on the pointer-event
1215
- * path, so derived overlays would otherwise wait for the next pointer
1216
- * move; redraw eagerly. `null` means modifiers are forced clear
1217
- * (blur / focus-out).
1218
- */
1219
- sync_modifiers(e) {
1220
- const next = e ? {
1221
- shift: e.shiftKey,
1222
- alt: e.altKey,
1223
- meta: e.metaKey,
1224
- ctrl: e.ctrlKey
1225
- } : NO_MODS;
1226
- const prev = this.hud.modifiers();
1227
- if (prev.shift === next.shift && prev.alt === next.alt && prev.meta === next.meta && prev.ctrl === next.ctrl) return;
1228
- const response = this.hud.dispatch({
1229
- kind: "modifiers",
1230
- mods: next
1231
- });
1232
- this.redraw();
1233
- if (response.cursorChanged) this.sync_cursor();
1234
- if (response.hoverChanged) this.editor_hover_internal?.push_surface_hover(this.hud.hover());
1235
- }
1236
- dispatch_pointer(e, kind) {
1237
- if (this.text_edit) {
1238
- if (kind === "pointer_down") {
1239
- e.preventDefault();
1240
- const el = this.text_edit_target ? this.element_index.get(this.text_edit_target) : null;
1241
- if (el && e.target instanceof Element && (e.target === el || el.contains(e.target))) this.text_edit.pointerDown(e.clientX, e.clientY, e.shiftKey);
1242
- else this.text_edit.commit();
1243
- } else if (kind === "pointer_move") this.text_edit.pointerMove(e.clientX, e.clientY);
1244
- else if (kind === "pointer_up") this.text_edit.pointerUp();
1245
- return;
1246
- }
1247
- const cr = this.container.getBoundingClientRect();
1248
- const x = e.clientX - cr.left;
1249
- const y = e.clientY - cr.top;
1250
- const mods = {
1251
- shift: e.shiftKey,
1252
- alt: e.altKey,
1253
- meta: e.metaKey,
1254
- ctrl: e.ctrlKey
1255
- };
1256
- const button = e.button === 0 ? "primary" : e.button === 2 ? "secondary" : "middle";
1257
- let event;
1258
- if (kind === "pointer_move") event = {
1259
- kind,
1260
- x,
1261
- y,
1262
- mods
1263
- };
1264
- else {
1265
- event = {
1266
- kind,
1267
- x,
1268
- y,
1269
- button,
1270
- mods
1271
- };
1272
- if (kind === "pointer_down") try {
1273
- this.container.setPointerCapture(e.pointerId);
1274
- } catch {}
1275
- }
1276
- const response = this.hud.dispatch(event);
1277
- if (response.needsRedraw) this.redraw();
1278
- if (response.cursorChanged) this.sync_cursor();
1279
- if (response.hoverChanged) this.editor_hover_internal?.push_surface_hover(this.hud.hover());
1280
- }
1281
- sync_cursor() {
1282
- const c = this.hud.cursor();
1283
- let css = "default";
1284
- if (typeof c === "string") css = c === "default" ? "default" : c;
1285
- else if (c.kind === "resize") css = `${c.direction}-resize`;
1286
- else if (c.kind === "rotate") css = "crosshair";
1287
- this.container.style.cursor = css;
1288
- }
1289
- on_keydown(e) {
1290
- if (this.text_edit) return;
1291
- if (e.code === "Escape" && this.active_preview) {
1292
- this.active_preview.session.discard();
1293
- this.active_preview = null;
1294
- }
1295
- this.editor.keymap.dispatch(e);
1296
- }
1297
- commit_intent(intent) {
1298
- switch (intent.kind) {
1299
- case "select":
1300
- this.editor.commands.select(intent.ids, { additive: intent.mode !== "replace" });
1301
- return;
1302
- case "deselect_all":
1303
- this.editor.commands.deselect();
1304
- return;
1305
- case "translate":
1306
- this.handle_translate(intent);
1307
- return;
1308
- case "resize":
1309
- this.handle_resize(intent);
1310
- return;
1311
- case "rotate": return;
1312
- case "marquee_select":
1313
- this.handle_marquee(intent);
1314
- return;
1315
- case "set_endpoint":
1316
- this.handle_set_endpoint(intent);
1317
- return;
1318
- case "enter_content_edit":
1319
- this.editor.commands.select(intent.id);
1320
- this.editor.enter_content_edit(intent.id);
1321
- return;
1322
- case "cancel_gesture":
1323
- if (this.active_preview) {
1324
- this.active_preview.session.discard();
1325
- this.active_preview = null;
1326
- }
1327
- return;
1328
- }
1329
- }
1330
- handle_translate(intent) {
1331
- const ids = intent.ids;
1332
- if (ids.length === 0) return;
1333
- const internal = this.editor_internal();
1334
- const doc = internal.doc;
1335
- const emit = internal.emit;
1336
- if (!this.active_preview || this.active_preview.kind !== "translate") {
1337
- if (this.active_preview) this.active_preview.session.discard();
1338
- const baselines = /* @__PURE__ */ new Map();
1339
- for (const id of ids) baselines.set(id, capture_translate_baseline(doc, id));
1340
- this.active_preview = {
1341
- kind: "translate",
1342
- ids,
1343
- baselines,
1344
- session: internal.history.preview("move")
1345
- };
1346
- }
1347
- const baselines = this.active_preview.baselines;
1348
- const deltas = /* @__PURE__ */ new Map();
1349
- for (const id of ids) deltas.set(id, this.screen_delta_in_parent_frame(id, intent.dx, intent.dy));
1350
- const apply = () => {
1351
- for (const id of ids) {
1352
- const baseline = baselines.get(id);
1353
- const d = deltas.get(id);
1354
- if (!baseline || !d) continue;
1355
- apply_translate(doc, id, baseline, d.x, d.y);
1356
- }
1357
- emit();
1358
- };
1359
- const revert = () => {
1360
- for (const id of ids) {
1361
- const baseline = baselines.get(id);
1362
- if (!baseline) continue;
1363
- apply_translate(doc, id, baseline, 0, 0);
1364
- }
1365
- emit();
1366
- };
1367
- this.active_preview.session.set({
1368
- providerId: "svg-editor",
1369
- apply,
1370
- revert
1371
- });
1372
- if (intent.phase === "commit") {
1373
- this.active_preview.session.commit();
1374
- this.active_preview = null;
1375
- }
1376
- }
1377
- handle_resize(intent) {
1378
- const id = intent.ids[0];
1379
- if (!id || !is_resizable(this.tag_of(id))) return;
1380
- const internal = this.editor_internal();
1381
- const doc = internal.doc;
1382
- const emit = internal.emit;
1383
- if (!this.active_preview || this.active_preview.kind !== "resize" || this.active_preview.id !== id) {
1384
- if (this.active_preview) this.active_preview.session.discard();
1385
- const bbox = this.bbox_local(id) ?? {
1386
- x: 0,
1387
- y: 0,
1388
- width: 0,
1389
- height: 0
1390
- };
1391
- const initial_screen = this.container_box(id) ?? {
1392
- x: 0,
1393
- y: 0,
1394
- width: 0,
1395
- height: 0
1396
- };
1397
- this.active_preview = {
1398
- kind: "resize",
1399
- id,
1400
- direction: intent.anchor,
1401
- baseline: capture_resize_baseline(doc, id, bbox),
1402
- initial_screen,
1403
- session: internal.history.preview("resize")
1404
- };
1405
- }
1406
- const baseline = this.active_preview.baseline;
1407
- const dir = this.active_preview.direction;
1408
- const initial = this.active_preview.initial_screen;
1409
- const dx_screen = intent.rect.width - initial.width;
1410
- const dy_screen = intent.rect.height - initial.height;
1411
- const signed_dx = dir === "w" || dir === "nw" || dir === "sw" ? -dx_screen : dx_screen;
1412
- const signed_dy = dir === "n" || dir === "ne" || dir === "nw" ? -dy_screen : dy_screen;
1413
- const d = this.screen_delta_in_own_frame(id, signed_dx, signed_dy);
1414
- const f = compute_resize_factors(baseline, dir, d.x, d.y, false);
1415
- const apply = () => {
1416
- apply_resize(doc, id, baseline, f.sx, f.sy, f.origin);
1417
- emit();
1418
- };
1419
- const revert = () => {
1420
- apply_resize(doc, id, baseline, 1, 1, f.origin);
1421
- emit();
1422
- };
1423
- this.active_preview.session.set({
1424
- providerId: "svg-editor",
1425
- apply,
1426
- revert
1427
- });
1428
- if (intent.phase === "commit") {
1429
- this.active_preview.session.commit();
1430
- this.active_preview = null;
1431
- }
1432
- }
1433
- /**
1434
- * Apply a `set_endpoint` intent — moving one endpoint of a vector
1435
- * `<line>` to a new container-space position. Unprojects to the element's
1436
- * own (SVG) coord space and updates the corresponding attribute.
1437
- */
1438
- handle_set_endpoint(intent) {
1439
- const id = intent.id;
1440
- if (this.tag_of(id) !== "line") return;
1441
- const internal = this.editor_internal();
1442
- const doc = internal.doc;
1443
- const emit = internal.emit;
1444
- if (!this.active_preview || this.active_preview.kind !== "endpoint" || this.active_preview.id !== id || this.active_preview.endpoint !== intent.endpoint) {
1445
- if (this.active_preview) this.active_preview.session.discard();
1446
- const initial = {
1447
- x1: numAttr(doc, id, "x1"),
1448
- y1: numAttr(doc, id, "y1"),
1449
- x2: numAttr(doc, id, "x2"),
1450
- y2: numAttr(doc, id, "y2")
1451
- };
1452
- this.active_preview = {
1453
- kind: "endpoint",
1454
- id,
1455
- endpoint: intent.endpoint,
1456
- initial,
1457
- session: internal.history.preview("set-endpoint")
1458
- };
1459
- }
1460
- const initial = this.active_preview.initial;
1461
- const endpoint = this.active_preview.endpoint;
1462
- const pos_own = this.container_point_in_own_frame(id, intent.pos[0], intent.pos[1]);
1463
- if (!pos_own) return;
1464
- const target_x = pos_own.x;
1465
- const target_y = pos_own.y;
1466
- const apply = () => {
1467
- if (endpoint === "p1") {
1468
- doc.set_attr(id, "x1", String(target_x));
1469
- doc.set_attr(id, "y1", String(target_y));
1470
- } else {
1471
- doc.set_attr(id, "x2", String(target_x));
1472
- doc.set_attr(id, "y2", String(target_y));
1473
- }
1474
- emit();
1475
- };
1476
- const revert = () => {
1477
- doc.set_attr(id, "x1", String(initial.x1));
1478
- doc.set_attr(id, "y1", String(initial.y1));
1479
- doc.set_attr(id, "x2", String(initial.x2));
1480
- doc.set_attr(id, "y2", String(initial.y2));
1481
- emit();
1482
- };
1483
- this.active_preview.session.set({
1484
- providerId: "svg-editor",
1485
- apply,
1486
- revert
1487
- });
1488
- if (intent.phase === "commit") {
1489
- this.active_preview.session.commit();
1490
- this.active_preview = null;
1491
- }
1492
- }
1493
- /**
1494
- * Convert a container-space point to the element's own SVG coord space.
1495
- * Inverse of `line_endpoints_in_container`'s projection.
1496
- */
1497
- container_point_in_own_frame(id, cx, cy) {
1498
- const el = this.element_index.get(id);
1499
- if (!(el instanceof SVGGraphicsElement)) return null;
1500
- if (typeof el.getScreenCTM !== "function") return null;
1501
- const ctm = el.getScreenCTM();
1502
- if (!ctm || !this.svg_root) return null;
1503
- const cr = this.container.getBoundingClientRect();
1504
- const inv = ctm.inverse();
1505
- const p = this.svg_root.createSVGPoint();
1506
- p.x = cx + cr.left - this.container.scrollLeft;
1507
- p.y = cy + cr.top - this.container.scrollTop;
1508
- const t = p.matrixTransform(inv);
1509
- return {
1510
- x: t.x,
1511
- y: t.y
1512
- };
1513
- }
1514
- handle_marquee(intent) {
1515
- if (intent.phase !== "commit") return;
1516
- const ids = [];
1517
- for (const [id, el] of this.element_index) {
1518
- if (id === this.editor.tree().root) continue;
1519
- const box = this.container_box(id);
1520
- if (!box) continue;
1521
- if (rect_intersects(box, intent.rect)) ids.push(id);
1522
- }
1523
- if (ids.length === 0) {
1524
- if (!intent.additive) this.editor.commands.deselect();
1525
- return;
1526
- }
1527
- this.editor.commands.select(ids, { additive: intent.additive });
1528
- }
1529
- enter_content_edit(id) {
1530
- if (this.text_edit) return false;
1531
- const el = this.element_index.get(id);
1532
- if (!(el instanceof SVGTextElement)) return false;
1533
- const doc = this.editor._internal;
1534
- this.text_edit_target = id;
1535
- this.text_edit_original = doc.doc.text_of(id);
1536
- this.text_edit = TEXT_EDIT_PENDING;
1537
- this.editor.commands.set_mode("edit-content");
1538
- this.sync_surface_selection();
1539
- this.redraw();
1540
- const text_surface = new SvgTextSurface(this.element_index.get(id) ?? el);
1541
- const is_mac = typeof navigator !== "undefined" && /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);
1542
- let settled = false;
1543
- const cleanup_after_commit_or_cancel = () => {
1544
- this.text_edit = null;
1545
- this.text_edit_target = null;
1546
- this.editor.commands.set_mode("select");
1547
- this.render();
1548
- this.sync_surface_selection();
1549
- this.redraw();
1550
- };
1551
- this.text_edit = createTextEditor({
1552
- container: this.container,
1553
- initialText: this.text_edit_original,
1554
- layout: text_surface,
1555
- surface: text_surface,
1556
- isMac: is_mac,
1557
- ariaLabel: "edit svg text",
1558
- requiresMutationsForCommit: (text) => /\s{2,}|^\s|\s$/.test(text),
1559
- callbacks: {
1560
- onChange: (text) => {
1561
- doc.doc.set_text(id, text);
1562
- },
1563
- onCommit: (final_text) => {
1564
- if (settled) return;
1565
- settled = true;
1566
- doc.doc.set_text(id, this.text_edit_original);
1567
- cleanup_after_commit_or_cancel();
1568
- if (final_text !== this.text_edit_original) this.editor.commands.set_text(final_text);
1569
- },
1570
- onCancel: () => {
1571
- if (settled) return;
1572
- settled = true;
1573
- doc.doc.set_text(id, this.text_edit_original);
1574
- cleanup_after_commit_or_cancel();
1575
- doc.emit();
1576
- },
1577
- onUndoFallthrough: () => {
1578
- this.text_edit?.commit();
1579
- this.editor.commands.undo();
1580
- },
1581
- onRedoFallthrough: () => {
1582
- this.text_edit?.commit();
1583
- this.editor.commands.redo();
1584
- }
1585
- }
1586
- });
1587
- return true;
1588
- }
1589
- tag_of(id) {
1590
- return this.editor.tree().nodes.get(id)?.tag ?? "";
1591
- }
1592
- bbox_local(id) {
1593
- const el = this.element_index.get(id);
1594
- if (!el) return null;
1595
- const ge = el;
1596
- if (typeof ge.getBBox !== "function") return null;
1597
- try {
1598
- const b = ge.getBBox();
1599
- return {
1600
- x: b.x,
1601
- y: b.y,
1602
- width: b.width,
1603
- height: b.height
1604
- };
1605
- } catch {
1606
- return null;
1607
- }
1608
- }
1609
- editor_internal() {
1610
- return this.editor._internal;
1611
- }
1612
- };
1613
- function numAttr(doc, id, name) {
1614
- const v = doc.get_attr(id, name);
1615
- if (v === null || v === "") return 0;
1616
- const n = parseFloat(v);
1617
- return Number.isFinite(n) ? n : 0;
1618
- }
1619
- function rect_intersects(a, b) {
1620
- return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
1621
- }
1622
- //#endregion
1623
- export { attach_dom_surface as t };