@grida/svg-editor 1.0.0-alpha.13 → 1.0.0-alpha.14

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.
@@ -1,6 +1,7 @@
1
- import { A as is_text_input_focused, C as hit_shape_of_doc, O as STRUCTURAL_GRAPHICS_SET, S as is_resizable_node, T as project_local_bbox, b as compute_resize_factors, d as NudgeDwellWatcher, f as TranslateOrchestrator, h as apply_resize, i as initial_attrs, l as RotateOrchestrator, n as default_attrs, o as TOOL_CURSOR, s as parse_paint, t as compute_drag_attrs, v as capture_resize_baseline, w as is_transparent_tag } from "./insertions-Okcuo-Ck.mjs";
1
+ import { _ as is_text_input_focused, a as paint, c as hit_shape_svg, d as NudgeDwellWatcher, f as TranslateOrchestrator, g as array_shallow_equal, h as group, i as TOOL_CURSOR, l as RotateOrchestrator, m as transform, n as insertions, o as ResizeOrchestrator, s as resize_pipeline, t as PathModel } from "./model-DIzZmeyf.mjs";
2
2
  import cmath from "@grida/cmath";
3
3
  import { svg_parse } from "@grida/svg/parse";
4
+ import vn from "@grida/vn";
4
5
  import { createTextEditor } from "@grida/text-editor/dom";
5
6
  import { NO_MODS, Surface, measurementToHUDDraw, snapGuideToHUDDraw } from "@grida/hud";
6
7
  import { cursors } from "@grida/hud/cursors";
@@ -295,7 +296,7 @@ function transform_equal(a, b) {
295
296
  //#region src/core/geometry.ts
296
297
  /**
297
298
  * Caches `bounds_of` results keyed on `NodeId`; full-clears on either
298
- * `structure_version` or `geometry_version` bump. See docs/wg/feat-svg-editor/geometry.md for
299
+ * `structure_version` or `geometry_version` bump. See ../../docs/geometry.md for
299
300
  * why the cache is load-bearing under the surface's per-tick re-render.
300
301
  */
301
302
  var MemoizedGeometryProvider = class {
@@ -670,7 +671,7 @@ function is_self_rendered(doc, id) {
670
671
  function collect_rendered_subtree(doc, parent, out) {
671
672
  for (const child of doc.element_children_of(parent)) {
672
673
  if (!is_self_rendered(doc, child)) continue;
673
- if (!STRUCTURAL_GRAPHICS_SET.has(doc.tag_of(child))) continue;
674
+ if (!group.STRUCTURAL_GRAPHICS.has(doc.tag_of(child))) continue;
674
675
  out.add(child);
675
676
  if (doc.tag_of(child) === "g") collect_rendered_subtree(doc, child, out);
676
677
  }
@@ -706,10 +707,10 @@ function compute_neighborhood(doc, dragged) {
706
707
  for (const id of dragged) {
707
708
  const parent = doc.parent_of(id);
708
709
  if (parent === null) continue;
709
- if (!excluded.has(parent) && STRUCTURAL_GRAPHICS_SET.has(doc.tag_of(parent)) && is_self_rendered(doc, parent)) out.add(parent);
710
+ if (!excluded.has(parent) && group.STRUCTURAL_GRAPHICS.has(doc.tag_of(parent)) && is_self_rendered(doc, parent)) out.add(parent);
710
711
  for (const sib of doc.element_children_of(parent)) {
711
712
  if (excluded.has(sib)) continue;
712
- if (!STRUCTURAL_GRAPHICS_SET.has(doc.tag_of(sib))) continue;
713
+ if (!group.STRUCTURAL_GRAPHICS.has(doc.tag_of(sib))) continue;
713
714
  if (!is_self_rendered(doc, sib)) continue;
714
715
  for (const inner of snap_descent(doc, sib)) {
715
716
  if (excluded.has(inner)) continue;
@@ -726,565 +727,28 @@ const DEFAULT_SNAP_OPTIONS = {
726
727
  threshold_px: 6
727
728
  };
728
729
  //#endregion
729
- //#region src/core/resize-pipeline/pipeline.ts
730
- /** The funnel. Threads `plan` through `stages` in order; aggregates guide
731
- * emissions. Pure: same inputs → same outputs. */
732
- function run_resize_pipeline(init, stages, ctx) {
733
- let plan = init;
734
- const guides = [];
735
- for (const stage of stages) {
736
- const out = stage.run(plan, ctx);
737
- plan = out.plan;
738
- if (out.emit?.guide) guides.push(out.emit.guide);
739
- }
740
- return {
741
- plan,
742
- guides
743
- };
744
- }
745
- //#endregion
746
- //#region src/core/resize-capability.ts
747
- function direction_mask(dir) {
748
- const has_n = dir === "n" || dir === "ne" || dir === "nw";
749
- const has_s = dir === "s" || dir === "se" || dir === "sw";
750
- const has_e = dir === "e" || dir === "ne" || dir === "se";
751
- const has_w = dir === "w" || dir === "nw" || dir === "sw";
752
- return {
753
- affects_x: has_e || has_w,
754
- affects_y: has_n || has_s,
755
- x_edge: has_e ? "right" : has_w ? "left" : null,
756
- y_edge: has_n ? "top" : has_s ? "bottom" : null
757
- };
758
- }
759
- /** Is this direction one of the four corners (vs. an edge handle)? */
760
- function is_corner_direction(dir) {
761
- return dir === "nw" || dir === "ne" || dir === "se" || dir === "sw";
762
- }
763
- /**
764
- * Apply per-element resize constraints to a gesture's proposed `(sx, sy)`.
765
- *
766
- * The constraint mirrors `apply_resize` exactly so that the *effective
767
- * rect* the caller computes from `(sx, sy)` matches what attribute writes
768
- * actually produce. This is the keystone of resize snap: snapping on the
769
- * gesture-proposed rect would lie about where the geometry lands when an
770
- * element-type constraint kicks in.
771
- *
772
- * Constraints:
773
- * - `rect` / `image` / `use` / `ellipse` / `line` / `polyline` /
774
- * `polygon` / `path`: free per-axis. Identity.
775
- * - `circle`: uniform. `s = min(sx, sy)`.
776
- * - `text`: uniform on corner drags; no-op on edge drags. Mirrors the
777
- * `isCorner = sx !== 1 && sy !== 1` check in `apply_resize`.
778
- * - `unsupported`: no-op.
779
- */
780
- function resize_constraint(baseline, dir, sx_gesture, sy_gesture) {
781
- switch (baseline.attrs.kind) {
782
- case "rect":
783
- case "image":
784
- case "use":
785
- case "ellipse":
786
- case "line":
787
- case "polyline":
788
- case "polygon":
789
- case "path": return {
790
- sx: sx_gesture,
791
- sy: sy_gesture,
792
- no_op: false,
793
- uniform: false
794
- };
795
- case "circle": {
796
- const s = Math.min(sx_gesture, sy_gesture);
797
- return {
798
- sx: s,
799
- sy: s,
800
- no_op: false,
801
- uniform: true
802
- };
803
- }
804
- case "text": {
805
- if (!is_corner_direction(dir)) return {
806
- sx: 1,
807
- sy: 1,
808
- no_op: true,
809
- uniform: true
810
- };
811
- const s = Math.min(sx_gesture, sy_gesture);
812
- return {
813
- sx: s,
814
- sy: s,
815
- no_op: false,
816
- uniform: true
817
- };
818
- }
819
- case "unsupported": return {
820
- sx: 1,
821
- sy: 1,
822
- no_op: true,
823
- uniform: false
824
- };
825
- }
826
- }
827
- /** Position of a bbox corner / edge midpoint by direction. */
828
- function corner_of_rect(r, dir) {
829
- switch (dir) {
830
- case "nw": return {
831
- x: r.x,
832
- y: r.y
833
- };
834
- case "n": return {
835
- x: r.x + r.width / 2,
836
- y: r.y
837
- };
838
- case "ne": return {
839
- x: r.x + r.width,
840
- y: r.y
841
- };
842
- case "e": return {
843
- x: r.x + r.width,
844
- y: r.y + r.height / 2
845
- };
846
- case "se": return {
847
- x: r.x + r.width,
848
- y: r.y + r.height
849
- };
850
- case "s": return {
851
- x: r.x + r.width / 2,
852
- y: r.y + r.height
853
- };
854
- case "sw": return {
855
- x: r.x,
856
- y: r.y + r.height
857
- };
858
- case "w": return {
859
- x: r.x,
860
- y: r.y + r.height / 2
861
- };
862
- }
863
- }
864
- /** The fixed-origin corner for a drag (opposite the moving corner). */
865
- function origin_of_direction(r, dir) {
866
- switch (dir) {
867
- case "nw": return {
868
- x: r.x + r.width,
869
- y: r.y + r.height
870
- };
871
- case "n": return {
872
- x: r.x + r.width / 2,
873
- y: r.y + r.height
874
- };
875
- case "ne": return {
876
- x: r.x,
877
- y: r.y + r.height
878
- };
879
- case "e": return {
880
- x: r.x,
881
- y: r.y + r.height / 2
882
- };
883
- case "se": return {
884
- x: r.x,
885
- y: r.y
886
- };
887
- case "s": return {
888
- x: r.x + r.width / 2,
889
- y: r.y
890
- };
891
- case "sw": return {
892
- x: r.x + r.width,
893
- y: r.y
894
- };
895
- case "w": return {
896
- x: r.x + r.width,
897
- y: r.y + r.height / 2
898
- };
899
- }
900
- }
730
+ //#region src/core/text-edit.ts
901
731
  /**
902
- * Compute the effective rect that `apply_resize` would write for the
903
- * given gesture. This is what snap operates on.
732
+ * Decide what happens when inline text content-editing exits.
904
733
  *
905
- * The rect is computed by scaling `baseline.bbox` around `origin` by the
906
- * constrained `(sx, sy)`. For free elements this matches the gesture
907
- * exactly; for circle / text-on-corner it collapses to a uniform-scale
908
- * rect; for text-on-edge it returns the baseline rect unchanged.
909
- */
910
- function effective_resize(baseline, dir, sx_gesture, sy_gesture) {
911
- const bbox = baseline.bbox;
912
- const origin = origin_of_direction(bbox, dir);
913
- const c = resize_constraint(baseline, dir, sx_gesture, sy_gesture);
914
- const mask = direction_mask(dir);
915
- const rect = {
916
- x: origin.x + (bbox.x - origin.x) * c.sx,
917
- y: origin.y + (bbox.y - origin.y) * c.sy,
918
- width: bbox.width * c.sx,
919
- height: bbox.height * c.sy
920
- };
921
- const moving_corner = corner_of_rect(rect, dir);
922
- return {
923
- rect,
924
- sx: c.sx,
925
- sy: c.sy,
926
- moving_corner,
927
- origin,
928
- no_op: c.no_op,
929
- uniform: c.uniform,
930
- mask
931
- };
932
- }
933
- //#endregion
934
- //#region src/core/resize-pipeline/stages.ts
935
- function pipeline_baseline(plan) {
936
- return plan.baseline;
937
- }
938
- /** Collapse `(dx, dy)` to a uniform scale when Shift-drag is active.
939
- * Element-driven uniform (circle / text-on-corner) is enforced inside
940
- * `resize_constraint`, not here — this stage is *only* the user-visible
941
- * modifier. No-op on edge handles (uniform across one axis isn't a
942
- * meaningful constraint). */
943
- const stage_aspect_lock = {
944
- name: "aspect_lock",
945
- run(plan, ctx) {
946
- if (ctx.modifiers.aspect_lock !== "uniform") return { plan };
947
- if (!is_corner_direction(plan.direction)) return { plan };
948
- const pbase = pipeline_baseline(plan);
949
- const locked = compute_resize_factors(pbase, plan.direction, plan.dx, plan.dy, true);
950
- const bbox = pbase.bbox;
951
- const Hx_base = (() => {
952
- switch (plan.direction) {
953
- case "nw":
954
- case "w":
955
- case "sw": return bbox.x;
956
- case "ne":
957
- case "e":
958
- case "se": return bbox.x + bbox.width;
959
- case "n":
960
- case "s": return bbox.x + bbox.width / 2;
961
- }
962
- })();
963
- const Hy_base = (() => {
964
- switch (plan.direction) {
965
- case "nw":
966
- case "n":
967
- case "ne": return bbox.y;
968
- case "sw":
969
- case "s":
970
- case "se": return bbox.y + bbox.height;
971
- case "e":
972
- case "w": return bbox.y + bbox.height / 2;
973
- }
974
- })();
975
- const new_Hx = locked.origin.x + (Hx_base - locked.origin.x) * locked.sx;
976
- const new_Hy = locked.origin.y + (Hy_base - locked.origin.y) * locked.sy;
977
- return { plan: {
978
- ...plan,
979
- dx: new_Hx - Hx_base,
980
- dy: new_Hy - Hy_base
981
- } };
982
- }
983
- };
984
- /** Consults `ctx.snap_session` for moving-edge alignment correction.
985
- * Identity on `force_disable_snap`, missing session, or
986
- * `snap_enabled === false`. */
987
- const stage_snap = {
988
- name: "snap",
989
- run(plan, ctx) {
990
- if (ctx.modifiers.force_disable_snap) return { plan };
991
- if (!ctx.snap_session) return { plan };
992
- if (!ctx.options.snap_enabled) return { plan };
993
- const pbase = pipeline_baseline(plan);
994
- const f = compute_resize_factors(pbase, plan.direction, plan.dx, plan.dy, false);
995
- const eff = effective_resize(pbase, plan.direction, f.sx, f.sy);
996
- if (eff.no_op) return { plan };
997
- const r = ctx.snap_session.snap_resize(eff.rect, {
998
- x: eff.mask.x_edge,
999
- y: eff.mask.y_edge
1000
- }, {
1001
- enabled: true,
1002
- threshold_px: ctx.options.snap_threshold_px
1003
- });
1004
- if (r.dx === 0 && r.dy === 0) return {
1005
- plan,
1006
- emit: r.guide ? { guide: r.guide } : void 0
1007
- };
1008
- if (eff.uniform) {
1009
- const bbox = pbase.bbox;
1010
- const new_Hx = eff.moving_corner.x + r.dx;
1011
- const new_Hy = eff.moving_corner.y + r.dy;
1012
- const sx_from_x = eff.mask.x_edge !== null && r.dx !== 0 && bbox.width !== 0 ? (new_Hx - eff.origin.x) / (eff.moving_corner.x - eff.origin.x) * eff.sx : null;
1013
- const sy_from_y = eff.mask.y_edge !== null && r.dy !== 0 && bbox.height !== 0 ? (new_Hy - eff.origin.y) / (eff.moving_corner.y - eff.origin.y) * eff.sy : null;
1014
- let s = eff.sx;
1015
- if (sx_from_x !== null && sy_from_y !== null) s = Math.min(sx_from_x, sy_from_y);
1016
- else if (sx_from_x !== null) s = sx_from_x;
1017
- else if (sy_from_y !== null) s = sy_from_y;
1018
- const Hx_base = corner_x_of(bbox, plan.direction);
1019
- const Hy_base = corner_y_of(bbox, plan.direction);
1020
- const target_Hx = eff.origin.x + (Hx_base - eff.origin.x) * s;
1021
- const target_Hy = eff.origin.y + (Hy_base - eff.origin.y) * s;
1022
- return {
1023
- plan: {
1024
- ...plan,
1025
- dx: eff.mask.affects_x ? target_Hx - Hx_base : 0,
1026
- dy: eff.mask.affects_y ? target_Hy - Hy_base : 0
1027
- },
1028
- emit: r.guide ? { guide: r.guide } : void 0
1029
- };
1030
- }
1031
- return {
1032
- plan: {
1033
- ...plan,
1034
- dx: eff.mask.affects_x ? plan.dx + r.dx : plan.dx,
1035
- dy: eff.mask.affects_y ? plan.dy + r.dy : plan.dy
1036
- },
1037
- emit: r.guide ? { guide: r.guide } : void 0
1038
- };
1039
- }
1040
- };
1041
- /** Quantize the moving corner's *post-resize* position to integer
1042
- * multiples of `pixel_grid_quantum` in own-frame space. Identity when
1043
- * quantum is `null` / `<= 0` or the gesture is a no-op. */
1044
- const stage_pixel_grid = {
1045
- name: "pixel_grid",
1046
- run(plan, ctx) {
1047
- const q = ctx.options.pixel_grid_quantum;
1048
- if (q === null || q <= 0) return { plan };
1049
- const pbase = pipeline_baseline(plan);
1050
- const f = compute_resize_factors(pbase, plan.direction, plan.dx, plan.dy, false);
1051
- const eff = effective_resize(pbase, plan.direction, f.sx, f.sy);
1052
- if (eff.no_op) return { plan };
1053
- const target_Hx = eff.mask.affects_x ? Math.round(eff.moving_corner.x / q) * q : eff.moving_corner.x;
1054
- const target_Hy = eff.mask.affects_y ? Math.round(eff.moving_corner.y / q) * q : eff.moving_corner.y;
1055
- const bbox = pbase.bbox;
1056
- const Hx_base = corner_x_of(bbox, plan.direction);
1057
- const Hy_base = corner_y_of(bbox, plan.direction);
1058
- return { plan: {
1059
- ...plan,
1060
- dx: eff.mask.affects_x ? target_Hx - Hx_base : 0,
1061
- dy: eff.mask.affects_y ? target_Hy - Hy_base : 0
1062
- } };
1063
- }
1064
- };
1065
- function corner_x_of(r, dir) {
1066
- switch (dir) {
1067
- case "nw":
1068
- case "w":
1069
- case "sw": return r.x;
1070
- case "ne":
1071
- case "e":
1072
- case "se": return r.x + r.width;
1073
- case "n":
1074
- case "s": return r.x + r.width / 2;
1075
- }
1076
- }
1077
- function corner_y_of(r, dir) {
1078
- switch (dir) {
1079
- case "nw":
1080
- case "n":
1081
- case "ne": return r.y;
1082
- case "sw":
1083
- case "s":
1084
- case "se": return r.y + r.height;
1085
- case "e":
1086
- case "w": return r.y + r.height / 2;
1087
- }
1088
- }
1089
- /** Default stage list for HUD-driven resize gestures (drag).
1090
- * No NUDGE / RPC analogs at v1 (no `commands.resize` per README). */
1091
- const STAGES_DEFAULT = Object.freeze([
1092
- stage_aspect_lock,
1093
- stage_snap,
1094
- stage_pixel_grid
1095
- ]);
1096
- //#endregion
1097
- //#region src/core/resize-pipeline/apply.ts
1098
- function applyResizePlan(doc, plan, phase = "commit") {
1099
- const f = compute_resize_factors(plan.baseline, plan.direction, plan.dx, plan.dy, false);
1100
- const members = plan.members ?? [{
1101
- id: plan.id,
1102
- baseline: plan.baseline
1103
- }];
1104
- for (const m of members) apply_resize(doc, m.id, m.baseline, f.sx, f.sy, f.origin, phase);
1105
- }
1106
- function revertResizePlan(doc, plan) {
1107
- const f = compute_resize_factors(plan.baseline, plan.direction, 0, 0, false);
1108
- const members = plan.members ?? [{
1109
- id: plan.id,
1110
- baseline: plan.baseline
1111
- }];
1112
- for (const m of members) apply_resize(doc, m.id, m.baseline, 1, 1, f.origin, "preview");
1113
- }
1114
- /**
1115
- * Synthesize a "group" baseline over an arbitrary union rect. The attrs
1116
- * carrier is `rect`-kind so the pipeline math (snap / pixel-grid)
1117
- * treats the group as free per-axis — per-member constraints (circle
1118
- * uniform, text edge no-op) kick in at apply time against each
1119
- * member's own captured baseline.
734
+ * `result` is the text that should remain the typed text on commit, the
735
+ * original on cancel. "Empty" means zero-length: a space is authored
736
+ * content and is kept. The rule is unconditional an empty result deletes
737
+ * the node however it got there (freshly placed and never typed, cleared by
738
+ * the author, or already empty on entry).
1120
739
  *
1121
- * For single-member groups callers should pass the member's own
1122
- * baseline directly so the per-element snap correction (`eff.uniform`
1123
- * branch) fires correctly.
740
+ * See docs/wg/feat-svg-editor/text-tool.md.
1124
741
  */
1125
- function synthesize_group_baseline(union) {
1126
- return {
1127
- bbox: {
1128
- x: union.x,
1129
- y: union.y,
1130
- width: union.width,
1131
- height: union.height
1132
- },
1133
- attrs: {
1134
- kind: "rect",
1135
- x: union.x,
1136
- y: union.y,
1137
- w: union.width,
1138
- h: union.height
1139
- }
1140
- };
1141
- }
1142
- //#endregion
1143
- //#region src/core/resize-pipeline/orchestrator.ts
1144
- const PROVIDER_ID = "svg-editor";
1145
- /** West/north-anchor flips invert the corresponding world delta so a
1146
- * positive value always grows the moving edge outward — the convention
1147
- * `compute_resize_factors` consumes. */
1148
- function sign_adjust(dir, dx_world, dy_world) {
1149
- return {
1150
- dx: dir === "w" || dir === "nw" || dir === "sw" ? -dx_world : dx_world,
1151
- dy: dir === "n" || dir === "ne" || dir === "nw" ? -dy_world : dy_world
742
+ function resolve_text_exit(input) {
743
+ const is_empty = input.result.length === 0;
744
+ if (input.origin === "fresh") return is_empty ? { kind: "discard_insert" } : { kind: "commit_insert" };
745
+ if (is_empty) return { kind: "remove" };
746
+ if (input.result !== input.original) return {
747
+ kind: "set_text",
748
+ value: input.result
1152
749
  };
750
+ return { kind: "noop" };
1153
751
  }
1154
- /** Stable, order-independent key for an id set — used by `is_active_for`
1155
- * to decide whether the current session targets the same group. */
1156
- function ids_key(ids) {
1157
- return [...ids].sort().join("\0");
1158
- }
1159
- var ResizeOrchestrator = class {
1160
- constructor(deps) {
1161
- this.deps = deps;
1162
- this.active = null;
1163
- this._last_guides = [];
1164
- }
1165
- /** Guides emitted by the most recent pipeline run. Cleared on
1166
- * cancel/dispose. */
1167
- get last_guides() {
1168
- return this._last_guides;
1169
- }
1170
- has_active_session() {
1171
- return this.active !== null;
1172
- }
1173
- /** Is the gesture currently targeting `ids` with `direction`? Used by
1174
- * the HUD dispatch to decide whether to reset the session on a new
1175
- * handle / target. Order-independent. */
1176
- is_active_for(ids, direction) {
1177
- return this.active !== null && this.active.direction === direction && this.active.ids_key === ids_key(ids);
1178
- }
1179
- /** Per-frame drive. Opens a session lazily on the first call. The
1180
- * HUD passes its gesture-target rect dimensions in **world space**;
1181
- * the orchestrator derives the signed world-frame delta against its
1182
- * captured `baseline.bbox`. The DOM adapter is responsible for the
1183
- * CSS-px → world conversion at the intent boundary. */
1184
- drive(input, modifiers, opts) {
1185
- if (input.ids.length === 0) return null;
1186
- const doc = this.deps.get_doc();
1187
- for (const id of input.ids) if (!is_resizable_node(doc, id)) return null;
1188
- const key = ids_key(input.ids);
1189
- if (this.active && (this.active.ids_key !== key || this.active.direction !== input.direction)) {
1190
- this.active.preview.discard();
1191
- this.dispose_session();
1192
- }
1193
- if (this.active === null) this.active = this.open(input.ids, input.direction, opts.snap, opts.label ?? "resize");
1194
- const session = this.active;
1195
- const bbox = session.baseline.bbox;
1196
- const dx_world = input.target_width - bbox.width;
1197
- const dy_world = input.target_height - bbox.height;
1198
- const d = sign_adjust(input.direction, dx_world, dy_world);
1199
- const stages = opts.stages ?? STAGES_DEFAULT;
1200
- const result = this.run_pass(session, d.dx, d.dy, modifiers, stages);
1201
- session.last_dx = d.dx;
1202
- session.last_dy = d.dy;
1203
- session.last_stages = stages;
1204
- this.write_preview(session, result.plan, opts.phase);
1205
- if (opts.phase === "commit") {
1206
- session.preview.commit();
1207
- this.dispose_session();
1208
- }
1209
- return result;
1210
- }
1211
- /** Re-run the current preview frame with new modifiers. */
1212
- redrive_modifiers(modifiers) {
1213
- if (!this.active) return null;
1214
- const session = this.active;
1215
- const result = this.run_pass(session, session.last_dx, session.last_dy, modifiers, session.last_stages);
1216
- this.write_preview(session, result.plan, "preview");
1217
- return result;
1218
- }
1219
- cancel() {
1220
- if (!this.active) return;
1221
- this.active.preview.discard();
1222
- this.dispose_session();
1223
- }
1224
- run_pass(session, dx, dy, modifiers, stages) {
1225
- const result = run_resize_pipeline({
1226
- id: session.primary_id,
1227
- baseline: session.baseline,
1228
- members: session.members,
1229
- direction: session.direction,
1230
- dx,
1231
- dy
1232
- }, stages, {
1233
- input: {
1234
- id: session.primary_id,
1235
- direction: session.direction,
1236
- dx,
1237
- dy
1238
- },
1239
- modifiers,
1240
- options: this.deps.options(),
1241
- snap_session: session.snap
1242
- });
1243
- this._last_guides = result.guides;
1244
- return result;
1245
- }
1246
- open(ids, direction, snap, label) {
1247
- const doc = this.deps.get_doc();
1248
- const members = ids.map((id) => ({
1249
- id,
1250
- baseline: capture_resize_baseline(doc, id, this.deps.bbox_world(id))
1251
- }));
1252
- const baseline = members.length === 1 ? members[0].baseline : synthesize_group_baseline(cmath.rect.union(members.map((m) => m.baseline.bbox)));
1253
- return {
1254
- ids_key: ids_key(ids),
1255
- primary_id: members[0].id,
1256
- direction,
1257
- members,
1258
- baseline,
1259
- snap: snap ? this.deps.open_snap(ids) : null,
1260
- preview: this.deps.open_preview(label),
1261
- last_dx: 0,
1262
- last_dy: 0,
1263
- last_stages: STAGES_DEFAULT
1264
- };
1265
- }
1266
- write_preview(session, plan, phase) {
1267
- const doc = this.deps.get_doc();
1268
- const emit = this.deps.emit;
1269
- session.preview.set({
1270
- providerId: PROVIDER_ID,
1271
- apply: () => {
1272
- applyResizePlan(doc, plan, phase);
1273
- emit();
1274
- },
1275
- revert: () => {
1276
- revertResizePlan(doc, plan);
1277
- emit();
1278
- }
1279
- });
1280
- }
1281
- dispose_session() {
1282
- if (!this.active) return;
1283
- this.active.snap?.dispose();
1284
- this.active = null;
1285
- this._last_guides = [];
1286
- }
1287
- };
1288
752
  //#endregion
1289
753
  //#region src/gestures/gestures.ts
1290
754
  /**
@@ -1420,7 +884,7 @@ const DEFAULT_GESTURE_BINDINGS = [
1420
884
  WHEEL_PAN_ZOOM,
1421
885
  {
1422
886
  id: "space-drag-pan",
1423
- install({ container, camera }) {
887
+ install({ container, camera, is_attended }) {
1424
888
  let space_held = false;
1425
889
  let prev_cursor = null;
1426
890
  const set_cursor = (next) => {
@@ -1431,6 +895,7 @@ const DEFAULT_GESTURE_BINDINGS = [
1431
895
  const on_keydown = (e) => {
1432
896
  if (e.code !== "Space" || e.repeat) return;
1433
897
  if (is_text_input_focused()) return;
898
+ if (!is_attended()) return;
1434
899
  space_held = true;
1435
900
  set_cursor("grab");
1436
901
  e.preventDefault();
@@ -1483,11 +948,10 @@ const DEFAULT_GESTURE_BINDINGS = [
1483
948
  },
1484
949
  {
1485
950
  id: "keyboard-zoom",
1486
- install({ container, camera }) {
951
+ install({ container, camera, is_attended }) {
1487
952
  const owner_doc = container.ownerDocument;
1488
953
  const on_keydown = (e) => {
1489
- const active = owner_doc.activeElement;
1490
- if (active && active !== owner_doc.body && !container.contains(active)) return;
954
+ if (!is_attended()) return;
1491
955
  if (is_text_input_focused()) return;
1492
956
  const mod = e.metaKey || e.ctrlKey;
1493
957
  if (e.shiftKey && !mod && (e.code === "Digit0" || e.code === "Numpad0")) {
@@ -1517,6 +981,39 @@ function applyDefaultGestures(gestures) {
1517
981
  for (const b of DEFAULT_GESTURE_BINDINGS) gestures.bind(b);
1518
982
  }
1519
983
  //#endregion
984
+ //#region src/util/attention.ts
985
+ /**
986
+ * Install pointer-tracking listeners on `container` and return the
987
+ * read-side handle. The tracker is owned by the surface and disposed
988
+ * alongside it; gesture bindings that need to consult it receive the
989
+ * read-only `is_attended` predicate through `GestureContext`.
990
+ */
991
+ function create_attention_tracker(container) {
992
+ let pointer_over = false;
993
+ const on_enter = () => {
994
+ pointer_over = true;
995
+ };
996
+ const on_leave = () => {
997
+ pointer_over = false;
998
+ };
999
+ container.addEventListener("pointerenter", on_enter);
1000
+ container.addEventListener("pointerleave", on_leave);
1001
+ const is_attended = () => {
1002
+ const owner = container.ownerDocument;
1003
+ if (!owner) return pointer_over;
1004
+ const active = owner.activeElement;
1005
+ if (active && active !== owner.body && container.contains(active)) return true;
1006
+ return pointer_over;
1007
+ };
1008
+ return {
1009
+ is_attended,
1010
+ dispose: () => {
1011
+ container.removeEventListener("pointerenter", on_enter);
1012
+ container.removeEventListener("pointerleave", on_leave);
1013
+ }
1014
+ };
1015
+ }
1016
+ //#endregion
1520
1017
  //#region src/text-surface.ts
1521
1018
  const SVG_NS = "http://www.w3.org/2000/svg";
1522
1019
  const XML_NS = "http://www.w3.org/XML/1998/namespace";
@@ -1676,6 +1173,312 @@ var SvgTextSurface = class {
1676
1173
  }
1677
1174
  };
1678
1175
  //#endregion
1176
+ //#region src/core/vector-edit/session.ts
1177
+ function tangents_equal(a, b) {
1178
+ return a[0] === b[0] && a[1] === b[1];
1179
+ }
1180
+ /**
1181
+ * Shallow equality over the three sub-selection arrays. Order-sensitive
1182
+ * (mirrors how the host stores them). Used by the orchestrator to skip
1183
+ * pushing a no-op undo entry when a selection handler resolves to the
1184
+ * same state — e.g. clicking an already-selected vertex in `replace`
1185
+ * mode.
1186
+ */
1187
+ function sub_selection_equal(a, b) {
1188
+ if (a === b) return true;
1189
+ if (a.vertices.length !== b.vertices.length) return false;
1190
+ if (a.segments.length !== b.segments.length) return false;
1191
+ if (a.tangents.length !== b.tangents.length) return false;
1192
+ for (let i = 0; i < a.vertices.length; i++) if (a.vertices[i] !== b.vertices[i]) return false;
1193
+ for (let i = 0; i < a.segments.length; i++) if (a.segments[i] !== b.segments[i]) return false;
1194
+ for (let i = 0; i < a.tangents.length; i++) if (!tangents_equal(a.tangents[i], b.tangents[i])) return false;
1195
+ return true;
1196
+ }
1197
+ /**
1198
+ * Host-side state for vector content-edit (vertex / segment / tangent
1199
+ * gestures) on the supported source tags. "Vector" here names the
1200
+ * editing mode — NOT a `vn.VectorNetwork` wrapper. The session holds
1201
+ * the source tag's authored attrs plus a path-form session-d, and
1202
+ * delegates geometry to {@link PathModel} via the apply.ts shim.
1203
+ */
1204
+ var VectorEditSession = class {
1205
+ constructor(node_id, source, session_d) {
1206
+ this.node_id = node_id;
1207
+ this.source = source;
1208
+ this._session_d = session_d;
1209
+ this._last_seen_d = session_d;
1210
+ this._selected_vertices = [];
1211
+ this._selected_segments = [];
1212
+ this._selected_tangents = [];
1213
+ this._hovered_control = null;
1214
+ }
1215
+ /** The session's current PathModel-form `d`. Gesture handlers read
1216
+ * this instead of `doc.get_attr(node_id, "d")` so they stay tag-
1217
+ * oblivious (non-path sources have no `d` on the document). */
1218
+ get current_d() {
1219
+ return this._session_d;
1220
+ }
1221
+ /** Update the session's view after a write produced `next_d`. Caller
1222
+ * is `apply_session_d` (or the gesture handler that called it). */
1223
+ update_session_d(next_d) {
1224
+ this._session_d = next_d;
1225
+ }
1226
+ get last_seen_d() {
1227
+ return this._last_seen_d;
1228
+ }
1229
+ get selected_vertices() {
1230
+ return this._selected_vertices;
1231
+ }
1232
+ get selected_segments() {
1233
+ return this._selected_segments;
1234
+ }
1235
+ get selected_tangents() {
1236
+ return this._selected_tangents;
1237
+ }
1238
+ get hovered_control() {
1239
+ return this._hovered_control;
1240
+ }
1241
+ /**
1242
+ * Record that the host's most recent gesture write produced `d`.
1243
+ * Updates both the session-d (the in-session canonical form) and the
1244
+ * last-seen mark. The next state-change tick uses last_seen to
1245
+ * distinguish "we wrote this" from "the document changed under us".
1246
+ */
1247
+ mark_seen(d) {
1248
+ this._session_d = d;
1249
+ this._last_seen_d = d;
1250
+ }
1251
+ /**
1252
+ * The session's response to a detected external mutation of `d`
1253
+ * (undo / redo / programmatic / collab). Atomically (a) advances
1254
+ * `last_seen_d` to the now-current value and (b) drops sub-selection
1255
+ * — selection indices reference vertices and segments by ordinal
1256
+ * position, and an external mutation may have shifted or removed
1257
+ * them.
1258
+ *
1259
+ * Exposed as a single method so callers cannot get the two halves
1260
+ * out of order. Doing `clear_selection` without `mark_seen` would
1261
+ * leave us "stuck dirty" — the next tick would reconcile again.
1262
+ * Doing `mark_seen` without `clear_selection` would leave stale
1263
+ * indices pointing into a geometry that no longer matches.
1264
+ */
1265
+ reconcile_after_external_mutation(d) {
1266
+ this.mark_seen(d);
1267
+ this.clear_selection();
1268
+ }
1269
+ select_vertex(index, mode) {
1270
+ switch (mode) {
1271
+ case "replace":
1272
+ this._selected_vertices = [index];
1273
+ break;
1274
+ case "add":
1275
+ if (!this._selected_vertices.includes(index)) this._selected_vertices = [...this._selected_vertices, index];
1276
+ break;
1277
+ case "toggle":
1278
+ this._selected_vertices = this._selected_vertices.includes(index) ? this._selected_vertices.filter((v) => v !== index) : [...this._selected_vertices, index];
1279
+ break;
1280
+ }
1281
+ if (mode === "replace") {
1282
+ this._selected_segments = [];
1283
+ this._selected_tangents = [];
1284
+ }
1285
+ }
1286
+ select_segment(index, mode) {
1287
+ switch (mode) {
1288
+ case "replace":
1289
+ this._selected_segments = [index];
1290
+ break;
1291
+ case "add":
1292
+ if (!this._selected_segments.includes(index)) this._selected_segments = [...this._selected_segments, index];
1293
+ break;
1294
+ case "toggle":
1295
+ this._selected_segments = this._selected_segments.includes(index) ? this._selected_segments.filter((s) => s !== index) : [...this._selected_segments, index];
1296
+ break;
1297
+ }
1298
+ if (mode === "replace") {
1299
+ this._selected_vertices = [];
1300
+ this._selected_tangents = [];
1301
+ }
1302
+ }
1303
+ select_tangent(ref, mode) {
1304
+ const has = this._selected_tangents.some((t) => tangents_equal(t, ref));
1305
+ switch (mode) {
1306
+ case "replace":
1307
+ this._selected_tangents = [ref];
1308
+ break;
1309
+ case "add":
1310
+ if (!has) this._selected_tangents = [...this._selected_tangents, ref];
1311
+ break;
1312
+ case "toggle":
1313
+ this._selected_tangents = has ? this._selected_tangents.filter((t) => !tangents_equal(t, ref)) : [...this._selected_tangents, ref];
1314
+ break;
1315
+ }
1316
+ if (mode === "replace") {
1317
+ this._selected_vertices = [];
1318
+ this._selected_segments = [];
1319
+ }
1320
+ }
1321
+ /**
1322
+ * Replace the entire sub-selection at once. Useful for marquee /
1323
+ * lasso results, which compute the full set up-front.
1324
+ */
1325
+ set_selection(next) {
1326
+ this._selected_vertices = [...next.vertices];
1327
+ this._selected_segments = [...next.segments];
1328
+ this._selected_tangents = next.tangents.map((t) => [t[0], t[1]]);
1329
+ }
1330
+ /**
1331
+ * Capture the current sub-selection as a frozen triple. The
1332
+ * orchestrator closes over snapshots in gesture deltas (so undo
1333
+ * restores selection alongside geometry) and in standalone selection
1334
+ * deltas (so a click on a vertex is itself undoable).
1335
+ *
1336
+ * Returned arrays are fresh copies — safe to retain across
1337
+ * subsequent mutations of the session.
1338
+ */
1339
+ snapshot_selection() {
1340
+ return Object.freeze({
1341
+ vertices: Object.freeze([...this._selected_vertices]),
1342
+ segments: Object.freeze([...this._selected_segments]),
1343
+ tangents: Object.freeze(this._selected_tangents.map((t) => [t[0], t[1]]))
1344
+ });
1345
+ }
1346
+ /**
1347
+ * Restore a previously-captured sub-selection. Counterpart to
1348
+ * {@link snapshot_selection}. Equivalent to calling
1349
+ * {@link set_selection} with the snapshot's contents.
1350
+ */
1351
+ restore_selection(snap) {
1352
+ this.set_selection(snap);
1353
+ }
1354
+ clear_selection() {
1355
+ if (this._selected_vertices.length === 0 && this._selected_segments.length === 0 && this._selected_tangents.length === 0) return;
1356
+ this._selected_vertices = [];
1357
+ this._selected_segments = [];
1358
+ this._selected_tangents = [];
1359
+ }
1360
+ };
1361
+ //#endregion
1362
+ //#region src/core/vector-edit/apply.ts
1363
+ /**
1364
+ * Build the in-session path-form `d` ("session-d") for a freshly-
1365
+ * entered vector-edit. For `<path>` this is the verbatim authored
1366
+ * string; for the two vertex-chain tags we route through
1367
+ * `vn.fromPolyline` / `vn.fromPolygon` and emit via `vn.toSVGPathData`
1368
+ * — same zero-tangent `M`/`L` sequence the gesture handlers'
1369
+ * `PathModel.toSvgPathD()` will produce on subsequent commits.
1370
+ *
1371
+ * The returned string is internal to the session — it is never written
1372
+ * to the document on its own. Native-attr writeback happens through
1373
+ * {@link apply_session_d} (which calls {@link PathModel.toNativeAttrs}
1374
+ * to project the path-form geometry back to source-tag attrs).
1375
+ */
1376
+ function source_to_session_d(source) {
1377
+ switch (source.kind) {
1378
+ case "path": return source.d;
1379
+ case "polyline": return vn.toSVGPathData(vn.fromPolyline(source.points.map((p) => [p[0], p[1]])));
1380
+ case "polygon": return vn.toSVGPathData(vn.fromPolygon(source.points.map((p) => [p[0], p[1]])));
1381
+ }
1382
+ }
1383
+ /**
1384
+ * Tag-aware document write. Given a new path-data `d` from a gesture,
1385
+ * project it back into the source tag's native attrs and write those —
1386
+ * unless the source is `<path>`, in which case `d` is written
1387
+ * directly.
1388
+ *
1389
+ * Returns `true` on success. Returns `false` for non-path sources when
1390
+ * the model can no longer be expressed in the source tag's native attrs
1391
+ * (tangent introduced, topology change). v1 treats `false` as gesture
1392
+ * refusal — the caller should NOT fall through and write `d` on a non-
1393
+ * path element. Promotion to `<path>` lives in v1.1+.
1394
+ *
1395
+ * Symmetric across apply / revert: gesture handlers call this for both
1396
+ * the in-flight write and the undo-revert (since both are just "set the
1397
+ * geometry to this d"), so apply/revert stay consistent even when one
1398
+ * writes native attrs and the other would.
1399
+ */
1400
+ function apply_session_d(doc, node_id, source, d) {
1401
+ if (source.kind === "path") {
1402
+ doc.set_attr(node_id, "d", d);
1403
+ return true;
1404
+ }
1405
+ const native = PathModel.fromSvgPathD(d).toNativeAttrs(source.kind);
1406
+ if (native === null) return false;
1407
+ const points = native.points.map((p) => `${p[0]},${p[1]}`).join(" ");
1408
+ doc.set_attr(node_id, "points", points);
1409
+ return true;
1410
+ }
1411
+ //#endregion
1412
+ //#region src/core/vector-edit/marquee.ts
1413
+ let marquee;
1414
+ (function(_marquee) {
1415
+ function points_in_rect(candidates, rect) {
1416
+ const hits = [];
1417
+ for (const c of candidates) if (cmath.rect.containsPoint(rect, c.pos)) hits.push(c.key);
1418
+ return hits;
1419
+ }
1420
+ _marquee.points_in_rect = points_in_rect;
1421
+ function points_in_polygon(candidates, polygon) {
1422
+ const hits = [];
1423
+ const poly = polygon;
1424
+ for (const c of candidates) if (cmath.polygon.pointInPolygon(c.pos, poly)) hits.push(c.key);
1425
+ return hits;
1426
+ }
1427
+ _marquee.points_in_polygon = points_in_polygon;
1428
+ function subpath_select_candidates(model, selection, to_doc = identity_proj) {
1429
+ const snap = model.snapshot();
1430
+ const vertices = snap.vertices.map((v, i) => ({
1431
+ key: i,
1432
+ pos: to_doc(v)
1433
+ }));
1434
+ const neigh_set = new Set(model.neighbouringVertices(selection));
1435
+ const tangents = [];
1436
+ for (let si = 0; si < snap.segments.length; si++) {
1437
+ const s = snap.segments[si];
1438
+ if (neigh_set.has(s.a)) {
1439
+ const va = snap.vertices[s.a];
1440
+ tangents.push({
1441
+ key: [s.a, 0],
1442
+ pos: to_doc([va[0] + s.ta[0], va[1] + s.ta[1]])
1443
+ });
1444
+ }
1445
+ if (neigh_set.has(s.b)) {
1446
+ const vb = snap.vertices[s.b];
1447
+ tangents.push({
1448
+ key: [s.b, 1],
1449
+ pos: to_doc([vb[0] + s.tb[0], vb[1] + s.tb[1]])
1450
+ });
1451
+ }
1452
+ }
1453
+ return {
1454
+ vertices,
1455
+ tangents,
1456
+ segments: Array.from({ length: snap.segments.length }, (_, i) => i)
1457
+ };
1458
+ }
1459
+ _marquee.subpath_select_candidates = subpath_select_candidates;
1460
+ function identity_proj(p) {
1461
+ return p;
1462
+ }
1463
+ function merge_subpath_hits(prev, hits, additive) {
1464
+ if (!additive) return {
1465
+ vertices: [...hits.vertices],
1466
+ segments: [...hits.segments],
1467
+ tangents: hits.tangents.map((t) => [t[0], t[1]])
1468
+ };
1469
+ const vertices = Array.from(new Set([...prev.vertices, ...hits.vertices]));
1470
+ const segments = Array.from(new Set([...prev.segments, ...hits.segments]));
1471
+ const tangents = prev.tangents.map((t) => [t[0], t[1]]);
1472
+ for (const t of hits.tangents) if (!tangents.some((x) => x[0] === t[0] && x[1] === t[1])) tangents.push(t);
1473
+ return {
1474
+ vertices,
1475
+ segments,
1476
+ tangents
1477
+ };
1478
+ }
1479
+ _marquee.merge_subpath_hits = merge_subpath_hits;
1480
+ })(marquee || (marquee = {}));
1481
+ //#endregion
1679
1482
  //#region src/dom.ts
1680
1483
  /** Stamped on every rendered SVG element by `render()` so external
1681
1484
  * tooling (host inspectors, the layers panel, snapshot tests) can map
@@ -1716,6 +1519,11 @@ const IS_MODIFIER_KEY = {
1716
1519
  * surface skips render() during the in-flight mount and doesn't yank the
1717
1520
  * live `<text>` element out from under the about-to-mount text surface. */
1718
1521
  const TEXT_EDIT_PENDING = { __pending: true };
1522
+ /** Per-frame `neighbours: []` for the `vector_of` HUD projection. Polyline
1523
+ * and polygon sources never render tangent handles in v1 (curve edits would
1524
+ * promote to `<path>`); using a frozen module-level array avoids allocating
1525
+ * a fresh empty array per redraw frame. */
1526
+ const EMPTY_NEIGHBOURS = Object.freeze([]);
1719
1527
  /**
1720
1528
  * Attach a DOM surface to a headless editor. Returns a `DomSurfaceHandle`
1721
1529
  * whose `detach()` is the inverse — DOM cleared, listeners removed,
@@ -1757,12 +1565,17 @@ var DomSurface = class DomSurface {
1757
1565
  this.text_edit = null;
1758
1566
  this.text_edit_target = null;
1759
1567
  this.text_edit_original = "";
1568
+ this.pending_text_insert = null;
1569
+ this.vector_edit = null;
1570
+ this.vector_edit_region_baseline = null;
1760
1571
  this.current_tool = TOOL_CURSOR;
1761
1572
  this.pending_insert = null;
1762
1573
  this.editor_hover_internal = null;
1763
1574
  this.container = options.container;
1764
1575
  const container = this.container;
1765
1576
  this.fit_on_attach = options.fit === true;
1577
+ this.attention = create_attention_tracker(container);
1578
+ this.teardown.push(() => this.attention.dispose());
1766
1579
  if (process.env.NODE_ENV !== "production" && container.children.length > 0) console.warn("@grida/svg-editor: surface container is not empty at attach time. Render chrome (toolbars, layer lists, inspectors) as siblings of the container, not children — otherwise clicks on those children will silently break. See README §Surface.");
1767
1580
  if (getComputedStyle(container).position === "static") container.style.position = "relative";
1768
1581
  container.style.userSelect = "none";
@@ -1847,6 +1660,7 @@ var DomSurface = class DomSurface {
1847
1660
  this.hud = new Surface(this.hud_canvas, {
1848
1661
  pick: (p) => this.hit_test(p[0], p[1]),
1849
1662
  shapeOf: (id) => this.shape_of(id),
1663
+ vectorOf: (id) => this.vector_of(id),
1850
1664
  onIntent: (i) => this.commit_intent(i),
1851
1665
  style: {
1852
1666
  chromeColor: editor.style.chrome_color,
@@ -1899,11 +1713,14 @@ var DomSurface = class DomSurface {
1899
1713
  hud_canvas: this.hud_canvas,
1900
1714
  camera: this.camera,
1901
1715
  editor,
1902
- handle: { detach: () => {} }
1716
+ handle: { detach: () => {} },
1717
+ is_attended: () => this.attention.is_attended()
1903
1718
  });
1904
1719
  if (options.gestures !== false) applyDefaultGestures(this.gestures);
1905
1720
  const unsub = editor.subscribe(() => {
1906
1721
  this.current_tool = editor.state.tool;
1722
+ this.hud.setVectorSelectionMode(this.current_tool.type === "lasso" ? "lasso" : "marquee");
1723
+ this.hud.setVectorBendMode(this.current_tool.type === "bend" ? "always" : "auto");
1907
1724
  this.render();
1908
1725
  this.sync_surface_selection();
1909
1726
  this.hud.setPixelGrid({
@@ -1920,6 +1737,23 @@ var DomSurface = class DomSurface {
1920
1737
  this.pending_insert = null;
1921
1738
  }
1922
1739
  }
1740
+ if (this.vector_edit && !this.active_preview) {
1741
+ const ses = this.vector_edit;
1742
+ const live_source = this.editor_internal().doc.is_vector_edit_target(ses.node_id);
1743
+ const had_selection = ses.selected_vertices.length > 0 || ses.selected_segments.length > 0 || ses.selected_tangents.length > 0;
1744
+ if (live_source === null || live_source.kind !== ses.source.kind) {
1745
+ if (had_selection) {
1746
+ ses.clear_selection();
1747
+ this.sync_selection_mirror();
1748
+ }
1749
+ } else {
1750
+ const live_d = source_to_session_d(live_source);
1751
+ if (live_d !== ses.last_seen_d) {
1752
+ ses.reconcile_after_external_mutation(live_d);
1753
+ if (had_selection) this.sync_selection_mirror();
1754
+ }
1755
+ }
1756
+ }
1923
1757
  this.request_redraw();
1924
1758
  });
1925
1759
  this.teardown.push(unsub);
@@ -1953,7 +1787,7 @@ var DomSurface = class DomSurface {
1953
1787
  if (computed === "") return null;
1954
1788
  return {
1955
1789
  computed,
1956
- resolved_paint: parse_paint(computed)
1790
+ resolved_paint: paint.parse(computed)
1957
1791
  };
1958
1792
  }
1959
1793
  });
@@ -2005,8 +1839,8 @@ var DomSurface = class DomSurface {
2005
1839
  });
2006
1840
  this.teardown.push(() => internal.set_surface_hover_override_driver(null));
2007
1841
  }
2008
- paint(_snapshot) {}
2009
1842
  hit_test(x, y) {
1843
+ if (this.vector_edit) return null;
2010
1844
  return this.pick_at(x, y, false);
2011
1845
  }
2012
1846
  /** Element-walk under (x, y) → first ancestor with `ID_ATTR`. When
@@ -2034,7 +1868,7 @@ var DomSurface = class DomSurface {
2034
1868
  * `<text>` / `<use>` / transformed nodes). Tolerance is screen-
2035
1869
  * CSS-px, converted to world units via `camera.zoom` so the band
2036
1870
  * stays the same width on screen regardless of zoom. Has known
2037
- * issues — see `docs/wg/feat-svg-editor/hit-test.md`.
1871
+ * issues — see https://grida.co/docs/wg/feat-svg-editor/hit-test.
2038
1872
  *
2039
1873
  * - **`<= 0` (legacy elementFromPoint)** — opt-out of the cmath
2040
1874
  * picker. Uses the browser's painted-pixel hit-test plus a
@@ -2112,15 +1946,17 @@ var DomSurface = class DomSurface {
2112
1946
  if (this._z_order_cache.length > 0 && this._z_order_cache[0] === root_id) return this._z_order_cache.slice(1);
2113
1947
  return this._z_order_cache.filter((id) => id !== root_id);
2114
1948
  }
2115
- on_input(_listener) {
2116
- return () => {};
2117
- }
2118
1949
  dispose() {
2119
1950
  if (this.text_edit) {
2120
1951
  this.text_edit.cancel();
2121
1952
  this.text_edit = null;
2122
1953
  this.text_edit_target = null;
2123
1954
  }
1955
+ if (this.vector_edit) {
1956
+ this.vector_edit = null;
1957
+ this.vector_edit_region_baseline = null;
1958
+ this.hud.setVectorSelection(null);
1959
+ }
2124
1960
  this.gestures._dispose();
2125
1961
  this.translate_orchestrator.cancel();
2126
1962
  this.resize_orchestrator.cancel();
@@ -2188,6 +2024,17 @@ var DomSurface = class DomSurface {
2188
2024
  style.left = "0";
2189
2025
  style.top = "0";
2190
2026
  style.transformOrigin = "0 0";
2027
+ const vb = this.svg_root.getAttribute("viewBox");
2028
+ if (vb) {
2029
+ const parts = vb.split(/[\s,]+/).map(Number);
2030
+ if (parts.length === 4 && parts.every((n) => Number.isFinite(n))) {
2031
+ const [, , w, h] = parts;
2032
+ if (w > 0 && h > 0) {
2033
+ style.width = `${w}px`;
2034
+ style.height = `${h}px`;
2035
+ }
2036
+ }
2037
+ }
2191
2038
  }
2192
2039
  /**
2193
2040
  * Push the current camera transform to the SVG as a CSS `matrix(...)`.
@@ -2835,6 +2682,17 @@ var DomSurface = class DomSurface {
2835
2682
  }
2836
2683
  }
2837
2684
  }
2685
+ if (tool.type === "insert-text") {
2686
+ if (kind === "pointer_down" && e.button === 0) {
2687
+ const world = this.camera.screen_to_world({
2688
+ x,
2689
+ y
2690
+ });
2691
+ this.editor.set_tool({ type: "cursor" });
2692
+ this.begin_text_insert(world);
2693
+ return;
2694
+ }
2695
+ }
2838
2696
  const button = e.button === 0 ? "primary" : e.button === 2 ? "secondary" : "middle";
2839
2697
  let event;
2840
2698
  if (kind === "pointer_move") event = {
@@ -2893,7 +2751,7 @@ var DomSurface = class DomSurface {
2893
2751
  }
2894
2752
  /** Transition `armed` → `drawing`: open `insert_preview` + snap session. */
2895
2753
  arm_to_draw(armed) {
2896
- const session = this.editor.commands.insert_preview(armed.tag, initial_attrs(armed.tag, armed.anchor));
2754
+ const session = this.editor.commands.insert_preview(armed.tag, insertions.initial_attrs(armed.tag, armed.anchor));
2897
2755
  const snap_session = this.editor.style.snap_enabled && (armed.tag === "rect" || armed.tag === "ellipse") ? this.open_snap_session_for([session.id]) : null;
2898
2756
  this.pending_insert = {
2899
2757
  phase: "drawing",
@@ -2915,7 +2773,7 @@ var DomSurface = class DomSurface {
2915
2773
  shift: mods.shift,
2916
2774
  alt: mods.alt
2917
2775
  };
2918
- drawing.session.update(compute_drag_attrs(drawing.tag, drawing.anchor, world, dm));
2776
+ drawing.session.update(insertions.compute_drag_attrs(drawing.tag, drawing.anchor, world, dm));
2919
2777
  }
2920
2778
  /** Commit on pointer-up. `armed` → one-shot `commands.insert` with
2921
2779
  * `default_attrs` (click-no-drag, never touches the IR mid-gesture).
@@ -2923,7 +2781,7 @@ var DomSurface = class DomSurface {
2923
2781
  commit_insert_gesture(screen_pt, mods) {
2924
2782
  const cur = this.pending_insert;
2925
2783
  if (!cur) return;
2926
- if (cur.phase === "armed") this.editor.commands.insert(cur.tag, default_attrs(cur.tag, cur.anchor));
2784
+ if (cur.phase === "armed") this.editor.commands.insert(cur.tag, insertions.default_attrs(cur.tag, cur.anchor));
2927
2785
  else {
2928
2786
  this.push_drawing_frame(cur, screen_pt, mods);
2929
2787
  cur.session.commit();
@@ -2974,11 +2832,20 @@ var DomSurface = class DomSurface {
2974
2832
  this.container.style.cursor = "crosshair";
2975
2833
  return;
2976
2834
  }
2835
+ if (this.current_tool.type === "insert-text") {
2836
+ this.container.style.cursor = "text";
2837
+ return;
2838
+ }
2977
2839
  this.container.style.cursor = this.hud.cursorCss();
2978
2840
  }
2979
2841
  on_keydown(e) {
2980
2842
  if (this.text_edit) return;
2981
- if (e.code === "Escape") this.cancel_in_flight();
2843
+ if (e.code !== "Escape" && !this.attention.is_attended()) return;
2844
+ if (e.code === "Escape") {
2845
+ const canceled = this.cancel_in_flight();
2846
+ if (!this.attention.is_attended()) return;
2847
+ if (!canceled && this.vector_edit) this.exit_vector_edit();
2848
+ }
2982
2849
  if ((this.active_preview || this.translate_orchestrator.has_active_session() || this.resize_orchestrator.has_active_session() || this.rotate_orchestrator.has_active_session() || this.pending_insert) && e.code !== "Escape") return;
2983
2850
  if (this.editor.keymap.claims(e)) e.preventDefault();
2984
2851
  this.editor.keymap.dispatch(e);
@@ -2991,6 +2858,15 @@ var DomSurface = class DomSurface {
2991
2858
  case "deselect_all":
2992
2859
  this.editor.commands.deselect();
2993
2860
  return;
2861
+ case "clear_vector_selection": {
2862
+ if (!this.vector_edit) return;
2863
+ const before = this.vector_edit.snapshot_selection();
2864
+ this.vector_edit.clear_selection();
2865
+ this.sync_selection_mirror();
2866
+ this.redraw();
2867
+ this.record_vector_selection_change(before, "clear vector selection");
2868
+ return;
2869
+ }
2994
2870
  case "translate":
2995
2871
  this.handle_translate(intent);
2996
2872
  return;
@@ -3003,6 +2879,9 @@ var DomSurface = class DomSurface {
3003
2879
  case "marquee_select":
3004
2880
  this.handle_marquee(intent);
3005
2881
  return;
2882
+ case "lasso_select":
2883
+ this.handle_lasso_select(intent);
2884
+ return;
3006
2885
  case "set_endpoint":
3007
2886
  this.handle_set_endpoint(intent);
3008
2887
  return;
@@ -3010,6 +2889,33 @@ var DomSurface = class DomSurface {
3010
2889
  this.editor.commands.select(intent.id);
3011
2890
  this.editor.enter_content_edit(intent.id);
3012
2891
  return;
2892
+ case "exit_content_edit":
2893
+ this.exit_vector_edit();
2894
+ return;
2895
+ case "select_vertex":
2896
+ this.handle_select_vertex(intent);
2897
+ return;
2898
+ case "translate_vertices":
2899
+ this.handle_translate_vertices(intent);
2900
+ return;
2901
+ case "translate_vector_selection":
2902
+ this.handle_translate_vector_selection(intent);
2903
+ return;
2904
+ case "select_segment":
2905
+ this.handle_select_segment(intent);
2906
+ return;
2907
+ case "select_tangent":
2908
+ this.handle_select_tangent(intent);
2909
+ return;
2910
+ case "set_tangent":
2911
+ this.handle_set_tangent_intent(intent);
2912
+ return;
2913
+ case "split_segment":
2914
+ this.handle_split_segment(intent);
2915
+ return;
2916
+ case "bend_segment":
2917
+ this.handle_bend_segment(intent);
2918
+ return;
3013
2919
  case "cancel_gesture":
3014
2920
  this.cancel_in_flight();
3015
2921
  return;
@@ -3049,7 +2955,7 @@ var DomSurface = class DomSurface {
3049
2955
  }
3050
2956
  handle_resize(intent) {
3051
2957
  if (intent.ids.length === 0) return;
3052
- for (const id of intent.ids) if (!is_resizable_node(this.editor.document, id)) return;
2958
+ for (const id of intent.ids) if (!resize_pipeline.intent.is_resizable_node(this.editor.document, id)) return;
3053
2959
  const dir = intent.anchor;
3054
2960
  let target_width;
3055
2961
  let target_height;
@@ -3097,9 +3003,7 @@ var DomSurface = class DomSurface {
3097
3003
  for (const v of verdicts.values()) {
3098
3004
  if (v.kind !== "refuse") continue;
3099
3005
  const message = v.reason === "non-trivial-transform" ? "Cannot rotate cleanly — element has a composite transform. Use Flatten Transform first." : v.reason === "text-with-glyph-rotate" ? "Cannot rotate — text has per-glyph rotation. Edit `rotate=` or remove it first." : v.reason === "css-property-transform" ? "Cannot rotate — transform is set via CSS. Move the declaration to the `transform` attribute first." : "Cannot rotate — element has an animated transform. Remove `<animateTransform>` first.";
3100
- const hud = this.hud;
3101
- if (typeof hud.setTransientToast === "function") hud.setTransientToast(message);
3102
- else console.warn(`[svg-editor] ${message}`);
3006
+ console.warn(`[svg-editor] ${message}`);
3103
3007
  return;
3104
3008
  }
3105
3009
  }
@@ -3184,7 +3088,28 @@ var DomSurface = class DomSurface {
3184
3088
  y: t.y
3185
3089
  };
3186
3090
  }
3091
+ /**
3092
+ * Capture the vector-edit sub-selection on the first region-gesture
3093
+ * preview, and reuse it for every subsequent preview + the commit.
3094
+ * Anchors additive merging and tangent-candidate eligibility to the
3095
+ * gesture-start state so they don't shift mid-drag. Shared by marquee
3096
+ * and lasso — both gestures emit a preview-per-move, both consume the
3097
+ * same baseline. See `vector_edit_region_baseline` doc-comment for the
3098
+ * full rationale. Caller must have a non-null `this.vector_edit`.
3099
+ */
3100
+ ensure_region_baseline() {
3101
+ if (!this.vector_edit_region_baseline) this.vector_edit_region_baseline = {
3102
+ vertices: this.vector_edit.selected_vertices.slice(),
3103
+ segments: this.vector_edit.selected_segments.slice(),
3104
+ tangents: this.vector_edit.selected_tangents.map((t) => [t[0], t[1]])
3105
+ };
3106
+ return this.vector_edit_region_baseline;
3107
+ }
3187
3108
  handle_marquee(intent) {
3109
+ if (this.vector_edit) {
3110
+ this.handle_marquee_vectors(intent);
3111
+ return;
3112
+ }
3188
3113
  if (intent.phase !== "commit") return;
3189
3114
  const ids = [];
3190
3115
  for (const id of this.element_index.keys()) {
@@ -3199,36 +3124,190 @@ var DomSurface = class DomSurface {
3199
3124
  }
3200
3125
  this.editor.commands.select(ids, { mode: intent.additive ? "add" : "replace" });
3201
3126
  }
3202
- enter_content_edit(id) {
3203
- if (this.text_edit) return false;
3204
- const el = this.element_index.get(id);
3205
- if (!(el instanceof SVGElement)) return false;
3206
- const doc = this.editor._internal;
3207
- if (!(el instanceof SVGTextContentElement)) return false;
3208
- this.text_edit_target = id;
3209
- this.text_edit_original = doc.doc.text_of(id);
3210
- this.text_edit = TEXT_EDIT_PENDING;
3211
- this.editor.commands.set_mode("edit-content");
3212
- this.sync_surface_selection();
3213
- this.sync_cursor();
3214
- this.redraw();
3215
- const text_surface = new SvgTextSurface(this.element_index.get(id) ?? el);
3216
- const is_mac = typeof navigator !== "undefined" && /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);
3217
- let settled = false;
3218
- const cleanup_after_commit_or_cancel = () => {
3219
- this.editor.commands.set_mode("select");
3220
- this.render();
3221
- this.sync_surface_selection();
3222
- this.sync_cursor();
3223
- this.redraw();
3224
- this.text_edit = null;
3225
- this.text_edit_target = null;
3127
+ /**
3128
+ * Vector marquee predicate — applies the **vertex-priority precedence
3129
+ * rule** ported from the main editor:
3130
+ *
3131
+ * 1. Vertices: keep those whose container-space position falls inside
3132
+ * the marquee rect.
3133
+ * 2. Tangents: keep only those at the (new) selection's neighbouring
3134
+ * vertices whose control point falls inside the rect.
3135
+ * 3. Segments: keep only segments **fully contained** in the rect AND
3136
+ * whose endpoints are NOT among the selected vertices. (If a vertex
3137
+ * is selected, the segments meeting it would double-credit the
3138
+ * drag, so they're dropped — "vertex priority.")
3139
+ *
3140
+ * The rect comes in container CSS-px (HUD's frame). We project it back
3141
+ * to path-local by applying the inverse-CTM linear part to its size and
3142
+ * shifting its position via `project_delta_inverse_ctm` against the
3143
+ * top-left in doc-space but a cleaner approach is to project each
3144
+ * vertex/tangent/segment-sample into doc-space and test against the rect
3145
+ * directly. For consistency with how `vector_of` projects, we do the
3146
+ * "project geometry to doc-space, test against doc-space rect" approach.
3147
+ */
3148
+ handle_marquee_vectors(intent) {
3149
+ if (!this.vector_edit) return;
3150
+ const node_id = this.vector_edit.node_id;
3151
+ const el = this.element_index.get(node_id);
3152
+ if (!(el instanceof SVGGraphicsElement)) return;
3153
+ if (typeof el.getScreenCTM !== "function") return;
3154
+ const ctm = el.getScreenCTM();
3155
+ if (!ctm) return;
3156
+ const cr = this.container.getBoundingClientRect();
3157
+ const offset = [-cr.left + this.container.scrollLeft, -cr.top + this.container.scrollTop];
3158
+ const model = this.session_model();
3159
+ if (!model) return;
3160
+ const rect = intent.rect;
3161
+ const baseline = this.ensure_region_baseline();
3162
+ const pre_selection = {
3163
+ vertices: baseline.vertices,
3164
+ segments: baseline.segments,
3165
+ tangents: baseline.tangents
3226
3166
  };
3227
- this.text_edit = createTextEditor({
3228
- container: this.container,
3229
- initialText: this.text_edit_original,
3230
- layout: text_surface,
3231
- surface: text_surface,
3167
+ const candidates = marquee.subpath_select_candidates(model, pre_selection, (p) => project_point_through_ctm(p[0], p[1], ctm, offset));
3168
+ const vertex_hits = marquee.points_in_rect(candidates.vertices, rect);
3169
+ const tangent_hits = marquee.points_in_rect(candidates.tangents, rect);
3170
+ const rect_local = inverse_project_rect(rect, ctm, offset);
3171
+ const vertex_hit_set = new Set(vertex_hits);
3172
+ const segment_hits = [];
3173
+ if (rect_local) {
3174
+ const segs = model.snapshot().segments;
3175
+ for (const sid of candidates.segments) {
3176
+ const s = segs[sid];
3177
+ if (vertex_hit_set.has(s.a) || vertex_hit_set.has(s.b)) continue;
3178
+ if (model.segmentContainedByRect(sid, rect_local)) segment_hits.push(sid);
3179
+ }
3180
+ }
3181
+ const merged = marquee.merge_subpath_hits(pre_selection, {
3182
+ vertices: vertex_hits,
3183
+ segments: segment_hits,
3184
+ tangents: tangent_hits
3185
+ }, intent.additive);
3186
+ this.vector_edit.set_selection(merged);
3187
+ this.sync_selection_mirror();
3188
+ if (intent.phase === "commit") {
3189
+ const baseline_snapshot = Object.freeze({
3190
+ vertices: baseline.vertices,
3191
+ segments: baseline.segments,
3192
+ tangents: baseline.tangents
3193
+ });
3194
+ this.vector_edit_region_baseline = null;
3195
+ this.record_vector_selection_change(baseline_snapshot, "marquee select");
3196
+ }
3197
+ this.redraw();
3198
+ }
3199
+ /**
3200
+ * Lasso (freeform polygon) sub-selection — vector analogue of
3201
+ * `handle_marquee`. Per the main editor's decision
3202
+ * (editor/grida-canvas/reducers/methods/vector.ts:163–291 +
3203
+ * event-target.reducer.ts:629–641) lasso targets **vertices and
3204
+ * tangents only** — segments are NOT tested against the polygon. The
3205
+ * segment-vs-region test is rect-only and lives in the marquee path.
3206
+ *
3207
+ * Lifecycle / baseline behaviour matches marquee: snapshot on first
3208
+ * preview, reuse for additive merge and tangent-eligibility, clear on
3209
+ * commit and on vector-edit exit. Scene (non-vector-edit) lasso is a
3210
+ * follow-up.
3211
+ */
3212
+ handle_lasso_select(intent) {
3213
+ if (!this.vector_edit) return;
3214
+ const node_id = this.vector_edit.node_id;
3215
+ const el = this.element_index.get(node_id);
3216
+ if (!(el instanceof SVGGraphicsElement)) return;
3217
+ if (typeof el.getScreenCTM !== "function") return;
3218
+ const ctm = el.getScreenCTM();
3219
+ if (!ctm) return;
3220
+ const cr = this.container.getBoundingClientRect();
3221
+ const offset = [-cr.left + this.container.scrollLeft, -cr.top + this.container.scrollTop];
3222
+ const model = this.session_model();
3223
+ if (!model) return;
3224
+ const polygon = intent.polygon;
3225
+ if (polygon.length < 3) return;
3226
+ const baseline = this.ensure_region_baseline();
3227
+ const pre_selection = {
3228
+ vertices: baseline.vertices,
3229
+ segments: baseline.segments,
3230
+ tangents: baseline.tangents
3231
+ };
3232
+ const candidates = marquee.subpath_select_candidates(model, pre_selection, (p) => project_point_through_ctm(p[0], p[1], ctm, offset));
3233
+ const vertex_hits = marquee.points_in_polygon(candidates.vertices, polygon);
3234
+ const tangent_hits = marquee.points_in_polygon(candidates.tangents, polygon);
3235
+ const merged = marquee.merge_subpath_hits(pre_selection, {
3236
+ vertices: vertex_hits,
3237
+ segments: [],
3238
+ tangents: tangent_hits
3239
+ }, intent.additive);
3240
+ this.vector_edit.set_selection(merged);
3241
+ this.sync_selection_mirror();
3242
+ if (intent.phase === "commit") {
3243
+ const baseline_snapshot = Object.freeze({
3244
+ vertices: baseline.vertices,
3245
+ segments: baseline.segments,
3246
+ tangents: baseline.tangents
3247
+ });
3248
+ this.vector_edit_region_baseline = null;
3249
+ this.record_vector_selection_change(baseline_snapshot, "lasso select");
3250
+ }
3251
+ this.redraw();
3252
+ }
3253
+ /**
3254
+ * Dispatched by the editor when `enter_content_edit(id)` is called. The
3255
+ * editor has already gated on text-OR-path eligibility; this method
3256
+ * routes on the actual tag.
3257
+ */
3258
+ enter_content_edit(id) {
3259
+ if (this.text_edit || this.vector_edit) return false;
3260
+ const tag = this.tag_of(id);
3261
+ if (tag === "text" || tag === "tspan") return this.enter_text_edit(id);
3262
+ if (tag === "path" || tag === "polyline" || tag === "polygon") return this.enter_vector_edit(id);
3263
+ return false;
3264
+ }
3265
+ /**
3266
+ * Place a new single-line `<text>` at `world` and immediately enter
3267
+ * content-edit on it. Creation + first edit are bracketed in one history
3268
+ * preview (via `insert_text_preview`): committing with content is one
3269
+ * undo step, exiting empty discards the node entirely (empty-equals-
3270
+ * delete). The bracket is finalized in {@link enter_text_edit}'s
3271
+ * commit/cancel callbacks via `this.pending_text_insert`.
3272
+ *
3273
+ * Default font appearance lives in `core/insertions.ts`
3274
+ * (`default_text_attrs`), alongside the shape insertion defaults — not
3275
+ * hard-coded here — so the per-element insert semantics stay in core (P3).
3276
+ */
3277
+ begin_text_insert(world) {
3278
+ if (this.text_edit || this.vector_edit) return;
3279
+ const session = this.editor_internal().insert_text_preview(insertions.default_text_attrs(world));
3280
+ this.pending_text_insert = {
3281
+ id: session.id,
3282
+ session
3283
+ };
3284
+ this.editor.enter_content_edit(session.id);
3285
+ if (this.text_edit_target !== session.id) {
3286
+ this.pending_text_insert = null;
3287
+ session.discard();
3288
+ }
3289
+ }
3290
+ enter_text_edit(id) {
3291
+ if (this.text_edit) return false;
3292
+ const el = this.element_index.get(id);
3293
+ if (!(el instanceof SVGElement)) return false;
3294
+ const doc = this.editor._internal;
3295
+ if (!(el instanceof SVGTextContentElement)) return false;
3296
+ this.text_edit_target = id;
3297
+ this.text_edit_original = doc.doc.text_of(id);
3298
+ this.text_edit = TEXT_EDIT_PENDING;
3299
+ this.editor.commands.set_mode("edit-content");
3300
+ this.sync_surface_selection();
3301
+ this.sync_cursor();
3302
+ this.redraw();
3303
+ const text_surface = new SvgTextSurface(this.element_index.get(id) ?? el);
3304
+ const is_mac = typeof navigator !== "undefined" && /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);
3305
+ let settled = false;
3306
+ this.text_edit = createTextEditor({
3307
+ container: this.container,
3308
+ initialText: this.text_edit_original,
3309
+ layout: text_surface,
3310
+ surface: text_surface,
3232
3311
  isMac: is_mac,
3233
3312
  ariaLabel: "edit svg text",
3234
3313
  requiresMutationsForCommit: (text) => /\s{2,}|^\s|\s$/.test(text),
@@ -3239,16 +3318,12 @@ var DomSurface = class DomSurface {
3239
3318
  onCommit: (final_text) => {
3240
3319
  if (settled) return;
3241
3320
  settled = true;
3242
- doc.doc.set_text(id, this.text_edit_original);
3243
- cleanup_after_commit_or_cancel();
3244
- if (final_text !== this.text_edit_original) this.editor.commands.set_text(final_text);
3321
+ this.finalize_text_exit(id, final_text);
3245
3322
  },
3246
3323
  onCancel: () => {
3247
3324
  if (settled) return;
3248
3325
  settled = true;
3249
- doc.doc.set_text(id, this.text_edit_original);
3250
- cleanup_after_commit_or_cancel();
3251
- doc.emit();
3326
+ this.finalize_text_exit(id, this.text_edit_original);
3252
3327
  },
3253
3328
  onUndoFallthrough: () => {
3254
3329
  this.text_edit?.commit();
@@ -3262,6 +3337,800 @@ var DomSurface = class DomSurface {
3262
3337
  });
3263
3338
  return true;
3264
3339
  }
3340
+ /**
3341
+ * Exit inline text-edit back to select mode. P4 — observers should see a
3342
+ * consistent post-edit state, so do all observable mutations + surface
3343
+ * syncs first, then clear the text-edit handles last (so anything polling
3344
+ * "is text-edit active?" still says yes until the world is settled).
3345
+ */
3346
+ cleanup_text_edit() {
3347
+ this.editor.commands.set_mode("select");
3348
+ this.render();
3349
+ this.sync_surface_selection();
3350
+ this.sync_cursor();
3351
+ this.redraw();
3352
+ this.text_edit = null;
3353
+ this.text_edit_target = null;
3354
+ }
3355
+ /**
3356
+ * Realize the result of a text content-edit session and exit. `result`
3357
+ * is the text that should remain — the typed text on commit, the original
3358
+ * on cancel. Implements the empty-equals-delete rule (design:
3359
+ * docs/wg/feat-svg-editor/text-tool.md): an empty result removes the node.
3360
+ * (see test/svg-editor-text-empty-delete.md)
3361
+ *
3362
+ * The empty-equals-delete decision is pure and lives in
3363
+ * {@link resolve_text_exit} (`core/text-edit.ts`) — tested headlessly.
3364
+ * This method is the thin dispatcher that realizes each action against
3365
+ * the surface + editor.
3366
+ */
3367
+ finalize_text_exit(id, result) {
3368
+ const internal = this.editor_internal();
3369
+ const insert = this.pending_text_insert;
3370
+ this.pending_text_insert = null;
3371
+ const action = resolve_text_exit({
3372
+ origin: insert && insert.id === id ? "fresh" : "existing",
3373
+ result,
3374
+ original: this.text_edit_original
3375
+ });
3376
+ if (action.kind === "commit_insert" || action.kind === "discard_insert") {
3377
+ if (!insert) return;
3378
+ if (action.kind === "discard_insert") {
3379
+ this.cleanup_text_edit();
3380
+ insert.session.discard();
3381
+ } else {
3382
+ this.cleanup_text_edit();
3383
+ insert.session.commit();
3384
+ }
3385
+ return;
3386
+ }
3387
+ internal.doc.set_text(id, this.text_edit_original);
3388
+ this.cleanup_text_edit();
3389
+ switch (action.kind) {
3390
+ case "remove":
3391
+ this.editor.commands.select(id);
3392
+ this.editor.commands.remove();
3393
+ break;
3394
+ case "set_text":
3395
+ this.editor.commands.set_text(action.value);
3396
+ break;
3397
+ case "noop":
3398
+ internal.emit();
3399
+ break;
3400
+ default:
3401
+ }
3402
+ }
3403
+ /**
3404
+ * Enter path-vertex-edit mode. Mirrors `enter_text_edit` shape: capture
3405
+ * the original `d`, flip the editor mode, push a vector-selection mirror
3406
+ * to the HUD, and start serving `vectorOf` from the live session.
3407
+ *
3408
+ * Exit happens via `exit_vector_edit` (Esc / `set_mode("select")` /
3409
+ * dblclick away). On exit, any in-flight preview is discarded; committed
3410
+ * intermediate states stay (each gesture's commit was its own history
3411
+ * entry, per the gesture-bracketed history doctrine).
3412
+ *
3413
+ * The enter is itself a history step (tagged `vector-mode-enter`) so
3414
+ * undo from inside vector-edit reverts the entry — symmetric to the
3415
+ * `vector-mode-exit` push in {@link exit_vector_edit}. Both deltas
3416
+ * delegate to the unchecked {@link _do_enter_vector_edit} /
3417
+ * {@link _do_exit_vector_edit} helpers; the public wrappers below own
3418
+ * the history side, the unchecked helpers own the state mutation.
3419
+ */
3420
+ enter_vector_edit(id) {
3421
+ if (this.vector_edit) return false;
3422
+ if (!this._do_enter_vector_edit(id)) return false;
3423
+ const internal = this.editor_internal();
3424
+ const node_id = id;
3425
+ const preview = internal.history.preview("enter vector edit");
3426
+ preview.set({
3427
+ providerId: "svg-editor",
3428
+ descriptor: { kind: "vector-mode-enter" },
3429
+ apply: () => {
3430
+ this._do_enter_vector_edit(node_id);
3431
+ },
3432
+ revert: () => {
3433
+ this._do_exit_vector_edit();
3434
+ }
3435
+ });
3436
+ preview.commit();
3437
+ return true;
3438
+ }
3439
+ /**
3440
+ * Discard any in-flight preview, clear the vector-edit session, and return
3441
+ * the editor to select mode. Safe to call when no vector-edit is active
3442
+ * (no-op). Idempotent.
3443
+ *
3444
+ * Pushes a `vector-mode-exit` history step that closes over the
3445
+ * session's `node_id` and its final sub-selection, so undo re-enters
3446
+ * the same path and restores the selection the user was about to
3447
+ * leave. Pairs with {@link enter_vector_edit}.
3448
+ */
3449
+ exit_vector_edit() {
3450
+ if (!this.vector_edit) return;
3451
+ const node_id = this.vector_edit.node_id;
3452
+ const final_selection = this.vector_edit.snapshot_selection();
3453
+ this._do_exit_vector_edit();
3454
+ const preview = this.editor_internal().history.preview("exit vector edit");
3455
+ preview.set({
3456
+ providerId: "svg-editor",
3457
+ descriptor: { kind: "vector-mode-exit" },
3458
+ apply: () => {
3459
+ this._do_exit_vector_edit();
3460
+ },
3461
+ revert: () => {
3462
+ if (this._do_enter_vector_edit(node_id)) {
3463
+ this.vector_edit?.restore_selection(final_selection);
3464
+ this.sync_selection_mirror();
3465
+ this.redraw();
3466
+ }
3467
+ }
3468
+ });
3469
+ preview.commit();
3470
+ }
3471
+ /**
3472
+ * Unchecked enter — performs the mode flip + HUD wiring without
3473
+ * pushing to history. Called by {@link enter_vector_edit} (user-facing,
3474
+ * which pushes the delta) and by the exit-delta's revert (history-
3475
+ * driven re-entry on undo). Returns `false` if the node has no usable
3476
+ * `d` attribute, leaving editor state untouched.
3477
+ */
3478
+ _do_enter_vector_edit(id) {
3479
+ if (this.vector_edit) return false;
3480
+ const source = this.editor_internal().doc.is_vector_edit_target(id);
3481
+ if (source === null) return false;
3482
+ const session_d = source_to_session_d(source);
3483
+ this.vector_edit = new VectorEditSession(id, source, session_d);
3484
+ this.editor.commands.set_mode("edit-content");
3485
+ this.sync_selection_mirror();
3486
+ this.sync_surface_selection();
3487
+ this.sync_cursor();
3488
+ this.redraw();
3489
+ return true;
3490
+ }
3491
+ /**
3492
+ * Unchecked exit — counterpart to {@link _do_enter_vector_edit}. No
3493
+ * history push. Safe to call when no session is active.
3494
+ */
3495
+ _do_exit_vector_edit() {
3496
+ if (!this.vector_edit) return;
3497
+ if (this.active_preview && (this.active_preview.kind === "vector_vertex_translate" || this.active_preview.kind === "vector_set_tangent" || this.active_preview.kind === "vector_bend_segment" || this.active_preview.kind === "vector_translate_selection")) {
3498
+ this.active_preview.session.discard();
3499
+ this.active_preview = null;
3500
+ }
3501
+ this.vector_edit = null;
3502
+ this.vector_edit_region_baseline = null;
3503
+ this.hud.setVectorSelection(null);
3504
+ if (this.current_tool.type === "lasso" || this.current_tool.type === "bend") this.editor.set_tool({ type: "cursor" });
3505
+ this.editor.commands.set_mode("select");
3506
+ this.sync_surface_selection();
3507
+ this.sync_cursor();
3508
+ this.redraw();
3509
+ }
3510
+ /**
3511
+ * `vectorOf` provider for the HUD. Returns the live PathSnapshot for the
3512
+ * named node when a vector-edit session is active for it; otherwise null.
3513
+ * HUD calls this each frame; cheap enough to recompute (snapshot just
3514
+ * copies the underlying network's arrays via the model's getter).
3515
+ */
3516
+ vector_of(id) {
3517
+ if (!this.vector_edit || this.vector_edit.node_id !== id) return null;
3518
+ const model = this.active_preview_model_for(id) ?? this.session_model();
3519
+ if (!model) return null;
3520
+ const snap = model.snapshot();
3521
+ const el = this.element_index.get(id);
3522
+ if (!(el instanceof SVGGraphicsElement)) return null;
3523
+ if (typeof el.getScreenCTM !== "function") return null;
3524
+ const ctm = el.getScreenCTM();
3525
+ if (!ctm) return null;
3526
+ const cr = this.container.getBoundingClientRect();
3527
+ const offset = [-cr.left + this.container.scrollLeft, -cr.top + this.container.scrollTop];
3528
+ return {
3529
+ vertices: Array.from({ length: snap.vertices.length }, (_, i) => {
3530
+ const v = snap.vertices[i];
3531
+ return project_point_through_ctm(v[0], v[1], ctm, offset);
3532
+ }),
3533
+ segments: snap.segments.map((s) => {
3534
+ const va = snap.vertices[s.a];
3535
+ const vb = snap.vertices[s.b];
3536
+ const a_ctrl_local = [va[0] + s.ta[0], va[1] + s.ta[1]];
3537
+ const b_ctrl_local = [vb[0] + s.tb[0], vb[1] + s.tb[1]];
3538
+ return {
3539
+ a: s.a,
3540
+ b: s.b,
3541
+ a_control: project_point_through_ctm(a_ctrl_local[0], a_ctrl_local[1], ctm, offset),
3542
+ b_control: project_point_through_ctm(b_ctrl_local[0], b_ctrl_local[1], ctm, offset)
3543
+ };
3544
+ }),
3545
+ neighbours: this.vector_edit.source.kind === "path" ? model.neighbouringVertices({
3546
+ vertices: this.vector_edit.selected_vertices,
3547
+ segments: this.vector_edit.selected_segments,
3548
+ tangents: this.vector_edit.selected_tangents
3549
+ }) : EMPTY_NEIGHBOURS,
3550
+ origin: [0, 0]
3551
+ };
3552
+ }
3553
+ /**
3554
+ * The session's in-memory PathModel-form `d`. For `<path>` sources
3555
+ * this stays in lock-step with `doc.get_attr(id, "d")`; for
3556
+ * `<line>` / `<polyline>` / `<polygon>` sources the document holds
3557
+ * native attrs and the session-d is the lingua-franca view that
3558
+ * gesture handlers parse from and write back to via
3559
+ * {@link apply_session_d}. Returns `null` if no session is active.
3560
+ */
3561
+ read_session_d() {
3562
+ if (!this.vector_edit) return null;
3563
+ return this.vector_edit.current_d;
3564
+ }
3565
+ /**
3566
+ * Derive a fresh `PathModel` from the current `d` for the path under
3567
+ * edit. Computed on read — there is no cached copy held on the session.
3568
+ * See `vector-edit/session.ts` for the doctrine ("d is the live store").
3569
+ */
3570
+ session_model() {
3571
+ const d = this.read_session_d();
3572
+ if (d === null) return null;
3573
+ return PathModel.fromSvgPathD(d);
3574
+ }
3575
+ /**
3576
+ * Republish the vector-edit sub-selection to the HUD. No-op when no
3577
+ * session is open. Every selection-changing handler ends with this so
3578
+ * the surface mirror stays in lock-step with `this.vector_edit` — the
3579
+ * inline `setVectorSelection({ node_id, vertices, segments, tangents })`
3580
+ * block was repeated at 6+ sites before this collapse.
3581
+ */
3582
+ sync_selection_mirror() {
3583
+ if (!this.vector_edit) return;
3584
+ this.hud.setVectorSelection({
3585
+ node_id: this.vector_edit.node_id,
3586
+ vertices: this.vector_edit.selected_vertices,
3587
+ segments: this.vector_edit.selected_segments,
3588
+ tangents: this.vector_edit.selected_tangents
3589
+ });
3590
+ }
3591
+ /**
3592
+ * Replay the session-side effects of a committed vector-edit delta onto
3593
+ * the LIVE `this.vector_edit` session — but only if it is still aimed at
3594
+ * the same node. Geometry restoration is the closure's `commit(d)` job
3595
+ * (document-level, always safe); this method handles the bits the
3596
+ * geometry write cannot reach on its own: advancing `last_seen_d` so
3597
+ * the external-mutation watcher doesn't pounce, and re-installing the
3598
+ * captured sub-selection.
3599
+ *
3600
+ * Closures used to call `session.mark_seen(...)` / `session.restore_selection(...)`
3601
+ * on a `const session = this.vector_edit` captured at gesture start.
3602
+ * After exit + undo-exit + undo-geometry, that capture pointed at the
3603
+ * disposed session while the live session was a fresh one — geometry
3604
+ * still restored correctly (via `commit`), but sub-selection didn't,
3605
+ * and the live session's stale `last_seen_d` would then cause the
3606
+ * watcher to clear the new session's selection on its next tick.
3607
+ *
3608
+ * Pass `d = null` for selection-only deltas (no geometry change → no
3609
+ * watermark advance).
3610
+ */
3611
+ replay_vector_session_state(target_node_id, d, selection) {
3612
+ const cur = this.vector_edit;
3613
+ if (!cur || cur.node_id !== target_node_id) return;
3614
+ if (d !== null) cur.mark_seen(d);
3615
+ cur.restore_selection(selection);
3616
+ this.sync_selection_mirror();
3617
+ }
3618
+ /**
3619
+ * Push a standalone vector sub-selection change as one history entry.
3620
+ *
3621
+ * Called by selection-only handlers (vertex / segment / tangent click,
3622
+ * marquee / lasso commit, clear-vector-selection) AFTER the
3623
+ * `VectorEditSession` has been mutated to the new state. `before` is the
3624
+ * snapshot captured before the mutation; the current session state is
3625
+ * captured here as `after`.
3626
+ *
3627
+ * Tagged with `descriptor: { kind: "vector-selection" }` so hosts that
3628
+ * want Figma-style "skip selection on undo" can filter on the
3629
+ * descriptor without inspecting closure internals. Default behavior:
3630
+ * standalone vector-selection IS undoable.
3631
+ *
3632
+ * No-op when the snapshot is unchanged — avoids spamming the stack
3633
+ * with entries from clicks that resolve to the same state (e.g.
3634
+ * clicking an already-selected vertex in `replace` mode).
3635
+ */
3636
+ record_vector_selection_change(before, label) {
3637
+ if (!this.vector_edit) return;
3638
+ const after = this.vector_edit.snapshot_selection();
3639
+ if (sub_selection_equal(before, after)) return;
3640
+ const target_node_id = this.vector_edit.node_id;
3641
+ const preview = this.editor_internal().history.preview(label);
3642
+ preview.set({
3643
+ providerId: "svg-editor",
3644
+ descriptor: { kind: "vector-selection" },
3645
+ apply: () => {
3646
+ this.replay_vector_session_state(target_node_id, null, after);
3647
+ this.redraw();
3648
+ },
3649
+ revert: () => {
3650
+ this.replay_vector_session_state(target_node_id, null, before);
3651
+ this.redraw();
3652
+ }
3653
+ });
3654
+ preview.commit();
3655
+ }
3656
+ /** Resolve the in-flight `PathModel` for the named node id when a
3657
+ * vector-preview is active; null otherwise. */
3658
+ active_preview_model_for(id) {
3659
+ const ap = this.active_preview;
3660
+ if (!ap) return null;
3661
+ switch (ap.kind) {
3662
+ case "vector_vertex_translate": return ap.node_id === id ? ap.preview_model : null;
3663
+ case "vector_set_tangent": return ap.node_id === id ? ap.preview_model : null;
3664
+ case "vector_bend_segment": return ap.node_id === id ? ap.preview_model : null;
3665
+ case "vector_translate_selection": return ap.node_id === id ? ap.preview_model : null;
3666
+ default: return null;
3667
+ }
3668
+ }
3669
+ /**
3670
+ * Apply a `select_vertex` intent. Updates the vector-edit session's sub-
3671
+ * selection and pushes a fresh mirror to the HUD.
3672
+ */
3673
+ handle_select_vertex(intent) {
3674
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
3675
+ const before = this.vector_edit.snapshot_selection();
3676
+ this.vector_edit.select_vertex(intent.index, intent.mode);
3677
+ this.sync_selection_mirror();
3678
+ this.redraw();
3679
+ this.record_vector_selection_change(before, "select vertex");
3680
+ }
3681
+ /**
3682
+ * Apply a `select_segment` intent. Mirrors {@link handle_select_vertex}.
3683
+ * Fired when the user clicks a segment OFF the ghost insertion knob —
3684
+ * clicking the ghost itself fires `split_segment` instead.
3685
+ */
3686
+ handle_select_segment(intent) {
3687
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
3688
+ const before = this.vector_edit.snapshot_selection();
3689
+ this.vector_edit.select_segment(intent.segment, intent.mode);
3690
+ this.sync_selection_mirror();
3691
+ this.redraw();
3692
+ this.record_vector_selection_change(before, "select segment");
3693
+ }
3694
+ /**
3695
+ * Apply a `translate_vertices` intent. Mirrors the `set_endpoint` flow:
3696
+ * - First frame opens a `history.preview` session capturing the original `d`.
3697
+ * - Each subsequent preview frame applies a fresh translation FROM the
3698
+ * original baseline (so the cumulative delta on the intent stays correct
3699
+ * and we don't accumulate drift across frames).
3700
+ * - The commit frame finalizes the preview; the session keeps its updated
3701
+ * model for the next gesture.
3702
+ *
3703
+ * The vector-edit session's `model` is updated to reflect the committed
3704
+ * state (preview model is computed on the fly each frame from the
3705
+ * baseline; only commit writes back into session.model).
3706
+ */
3707
+ handle_translate_vertices(intent) {
3708
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
3709
+ const internal = this.editor_internal();
3710
+ const doc = internal.doc;
3711
+ const emit = internal.emit;
3712
+ const node_id = intent.node_id;
3713
+ const source = this.vector_edit.source;
3714
+ const commit = (d) => apply_session_d(doc, node_id, source, d);
3715
+ if (!this.active_preview || this.active_preview.kind !== "vector_vertex_translate" || this.active_preview.node_id !== node_id || !array_shallow_equal(this.active_preview.indices, intent.indices)) {
3716
+ if (this.active_preview) {
3717
+ if ("session" in this.active_preview) this.active_preview.session.discard();
3718
+ }
3719
+ const initial_d = this.read_session_d();
3720
+ if (initial_d === null) return;
3721
+ const baseline_model = PathModel.fromSvgPathD(initial_d);
3722
+ this.active_preview = {
3723
+ kind: "vector_vertex_translate",
3724
+ node_id,
3725
+ indices: [...intent.indices],
3726
+ initial_d,
3727
+ baseline_model,
3728
+ before_selection: this.vector_edit.snapshot_selection(),
3729
+ preview_model: baseline_model,
3730
+ session: internal.history.preview("vector/translate-vertex")
3731
+ };
3732
+ }
3733
+ const baseline_d = this.active_preview.initial_d;
3734
+ const indices = this.active_preview.indices;
3735
+ let local_dx = intent.dx;
3736
+ let local_dy = intent.dy;
3737
+ const el = this.element_index.get(node_id);
3738
+ if (el instanceof SVGGraphicsElement && typeof el.getScreenCTM === "function") {
3739
+ const ctm = el.getScreenCTM();
3740
+ if (ctm) {
3741
+ if (ctm.a * ctm.d - ctm.c * ctm.b !== 0) [local_dx, local_dy] = project_delta_inverse_ctm(intent.dx, intent.dy, ctm);
3742
+ }
3743
+ }
3744
+ const preview_model = this.active_preview.baseline_model.translateVertices(indices, [local_dx, local_dy]);
3745
+ const target_d = preview_model.toSvgPathD();
3746
+ this.active_preview.preview_model = preview_model;
3747
+ if (intent.phase === "commit") {
3748
+ const before_selection = this.active_preview.before_selection;
3749
+ const after_selection = this.vector_edit.snapshot_selection();
3750
+ this.active_preview.session.set({
3751
+ providerId: "svg-editor",
3752
+ apply: () => {
3753
+ commit(target_d);
3754
+ this.replay_vector_session_state(node_id, target_d, after_selection);
3755
+ emit();
3756
+ },
3757
+ revert: () => {
3758
+ commit(baseline_d);
3759
+ this.replay_vector_session_state(node_id, baseline_d, before_selection);
3760
+ emit();
3761
+ }
3762
+ });
3763
+ this.active_preview.session.commit();
3764
+ this.active_preview = null;
3765
+ } else this.active_preview.session.set({
3766
+ providerId: "svg-editor",
3767
+ apply: () => {
3768
+ commit(target_d);
3769
+ emit();
3770
+ },
3771
+ revert: () => {
3772
+ commit(baseline_d);
3773
+ emit();
3774
+ }
3775
+ });
3776
+ }
3777
+ /**
3778
+ * `translate_vector_selection` — the sub-selection-aware delta-translate.
3779
+ *
3780
+ * Mirrors main editor's `translate-vector-controls`
3781
+ * (`editor/grida-canvas/reducers/tools/event-target.cem-vector.reducer.ts:667-675`).
3782
+ * Translates the union of:
3783
+ *
3784
+ * - selected vertices (authoritative sub-selection)
3785
+ * - endpoints of selected segments (segment selection implies
3786
+ * its two endpoints translate)
3787
+ * - intent.additional_vertex_indices (carried by segment drag so
3788
+ * endpoints translate even
3789
+ * when the segment isn't yet
3790
+ * in sub-selection — the
3791
+ * deferred select_segment was
3792
+ * canceled by drag promotion)
3793
+ *
3794
+ * AND delta-translates selected tangents, EXCLUDING tangents whose parent
3795
+ * vertex is already in the translated set (mirrors `vector.ts:39-42`'s
3796
+ * `getUXNeighbouringVertices`-style exclusion: the vertex move already
3797
+ * carries its tangent controls, so double-applying would shift them
3798
+ * twice). Mirror policy pinned to `"none"` during multi-translate; mirror
3799
+ * behavior is reserved for the singleton-tangent curve gesture.
3800
+ *
3801
+ * Opens a dedicated `vector_translate_selection` preview so the
3802
+ * vertex translate AND tangent delta apply atomically per frame.
3803
+ */
3804
+ handle_translate_vector_selection(intent) {
3805
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
3806
+ const internal = this.editor_internal();
3807
+ const doc = internal.doc;
3808
+ const emit = internal.emit;
3809
+ const node_id = intent.node_id;
3810
+ const source = this.vector_edit.source;
3811
+ const commit = (d) => apply_session_d(doc, node_id, source, d);
3812
+ const ses = this.vector_edit;
3813
+ const current_d = this.read_session_d();
3814
+ if (current_d === null) return;
3815
+ const resolved_model = PathModel.fromSvgPathD(current_d);
3816
+ const vertex_count = resolved_model.vertexCount();
3817
+ const segment_snapshot = resolved_model.snapshot().segments;
3818
+ const indices_set = /* @__PURE__ */ new Set();
3819
+ const add_if_valid = (i) => {
3820
+ if (i >= 0 && i < vertex_count) indices_set.add(i);
3821
+ };
3822
+ for (const v of ses.selected_vertices) add_if_valid(v);
3823
+ for (const s of ses.selected_segments) {
3824
+ const seg = segment_snapshot[s];
3825
+ if (!seg) continue;
3826
+ add_if_valid(seg.a);
3827
+ add_if_valid(seg.b);
3828
+ }
3829
+ for (const v of intent.additional_vertex_indices) add_if_valid(v);
3830
+ const tangent_refs = [];
3831
+ for (const ref of ses.selected_tangents) {
3832
+ if (indices_set.has(ref[0])) continue;
3833
+ tangent_refs.push(ref);
3834
+ }
3835
+ if (indices_set.size === 0 && tangent_refs.length === 0) return;
3836
+ const indices = Array.from(indices_set).sort((a, b) => a - b);
3837
+ if (!this.active_preview || this.active_preview.kind !== "vector_translate_selection" || this.active_preview.node_id !== node_id || !array_shallow_equal(this.active_preview.indices, indices) || !sameTangentRefs(this.active_preview.tangent_refs, tangent_refs)) {
3838
+ if (this.active_preview) {
3839
+ if ("session" in this.active_preview) this.active_preview.session.discard();
3840
+ }
3841
+ const initial_d = this.read_session_d();
3842
+ if (initial_d === null) return;
3843
+ const baseline_model = PathModel.fromSvgPathD(initial_d);
3844
+ const baseline_tangent_abs = tangent_refs.map((ref) => baseline_model.tangentAbsolute(ref, [0, 0]));
3845
+ this.active_preview = {
3846
+ kind: "vector_translate_selection",
3847
+ node_id,
3848
+ indices: [...indices],
3849
+ tangent_refs: [...tangent_refs],
3850
+ initial_d,
3851
+ before_selection: this.vector_edit.snapshot_selection(),
3852
+ preview_model: baseline_model,
3853
+ baseline_model,
3854
+ baseline_tangent_abs,
3855
+ session: internal.history.preview("vector/translate-selection")
3856
+ };
3857
+ }
3858
+ const baseline_d = this.active_preview.initial_d;
3859
+ let local_dx = intent.dx;
3860
+ let local_dy = intent.dy;
3861
+ const el = this.element_index.get(node_id);
3862
+ if (el instanceof SVGGraphicsElement && typeof el.getScreenCTM === "function") {
3863
+ const ctm = el.getScreenCTM();
3864
+ if (ctm) {
3865
+ if (ctm.a * ctm.d - ctm.c * ctm.b !== 0) [local_dx, local_dy] = project_delta_inverse_ctm(intent.dx, intent.dy, ctm);
3866
+ }
3867
+ }
3868
+ const baseline_model = this.active_preview.baseline_model;
3869
+ const baseline_tangent_abs = this.active_preview.baseline_tangent_abs;
3870
+ let preview_model = indices.length > 0 ? baseline_model.translateVertices(indices, [local_dx, local_dy]) : baseline_model;
3871
+ for (let i = 0; i < tangent_refs.length; i++) {
3872
+ const baseline_abs = baseline_tangent_abs[i];
3873
+ if (baseline_abs === null) continue;
3874
+ preview_model = preview_model.setTangent(tangent_refs[i], [baseline_abs[0] + local_dx, baseline_abs[1] + local_dy], "none");
3875
+ }
3876
+ const target_d = preview_model.toSvgPathD();
3877
+ this.active_preview.preview_model = preview_model;
3878
+ if (intent.phase === "commit") {
3879
+ const before_selection = this.active_preview.before_selection;
3880
+ const after_selection = this.vector_edit.snapshot_selection();
3881
+ this.active_preview.session.set({
3882
+ providerId: "svg-editor",
3883
+ apply: () => {
3884
+ commit(target_d);
3885
+ this.replay_vector_session_state(node_id, target_d, after_selection);
3886
+ emit();
3887
+ },
3888
+ revert: () => {
3889
+ commit(baseline_d);
3890
+ this.replay_vector_session_state(node_id, baseline_d, before_selection);
3891
+ emit();
3892
+ }
3893
+ });
3894
+ this.active_preview.session.commit();
3895
+ this.active_preview = null;
3896
+ } else this.active_preview.session.set({
3897
+ providerId: "svg-editor",
3898
+ apply: () => {
3899
+ commit(target_d);
3900
+ emit();
3901
+ },
3902
+ revert: () => {
3903
+ commit(baseline_d);
3904
+ emit();
3905
+ }
3906
+ });
3907
+ }
3908
+ /** Mirror handler for `select_tangent` (analogous to `select_vertex`). */
3909
+ handle_select_tangent(intent) {
3910
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
3911
+ const before = this.vector_edit.snapshot_selection();
3912
+ this.vector_edit.select_tangent(intent.tangent, intent.mode);
3913
+ this.sync_selection_mirror();
3914
+ this.redraw();
3915
+ this.record_vector_selection_change(before, "select tangent");
3916
+ }
3917
+ /**
3918
+ * Tangent drag handler. Mirrors `handle_translate_vertices`:
3919
+ *
3920
+ * - First frame opens a `history.preview` session, captures `original_d`.
3921
+ * - Each preview frame replays setTangent from the baseline model so
3922
+ * cumulative drift never accumulates.
3923
+ * - Commit finalizes the preview and reseeds the session.
3924
+ *
3925
+ * `intent.pos` arrives in container CSS-px (HUD's doc-space). We project
3926
+ * it back through the inverse-CTM to path-local before calling
3927
+ * `PathModel.setTangent`.
3928
+ */
3929
+ handle_set_tangent_intent(intent) {
3930
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
3931
+ if (this.vector_edit.source.kind !== "path") return;
3932
+ const internal = this.editor_internal();
3933
+ const doc = internal.doc;
3934
+ const emit = internal.emit;
3935
+ const node_id = intent.node_id;
3936
+ const source = this.vector_edit.source;
3937
+ const commit = (d) => apply_session_d(doc, node_id, source, d);
3938
+ if (!this.active_preview || this.active_preview.kind !== "vector_set_tangent" || this.active_preview.node_id !== node_id || this.active_preview.tangent[0] !== intent.tangent[0] || this.active_preview.tangent[1] !== intent.tangent[1]) {
3939
+ if (this.active_preview && "session" in this.active_preview) this.active_preview.session.discard();
3940
+ const initial_d = this.read_session_d();
3941
+ if (initial_d === null) return;
3942
+ const baseline_model = PathModel.fromSvgPathD(initial_d);
3943
+ this.active_preview = {
3944
+ kind: "vector_set_tangent",
3945
+ node_id,
3946
+ tangent: [intent.tangent[0], intent.tangent[1]],
3947
+ initial_d,
3948
+ baseline_model,
3949
+ before_selection: this.vector_edit.snapshot_selection(),
3950
+ preview_model: baseline_model,
3951
+ session: internal.history.preview("vector/set-tangent")
3952
+ };
3953
+ }
3954
+ const baseline_d = this.active_preview.initial_d;
3955
+ const local_pos = this.project_doc_point_to_local(node_id, intent.pos);
3956
+ if (!local_pos) return;
3957
+ const preview_model = this.active_preview.baseline_model.setTangent(intent.tangent, local_pos, intent.mirror);
3958
+ const target_d = preview_model.toSvgPathD();
3959
+ this.active_preview.preview_model = preview_model;
3960
+ if (intent.phase === "commit") {
3961
+ const before_selection = this.active_preview.before_selection;
3962
+ const after_selection = this.vector_edit.snapshot_selection();
3963
+ this.active_preview.session.set({
3964
+ providerId: "svg-editor",
3965
+ apply: () => {
3966
+ commit(target_d);
3967
+ this.replay_vector_session_state(node_id, target_d, after_selection);
3968
+ emit();
3969
+ },
3970
+ revert: () => {
3971
+ commit(baseline_d);
3972
+ this.replay_vector_session_state(node_id, baseline_d, before_selection);
3973
+ emit();
3974
+ }
3975
+ });
3976
+ this.active_preview.session.commit();
3977
+ this.active_preview = null;
3978
+ } else this.active_preview.session.set({
3979
+ providerId: "svg-editor",
3980
+ apply: () => {
3981
+ commit(target_d);
3982
+ emit();
3983
+ },
3984
+ revert: () => {
3985
+ commit(baseline_d);
3986
+ emit();
3987
+ }
3988
+ });
3989
+ }
3990
+ /**
3991
+ * Split a segment at parametric position `t`. One-shot atomic edit; no
3992
+ * preview phase. After the split, the new vertex is auto-selected — this
3993
+ * matches Figma's add-anchor behavior and prepares the user to immediately
3994
+ * drag the newly inserted anchor.
3995
+ */
3996
+ handle_split_segment(intent) {
3997
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
3998
+ const node_id = intent.node_id;
3999
+ const source = this.vector_edit.source;
4000
+ const commit = (d) => apply_session_d(doc, node_id, source, d);
4001
+ const baseline_d = this.read_session_d();
4002
+ if (baseline_d === null) return;
4003
+ const { model: next_model, new_vertex } = PathModel.fromSvgPathD(baseline_d).splitSegment(intent.segment, intent.t);
4004
+ const target_d = next_model.toSvgPathD();
4005
+ const internal = this.editor_internal();
4006
+ const doc = internal.doc;
4007
+ const emit = internal.emit;
4008
+ const before_selection = this.vector_edit.snapshot_selection();
4009
+ const after_selection = Object.freeze({
4010
+ vertices: Object.freeze([new_vertex]),
4011
+ segments: Object.freeze([]),
4012
+ tangents: Object.freeze([])
4013
+ });
4014
+ const split_session = internal.history.preview("vector/split-segment");
4015
+ split_session.set({
4016
+ providerId: "svg-editor",
4017
+ apply: () => {
4018
+ commit(target_d);
4019
+ this.replay_vector_session_state(node_id, target_d, after_selection);
4020
+ emit();
4021
+ },
4022
+ revert: () => {
4023
+ commit(baseline_d);
4024
+ this.replay_vector_session_state(node_id, baseline_d, before_selection);
4025
+ emit();
4026
+ }
4027
+ });
4028
+ split_session.commit();
4029
+ this.redraw();
4030
+ }
4031
+ /**
4032
+ * Bend a segment by dragging an interior point. Mirrors set_tangent —
4033
+ * preview session opened on first frame, replays from baseline each
4034
+ * frame, commits / reseeds on phase===commit.
4035
+ *
4036
+ * `frozen` is captured ONCE at session open from the baseline model;
4037
+ * `vne.bendSegment` solves for new tangents against this snapshot, so
4038
+ * the cumulative drag delta is correct without per-frame drift.
4039
+ */
4040
+ handle_bend_segment(intent) {
4041
+ if (!this.vector_edit || this.vector_edit.node_id !== intent.node_id) return;
4042
+ if (this.vector_edit.source.kind !== "path") return;
4043
+ const internal = this.editor_internal();
4044
+ const doc = internal.doc;
4045
+ const emit = internal.emit;
4046
+ const node_id = intent.node_id;
4047
+ const source = this.vector_edit.source;
4048
+ const commit = (d) => apply_session_d(doc, node_id, source, d);
4049
+ if (!this.active_preview || this.active_preview.kind !== "vector_bend_segment" || this.active_preview.node_id !== node_id || this.active_preview.segment !== intent.segment || this.active_preview.ca !== intent.ca) {
4050
+ if (this.active_preview && "session" in this.active_preview) this.active_preview.session.discard();
4051
+ const initial_d = this.read_session_d();
4052
+ if (initial_d === null) return;
4053
+ const baseline_model = PathModel.fromSvgPathD(initial_d);
4054
+ const snap = baseline_model.snapshot();
4055
+ const s = snap.segments[intent.segment];
4056
+ if (!s) return;
4057
+ const va = snap.vertices[s.a];
4058
+ const vb = snap.vertices[s.b];
4059
+ this.active_preview = {
4060
+ kind: "vector_bend_segment",
4061
+ node_id,
4062
+ segment: intent.segment,
4063
+ ca: intent.ca,
4064
+ frozen: {
4065
+ a: [va[0], va[1]],
4066
+ b: [vb[0], vb[1]],
4067
+ ta: [s.ta[0], s.ta[1]],
4068
+ tb: [s.tb[0], s.tb[1]]
4069
+ },
4070
+ initial_d,
4071
+ baseline_model,
4072
+ before_selection: this.vector_edit.snapshot_selection(),
4073
+ preview_model: baseline_model,
4074
+ session: internal.history.preview("vector/bend-segment")
4075
+ };
4076
+ }
4077
+ const baseline_d = this.active_preview.initial_d;
4078
+ const frozen = this.active_preview.frozen;
4079
+ const local_cb = this.project_doc_point_to_local(node_id, intent.cb);
4080
+ if (!local_cb) return;
4081
+ const preview_model = this.active_preview.baseline_model.bendSegment(intent.segment, intent.ca, local_cb, frozen);
4082
+ const target_d = preview_model.toSvgPathD();
4083
+ this.active_preview.preview_model = preview_model;
4084
+ if (intent.phase === "commit") {
4085
+ const before_selection = this.active_preview.before_selection;
4086
+ const after_selection = this.vector_edit.snapshot_selection();
4087
+ this.active_preview.session.set({
4088
+ providerId: "svg-editor",
4089
+ apply: () => {
4090
+ commit(target_d);
4091
+ this.replay_vector_session_state(node_id, target_d, after_selection);
4092
+ emit();
4093
+ },
4094
+ revert: () => {
4095
+ commit(baseline_d);
4096
+ this.replay_vector_session_state(node_id, baseline_d, before_selection);
4097
+ emit();
4098
+ }
4099
+ });
4100
+ this.active_preview.session.commit();
4101
+ this.active_preview = null;
4102
+ } else this.active_preview.session.set({
4103
+ providerId: "svg-editor",
4104
+ apply: () => {
4105
+ commit(target_d);
4106
+ emit();
4107
+ },
4108
+ revert: () => {
4109
+ commit(baseline_d);
4110
+ emit();
4111
+ }
4112
+ });
4113
+ }
4114
+ /**
4115
+ * Project a doc-space point (HUD's container CSS-px frame) back to the
4116
+ * named element's local frame via inverse-CTM. Returns null if no CTM
4117
+ * is available or the CTM is singular.
4118
+ */
4119
+ project_doc_point_to_local(id, p) {
4120
+ const el = this.element_index.get(id);
4121
+ if (!(el instanceof SVGGraphicsElement)) return null;
4122
+ if (typeof el.getScreenCTM !== "function") return null;
4123
+ const ctm = el.getScreenCTM();
4124
+ if (!ctm) return null;
4125
+ const cr = this.container.getBoundingClientRect();
4126
+ const offset_x = -cr.left + this.container.scrollLeft;
4127
+ const offset_y = -cr.top + this.container.scrollTop;
4128
+ const det = ctm.a * ctm.d - ctm.c * ctm.b;
4129
+ if (det === 0) return null;
4130
+ const px = p[0] - offset_x;
4131
+ const py = p[1] - offset_y;
4132
+ return [(ctm.d * (px - ctm.e) - ctm.c * (py - ctm.f)) / det, (-ctm.b * (px - ctm.e) + ctm.a * (py - ctm.f)) / det];
4133
+ }
3265
4134
  tag_of(id) {
3266
4135
  return this.editor.tree().nodes.get(id)?.tag ?? "";
3267
4136
  }
@@ -3294,7 +4163,8 @@ var DomSurface = class DomSurface {
3294
4163
  bbox_world(id) {
3295
4164
  const local = this.bbox_local(id);
3296
4165
  if (!local) return null;
3297
- return project_local_bbox(local, this.editor.document.get_attr(id, "transform"));
4166
+ const transform_str = this.editor.document.get_attr(id, "transform");
4167
+ return transform.project(local, transform_str);
3298
4168
  }
3299
4169
  /** World-space rect for snap purposes. Differs from `bbox_world` for
3300
4170
  * `<svg>` viewport-establishing elements: `getBBox()` on an `<svg>`
@@ -3321,13 +4191,92 @@ var DomSurface = class DomSurface {
3321
4191
  function numAttr(doc, id, name) {
3322
4192
  return svg_parse.parse_number(doc.get_attr(id, name));
3323
4193
  }
4194
+ /** Order-sensitive shallow equality for tangent-ref arrays. */
4195
+ function sameTangentRefs(a, b) {
4196
+ if (a.length !== b.length) return false;
4197
+ for (let i = 0; i < a.length; i++) if (a[i][0] !== b[i][0] || a[i][1] !== b[i][1]) return false;
4198
+ return true;
4199
+ }
4200
+ /**
4201
+ * Affine projection of a point through a 2×3 CTM, then offset by a
4202
+ * container origin (in page CSS-px). Mirrors how `line_endpoints_in_container`
4203
+ * and `shape_of` (transformed branch) bridge from local SVG coords to the
4204
+ * HUD's container-CSS-px space (HUD keeps its own transform at identity;
4205
+ * the SVG carries the camera as a CSS transform, which getScreenCTM
4206
+ * folds in).
4207
+ *
4208
+ * Exported for headless test coverage — pure function, no DOM types.
4209
+ */
4210
+ function project_point_through_ctm(px, py, ctm, container_offset) {
4211
+ const [sx, sy] = cmath.vector2.transform([px, py], [[
4212
+ ctm.a,
4213
+ ctm.c,
4214
+ ctm.e
4215
+ ], [
4216
+ ctm.b,
4217
+ ctm.d,
4218
+ ctm.f
4219
+ ]]);
4220
+ return [sx + container_offset[0], sy + container_offset[1]];
4221
+ }
4222
+ /**
4223
+ * Inverse of the CTM's linear part applied to a delta vector. Drops
4224
+ * translation. Used to convert a HUD-reported container-space drag delta
4225
+ * back to the path's local coord space for `PathModel.translateVertices`.
4226
+ *
4227
+ * Throws on a degenerate (det = 0) matrix — the caller is expected to
4228
+ * have a non-singular CTM for any visible element.
4229
+ */
4230
+ function project_delta_inverse_ctm(dx, dy, ctm) {
4231
+ if (ctm.a * ctm.d - ctm.c * ctm.b === 0) throw new Error("project_delta_inverse_ctm: singular CTM linear part");
4232
+ const inv = cmath.transform.invert([[
4233
+ ctm.a,
4234
+ ctm.c,
4235
+ 0
4236
+ ], [
4237
+ ctm.b,
4238
+ ctm.d,
4239
+ 0
4240
+ ]]);
4241
+ return cmath.vector2.transform([dx, dy], inv);
4242
+ }
4243
+ /**
4244
+ * Inverse-project a doc-space rect through a CTM + container offset back
4245
+ * into the element's local frame. The output is the AABB of the four
4246
+ * inverse-projected corners — when the CTM has a rotation component the
4247
+ * AABB is an approximation, but it matches what the user visually
4248
+ * expects from a screen-aligned marquee drag.
4249
+ *
4250
+ * Returns `null` when the CTM's linear part is singular (degenerate
4251
+ * camera) — the caller should skip any test that needs the local rect.
4252
+ */
4253
+ function inverse_project_rect(rect, ctm, offset) {
4254
+ if (ctm.a * ctm.d - ctm.c * ctm.b === 0) return null;
4255
+ const inv = cmath.transform.invert([[
4256
+ ctm.a,
4257
+ ctm.c,
4258
+ ctm.e
4259
+ ], [
4260
+ ctm.b,
4261
+ ctm.d,
4262
+ ctm.f
4263
+ ]]);
4264
+ const to_local = (px, py) => cmath.vector2.transform([px - offset[0], py - offset[1]], inv);
4265
+ const corners = [
4266
+ to_local(rect.x, rect.y),
4267
+ to_local(rect.x + rect.width, rect.y),
4268
+ to_local(rect.x, rect.y + rect.height),
4269
+ to_local(rect.x + rect.width, rect.y + rect.height)
4270
+ ];
4271
+ return cmath.rect.fromPoints(corners);
4272
+ }
3324
4273
  /** World-space viewport rect of an `<svg>` element. Prefers `viewBox`
3325
4274
  * (the declared user-space rect — what the user perceives as canvas),
3326
4275
  * falls back to `width`/`height` at (0,0). For nested `<svg>` with a
3327
4276
  * positional `x`/`y`, the declared viewBox/(0,0) is in the nested
3328
4277
  * element's OWN user space; callers are responsible for CTM
3329
4278
  * projection if a different frame is desired. v1 nested-svg story is
3330
- * documented in docs/wg/feat-svg-editor/geometry.md as out of scope. */
4279
+ * documented in ../docs/geometry.md as out of scope. */
3331
4280
  function svg_viewport_bounds(el) {
3332
4281
  const vb = el.getAttribute("viewBox");
3333
4282
  if (vb) {
@@ -3497,9 +4446,9 @@ var SvgHitShapeDriver = class {
3497
4446
  hit_shape_of(id) {
3498
4447
  const doc = this.accessors.doc();
3499
4448
  if (!doc) return null;
3500
- const intrinsic = hit_shape_of_doc(doc, id);
4449
+ const intrinsic = hit_shape_svg.of_doc(doc, id);
3501
4450
  if (intrinsic) return intrinsic;
3502
- if (is_transparent_tag(doc.tag_of(id))) return null;
4451
+ if (hit_shape_svg.is_transparent_tag(doc.tag_of(id))) return null;
3503
4452
  const bounds = this.accessors.bounds_of(id);
3504
4453
  if (!bounds) return null;
3505
4454
  return {
@@ -3512,4 +4461,4 @@ var SvgHitShapeDriver = class {
3512
4461
  }
3513
4462
  };
3514
4463
  //#endregion
3515
- export { Camera as a, MemoizedGeometryProvider as i, Gestures as n, DEFAULT_SNAP_OPTIONS as r, attach_dom_surface as t };
4464
+ export { Gestures as a, Camera as c, project_point_through_ctm as i, inverse_project_rect as n, DEFAULT_SNAP_OPTIONS as o, project_delta_inverse_ctm as r, MemoizedGeometryProvider as s, attach_dom_surface as t };