@johnoscott/isometric-engine 0.12.3 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/EDITOR-GUIDE.md +10 -2
  2. package/README.md +1 -1
  3. package/assets/app.css +12 -0
  4. package/assets/marks.css +2 -0
  5. package/iso-editor.js +189 -188
  6. package/iso-render.js +82 -82
  7. package/iso-systems.js +79 -79
  8. package/js/iso-editor/commands.js +7 -0
  9. package/js/iso-editor/connections.js +24 -0
  10. package/js/iso-editor/make-way.js +62 -0
  11. package/js/iso-editor/model.js +17 -3
  12. package/js/iso-editor/ui/actions.js +22 -24
  13. package/js/iso-editor/ui/canvas.js +564 -223
  14. package/js/iso-editor/ui/mount.js +2 -1
  15. package/js/iso-editor/ui/palette-look.js +53 -0
  16. package/js/iso-editor/ui/props.js +2 -2
  17. package/js/iso-editor/ui/rename.js +114 -0
  18. package/js/iso-editor/ui/setup.js +4 -0
  19. package/js/iso-viewer/viewport.js +17 -5
  20. package/package.json +1 -1
  21. package/src/iso-editor/commands.ts +9 -0
  22. package/src/iso-editor/connections.ts +28 -0
  23. package/src/iso-editor/make-way.ts +89 -0
  24. package/src/iso-editor/model.ts +17 -3
  25. package/src/iso-editor/ui/actions.ts +20 -23
  26. package/src/iso-editor/ui/app.css +10 -0
  27. package/src/iso-editor/ui/canvas.ts +469 -180
  28. package/src/iso-editor/ui/marks.css +2 -0
  29. package/src/iso-editor/ui/mount.ts +4 -3
  30. package/src/iso-editor/ui/palette-look.ts +51 -0
  31. package/src/iso-editor/ui/props.ts +3 -3
  32. package/src/iso-editor/ui/rename.ts +105 -0
  33. package/src/iso-editor/ui/setup.ts +11 -0
  34. package/src/iso-viewer/viewport.ts +25 -5
  35. package/types/iso-editor/connections.d.ts +8 -0
  36. package/types/iso-editor/make-way.d.ts +40 -0
  37. package/types/iso-editor/model.d.ts +8 -2
  38. package/types/iso-editor/ui/actions.d.ts +5 -2
  39. package/types/iso-editor/ui/canvas.d.ts +42 -12
  40. package/types/iso-editor/ui/mount.d.ts +6 -2
  41. package/types/iso-editor/ui/palette-look.d.ts +5 -0
  42. package/types/iso-editor/ui/props.d.ts +1 -1
  43. package/types/iso-editor/ui/rename.d.ts +43 -0
  44. package/types/iso-editor/ui/setup.d.ts +7 -0
  45. package/types/iso-viewer/viewport.d.ts +13 -1
@@ -1,11 +1,13 @@
1
1
  import { h, icon } from "./icons.js";
2
2
  import { openMenu } from "./menu.js";
3
3
  import { run } from "./actions.js";
4
+ import { connectionsOf, nearestOn } from "../connections.js";
4
5
  import { screenToGrid, localAt, boxSilhouette, floorOf, snapMove, overlaps, paddingOf } from "../../iso-objects/geometry.js";
5
6
  import { regionKind } from "../../iso-objects/kinds.js";
6
7
  import { iso, C, S } from "../../iso-core/kernel.js";
7
8
  import { applyStep } from "../splice.js";
8
9
  import { seqCmd } from "../commands.js";
10
+ import { makeWay, hits, DWELL_HINT, DWELL_GIVE, BACK_AFTER, GLIDE, JIGGLE } from "../make-way.js";
9
11
  import { fromPointer, toPointer } from "../path.js";
10
12
  import { buildSvg } from "../../iso-core/svg-dom.js";
11
13
  import { viewport } from "../../iso-viewer/viewport.js";
@@ -13,7 +15,7 @@ const SVGNS = "http://www.w3.org/2000/svg";
13
15
  function canvasView(host, doc, opts) {
14
16
  const K = opts.kit, ui = K.ui, T = ui.text;
15
17
  const { setCmd, deleteCmd, insertCmd, insertItemCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
16
- const { deletePaths, renameDialog, duplicate, connected } = K.actions;
18
+ const { deletePaths, duplicate, connected } = K.actions;
17
19
  const resourceOf = (ptr) => K.objectOf(ptr);
18
20
  const kindOf = (k) => K.kinds.find((x) => x.kind === k);
19
21
  const PINS_KEY = K.pins.key;
@@ -118,6 +120,10 @@ function canvasView(host, doc, opts) {
118
120
  const key2 = JSON.stringify(data);
119
121
  if (key2 === lastKey && svg) {
120
122
  if (!pinDrag()) paintOverlay();
123
+ if (toFit) {
124
+ toFit = false;
125
+ fitItems();
126
+ }
121
127
  return;
122
128
  }
123
129
  if (mode === "2d" && !flatImpl) {
@@ -143,13 +149,15 @@ function canvasView(host, doc, opts) {
143
149
  lastKey = key2;
144
150
  lastS3 = s3;
145
151
  lastData = data;
146
- if (pinDrag()) {
152
+ drawLooks();
153
+ if (pinDrag() || dropping) {
147
154
  pendingAfterDrag = true;
148
155
  return;
149
156
  }
150
157
  await draw(next);
151
158
  if (cd.pinNotes.length) opts.note(`Pins: ${cd.pinNotes.join("; ")}`, "warn");
152
159
  }
160
+ let toFit = false;
153
161
  let lastS3, lastData, pendingAfterDrag = false;
154
162
  let morphFrom;
155
163
  let morphing;
@@ -222,7 +230,11 @@ function canvasView(host, doc, opts) {
222
230
  svg = s;
223
231
  const [x, y, w, hh] = full;
224
232
  V.full = { x, y, w, h: hh };
225
- if (!V.view) {
233
+ if (toFit) {
234
+ toFit = false;
235
+ V.view = { ...V.full };
236
+ fitItems();
237
+ } else if (!V.view) {
226
238
  V.view = { ...V.full };
227
239
  autoFit();
228
240
  } else quietly(applyView);
@@ -253,6 +265,11 @@ function canvasView(host, doc, opts) {
253
265
  const live = layer?.extent?.() ?? [];
254
266
  return union([...ptrs.flatMap((p) => elementsFor(p)).filter((e) => e.getBBox().width || e.getBBox().height).map(boxOf), ...live]);
255
267
  }
268
+ function routesBox() {
269
+ if (!cd || !svg) return void 0;
270
+ const els = Object.keys(cd.scene.rendered.paths).flatMap((id) => [...svg.querySelectorAll(`[data-id="${CSS.escape(id)}"], [data-hl="${CSS.escape(id)}"], [data-for="${CSS.escape(id)}"]`)]).filter((e) => !e.closest(".pre, .overlay, .g-marks, .g-badges, .g-anim"));
271
+ return union(els.filter((e) => e.getBBox().width || e.getBBox().height).map(boxOf));
272
+ }
256
273
  const docked = ui.paletteLayout === "docked";
257
274
  const viewEl = docked ? stage : host;
258
275
  const V = viewport(viewEl, {
@@ -265,6 +282,7 @@ function canvasView(host, doc, opts) {
265
282
  },
266
283
  onRezoom: () => paintOverlay(),
267
284
  itemsBox: () => itemsBox(),
285
+ alsoBox: () => routesBox(),
268
286
  marksShowing: () => !!layer?.showing?.()
269
287
  });
270
288
  const { size, scale, quietly, applyView, toSvg, zoomAt, fit, fitItems, autoFit, actual, settled } = V;
@@ -314,6 +332,35 @@ function canvasView(host, doc, opts) {
314
332
  }
315
333
  return void 0;
316
334
  };
335
+ const isRouteId = (id) => !!cd && Object.hasOwn(cd.scene.rendered.paths, id);
336
+ const connections = () => cd ? connectionsOf(cd.pathOf, isRouteId, K.objectOf) : /* @__PURE__ */ new Map();
337
+ const NEAR = 6;
338
+ const pathAt = (target, px, py) => {
339
+ const direct = pathAtEvent(target);
340
+ const isNode = (el2) => {
341
+ const id = el2?.closest?.("[data-id]")?.getAttribute("data-id");
342
+ if (!id || !cd || isRouteId(id)) return false;
343
+ if (flat) {
344
+ const q = toSvg(px, py);
345
+ return !flat.panelsAt(q.x, q.y).includes(id) && cd.scene.layout.byId.has(id);
346
+ }
347
+ return cd.scene.layout.byId.get(id)?.type === "node";
348
+ };
349
+ const el = target;
350
+ if (!cd || !svg || !el?.closest || el !== svg && !svg.contains(el) && el !== stage || isNode(el)) return direct;
351
+ const conns = connections();
352
+ if (!conns.size || direct !== void 0 && conns.has(direct)) return direct;
353
+ const at = toSvg(px, py), k = scale(), r = viewEl.getBoundingClientRect();
354
+ let best;
355
+ for (const ptr of conns.keys()) for (const sh of outlinesFor(ptr)) {
356
+ if (sh.kind !== "route") continue;
357
+ const q = nearestOn(sh.d, at.x, at.y);
358
+ if (!q || q.dist * k > NEAR || best && q.dist >= best.dist) continue;
359
+ if (isNode(fdoc().elementFromPoint(r.left + (q.x - V.view.x) * k, r.top + (q.y - V.view.y) * k))) continue;
360
+ best = { ptr, dist: q.dist };
361
+ }
362
+ return best ? best.ptr : direct;
363
+ };
317
364
  function outlinesFor(ptr) {
318
365
  if (!cd) return [];
319
366
  const out = [];
@@ -444,11 +491,20 @@ function canvasView(host, doc, opts) {
444
491
  stage.addEventListener("pointerdown", down);
445
492
  stage.addEventListener("pointermove", move);
446
493
  stage.addEventListener("pointerup", up);
447
- stage.addEventListener("pointercancel", up);
494
+ stage.addEventListener("pointercancel", (e) => {
495
+ if (pinDrag()) void endPin(false);
496
+ else up(e);
497
+ });
448
498
  stage.addEventListener("wheel", wheel, { passive: false });
449
499
  stage.addEventListener("contextmenu", context);
450
500
  stage.addEventListener("dblclick", (e) => {
451
- const p = pathAtEvent(e.target);
501
+ const t = e.target === stage ? fdoc().elementFromPoint(e.clientX, e.clientY) : e.target;
502
+ if (ui.doubleClick === "rename") {
503
+ const p2 = pathAtEvent(t), r = p2 === void 0 ? p2 : resourceOf(p2);
504
+ if (r && doc.doc.ok) rename(fromPointer(r.path));
505
+ return;
506
+ }
507
+ const p = pathAt(t, e.clientX, e.clientY);
452
508
  if (p !== void 0) opts.showInText(fromPointer(p));
453
509
  });
454
510
  };
@@ -490,7 +546,7 @@ function canvasView(host, doc, opts) {
490
546
  return;
491
547
  }
492
548
  if (e.button !== 0) return;
493
- const ptr = pathAtEvent(e.target);
549
+ const ptr = pathAt(e.target, x, y);
494
550
  if (ptr === void 0) {
495
551
  const mod = e.shiftKey || e.metaKey || e.ctrlKey;
496
552
  if (nav.drag === "pan" && !mod) {
@@ -519,7 +575,6 @@ function canvasView(host, doc, opts) {
519
575
  const start = localAt(cd.scene, id);
520
576
  if (item && start) {
521
577
  const b = item.box, par = item.parent;
522
- const siblings = (par ? par.children : cd.scene.layout.items.filter((i) => !i.parent)).filter((i) => i !== item).map((i) => ({ x0: i.box.x0, y0: i.box.y0, x1: i.box.x1, y1: i.box.y1 }));
523
578
  drag = {
524
579
  kind: "pin",
525
580
  x0: x,
@@ -532,8 +587,8 @@ function canvasView(host, doc, opts) {
532
587
  shown: start,
533
588
  z0: b.z0,
534
589
  size: [b.x1 - b.x0, b.y1 - b.y0],
535
- siblings,
536
- parent: par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region), box: par.box, label: par.region?.label ?? par.id } : void 0,
590
+ beside: besideOf(cd, id),
591
+ parent: par ? { id: par.id, w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region), box: par.box, label: par.region?.label ?? par.id } : void 0,
537
592
  origCd: cd
538
593
  };
539
594
  }
@@ -549,7 +604,7 @@ function canvasView(host, doc, opts) {
549
604
  return;
550
605
  }
551
606
  if (!drag) {
552
- const p = pathAtEvent(e.target);
607
+ const p = pathAt(e.target, x, y);
553
608
  if (p !== hoverId) {
554
609
  hoverId = p;
555
610
  paintOverlay();
@@ -576,15 +631,15 @@ function canvasView(host, doc, opts) {
576
631
  }
577
632
  const [ax, ay] = screenToGrid(a.x, a.y), [bx, by] = screenToGrid(b.x, b.y);
578
633
  const g = { x0: Math.min(ax, bx), y0: Math.min(ay, by), x1: Math.max(ax, bx), y1: Math.max(ay, by) };
579
- const hits = /* @__PURE__ */ new Map();
634
+ const hits2 = /* @__PURE__ */ new Map();
580
635
  for (const [ptr, foot] of footprints()) {
581
636
  const f = foot;
582
637
  const inside = f.x0 >= g.x0 && f.y0 >= g.y0 && f.x1 <= g.x1 && f.y1 <= g.y1;
583
638
  const touches = f.x0 < g.x1 && f.x1 > g.x0 && f.y0 < g.y1 && f.y1 > g.y0;
584
- if (drag.touch ? touches : inside) hits.set(ptr, fromPointer(ptr));
639
+ if (drag.touch ? touches : inside) hits2.set(ptr, fromPointer(ptr));
585
640
  }
586
641
  const base2 = new Map((drag.sel0 ?? []).map((p) => [toPointer(p), p]));
587
- for (const [k2, p] of hits) base2.set(k2, p);
642
+ for (const [k2, p] of hits2) base2.set(k2, p);
588
643
  doc.select([...base2.values()], "canvas");
589
644
  paintOverlay();
590
645
  const poly = fdoc().createElementNS(SVGNS, "polygon");
@@ -612,13 +667,13 @@ function canvasView(host, doc, opts) {
612
667
  function marquee2d(a, b) {
613
668
  if (!drag || !flat || !cd) return;
614
669
  const g = { l: Math.min(a.x, b.x), t: Math.min(a.y, b.y), r: Math.max(a.x, b.x), b: Math.max(a.y, b.y) };
615
- const hits = /* @__PURE__ */ new Map();
670
+ const hits2 = /* @__PURE__ */ new Map();
616
671
  for (const id of flat.hits(g, !!drag.touch)) {
617
672
  const ptr = cd.pathOf.get(id);
618
- if (ptr !== void 0 && resourceOf(ptr)?.path === ptr) hits.set(ptr, fromPointer(ptr));
673
+ if (ptr !== void 0 && resourceOf(ptr)?.path === ptr) hits2.set(ptr, fromPointer(ptr));
619
674
  }
620
675
  const base2 = new Map((drag.sel0 ?? []).map((p) => [toPointer(p), p]));
621
- for (const [k2, p] of hits) base2.set(k2, p);
676
+ for (const [k2, p] of hits2) base2.set(k2, p);
622
677
  doc.select([...base2.values()], "canvas");
623
678
  paintOverlay();
624
679
  const r = fdoc().createElementNS(SVGNS, "rect");
@@ -631,74 +686,246 @@ function canvasView(host, doc, opts) {
631
686
  }
632
687
  let pinFrame = false, lastPin, relayout = 0;
633
688
  const pinDrag = () => drag?.kind === "pin" && drag.moved ? drag : void 0;
689
+ function besideOf(d, id, inside = d.scene.layout.byId.get(id)?.parent) {
690
+ const pinned = new Set(d.pinId.values());
691
+ return (inside ? inside.children : d.scene.layout.items.filter((i) => !i.parent)).filter((i) => i.id !== id).map((i) => ({ id: i.id, x0: i.box.x0, y0: i.box.y0, x1: i.box.x1, y1: i.box.y1, movable: pinned.has(i.id) && !!localAt(d.scene, i.id) }));
692
+ }
693
+ const besideNow = (g) => g.beside.map((b) => {
694
+ const [dx, dy] = g.given?.get(b.id) ?? [0, 0];
695
+ return { ...b, x0: b.x0 + dx, x1: b.x1 + dx, y0: b.y0 + dy, y1: b.y1 + dy };
696
+ });
697
+ const footAt = (g, [x, y]) => {
698
+ const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
699
+ return { x0: ox + x, y0: oy + y, x1: ox + x + g.size[0], y1: oy + y + g.size[1] };
700
+ };
701
+ const motionOn = () => ui.dragMotion !== "respect" || !matchMedia("(prefers-reduced-motion: reduce)").matches;
634
702
  function pinStep() {
635
703
  const g = pinDrag();
636
704
  if (!g || !lastPin || !cd) return;
637
705
  const k = scale();
638
706
  const step = lastPin.alt ? 0.5 : 1;
639
707
  g.step = step;
640
- const m = snapMove(g.start, screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k), step, g.size, g.parent);
641
- const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
642
- const foot = { x0: ox + m.at[0], y0: oy + m.at[1], x1: ox + m.at[0] + g.size[0], y1: oy + m.at[1] + g.size[1] };
708
+ const p = g.fresh ? toSvg(lastPin.x, lastPin.y) : void 0;
709
+ const f0 = footAt(g, g.start), grip = iso((f0.x0 + f0.x1) / 2, (f0.y0 + f0.y1) / 2, g.z0);
710
+ const d = p ? screenToGrid(p.x - grip[0], p.y - grip[1]) : screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k);
711
+ const m = snapMove(g.start, d, step, g.size, g.parent);
712
+ const foot = footAt(g, m.at);
643
713
  const changed = !g.move || g.move.at[0] !== m.at[0] || g.move.at[1] !== m.at[1];
644
714
  g.move = m;
645
- g.invalid = overlaps(foot, g.siblings);
715
+ g.invalid = overlaps(foot, besideNow(g));
716
+ if (changed) dwell(g);
717
+ if (!g.invalid) g.clearAt = m.at;
646
718
  svg?.classList.add("dragging");
647
719
  svg?.classList.toggle("drag-bad", g.invalid);
648
720
  shiftDragged(g.id, [m.at[0] - g.shown[0], m.at[1] - g.shown[1]]);
649
721
  paintDrag(foot);
650
- const within = g.parent ? `within ${g.parent.label}` : "on the canvas";
651
- opts.onHint?.(`Moving ${g.name} ${within} \xB7 ${step === 1 ? "whole cells (\u2325: half cells)" : "half cells"} \xB7 ${g.invalid ? "overlaps: it won't drop here" : "Esc cancels"}${T.pinHint}`);
652
- if (changed && !g.invalid && lastS3) {
653
- clearTimeout(relayout);
654
- relayout = window.setTimeout(async () => {
655
- const now = pinDrag();
656
- if (!now || now.invalid || !now.move) return;
657
- let next;
658
- try {
659
- ({ next, keep: now.keep } = trialLayout(now));
660
- } catch {
661
- return;
662
- }
663
- if (pinDrag() !== now) return;
664
- await draw(next);
665
- if (pinDrag() !== now) return;
666
- now.shown = now.move.at;
667
- shiftDragged(now.id, [0, 0]);
668
- paintDrag(now.parent ? { x0: now.parent.box.x0 + now.move.at[0], y0: now.parent.box.y0 + now.move.at[1], x1: now.parent.box.x0 + now.move.at[0] + now.size[0], y1: now.parent.box.y0 + now.move.at[1] + now.size[1] } : foot);
669
- }, 0);
722
+ sayDrag(g);
723
+ if (changed && !g.invalid) relayoutSoon(g);
724
+ }
725
+ function sayDrag(g) {
726
+ const within = g.parent ? `${g.fresh ? "in" : "within"} ${g.parent.label}` : "on the canvas";
727
+ const n = g.given?.size ?? 0;
728
+ opts.onHint?.(`${g.fresh ? "Adding" : "Moving"} ${g.name} ${within} \xB7 ${g.step === 1 ? "whole cells (\u2325: half cells)" : "half cells"} \xB7 ${g.invalid ? g.way ? "hold still: it makes way" : g.fresh ? "taken: the layout places it" : "overlaps: it won't drop here" : n ? `${n} made way \xB7 Esc cancels` : "Esc cancels"}${T.pinHint}`);
729
+ }
730
+ function relayoutSoon(g, glide = false) {
731
+ if (!g.fresh && !lastS3) return;
732
+ clearTimeout(relayout);
733
+ const go = () => {
734
+ const now = pinDrag();
735
+ if (!now || now !== g || now.invalid || !now.move) return;
736
+ let next;
737
+ try {
738
+ ({ next, keep: now.keep } = trialLayout(now));
739
+ } catch {
740
+ return;
741
+ }
742
+ showTrial(now, next, now.move.at, glide);
743
+ };
744
+ if (glide) go();
745
+ else relayout = window.setTimeout(go, 0);
746
+ }
747
+ function showTrial(g, next, at, glide) {
748
+ const was = cd;
749
+ stillOn(g, next);
750
+ void draw(next);
751
+ if (pinDrag() !== g) return;
752
+ g.shown = at;
753
+ shiftDragged(g.id, [g.move.at[0] - at[0], g.move.at[1] - at[1]]);
754
+ paintDrag(footAt(g, g.move.at));
755
+ if (!glide || !motionOn()) return;
756
+ const from = /* @__PURE__ */ new Map();
757
+ for (const b of g.beside) {
758
+ const a = was.scene.layout.byId.get(b.id)?.box, z = next.scene.layout.byId.get(b.id)?.box;
759
+ if (a && z && (Math.abs(a.x0 - z.x0) > 1e-6 || Math.abs(a.y0 - z.y0) > 1e-6)) from.set(b.id, [a.x0 - z.x0, a.y0 - z.y0]);
760
+ }
761
+ glideFrom(from);
762
+ }
763
+ function stillOn(g, next) {
764
+ const now = g.parent && next.scene.layout.byId.get(g.parent.id)?.box;
765
+ if (!g.parent || !now || !V.view) return;
766
+ const was = g.parent.box, dx = now.x0 - was.x0, dy = now.y0 - was.y0;
767
+ g.parent = { ...g.parent, box: now, w: Math.max(g.parent.w, now.x1 - now.x0), d: Math.max(g.parent.d, now.y1 - now.y0) };
768
+ if (Math.abs(dx) < 1e-9 && Math.abs(dy) < 1e-9) return;
769
+ g.beside = g.beside.map((b) => ({ ...b, x0: b.x0 + dx, x1: b.x1 + dx, y0: b.y0 + dy, y1: b.y1 + dy }));
770
+ shiftView(g, (dx - dy) * C * S, (dx + dy) * 0.5 * S);
771
+ }
772
+ function shiftView(g, x, y) {
773
+ if (!V.view) return;
774
+ V.view = { ...V.view, x: V.view.x + x, y: V.view.y + y };
775
+ g.shifted = [(g.shifted?.[0] ?? 0) + x, (g.shifted?.[1] ?? 0) + y];
776
+ }
777
+ function unshift(g) {
778
+ if (g.shifted) {
779
+ shiftView(g, -g.shifted[0], -g.shifted[1]);
780
+ g.shifted = void 0;
670
781
  }
671
782
  }
672
- function trialLayout(g) {
673
- const base2 = JSON.parse(JSON.stringify(lastData ?? {}));
674
- if (K.pins.legacyOnly(base2)) {
675
- base2[PINS_KEY] = base2[K.pins.legacyKey];
676
- delete base2[K.pins.legacyKey];
783
+ let hintTimer = 0, giveTimer = 0, backTimer = 0, wayFrame = 0, jiggling = [];
784
+ function stillWay() {
785
+ cancelAnimationFrame(wayFrame);
786
+ wayFrame = 0;
787
+ for (const id of jiggling) shiftDragged(id, [0, 0]);
788
+ jiggling = [];
789
+ }
790
+ function restart() {
791
+ clearTimeout(hintTimer);
792
+ clearTimeout(giveTimer);
793
+ stillWay();
794
+ }
795
+ function endWay() {
796
+ clearTimeout(backTimer);
797
+ backTimer = 0;
798
+ restart();
799
+ }
800
+ const needed = (g, foot) => g.beside.some((b) => g.given?.has(b.id) && hits(b, foot));
801
+ function dwell(g) {
802
+ restart();
803
+ g.way = void 0;
804
+ const foot = footAt(g, g.move.at);
805
+ if (!g.given?.size || needed(g, foot)) {
806
+ clearTimeout(backTimer);
807
+ backTimer = 0;
808
+ } else if (!backTimer) backTimer = window.setTimeout(() => {
809
+ backTimer = 0;
810
+ if (pinDrag() === g) putBack(g);
811
+ }, BACK_AFTER);
812
+ if (!g.invalid || !g.beside.some((b) => hits(b, foot))) return;
813
+ hintTimer = window.setTimeout(() => {
814
+ if (pinDrag() !== g) return;
815
+ const from = g.clearAt ?? g.start, par = g.parent, pad = par?.pad ?? 0;
816
+ const way = makeWay({
817
+ foot,
818
+ others: g.beside,
819
+ going: [g.move.at[0] - from[0], g.move.at[1] - from[1]],
820
+ bounds: par ? { x0: par.box.x0 + pad, y0: par.box.y0 + pad, x1: par.box.x1 - pad, y1: par.box.y1 - pad } : void 0
821
+ });
822
+ if (!way?.size) return;
823
+ g.way = way;
824
+ paintDrag(foot);
825
+ sayDrag(g);
826
+ jiggle(g);
827
+ giveTimer = window.setTimeout(() => {
828
+ if (pinDrag() === g && g.way === way) give(g, way);
829
+ }, DWELL_GIVE - DWELL_HINT);
830
+ }, DWELL_HINT);
831
+ }
832
+ function give(g, way) {
833
+ stillWay();
834
+ g.given = way;
835
+ g.way = void 0;
836
+ g.invalid = false;
837
+ g.clearAt = g.move.at;
838
+ relayoutSoon(g, true);
839
+ sayDrag(g);
840
+ }
841
+ function putBack(g) {
842
+ stillWay();
843
+ g.given = void 0;
844
+ g.invalid = overlaps(footAt(g, g.move.at), besideNow(g));
845
+ sayDrag(g);
846
+ if (!g.invalid) {
847
+ relayoutSoon(g, true);
848
+ return;
677
849
  }
678
- base2[PINS_KEY] ??= {};
679
- base2[PINS_KEY].layout ??= {};
680
- const pins = base2[PINS_KEY].layout;
681
- pins[g.name] = { at: g.move.at };
682
- let next = K.draw(lastS3, base2, opts.theme);
850
+ showTrial(g, g.fresh?.base ?? g.origCd, g.start, true);
851
+ dwell(g);
852
+ }
853
+ function jiggle(g) {
854
+ if (!motionOn()) return;
855
+ const t0 = performance.now(), ids = [...g.way.keys()];
856
+ jiggling = ids;
857
+ const frame = (now) => {
858
+ if (pinDrag() !== g || !g.way) return;
859
+ const t = now - t0, a = JIGGLE.px * Math.min(1, 0.25 + 0.75 * t / (DWELL_GIVE - DWELL_HINT)) / scale();
860
+ ids.forEach((id, i) => shiftScreen(id, a * Math.sin(t / 1e3 * JIGGLE.hz * 2 * Math.PI + i * 1.7)));
861
+ wayFrame = requestAnimationFrame(frame);
862
+ };
863
+ wayFrame = requestAnimationFrame(frame);
864
+ }
865
+ function glideFrom(from) {
866
+ if (!from.size) return;
867
+ const t0 = performance.now(), on = svg;
868
+ jiggling = [...from.keys()];
869
+ const frame = (now) => {
870
+ if (svg !== on) {
871
+ jiggling = [];
872
+ return;
873
+ }
874
+ const f = Math.min(1, Math.max(0, (now - t0) / GLIDE)), left = Math.pow(1 - f, 3);
875
+ for (const [id, [dx, dy]] of from) shiftDragged(id, [dx * left, dy * left]);
876
+ if (f < 1) wayFrame = requestAnimationFrame(frame);
877
+ else jiggling = [];
878
+ };
879
+ frame(t0);
880
+ }
881
+ function trialLayout(g, at = g.move.at) {
683
882
  const orig = g.origCd, nameOf = new Map([...orig.pinId].map(([n, id]) => [id, n]));
684
- const me = orig.scene.layout.byId.get(g.id);
685
- const sibs = me.parent ? me.parent.children : orig.scene.layout.items.filter((i) => !i.parent);
883
+ const gave = [];
884
+ for (const [id, [dx, dy]] of g.given ?? []) {
885
+ const was = localAt(orig.scene, id);
886
+ gave.push([nameOf.get(id), [was[0] + dx, was[1] + dy]]);
887
+ }
888
+ const set = [[g.name, at], ...gave];
889
+ const lay = layWith(g);
890
+ let next = lay(set);
891
+ const have = /* @__PURE__ */ new Set([...Object.keys(K.pins.of(lastData) ?? {}), ...set.map(([n]) => n)]);
686
892
  const keep = [];
687
- for (const sb of sibs) {
688
- if (sb === me) continue;
689
- const n = nameOf.get(sb.id), was = localAt(orig.scene, sb.id), now = next.scene.layout.byId.get(sb.id)?.box;
690
- if (!n || !was || !now || n in pins) continue;
691
- if (Math.abs(now.x0 - sb.box.x0) > 1e-6 || Math.abs(now.y0 - sb.box.y0) > 1e-6) keep.push([n, was]);
893
+ for (const b of g.beside) {
894
+ const n = nameOf.get(b.id), was = localAt(orig.scene, b.id), now = localAt(next.scene, b.id);
895
+ if (!n || !was || !now || have.has(n)) continue;
896
+ if (Math.abs(now[0] - was[0]) > 1e-6 || Math.abs(now[1] - was[1]) > 1e-6) keep.push([n, was]);
692
897
  }
693
- if (keep.length) {
694
- for (const [n, at] of keep) pins[n] = { at };
695
- next = K.draw(lastS3, base2, opts.theme);
898
+ if (keep.length) next = lay([...set, ...keep]);
899
+ return { next, keep: [...gave, ...keep] };
900
+ }
901
+ function layWith(g) {
902
+ if (g.fresh) {
903
+ const text = g.fresh.text;
904
+ return (list) => {
905
+ const t = K.trial(pinsCmd(list, "").build(text).steps.reduce((u, st) => applyStep(u, st), text), opts.theme);
906
+ if (!t) throw new Error("not drawn");
907
+ return t;
908
+ };
696
909
  }
697
- return { next, keep };
910
+ return (list) => {
911
+ const base2 = JSON.parse(JSON.stringify(lastData ?? {}));
912
+ if (K.pins.legacyOnly(base2)) {
913
+ base2[PINS_KEY] = base2[K.pins.legacyKey];
914
+ delete base2[K.pins.legacyKey];
915
+ }
916
+ base2[PINS_KEY] ??= {};
917
+ base2[PINS_KEY].layout ??= {};
918
+ for (const [n, at] of list) base2[PINS_KEY].layout[n] = { at };
919
+ return K.draw(lastS3, base2, opts.theme);
920
+ };
698
921
  }
699
922
  function shiftDragged(id, [gx, gy]) {
700
923
  if (!svg || !cd) return;
701
- const [sx, sy] = [(gx - gy) * C * S, (gx + gy) * 0.5 * S];
924
+ shiftBy(id, (gx - gy) * C * S, (gx + gy) * 0.5 * S);
925
+ }
926
+ const shiftScreen = (id, dx) => shiftBy(id, dx, 0);
927
+ function shiftBy(id, sx, sy) {
928
+ if (!svg || !cd) return;
702
929
  const ids = /* @__PURE__ */ new Set([id]);
703
930
  for (const it of cd.scene.layout.items) {
704
931
  let p = it.parent;
@@ -713,7 +940,7 @@ function canvasView(host, doc, opts) {
713
940
  for (const el of svg.querySelectorAll("[data-id]")) {
714
941
  if (!ids.has(el.getAttribute("data-id") ?? "")) continue;
715
942
  if (el.parentElement?.closest(`[data-id="${CSS.escape(el.getAttribute("data-id"))}"]`)) continue;
716
- el.setAttribute("transform", gx || gy ? `translate(${sx.toFixed(1)} ${sy.toFixed(1)})` : "");
943
+ el.setAttribute("transform", sx || sy ? `translate(${sx.toFixed(2)} ${sy.toFixed(2)})` : "");
717
944
  }
718
945
  }
719
946
  function paintDrag(foot) {
@@ -738,10 +965,20 @@ function canvasView(host, doc, opts) {
738
965
  for (let v = Math.ceil((area.x0 - ox) / st) * st; ox + v <= area.x1 + 1e-9; v += st) line(ox + v, area.y0, ox + v, area.y1, Number.isInteger(v) ? "dgrid" : "dgrid sub");
739
966
  for (let v = Math.ceil((area.y0 - oy) / st) * st; oy + v <= area.y1 + 1e-9; v += st) line(area.x0, oy + v, area.x1, oy + v, Number.isInteger(v) ? "dgrid" : "dgrid sub");
740
967
  overlay.append(wrap);
741
- const t = d.createElementNS(SVGNS, "polygon");
742
- t.setAttribute("class", `drop${g.invalid ? " bad" : ""}`);
743
- t.setAttribute("points", [[foot.x0, foot.y0], [foot.x1, foot.y0], [foot.x1, foot.y1], [foot.x0, foot.y1]].map(([x, y]) => P(x, y)).join(" "));
744
- overlay.append(t);
968
+ const poly = (b, cls) => {
969
+ const t = d.createElementNS(SVGNS, "polygon");
970
+ t.setAttribute("class", cls);
971
+ t.setAttribute("points", [P(b.x0, b.y0), P(b.x1, b.y0), P(b.x1, b.y1), P(b.x0, b.y1)].join(" "));
972
+ overlay.append(t);
973
+ return t;
974
+ };
975
+ poly(foot, `drop${g.invalid ? " bad" : ""}`);
976
+ for (const b of g.way ? besideNow({ ...g, given: g.way }) : []) {
977
+ if (!g.way.has(b.id)) continue;
978
+ const w = poly(b, "drop way");
979
+ w.setAttribute("stroke-dasharray", "5 4");
980
+ w.dataset.way = b.id;
981
+ }
745
982
  if (g.parent && g.move) {
746
983
  const pb = g.parent.box, c = g.move.clamped, pad = g.parent.pad;
747
984
  const e = (x1, y1, x2, y2) => {
@@ -756,11 +993,31 @@ function canvasView(host, doc, opts) {
756
993
  if (c.bottom) e(pb.x0, pb.y1 - pad, pb.x1, pb.y1 - pad);
757
994
  }
758
995
  }
996
+ let dropping = 0;
759
997
  async function endPin(commit) {
998
+ if (!pinDrag()) return;
999
+ dropping++;
1000
+ try {
1001
+ await endDrop(commit);
1002
+ } finally {
1003
+ dropping--;
1004
+ }
1005
+ }
1006
+ async function endDrop(commit) {
760
1007
  const g = pinDrag();
761
1008
  if (!g) return;
762
1009
  drag = void 0;
763
1010
  clearTimeout(relayout);
1011
+ endWay();
1012
+ let stale = false;
1013
+ if (commit && g.given?.size && g.move) {
1014
+ const foot = footAt(g, g.move.at);
1015
+ if (!needed(g, foot)) {
1016
+ g.given = void 0;
1017
+ g.invalid = overlaps(foot, besideNow(g));
1018
+ stale = true;
1019
+ }
1020
+ }
764
1021
  const shown = overlay ? [...overlay.querySelectorAll(".gridwrap, .drop, .edge")] : [];
765
1022
  if (shown.length) {
766
1023
  for (const e of shown) e.classList.add("out");
@@ -770,29 +1027,182 @@ function canvasView(host, doc, opts) {
770
1027
  svg?.classList.remove("dragging", "drag-bad");
771
1028
  paintNav();
772
1029
  const m = g.move;
1030
+ if (g.fresh) {
1031
+ await endFresh(g, commit, stale);
1032
+ return;
1033
+ }
773
1034
  const moved = m && (m.at[0] !== g.start[0] || m.at[1] !== g.start[1]);
774
1035
  if (commit && m && moved && !g.invalid) {
775
1036
  const label = `Pin ${describe(fromPointer(g.ptr))} at [${m.at.join(", ")}]`;
776
1037
  let keep = g.keep ?? [];
777
- if (!g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1]) try {
1038
+ if (stale || !g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1]) try {
778
1039
  keep = trialLayout(g).keep;
779
1040
  } catch {
780
1041
  }
781
- run(doc, keep.length ? pinsCmd([[g.name, m.at], ...keep], `${label} (${keep.map(([n]) => n).join(", ")} kept in place)`) : withPinsMoved(setCmd([PINS_KEY, "layout", g.name], { at: m.at }, label)), "canvas", opts.note);
782
- if (pendingAfterDrag && lastS3) {
783
- pendingAfterDrag = false;
784
- lastKey = "";
785
- render(lastS3, lastData);
786
- }
1042
+ run(doc, keep.length ? pinsCmd([[g.name, m.at], ...keep], `${label}${wayWords(g, keep)}`) : withPinsMoved(setCmd([PINS_KEY, "layout", g.name], { at: m.at }, label)), "canvas", opts.note);
1043
+ pendingAfterDrag = false;
787
1044
  return;
788
1045
  }
789
1046
  if (commit && g.invalid) opts.note(`${g.name} can't go there: it would overlap`, "warn");
1047
+ unshift(g);
790
1048
  await draw(g.origCd);
791
- if (pendingAfterDrag && lastS3) {
1049
+ redrawPending();
1050
+ }
1051
+ function redrawPending() {
1052
+ if (pendingAfterDrag) {
792
1053
  pendingAfterDrag = false;
793
1054
  lastKey = "";
794
- render(lastS3, lastData);
1055
+ setTimeout(() => {
1056
+ if (lastS3 && !pinDrag()) void render(lastS3, lastData);
1057
+ }, 0);
1058
+ }
1059
+ }
1060
+ function wayWords(g, keep) {
1061
+ const nameOf = new Map([...g.origCd.pinId].map(([n, id]) => [id, n])), gave = new Set([...g.given?.keys() ?? []].map((id) => nameOf.get(id)));
1062
+ const a = keep.filter(([n]) => gave.has(n)).map(([n]) => n), b = keep.filter(([n]) => !gave.has(n)).map(([n]) => n);
1063
+ const words = [...a.length ? [`${a.join(", ")} made way`] : [], ...b.length ? [`${b.join(", ")} kept in place`] : []].join("; ");
1064
+ return words && ` (${words})`;
1065
+ }
1066
+ function freshPlan(sec, item, name, p, at, home) {
1067
+ const k = kindOf(sec), preset = item?.value?.();
1068
+ const what = item && preset !== void 0 ? item.label.toLowerCase() : k.singular;
1069
+ const under = at && home ? outlinesAt(home, at) : [], drop = K.dropInto?.(sec);
1070
+ let value = preset ?? k.template(), into, words = "";
1071
+ const c = drop ? under.find((u) => u.kind === drop.container) : void 0;
1072
+ if (drop && c) {
1073
+ into = c.name;
1074
+ value = { ...drop.value(c.name), ...preset ?? {} };
1075
+ words = drop.label(c.name);
1076
+ }
1077
+ if (!into && K.dropOnto) for (const t of under) {
1078
+ const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
1079
+ if (plan) {
1080
+ into = t.name;
1081
+ value = plan.value;
1082
+ words = plan.label ? ` ${plan.label}` : ` in ${t.name}`;
1083
+ break;
1084
+ }
795
1085
  }
1086
+ const label = `Add ${what} ${name}${words}`;
1087
+ return { into, label, add: insertCmd(p.slice(0, -1), name, value, { label }) };
1088
+ }
1089
+ function outlinesAt(d, q) {
1090
+ if (flat) return flat.panelsAt(q.x, q.y).map((id) => {
1091
+ const ptr = d.pathOf.get(id), ref = ptr === void 0 ? void 0 : resourceOf(ptr);
1092
+ return ref && ref.path === ptr ? ref : void 0;
1093
+ }).filter((x) => !!x);
1094
+ const e = 2 / scale() / S;
1095
+ const inside = (poly) => {
1096
+ let c = false;
1097
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
1098
+ const [xi, yi] = poly[i], [xj, yj] = poly[j];
1099
+ if (yi > q.y !== yj > q.y && q.x < (xj - xi) * (q.y - yi) / (yj - yi) + xi) c = !c;
1100
+ }
1101
+ return c;
1102
+ };
1103
+ const out = [];
1104
+ for (const [id, ptr] of d.pathOf) {
1105
+ const it = d.scene.layout.byId.get(id), ref = resourceOf(ptr);
1106
+ if (!it || !ref || ref.path !== ptr) continue;
1107
+ const b = it.box;
1108
+ if (!inside(boxSilhouette({ ...b, x0: b.x0 - e, y0: b.y0 - e, x1: b.x1 + e, y1: b.y1 + e }))) continue;
1109
+ let depth = 0;
1110
+ for (let up2 = it.parent; up2; up2 = up2.parent) depth++;
1111
+ out.push({ r: ref, depth, area: (b.x1 - b.x0) * (b.y1 - b.y0) });
1112
+ }
1113
+ return out.sort((a, b) => b.depth - a.depth || a.area - b.area).map((x) => x.r);
1114
+ }
1115
+ function dragFresh(sec, item, at) {
1116
+ if (mode !== "3d" || !cd || !svg || !doc.doc.ok || !lastS3) return false;
1117
+ const was = pinDrag()?.fresh ? pinDrag() : void 0, home = was?.origCd ?? cd;
1118
+ const k = kindOf(sec), name = was?.fresh.name ?? freshName(doc.text, item?.name ?? k.singular), path = [...k.section, name];
1119
+ const sv = toSvg(at.x, at.y), off = was?.shifted ?? [0, 0];
1120
+ const plan = freshPlan(sec, item, name, path, { x: sv.x - off[0], y: sv.y - off[1] }, home);
1121
+ if (!was || was.fresh.plan.into !== plan.into) {
1122
+ const text = plan.add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
1123
+ let trial;
1124
+ try {
1125
+ trial = K.trial(text, opts.theme);
1126
+ } catch {
1127
+ }
1128
+ const id = trial?.pinId.get(name), it = id ? trial.scene.layout.byId.get(id) : void 0, start = id ? localAt(trial.scene, id) : void 0;
1129
+ if (!trial || trial.diags.length || !id || !it || !start) return false;
1130
+ const b = it.box, par = it.parent, inHome = par ? home.scene.layout.byId.get(par.id) : void 0;
1131
+ if (par && !inHome) return false;
1132
+ endWay();
1133
+ clearTimeout(relayout);
1134
+ const g = {
1135
+ kind: "pin",
1136
+ x0: at.x,
1137
+ y0: at.y,
1138
+ moved: true,
1139
+ name,
1140
+ id,
1141
+ start,
1142
+ shown: start,
1143
+ z0: b.z0,
1144
+ size: [b.x1 - b.x0, b.y1 - b.y0],
1145
+ origCd: home,
1146
+ // its container, as it was: what is drawn is moved to it (stillOn)
1147
+ parent: par && inHome ? { id: par.id, w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region), box: inHome.box, label: par.region?.label ?? par.id } : void 0,
1148
+ beside: besideOf(home, id, inHome),
1149
+ shifted: was?.shifted,
1150
+ fresh: { base: trial, name, path, plan, text },
1151
+ gridShown: was?.gridShown
1152
+ };
1153
+ drag = g;
1154
+ unshift(g);
1155
+ try {
1156
+ g.fresh.base = trialLayout(g, start).next;
1157
+ } catch {
1158
+ }
1159
+ stillOn(g, g.fresh.base);
1160
+ void draw(g.fresh.base);
1161
+ if (pinDrag() !== g) return false;
1162
+ }
1163
+ lastPin = { x: at.x, y: at.y, alt: at.alt };
1164
+ pinStep();
1165
+ return true;
1166
+ }
1167
+ function hideFresh() {
1168
+ const g = pinDrag();
1169
+ if (!g?.fresh) return;
1170
+ endWay();
1171
+ clearTimeout(relayout);
1172
+ drag = void 0;
1173
+ lastKey = "";
1174
+ unshift(g);
1175
+ void draw(g.origCd);
1176
+ paintNav();
1177
+ }
1178
+ async function endFresh(g, commit, stale) {
1179
+ const f = g.fresh, m = g.move;
1180
+ if (!commit || !m) {
1181
+ unshift(g);
1182
+ await draw(g.origCd);
1183
+ redrawPending();
1184
+ return;
1185
+ }
1186
+ pendingAfterDrag = false;
1187
+ let keep = g.keep ?? [];
1188
+ if (!g.invalid && (stale || !g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1] || g.keep === void 0)) try {
1189
+ keep = trialLayout(g).keep;
1190
+ } catch {
1191
+ keep = [];
1192
+ }
1193
+ const own = snapMove(g.start, [0, 0], g.step ?? 1, g.size, g.parent).at, its = m.at[0] !== own[0] || m.at[1] !== own[1];
1194
+ const pins = g.invalid ? [] : [...its || keep.length ? [[f.name, m.at]] : [], ...keep];
1195
+ const cmd = pins.length ? seqCmd(`${f.plan.label} at [${m.at.join(", ")}]${wayWords(g, keep)}`, [f.plan.add, pinsCmd(pins, "")]) : f.plan.add;
1196
+ if (g.invalid) unshift(g);
1197
+ if (!run(doc, { ...cmd, select: [f.path] }, "canvas", opts.note)) {
1198
+ lastKey = "";
1199
+ unshift(g);
1200
+ await draw(g.origCd);
1201
+ return;
1202
+ }
1203
+ if (g.invalid) opts.note(`${f.name} added; that spot is taken, so the layout placed it`);
1204
+ doc.select([f.path], "canvas");
1205
+ rename(f.path, { joins: doc.undoId, at: lastPin });
796
1206
  }
797
1207
  function up(e) {
798
1208
  if (linking && !linking.pick) {
@@ -834,13 +1244,6 @@ function canvasView(host, doc, opts) {
834
1244
  }
835
1245
  return out;
836
1246
  }
837
- const round = (v) => Math.round(v * 2) / 2;
838
- const snap = ([x, y]) => [round(x), round(y)];
839
- const gridToScreen = (gx, gy) => {
840
- const [ux, uy] = screenToGrid(1, 0), [vx, vy] = screenToGrid(0, 1);
841
- const det = ux * vy - uy * vx;
842
- return [(gx * vy - gy * vx) / det, (gy * ux - gx * uy) / det];
843
- };
844
1247
  function wheel(e) {
845
1248
  e.preventDefault();
846
1249
  const { x, y } = pageXY(e);
@@ -864,7 +1267,7 @@ function canvasView(host, doc, opts) {
864
1267
  e.preventDefault();
865
1268
  const { x, y } = pageXY(e);
866
1269
  if (layer?.context?.(e, { x, y })) return;
867
- const ptr = pathAtEvent(e.target);
1270
+ const ptr = pathAt(e.target, x, y);
868
1271
  if (ptr !== void 0 && !doc.selection.some((p) => toPointer(p) === ptr)) doc.select([fromPointer(ptr)], "canvas");
869
1272
  openMenu(menuItems(ptr), { x, y }, "Canvas");
870
1273
  }
@@ -885,7 +1288,7 @@ function canvasView(host, doc, opts) {
885
1288
  if (one) {
886
1289
  items.push(...K.objectItems(doc, one, "canvas", opts.note));
887
1290
  if (items.length) items.push({ sep: true });
888
- items.push({ label: "Rename\u2026", icon: "pencil", keys: "F2", disabled: ro || !isRes, why: T.renameWhy, onSelect: () => renameDialog(doc, one, "canvas", opts.note) });
1291
+ items.push({ label: "Rename\u2026", icon: "pencil", keys: "F2", disabled: ro || !isRes, why: T.renameWhy, onSelect: () => rename(one) });
889
1292
  items.push({ label: "Duplicate", icon: "copy", keys: "\u2318D", disabled: ro || !isRes, why: T.duplicateWhy, onSelect: () => duplicate(doc, one, "canvas", opts.note) });
890
1293
  const name = isRes ? resourceOf(toPointer(one)).name : "";
891
1294
  const pinned = !!K.pins.of(doc.goodDoc.data)?.[name];
@@ -978,142 +1381,25 @@ function canvasView(host, doc, opts) {
978
1381
  const p = [...k.section, name];
979
1382
  if (run(doc, insertCmd(p.slice(0, -1), name, k.template(), { label: `Add ${k.singular} ${name}` }), "canvas", opts.note)) {
980
1383
  doc.select([p], "canvas");
981
- renameDialog(doc, p, "canvas", opts.note);
982
- }
983
- }
984
- function placeAt(name, add, at) {
985
- if (!cd || !svg) return void 0;
986
- const text = add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
987
- let trial;
988
- try {
989
- trial = K.trial(text, opts.theme);
990
- } catch {
991
- return void 0;
992
- }
993
- if (!trial) return void 0;
994
- const id = trial.pinId.get(name), item = id ? trial.scene.layout.byId.get(id) : void 0, start = id ? localAt(trial.scene, id) : void 0;
995
- if (!item || !start) return void 0;
996
- const b = item.box, par = item.parent;
997
- const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
998
- const centre = [(cx - cy) * C * S, (cx + cy) * 0.5 * S - b.z0 * S], drop = toSvg(at.x, at.y);
999
- const m = snapMove(
1000
- start,
1001
- screenToGrid(drop.x - centre[0], drop.y - centre[1]),
1002
- 1,
1003
- [b.x1 - b.x0, b.y1 - b.y0],
1004
- par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region) } : void 0
1005
- );
1006
- const dx = m.at[0] - start[0], dy = m.at[1] - start[1];
1007
- const moved = { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy };
1008
- const siblings = (par ? par.children : trial.scene.layout.items.filter((i) => !i.parent)).filter((i) => i !== item).map((i) => i.box);
1009
- return overlaps(moved, siblings) ? void 0 : m.at;
1010
- }
1011
- function containerAt(kind, at) {
1012
- if (!cd) return void 0;
1013
- const p = toSvg(at.x, at.y);
1014
- if (flat) {
1015
- for (const id of flat.panelsAt(p.x, p.y)) {
1016
- const name = [...cd.pinId].find(([, pid]) => pid === id)?.[0];
1017
- if (name && resourceOf(cd.pathOf.get(id) ?? "")?.kind === kind) return name;
1018
- }
1019
- return void 0;
1020
- }
1021
- const inside = (poly) => {
1022
- let c = false;
1023
- for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
1024
- const [xi, yi] = poly[i], [xj, yj] = poly[j];
1025
- if (yi > p.y !== yj > p.y && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c;
1026
- }
1027
- return c;
1028
- };
1029
- for (const [name, id] of cd.pinId) {
1030
- if (resourceOf(cd.pathOf.get(id) ?? "")?.kind !== kind) continue;
1031
- const item = cd.scene.layout.byId.get(id);
1032
- if (item && inside(floorOf(item.box))) return name;
1384
+ rename(p, { joins: doc.undoId });
1033
1385
  }
1034
- return void 0;
1035
- }
1036
- function objectsUnder(at) {
1037
- if (!cd) return [];
1038
- const p = toSvg(at.x, at.y);
1039
- const refOf = (id) => {
1040
- const ptr = cd.pathOf.get(id);
1041
- const r = ptr === void 0 ? void 0 : resourceOf(ptr);
1042
- return r && r.path === ptr ? r : void 0;
1043
- };
1044
- if (flat) return flat.panelsAt(p.x, p.y).map(refOf).filter((r) => !!r);
1045
- const inside = (poly) => {
1046
- let c = false;
1047
- for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
1048
- const [xi, yi] = poly[i], [xj, yj] = poly[j];
1049
- if (yi > p.y !== yj > p.y && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c;
1050
- }
1051
- return c;
1052
- };
1053
- const depth = (i) => {
1054
- let n = 0;
1055
- for (let q = i.parent; q; q = q.parent) n++;
1056
- return n;
1057
- };
1058
- const seen = /* @__PURE__ */ new Map();
1059
- for (const e of fdoc().elementsFromPoint(at.x, at.y)) {
1060
- if (!svg?.contains(e)) continue;
1061
- for (let el = e.closest("[data-id]"); el; el = el.parentElement?.closest("[data-id]") ?? null) {
1062
- const r = refOf(el.getAttribute("data-id") ?? "");
1063
- if (r && !seen.has(r.path)) seen.set(r.path, r);
1064
- }
1065
- }
1066
- const hits = [];
1067
- for (const [, id] of cd.pinId) {
1068
- const item = cd.scene.layout.byId.get(id), r = refOf(id);
1069
- if (item && r && !seen.has(r.path) && inside(floorOf(item.box))) hits.push({ r, d: depth(item), a: (item.box.x1 - item.box.x0) * (item.box.y1 - item.box.y0) });
1070
- }
1071
- return [...seen.values(), ...hits.sort((x, y) => y.d - x.d || x.a - y.a).map((h2) => h2.r)];
1072
1386
  }
1073
1387
  function addFromPalette(sec, at, item) {
1074
1388
  if (!doc.doc.ok) {
1075
1389
  opts.note("Fix the YAML first", "warn");
1076
1390
  return void 0;
1077
1391
  }
1078
- const k = kindOf(sec);
1079
- const preset = item?.value?.();
1080
- const what = item && preset !== void 0 ? item.label.toLowerCase() : k.singular;
1081
- const name = freshName(doc.text, item?.name ?? k.singular);
1082
- const p = [...k.section, name];
1083
- let value = preset ?? k.template();
1084
- let into;
1085
- const drop = at ? K.dropInto?.(sec) : void 0;
1086
- if (at && drop) {
1087
- const c = containerAt(drop.container, at);
1088
- if (c) {
1089
- into = c;
1090
- value = { ...drop.value(c), ...preset ?? {} };
1091
- }
1092
- }
1093
- let intoLabel = into ? drop.label(into) : "";
1094
- if (at && !into && K.dropOnto) {
1095
- for (const t of objectsUnder(at)) {
1096
- const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
1097
- if (plan) {
1098
- into = t.name;
1099
- value = plan.value;
1100
- intoLabel = plan.label ? ` ${plan.label}` : ` in ${t.name}`;
1101
- break;
1102
- }
1103
- }
1104
- }
1105
- const label = `Add ${what} ${name}${intoLabel}`;
1106
- const add = insertCmd(p.slice(0, -1), name, value, { label });
1107
- const pin = at && !into && mode === "3d" ? placeAt(name, add, at) : void 0;
1108
- const cmd = pin ? seqCmd(`${label} at [${pin.join(", ")}]`, [add, withPinsMoved(setCmd([PINS_KEY, "layout", name], { at: pin }))]) : add;
1109
- if (!run(doc, { ...cmd, select: [p] }, "canvas", opts.note)) return void 0;
1110
- if (at && !into && !pin) opts.note(mode === "2d" ? `${k.singular} ${name} added; the layout placed it (in 3D a drop pins it where it lands)` : `${k.singular} ${name} added; that spot is taken, so the layout placed it`);
1392
+ const k = kindOf(sec), name = freshName(doc.text, item?.name ?? k.singular), p = [...k.section, name];
1393
+ const plan = freshPlan(sec, item, name, p, at && toSvg(at.x, at.y), cd);
1394
+ if (!run(doc, { ...plan.add, select: [p] }, "canvas", opts.note)) return void 0;
1395
+ if (at && !plan.into) opts.note(`${k.singular} ${name} added; the layout placed it${mode === "2d" ? " (in 3D a drop pins it where it lands)" : ""}`);
1111
1396
  doc.select([p], "canvas");
1112
- stage.focus({ preventScroll: true });
1113
- renameDialog(doc, p, "canvas", opts.note);
1397
+ rename(p, { joins: doc.undoId, at });
1114
1398
  return p;
1115
1399
  }
1116
1400
  const palette = h("div", { class: "palette", role: "toolbar", "aria-label": T.palette, "aria-orientation": "vertical" });
1401
+ const drawLooks = K.looks?.(palette, () => disposed ? void 0 : doc.goodDoc.data, ui, opts.theme) ?? (() => {
1402
+ });
1117
1403
  const sections = /* @__PURE__ */ new Map();
1118
1404
  const PAL_KEY = "canvas-palette";
1119
1405
  let lastSection;
@@ -1129,6 +1415,7 @@ function canvasView(host, doc, opts) {
1129
1415
  if (!g) return;
1130
1416
  g.head.setAttribute("aria-expanded", String(open));
1131
1417
  g.body.hidden = !open;
1418
+ if (open) drawLooks();
1132
1419
  };
1133
1420
  function sectionBody(sec) {
1134
1421
  const have = sections.get(sec);
@@ -1184,6 +1471,7 @@ function canvasView(host, doc, opts) {
1184
1471
  before = void 0;
1185
1472
  }
1186
1473
  none.hidden = shown > 0;
1474
+ drawLooks();
1187
1475
  none.textContent = shown ? "" : `Nothing matches "${search.value.trim()}"`;
1188
1476
  }
1189
1477
  const setDockW = (w, keep = true) => {
@@ -1293,29 +1581,58 @@ function canvasView(host, doc, opts) {
1293
1581
  } catch {
1294
1582
  }
1295
1583
  const x0 = e.clientX, y0 = e.clientY;
1296
- let ghost;
1584
+ let ghost, dragged = false, real = false, frame = 0, last;
1297
1585
  const over = (ev) => {
1298
1586
  const r = stage.getBoundingClientRect();
1299
1587
  return ev.clientX >= r.left && ev.clientX <= r.right && ev.clientY >= r.top && ev.clientY <= r.bottom && !palHome.contains(document.elementFromPoint(ev.clientX, ev.clientY));
1300
1588
  };
1301
- const mv = (ev) => {
1302
- if (!ghost && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
1303
- if (!ghost) {
1304
- ghost = h("div", { class: "pal-ghost", "aria-hidden": "true" }, icon(ic), label);
1305
- host.append(ghost);
1589
+ const step = (ev) => {
1590
+ const on = over(ev);
1591
+ real = on && dragFresh(sec, item, { x: ev.clientX, y: ev.clientY, alt: ev.altKey });
1592
+ if (!on || !real) hideFresh();
1593
+ if (!real) {
1594
+ if (!ghost) {
1595
+ ghost = h("div", { class: "pal-ghost", "aria-hidden": "true" }, icon(ic), label);
1596
+ host.append(ghost);
1597
+ }
1598
+ const hr = host.getBoundingClientRect();
1599
+ ghost.style.left = `${ev.clientX - hr.left + 8}px`;
1600
+ ghost.style.top = `${ev.clientY - hr.top + 8}px`;
1601
+ ghost.classList.toggle("bad", !on);
1602
+ } else {
1603
+ ghost?.remove();
1604
+ ghost = void 0;
1306
1605
  }
1307
- const hr = host.getBoundingClientRect();
1308
- ghost.style.left = `${ev.clientX - hr.left + 8}px`;
1309
- ghost.style.top = `${ev.clientY - hr.top + 8}px`;
1310
- ghost.classList.toggle("bad", !over(ev));
1606
+ };
1607
+ const mv = (ev) => {
1608
+ if (!dragged && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
1609
+ dragged = true;
1610
+ last = ev;
1611
+ if (frame) return;
1612
+ const go = () => {
1613
+ if (!frame) return;
1614
+ cancelAnimationFrame(frame);
1615
+ frame = 0;
1616
+ if (last) step(last);
1617
+ };
1618
+ frame = requestAnimationFrame(go);
1619
+ setTimeout(go, 32);
1311
1620
  };
1312
1621
  const done = (ev, drop) => {
1313
1622
  b.removeEventListener("pointermove", mv);
1314
1623
  b.removeEventListener("pointerup", upH);
1315
1624
  b.removeEventListener("pointercancel", cancelH);
1316
1625
  removeEventListener("keydown", esc, true);
1317
- const dragged = !!ghost;
1626
+ cancelAnimationFrame(frame);
1627
+ frame = 0;
1628
+ if (drop && dragged) step(ev);
1318
1629
  ghost?.remove();
1630
+ if (real && pinDrag()?.fresh) {
1631
+ if (drop) usedSection(item);
1632
+ void endPin(drop);
1633
+ return;
1634
+ }
1635
+ hideFresh();
1319
1636
  if (!drop) return;
1320
1637
  if (!dragged) {
1321
1638
  usedSection(item);
@@ -1355,6 +1672,25 @@ function canvasView(host, doc, opts) {
1355
1672
  const only = x && Object.keys(x).length === 1;
1356
1673
  run(doc, { ...deleteCmd(only ? [key2] : [key2, "layout"]), label: "Reset the layout" }, "canvas", opts.note);
1357
1674
  }
1675
+ function rename(p, o = {}) {
1676
+ let path = p;
1677
+ const off = doc.on((c) => {
1678
+ if (path && c.remap) path = c.remap(path);
1679
+ });
1680
+ void K.actions.rename(doc, p, "canvas", opts.note, {
1681
+ ...o,
1682
+ back: stage,
1683
+ late: stage,
1684
+ busy: () => !!drag || dropping > 0,
1685
+ bounds: () => stage.getBoundingClientRect(),
1686
+ place: () => {
1687
+ const b = path && V.view ? boxFor(path) : void 0;
1688
+ if (!b) return void 0;
1689
+ const r = viewEl.getBoundingClientRect(), k = scale();
1690
+ return { left: r.left + (b.x - V.view.x) * k, top: r.top + (b.y - V.view.y) * k, width: b.w * k, height: b.h * k };
1691
+ }
1692
+ }).finally(off);
1693
+ }
1358
1694
  function selectParent() {
1359
1695
  const up2 = /* @__PURE__ */ new Map();
1360
1696
  for (const p of doc.selection) {
@@ -1421,7 +1757,7 @@ function canvasView(host, doc, opts) {
1421
1757
  if (sel.length && !ro) deletePaths(doc, sel, "canvas", opts.note);
1422
1758
  break;
1423
1759
  case "F2":
1424
- if (sel.length === 1 && !ro) renameDialog(doc, sel[0], "canvas", opts.note);
1760
+ if (sel.length === 1 && !ro) rename(sel[0]);
1425
1761
  break;
1426
1762
  case "ArrowUp":
1427
1763
  if (mod) {
@@ -1433,6 +1769,7 @@ function canvasView(host, doc, opts) {
1433
1769
  case "ArrowRight":
1434
1770
  case "ArrowLeft":
1435
1771
  case "ArrowDown": {
1772
+ drawn.push(...connections().keys());
1436
1773
  if (!drawn.length) return;
1437
1774
  const i = sel.length ? drawn.indexOf(toPointer(sel[0])) : -1;
1438
1775
  const back = e.key === "ArrowLeft" || e.key === "Tab" && e.shiftKey;
@@ -1510,7 +1847,6 @@ function canvasView(host, doc, opts) {
1510
1847
  palette,
1511
1848
  groupSelection,
1512
1849
  startPick,
1513
- objectsUnder,
1514
1850
  get linking() {
1515
1851
  return linking;
1516
1852
  },
@@ -1518,10 +1854,14 @@ function canvasView(host, doc, opts) {
1518
1854
  setTheme,
1519
1855
  paintOverlay,
1520
1856
  fit: fitItems,
1857
+ fitNext() {
1858
+ toFit = true;
1859
+ },
1521
1860
  fitAll: fit,
1522
1861
  actual,
1523
1862
  zoomAt,
1524
1863
  itemsBox,
1864
+ routesBox,
1525
1865
  get moved() {
1526
1866
  return V.moved;
1527
1867
  },
@@ -1531,6 +1871,7 @@ function canvasView(host, doc, opts) {
1531
1871
  },
1532
1872
  dispose() {
1533
1873
  endMorph();
1874
+ endWay();
1534
1875
  clearTimeout(relayout);
1535
1876
  V.dispose();
1536
1877
  disposed = true;