@johnoscott/isometric-engine 0.12.6 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/EDITOR-GUIDE.md +9 -2
  2. package/README.md +1 -1
  3. package/assets/app.css +6 -0
  4. package/assets/marks.css +2 -0
  5. package/iso-editor.js +194 -184
  6. package/iso-render.js +157 -148
  7. package/iso-systems.js +170 -159
  8. package/js/iso-editor/make-way.js +62 -0
  9. package/js/iso-editor/ui/canvas.js +477 -216
  10. package/js/iso-editor/ui/palette-look.js +53 -0
  11. package/js/iso-editor/ui/setup.js +3 -0
  12. package/js/iso-objects/ants.js +36 -0
  13. package/js/iso-objects/index.js +47 -1
  14. package/js/iso-objects/looks.js +25 -0
  15. package/js/iso-objects/motion-builder.js +130 -0
  16. package/js/iso-objects/motion-doc.js +500 -0
  17. package/js/iso-objects/motion-entry.js +32 -0
  18. package/js/iso-objects/motion.js +635 -0
  19. package/js/iso-objects/resolve.js +238 -0
  20. package/js/iso-objects/scene.js +15 -13
  21. package/js/iso-objects/timeline.js +553 -0
  22. package/js/iso-systems/compile.js +59 -1
  23. package/js/iso-systems/index.js +4 -1
  24. package/js/iso-systems/render.js +20 -0
  25. package/js/iso-systems/schema.json +39 -0
  26. package/js/iso-viewer/page.js +2 -1
  27. package/js/iso-viewer/player.js +23 -34
  28. package/package.json +46 -1
  29. package/src/iso-editor/make-way.ts +89 -0
  30. package/src/iso-editor/ui/app.css +4 -0
  31. package/src/iso-editor/ui/canvas.ts +390 -170
  32. package/src/iso-editor/ui/marks.css +2 -0
  33. package/src/iso-editor/ui/palette-look.ts +51 -0
  34. package/src/iso-editor/ui/setup.ts +8 -0
  35. package/src/iso-objects/ants.ts +53 -0
  36. package/src/iso-objects/compile.ts +4 -1
  37. package/src/iso-objects/index.ts +14 -1
  38. package/src/iso-objects/looks.ts +21 -0
  39. package/src/iso-objects/motion-builder.ts +79 -0
  40. package/src/iso-objects/motion-doc.ts +361 -0
  41. package/src/iso-objects/motion-entry.ts +12 -0
  42. package/src/iso-objects/motion.ts +616 -0
  43. package/src/iso-objects/resolve.ts +196 -0
  44. package/src/iso-objects/scene.ts +29 -13
  45. package/src/iso-objects/timeline.ts +443 -0
  46. package/src/iso-objects/types.ts +20 -2
  47. package/src/iso-systems/compile.ts +58 -3
  48. package/src/iso-systems/index.ts +4 -1
  49. package/src/iso-systems/render.ts +41 -0
  50. package/src/iso-systems/schema.json +39 -0
  51. package/src/iso-viewer/page.ts +2 -1
  52. package/src/iso-viewer/player.ts +24 -41
  53. package/types/iso-editor/make-way.d.ts +40 -0
  54. package/types/iso-editor/ui/canvas.d.ts +33 -12
  55. package/types/iso-editor/ui/palette-look.d.ts +5 -0
  56. package/types/iso-editor/ui/setup.d.ts +5 -0
  57. package/types/iso-objects/ants.d.ts +33 -0
  58. package/types/iso-objects/compile.d.ts +3 -0
  59. package/types/iso-objects/index.d.ts +14 -1
  60. package/types/iso-objects/looks.d.ts +4 -0
  61. package/types/iso-objects/motion-builder.d.ts +105 -0
  62. package/types/iso-objects/motion-doc.d.ts +787 -0
  63. package/types/iso-objects/motion-entry.d.ts +10 -0
  64. package/types/iso-objects/motion.d.ts +200 -0
  65. package/types/iso-objects/resolve.d.ts +20 -0
  66. package/types/iso-objects/scene.d.ts +11 -0
  67. package/types/iso-objects/timeline.d.ts +46 -0
  68. package/types/iso-objects/types.d.ts +32 -0
  69. package/types/iso-systems/compile.d.ts +20 -3
  70. package/types/iso-systems/index.d.ts +4 -1
  71. package/types/iso-systems/render.d.ts +21 -0
@@ -23,6 +23,7 @@ import type { EditorModel, Command } from '../model.ts';
23
23
  import type { Problem } from '../validate.ts';
24
24
  import { applyStep } from '../splice.ts';
25
25
  import { seqCmd, type Commands } from '../commands.ts';
26
+ import { makeWay, hits, DWELL_HINT, DWELL_GIVE, BACK_AFTER, GLIDE, JIGGLE, type Beside } from '../make-way.ts';
26
27
  import type { ObjectKindInfo, ObjectRef, ConnectPlan, GroupPlan } from '../adapter.ts';
27
28
  import { fromPointer, toPointer, type Path } from '../path.ts';
28
29
  import { buildSvg } from '../../iso-core/svg-dom.ts';
@@ -82,8 +83,12 @@ export interface CanvasUi {
82
83
  * its own at the canvas's left, with a search box filtering by label and section, resizable and collapsible; its
83
84
  * width and whether it is collapsed are kept in the host's store as `canvas-palette-dock`) */
84
85
  paletteLayout?: 'floating' | 'docked';
85
- /** (0.12.5) what a double click on an object does: shows it in the text (the default), or renames it */
86
+ /** (0.12.5) what a double click on an object does: shows it in the text (the default), or renames it (0.14.1: what has no
87
+ * name, a connection, does nothing then) */
86
88
  doubleClick?: 'text' | 'rename';
89
+ /** (0.14.0) whether what is in a drag's way jiggles before it gives way, and glides: 'always' (the default), or
90
+ * 'respect': not where the viewer prefers reduced motion (the outlines of where it would go still show) */
91
+ dragMotion?: 'always' | 'respect';
87
92
  text: {
88
93
  stage: string; dragGroup: string; dragSelectTip: string; unreadable: string; palette: string;
89
94
  /** the end of a pin drag's hint */
@@ -113,6 +118,9 @@ export interface CanvasKit<M, D extends CanvasDrawing> {
113
118
  dropOnto?(target: ObjectRef, value: unknown, kind: string, data: unknown): { value: unknown; label?: string } | undefined;
114
119
  /** (0.10.0) the selection made into a new container (the adapter's group): Group, ⌘G, one undo step */
115
120
  group?(members: ObjectRef[], data: unknown): GroupPlan | undefined;
121
+ /** (0.14.0) the palette's entries as what they make, drawn small (palette-look.ts): what draws those that show and aren't
122
+ * drawn yet. None: the entries' icons */
123
+ looks?(palette: HTMLElement, data: () => unknown, ui: CanvasUi, theme: string): () => void;
116
124
  actions: Actions;
117
125
  /** what an object's own menu offers, beyond rename, duplicate and delete */
118
126
  objectItems(doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void): MenuItem[];
@@ -148,6 +156,9 @@ export interface CanvasOpts<M, D extends CanvasDrawing, A extends object = objec
148
156
  layer?: (ctx: CanvasCtx<D>) => CanvasLayer<A>;
149
157
  }
150
158
 
159
+ /** a new thing as a drag would make it: inside what (none: the canvas), by which command */
160
+ export interface FreshPlan { into?: string; label: string; add: Command }
161
+
151
162
  const SVGNS = 'http://www.w3.org/2000/svg';
152
163
 
153
164
 
@@ -249,7 +260,8 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
249
260
  if (next.diags.length) { showEmpty(`The canvas couldn't draw this: ${next.diags[0]}`); return; }
250
261
  lastKey = key;
251
262
  lastS3 = s3; lastData = data;
252
- if (pinDrag()) { pendingAfterDrag = true; return; } // a model change mid-drag: drawn when the drag ends
263
+ drawLooks();
264
+ if (pinDrag() || dropping) { pendingAfterDrag = true; return; } // a model change mid-drag (or while its drop fades): drawn when the drag ends
253
265
  await draw(next);
254
266
  if (cd!.pinNotes.length) opts.note(`Pins: ${cd!.pinNotes.join('; ')}`, 'warn');
255
267
  }
@@ -568,8 +580,16 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
568
580
  kind: 'pan' | 'marquee' | 'pin' | 'click'; x0: number; y0: number; v0?: View; emptyClick?: boolean;
569
581
  // a pin drag: where it started and what it is shown at, its size and floor, its parent and siblings, the move so far
570
582
  start?: [number, number]; shown?: [number, number]; z0?: number; size?: [number, number];
571
- parent?: { w: number; d: number; pad: number; box: { x0: number; y0: number; x1: number; y1: number }; label: string };
572
- siblings?: { x0: number; y0: number; x1: number; y1: number }[]; move?: Move; invalid?: boolean; step?: number; origCd?: D; gridShown?: boolean;
583
+ parent?: { id: string; w: number; d: number; pad: number; box: { x0: number; y0: number; x1: number; y1: number }; label: string };
584
+ /** (0.14.0) how far the view was moved to keep the container still on screen (a trial may lay it out elsewhere) */
585
+ shifted?: [number, number];
586
+ move?: Move; invalid?: boolean; step?: number; origCd?: D; gridShown?: boolean;
587
+ /** what stands beside it in its container, where it stood when the drag began */
588
+ beside?: Beside[];
589
+ /** (0.14.0) what gave way to it, by how many cells; what would, while the drop waits; the last cell it could drop on */
590
+ given?: Map<string, [number, number]>; way?: Map<string, [number, number]>; clearAt?: [number, number];
591
+ /** (0.14.0) a new thing, from the palette (origCd: the drawing without it): the drawing with it, and what it is made as */
592
+ fresh?: { base: D; name: string; path: Path; plan: FreshPlan; text: string };
573
593
  /** siblings that flow after the dragged item, pinned where they stand so the drag doesn't push them */
574
594
  keep?: [string, [number, number]][]; sel0?: Path[]; add?: boolean; touch?: boolean; name?: string; id?: string; box?: { x: number; y: number; w: number; h: number }; moved?: boolean; ptr?: string; narrow?: string } | undefined;
575
595
  let spaceKeyDown = false;
@@ -577,15 +597,16 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
577
597
  stage.addEventListener('pointerdown', down);
578
598
  stage.addEventListener('pointermove', move);
579
599
  stage.addEventListener('pointerup', up);
580
- stage.addEventListener('pointercancel', up);
600
+ stage.addEventListener('pointercancel', e => { if (pinDrag()) void endPin(false); else up(e); });
581
601
  stage.addEventListener('wheel', wheel, { passive: false });
582
602
  stage.addEventListener('contextmenu', context);
583
603
  stage.addEventListener('dblclick', e => {
584
604
  // (0.12.5) what is under the pointer: the presses were captured, so a real double click's target is the stage
585
- const p = pathAt(e.target === stage ? fdoc().elementFromPoint(e.clientX, e.clientY) : e.target, e.clientX, e.clientY);
586
- if (p === undefined) return;
587
- if (ui.doubleClick === 'rename' && doc.doc.ok && resourceOf(p)?.path === p) rename(fromPointer(p));
588
- else opts.showInText(fromPointer(p));
605
+ const t = e.target === stage ? fdoc().elementFromPoint(e.clientX, e.clientY) : e.target;
606
+ // (0.14.1) to rename: the thing drawn there (not a connection near it); what has no name, nothing
607
+ if (ui.doubleClick === 'rename') { const p = pathAtEvent(t), r = p === undefined ? p : resourceOf(p); if (r && doc.doc.ok) rename(fromPointer(r.path)); return; }
608
+ const p = pathAt(t, e.clientX, e.clientY);
609
+ if (p !== undefined) opts.showInText(fromPointer(p));
589
610
  });
590
611
  };
591
612
  // in the page, a pointer's coordinates are already the page's
@@ -635,10 +656,9 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
635
656
  const start = localAt(cd.scene, id);
636
657
  if (item && start) {
637
658
  const b = item.box, par = item.parent;
638
- 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 }));
639
659
  drag = {
640
- kind: 'pin', x0: x, y0: y, name, id, ptr, narrow, start, shown: start, z0: b.z0, size: [b.x1 - b.x0, b.y1 - b.y0], siblings,
641
- 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 } : undefined,
660
+ kind: 'pin', x0: x, y0: y, name, id, ptr, narrow, start, shown: start, z0: b.z0, size: [b.x1 - b.x0, b.y1 - b.y0], beside: besideOf(cd, id),
661
+ 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 } : undefined,
642
662
  origCd: cd,
643
663
  };
644
664
  }
@@ -721,6 +741,16 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
721
741
  }
722
742
  let pinFrame = false, lastPin: { x: number; y: number; alt: boolean } | undefined, relayout = 0;
723
743
  const pinDrag = () => (drag?.kind === 'pin' && drag.moved ? drag : undefined);
744
+ /** what stands beside a drawn thing, in its container (or on the canvas), and whether each can be pinned elsewhere */
745
+ function besideOf(d: D, id: string, inside = d.scene.layout.byId.get(id)?.parent): Beside[] {
746
+ const pinned = new Set(d.pinId.values());
747
+ return (inside ? inside.children : d.scene.layout.items.filter(i => !i.parent)).filter(i => i.id !== id)
748
+ .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) }));
749
+ }
750
+ /** where those are now: where they stood, or where they gave way to */
751
+ const besideNow = (g: NonNullable<typeof drag>) => g.beside!.map(b => { const [dx, dy] = g.given?.get(b.id) ?? [0, 0]; return { ...b, x0: b.x0 + dx, x1: b.x1 + dx, y0: b.y0 + dy, y1: b.y1 + dy }; });
752
+ const footAt = (g: NonNullable<typeof drag>, [x, y]: [number, number]) => { const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0; return { x0: ox + x, y0: oy + y, x1: ox + x + g.size![0], y1: oy + y + g.size![1] }; };
753
+ const motionOn = () => ui.dragMotion !== 'respect' || !matchMedia('(prefers-reduced-motion: reduce)').matches;
724
754
  /** one step of a pin drag: snap, clamp, check, move the drawing, and lay it out again when the cell changes */
725
755
  function pinStep() {
726
756
  const g = pinDrag();
@@ -728,71 +758,201 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
728
758
  const k = scale();
729
759
  const step = lastPin.alt ? 0.5 : 1;
730
760
  g.step = step;
731
- const m = snapMove(g.start!, screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k), step, g.size!, g.parent);
732
- const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
733
- 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] };
761
+ const p = g.fresh ? toSvg(lastPin.x, lastPin.y) : undefined;
762
+ // a new thing is held by its floor's middle
763
+ const f0 = footAt(g, g.start!), grip = iso((f0.x0 + f0.x1) / 2, (f0.y0 + f0.y1) / 2, g.z0!);
764
+ const d = p ? screenToGrid(p.x - grip[0], p.y - grip[1]) : screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k);
765
+ const m = snapMove(g.start!, d, step, g.size!, g.parent);
766
+ const foot = footAt(g, m.at);
734
767
  const changed = !g.move || g.move.at[0] !== m.at[0] || g.move.at[1] !== m.at[1];
735
768
  g.move = m;
736
- g.invalid = overlaps(foot, g.siblings!);
769
+ g.invalid = overlaps(foot, besideNow(g));
770
+ if (changed) dwell(g);
771
+ if (!g.invalid) g.clearAt = m.at;
737
772
  svg?.classList.add('dragging');
738
773
  svg?.classList.toggle('drag-bad', g.invalid);
739
774
  // at once: the drawn item (and what stands on it) moved by transform, from where the drawing has it
740
775
  shiftDragged(g.id!, [m.at[0] - g.shown![0], m.at[1] - g.shown![1]]);
741
776
  paintDrag(foot);
742
- const within = g.parent ? `within ${g.parent.label}` : 'on the canvas';
743
- opts.onHint?.(`Moving ${g.name} ${within} · ${step === 1 ? 'whole cells (⌥: half cells)' : 'half cells'} · ${g.invalid ? 'overlaps: it won\'t drop here' : 'Esc cancels'}${T.pinHint}`);
777
+ sayDrag(g);
744
778
  // then the real layout, with its routes and labels, once per cell (and only where it may drop)
745
- if (changed && !g.invalid && lastS3) {
746
- clearTimeout(relayout);
747
- relayout = window.setTimeout(async () => {
748
- const now = pinDrag();
749
- if (!now || now.invalid || !now.move) return;
750
- let next: D;
751
- try { ({ next, keep: now.keep } = trialLayout(now)); } catch { return; }
752
- if (pinDrag() !== now) return; // the drag ended meanwhile: don't draw a stale trial
753
- await draw(next);
754
- if (pinDrag() !== now) return;
755
- now.shown = now.move.at;
756
- shiftDragged(now.id!, [0, 0]);
757
- 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);
758
- }, 0);
759
- }
779
+ if (changed && !g.invalid) relayoutSoon(g);
780
+ }
781
+ function sayDrag(g: NonNullable<typeof drag>) {
782
+ const within = g.parent ? `${g.fresh ? 'in' : 'within'} ${g.parent.label}` : 'on the canvas';
783
+ const n = g.given?.size ?? 0;
784
+ opts.onHint?.(`${g.fresh ? 'Adding' : 'Moving'} ${g.name} ${within} · ${g.step === 1 ? 'whole cells (⌥: half cells)' : 'half cells'} · ${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 · Esc cancels` : 'Esc cancels'}${T.pinHint}`);
785
+ }
786
+ function relayoutSoon(g: NonNullable<typeof drag>, glide = false) {
787
+ if (!g.fresh && !lastS3) return;
788
+ clearTimeout(relayout);
789
+ const go = () => {
790
+ const now = pinDrag();
791
+ if (!now || now !== g || now.invalid || !now.move) return;
792
+ let next: D;
793
+ try { ({ next, keep: now.keep } = trialLayout(now)); } catch { return; }
794
+ showTrial(now, next, now.move.at, glide);
795
+ };
796
+ if (glide) go(); else relayout = window.setTimeout(go, 0);
797
+ }
798
+ /** a trial drawing on the stage, the dragged thing at `at` in it; what moved since the last one glides there, if asked */
799
+ function showTrial(g: NonNullable<typeof drag>, next: D, at: [number, number], glide: boolean) {
800
+ const was = cd!;
801
+ stillOn(g, next);
802
+ void draw(next);
803
+ if (pinDrag() !== g) return;
804
+ g.shown = at;
805
+ shiftDragged(g.id!, [g.move!.at[0] - at[0], g.move!.at[1] - at[1]]);
806
+ paintDrag(footAt(g, g.move!.at));
807
+ if (!glide || !motionOn()) return;
808
+ const from = new Map<string, [number, number]>();
809
+ for (const b of g.beside!) { const a = was.scene.layout.byId.get(b.id)?.box, z = next.scene.layout.byId.get(b.id)?.box; 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]); }
810
+ glideFrom(from);
811
+ }
812
+ /** a trial lays the container out at another place (it fits what it holds): the view moved with it, so it stands still on
813
+ * screen, and what the drag knows of the container with it */
814
+ function stillOn(g: NonNullable<typeof drag>, next: D) {
815
+ const now = g.parent && next.scene.layout.byId.get(g.parent.id)?.box;
816
+ if (!g.parent || !now || !V.view) return;
817
+ const was = g.parent.box, dx = now.x0 - was.x0, dy = now.y0 - was.y0;
818
+ 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) };
819
+ if (Math.abs(dx) < 1e-9 && Math.abs(dy) < 1e-9) return;
820
+ g.beside = g.beside!.map(b => ({ ...b, x0: b.x0 + dx, x1: b.x1 + dx, y0: b.y0 + dy, y1: b.y1 + dy }));
821
+ shiftView(g, (dx - dy) * C * S, (dx + dy) * 0.5 * S);
822
+ }
823
+ function shiftView(g: NonNullable<typeof drag>, x: number, y: number) {
824
+ if (!V.view) return;
825
+ V.view = { ...V.view, x: V.view.x + x, y: V.view.y + y };
826
+ g.shifted = [(g.shifted?.[0] ?? 0) + x, (g.shifted?.[1] ?? 0) + y];
827
+ }
828
+ /** the view as it would be without that (the drag put back) */
829
+ function unshift(g: NonNullable<typeof drag>) { if (g.shifted) { shiftView(g, -g.shifted[0], -g.shifted[1]); g.shifted = undefined; } }
830
+ // ---------- (0.14.0) making way: a drop that waits on a taken cell (make-way.ts has the numbers and the arithmetic) ----------
831
+ let hintTimer = 0, giveTimer = 0, backTimer = 0, wayFrame = 0, jiggling: string[] = [];
832
+ /** the jiggle and the glide, off; what they moved, back where the drawing has it */
833
+ function stillWay() {
834
+ cancelAnimationFrame(wayFrame); wayFrame = 0;
835
+ for (const id of jiggling) shiftDragged(id, [0, 0]);
836
+ jiggling = [];
837
+ }
838
+ function restart() { clearTimeout(hintTimer); clearTimeout(giveTimer); stillWay(); }
839
+ function endWay() { clearTimeout(backTimer); backTimer = 0; restart(); }
840
+ /** does what gave way still have to, with the dragged thing here */
841
+ const needed = (g: NonNullable<typeof drag>, foot: Beside | { x0: number; y0: number; x1: number; y1: number }) => g.beside!.some(b => g.given?.has(b.id) && hits(b, foot));
842
+ /** the dragged thing is on another cell: the clock starts again; what gave way and is no longer needed goes back */
843
+ function dwell(g: NonNullable<typeof drag>) {
844
+ restart();
845
+ g.way = undefined;
846
+ const foot = footAt(g, g.move!.at);
847
+ // what gave way: kept while this cell needs it, else back after a moment (so a wobble doesn't flicker)
848
+ if (!g.given?.size || needed(g, foot)) { clearTimeout(backTimer); backTimer = 0; }
849
+ else if (!backTimer) backTimer = window.setTimeout(() => { backTimer = 0; if (pinDrag() === g) putBack(g); }, BACK_AFTER);
850
+ if (!g.invalid || !g.beside!.some(b => hits(b, foot))) return;
851
+ hintTimer = window.setTimeout(() => {
852
+ if (pinDrag() !== g) return;
853
+ const from = g.clearAt ?? g.start!, par = g.parent, pad = par?.pad ?? 0;
854
+ const way = makeWay({
855
+ foot, others: g.beside!, going: [g.move!.at[0] - from[0], g.move!.at[1] - from[1]],
856
+ bounds: par ? { x0: par.box.x0 + pad, y0: par.box.y0 + pad, x1: par.box.x1 - pad, y1: par.box.y1 - pad } : undefined,
857
+ });
858
+ if (!way?.size) return;
859
+ g.way = way;
860
+ paintDrag(foot); sayDrag(g); jiggle(g);
861
+ giveTimer = window.setTimeout(() => { if (pinDrag() === g && g.way === way) give(g, way); }, DWELL_GIVE - DWELL_HINT);
862
+ }, DWELL_HINT);
863
+ }
864
+ function give(g: NonNullable<typeof drag>, way: Map<string, [number, number]>) {
865
+ stillWay();
866
+ g.given = way; g.way = undefined; g.invalid = false; g.clearAt = g.move!.at;
867
+ relayoutSoon(g, true);
868
+ sayDrag(g);
869
+ }
870
+ function putBack(g: NonNullable<typeof drag>) {
871
+ stillWay();
872
+ g.given = undefined;
873
+ g.invalid = overlaps(footAt(g, g.move!.at), besideNow(g));
874
+ sayDrag(g);
875
+ if (!g.invalid) { relayoutSoon(g, true); return; }
876
+ // over something else: as the drag began, the dragged thing shown where it is held
877
+ showTrial(g, g.fresh?.base ?? g.origCd!, g.start!, true);
878
+ dwell(g);
879
+ }
880
+ function jiggle(g: NonNullable<typeof drag>) {
881
+ if (!motionOn()) return;
882
+ const t0 = performance.now(), ids = [...g.way!.keys()];
883
+ jiggling = ids;
884
+ const frame = (now: number) => {
885
+ if (pinDrag() !== g || !g.way) return;
886
+ const t = now - t0, a = (JIGGLE.px * Math.min(1, 0.25 + 0.75 * t / (DWELL_GIVE - DWELL_HINT))) / scale();
887
+ ids.forEach((id, i) => shiftScreen(id, a * Math.sin((t / 1000) * JIGGLE.hz * 2 * Math.PI + i * 1.7)));
888
+ wayFrame = requestAnimationFrame(frame);
889
+ };
890
+ wayFrame = requestAnimationFrame(frame);
891
+ }
892
+ function glideFrom(from: Map<string, [number, number]>) {
893
+ if (!from.size) return;
894
+ const t0 = performance.now(), on = svg;
895
+ jiggling = [...from.keys()];
896
+ const frame = (now: number) => {
897
+ if (svg !== on) { jiggling = []; return; }
898
+ const f = Math.min(1, Math.max(0, (now - t0) / GLIDE)), left = Math.pow(1 - f, 3);
899
+ for (const [id, [dx, dy]] of from) shiftDragged(id, [dx * left, dy * left]);
900
+ if (f < 1) wayFrame = requestAnimationFrame(frame); else jiggling = [];
901
+ };
902
+ frame(t0);
760
903
  }
761
904
  /**
762
905
  * The drawing with the dragged item pinned at its move. Siblings placed after it (in the flow, or beside it) would move
763
906
  * with it; any that did, and can be pinned, are kept where they stood, and the drop pins them too.
764
907
  */
765
- function trialLayout(g: NonNullable<typeof drag>): { next: D; keep: [string, [number, number]][] } {
766
- const base = JSON.parse(JSON.stringify(lastData ?? {})) as Record<string, Record<string, Record<string, unknown>>>;
767
- // pins kept under the legacy key are read there; the trial puts them where the drop will (x-editor)
768
- if (K.pins.legacyOnly(base)) { base[PINS_KEY] = base[K.pins.legacyKey!]; delete base[K.pins.legacyKey!]; }
769
- base[PINS_KEY] ??= {}; base[PINS_KEY].layout ??= {};
770
- const pins = base[PINS_KEY].layout;
771
- pins[g.name!] = { at: g.move!.at };
772
- let next = K.draw(lastS3!, base, opts.theme);
908
+ function trialLayout(g: NonNullable<typeof drag>, at = g.move!.at): { next: D; keep: [string, [number, number]][] } {
773
909
  const orig = g.origCd!, nameOf = new Map([...orig.pinId].map(([n, id]) => [id, n]));
774
- const me = orig.scene.layout.byId.get(g.id!)!;
775
- const sibs = me.parent ? me.parent.children : orig.scene.layout.items.filter(i => !i.parent);
910
+ // what gave way, where it gave way to (a pin each)
911
+ const gave: [string, [number, number]][] = [];
912
+ for (const [id, [dx, dy]] of g.given ?? []) { const was = localAt(orig.scene, id)!; gave.push([nameOf.get(id)!, [was[0] + dx, was[1] + dy]]); }
913
+ const set: [string, [number, number]][] = [[g.name!, at], ...gave];
914
+ const lay = layWith(g);
915
+ let next = lay(set);
916
+ const have = new Set([...Object.keys(K.pins.of(lastData) ?? {}), ...set.map(([n]) => n)]);
776
917
  const keep: [string, [number, number]][] = [];
777
- for (const sb of sibs) {
778
- if (sb === me) continue;
779
- const n = nameOf.get(sb.id), was = localAt(orig.scene, sb.id), now = next.scene.layout.byId.get(sb.id)?.box;
780
- if (!n || !was || !now || n in pins) continue;
781
- if (Math.abs(now.x0 - sb.box.x0) > 1e-6 || Math.abs(now.y0 - sb.box.y0) > 1e-6) keep.push([n, was]);
918
+ for (const b of g.beside!) {
919
+ const n = nameOf.get(b.id), was = localAt(orig.scene, b.id), now = localAt(next.scene, b.id);
920
+ if (!n || !was || !now || have.has(n)) continue;
921
+ if (Math.abs(now[0] - was[0]) > 1e-6 || Math.abs(now[1] - was[1]) > 1e-6) keep.push([n, was]);
922
+ }
923
+ if (keep.length) next = lay([...set, ...keep]);
924
+ return { next, keep: [...gave, ...keep] };
925
+ }
926
+ /** the drawing with these pins: of the file's data, or (a new thing) of the text it would make */
927
+ function layWith(g: NonNullable<typeof drag>): (pins: [string, [number, number]][]) => D {
928
+ if (g.fresh) {
929
+ const text = g.fresh.text;
930
+ return list => { const t = K.trial(pinsCmd(list, '').build(text).steps.reduce((u, st) => applyStep(u, st), text), opts.theme); if (!t) throw new Error('not drawn'); return t; };
782
931
  }
783
- if (keep.length) { for (const [n, at] of keep) pins[n] = { at }; next = K.draw(lastS3!, base, opts.theme); }
784
- return { next, keep };
932
+ return list => {
933
+ const base = JSON.parse(JSON.stringify(lastData ?? {})) as Record<string, Record<string, Record<string, unknown>>>;
934
+ // pins kept under the legacy key are read there; the trial puts them where the drop will (x-editor)
935
+ if (K.pins.legacyOnly(base)) { base[PINS_KEY] = base[K.pins.legacyKey!]; delete base[K.pins.legacyKey!]; }
936
+ base[PINS_KEY] ??= {}; base[PINS_KEY].layout ??= {};
937
+ for (const [n, at] of list) base[PINS_KEY].layout[n] = { at };
938
+ return K.draw(lastS3!, base, opts.theme);
939
+ };
785
940
  }
786
941
  /** move a drawn item, and everything standing on it, by a grid offset (a transform: the next layout replaces it) */
787
942
  function shiftDragged(id: string, [gx, gy]: [number, number]) {
788
943
  if (!svg || !cd) return;
789
- const [sx, sy] = [(gx - gy) * C * S, (gx + gy) * 0.5 * S];
944
+ shiftBy(id, (gx - gy) * C * S, (gx + gy) * 0.5 * S);
945
+ }
946
+ /** the same, sideways on screen */
947
+ const shiftScreen = (id: string, dx: number) => shiftBy(id, dx, 0);
948
+ function shiftBy(id: string, sx: number, sy: number) {
949
+ if (!svg || !cd) return;
790
950
  const ids = new Set([id]);
791
951
  for (const it of cd.scene.layout.items) { let p = it.parent; while (p) { if (p.id === id) { ids.add(it.id); break; } p = p.parent; } }
792
952
  for (const el of svg.querySelectorAll<SVGElement>('[data-id]')) {
793
953
  if (!ids.has(el.getAttribute('data-id') ?? '')) continue;
794
954
  if (el.parentElement?.closest(`[data-id="${CSS.escape(el.getAttribute('data-id')!)}"]`)) continue;
795
- el.setAttribute('transform', gx || gy ? `translate(${sx.toFixed(1)} ${sy.toFixed(1)})` : '');
955
+ el.setAttribute('transform', sx || sy ? `translate(${sx.toFixed(2)} ${sy.toFixed(2)})` : '');
796
956
  }
797
957
  }
798
958
  /** the drag's overlay: the grid on the parent's floor (half cells too, with ⌥), the drop target, the clamped edges */
@@ -820,10 +980,21 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
820
980
  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');
821
981
  overlay.append(wrap);
822
982
  // the drop target: the footprint, accent where it may drop, red where it can't
823
- const t = d.createElementNS(SVGNS, 'polygon');
824
- t.setAttribute('class', `drop${g.invalid ? ' bad' : ''}`);
825
- 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(' '));
826
- overlay.append(t);
983
+ const poly = (b: { x0: number; y0: number; x1: number; y1: number }, cls: string) => {
984
+ const t = d.createElementNS(SVGNS, 'polygon');
985
+ t.setAttribute('class', cls);
986
+ t.setAttribute('points', [P(b.x0, b.y0), P(b.x1, b.y0), P(b.x1, b.y1), P(b.x0, b.y1)].join(' '));
987
+ overlay!.append(t);
988
+ return t;
989
+ };
990
+ poly(foot, `drop${g.invalid ? ' bad' : ''}`);
991
+ // what would make way, outlined where it would go
992
+ for (const b of g.way ? besideNow({ ...g, given: g.way }) : []) {
993
+ if (!g.way!.has(b.id)) continue;
994
+ const w = poly(b, 'drop way');
995
+ w.setAttribute('stroke-dasharray', '5 4');
996
+ w.dataset.way = b.id;
997
+ }
827
998
  // the parent's edges the move is held at
828
999
  if (g.parent && g.move) {
829
1000
  const pb = g.parent.box, c = g.move.clamped, pad = g.parent.pad;
@@ -847,6 +1018,13 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
847
1018
  if (!g) return;
848
1019
  drag = undefined;
849
1020
  clearTimeout(relayout);
1021
+ endWay();
1022
+ // dropped where what gave way isn't needed, before it went back: it stays where it was
1023
+ let stale = false;
1024
+ if (commit && g.given?.size && g.move) {
1025
+ const foot = footAt(g, g.move.at);
1026
+ if (!needed(g, foot)) { g.given = undefined; g.invalid = overlaps(foot, besideNow(g)); stale = true; }
1027
+ }
850
1028
  // the grid and the drop target fade out, then the drop
851
1029
  const shown = overlay ? [...overlay.querySelectorAll('.gridwrap, .drop, .edge')] : [];
852
1030
  if (shown.length) {
@@ -857,19 +1035,137 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
857
1035
  svg?.classList.remove('dragging', 'drag-bad');
858
1036
  paintNav();
859
1037
  const m = g.move;
1038
+ if (g.fresh) { await endFresh(g, commit, stale); return; }
860
1039
  const moved = m && (m.at[0] !== g.start![0] || m.at[1] !== g.start![1]);
861
1040
  if (commit && m && moved && !g.invalid) {
862
1041
  // the item, and the neighbours the move would have pushed, kept where they stand: one command, one undo step
863
1042
  const label = `Pin ${describe(fromPointer(g.ptr!))} at [${m.at.join(', ')}]`;
864
1043
  let keep = g.keep ?? [];
865
- if (!g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1]) try { keep = trialLayout(g).keep; } catch { /* drop it as it is */ }
866
- 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);
867
- if (pendingAfterDrag && lastS3) { pendingAfterDrag = false; lastKey = ''; render(lastS3, lastData); }
1044
+ if (stale || !g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1]) try { keep = trialLayout(g).keep; } catch { /* drop it as it is */ }
1045
+ 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);
1046
+ pendingAfterDrag = false; // the drop's own reading draws what came meanwhile too
868
1047
  return;
869
1048
  }
870
1049
  if (commit && g.invalid) opts.note(`${g.name} can't go there: it would overlap`, 'warn');
1050
+ unshift(g);
871
1051
  await draw(g.origCd!);
872
- if (pendingAfterDrag && lastS3) { pendingAfterDrag = false; lastKey = ''; render(lastS3, lastData); }
1052
+ redrawPending();
1053
+ }
1054
+
1055
+ /** a reading that came during a drag that changed nothing: drawn now it is over */
1056
+ function redrawPending() { if (pendingAfterDrag) { pendingAfterDrag = false; lastKey = ''; setTimeout(() => { if (lastS3 && !pinDrag()) void render(lastS3, lastData); }, 0); } }
1057
+ /** what a drop's command says of the things it pins beside the dragged one */
1058
+ function wayWords(g: NonNullable<typeof drag>, keep: [string, [number, number]][]): string {
1059
+ const nameOf = new Map([...g.origCd!.pinId].map(([n, id]) => [id, n])), gave = new Set([...g.given?.keys() ?? []].map(id => nameOf.get(id)));
1060
+ const a = keep.filter(([n]) => gave.has(n)).map(([n]) => n), b = keep.filter(([n]) => !gave.has(n)).map(([n]) => n);
1061
+ const words = [...(a.length ? [`${a.join(', ')} made way`] : []), ...(b.length ? [`${b.join(', ')} kept in place`] : [])].join('; ');
1062
+ return words && ` (${words})`;
1063
+ }
1064
+ // ---------- (0.14.0) a new thing dragged from the palette: the real one, in a trial drawing, by the drag above ----------
1065
+ /** what it would be made as at a point: the container (or the object that holds it) under the point, as the drawing
1066
+ * was before it, so what it does to the drawing never changes the answer */
1067
+ function freshPlan(sec: string, item: PaletteItem | undefined, name: string, p: Path, at: { x: number; y: number } | undefined, home: D | undefined): FreshPlan {
1068
+ const k = kindOf(sec), preset = item?.value?.() as Record<string, unknown> | undefined;
1069
+ const what = item && preset !== undefined ? item.label.toLowerCase() : k.singular;
1070
+ const under = at && home ? outlinesAt(home, at) : [], drop = K.dropInto?.(sec);
1071
+ let value = (preset ?? k.template()) as Record<string, unknown>, into: string | undefined, words = '';
1072
+ const c = drop ? under.find(u => u.kind === drop.container) : undefined;
1073
+ if (drop && c) { into = c.name; value = { ...(drop.value(c.name) as Record<string, unknown>), ...(preset ?? {}) }; words = drop.label(c.name); }
1074
+ if (!into && K.dropOnto) for (const t of under) {
1075
+ const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
1076
+ if (plan) { into = t.name; value = plan.value as Record<string, unknown>; words = plan.label ? ` ${plan.label}` : ` in ${t.name}`; break; }
1077
+ }
1078
+ const label = `Add ${what} ${name}${words}`;
1079
+ return { into, label, add: insertCmd(p.slice(0, -1), name, value, { label }) };
1080
+ }
1081
+ /** the objects whose outline a point of the drawing is in, innermost first */
1082
+ function outlinesAt(d: D, q: { x: number; y: number }): ObjectRef[] {
1083
+ // 2D: the panels under it
1084
+ if (flat) return flat.panelsAt(q.x, q.y).map(id => { const ptr = d.pathOf.get(id), ref = ptr === undefined ? undefined : resourceOf(ptr); return ref && ref.path === ptr ? ref : undefined; }).filter((x): x is ObjectRef => !!x);
1085
+ // on its drawn outline counts too: 2 px more each way
1086
+ const e = 2 / scale() / S;
1087
+ const inside = (poly: [number, number][]) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > q.y) !== (yj > q.y) && q.x < (xj - xi) * (q.y - yi) / (yj - yi) + xi) c = !c; } return c; };
1088
+ const out: { r: ObjectRef; depth: number; area: number }[] = [];
1089
+ for (const [id, ptr] of d.pathOf) {
1090
+ const it = d.scene.layout.byId.get(id), ref = resourceOf(ptr);
1091
+ if (!it || !ref || ref.path !== ptr) continue;
1092
+ const b = it.box;
1093
+ if (!inside(boxSilhouette({ ...b, x0: b.x0 - e, y0: b.y0 - e, x1: b.x1 + e, y1: b.y1 + e }))) continue;
1094
+ let depth = 0; for (let up = it.parent; up; up = up.parent) depth++;
1095
+ out.push({ r: ref, depth, area: (b.x1 - b.x0) * (b.y1 - b.y0) });
1096
+ }
1097
+ return out.sort((a, b) => b.depth - a.depth || a.area - b.area).map(x => x.r);
1098
+ }
1099
+ /** begin, or go on, dragging a new thing at a point (client px); false: it can't be drawn (the label is dragged) */
1100
+ function dragFresh(sec: string, item: PaletteItem | undefined, at: { x: number; y: number; alt: boolean }): boolean {
1101
+ if (mode !== '3d' || !cd || !svg || !doc.doc.ok || !lastS3) return false;
1102
+ const was = pinDrag()?.fresh ? pinDrag() : undefined, home = was?.origCd ?? cd;
1103
+ const k = kindOf(sec), name = was?.fresh!.name ?? freshName(doc.text, item?.name ?? k.singular), path = [...k.section, name] as Path;
1104
+ const sv = toSvg(at.x, at.y), off = was?.shifted ?? [0, 0];
1105
+ const plan = freshPlan(sec, item, name, path, { x: sv.x - off[0], y: sv.y - off[1] }, home);
1106
+ if (!was || was.fresh!.plan.into !== plan.into) {
1107
+ const text = plan.add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
1108
+ let trial: D | undefined;
1109
+ try { trial = K.trial(text, opts.theme); } catch { /* not drawn */ }
1110
+ const id = trial?.pinId.get(name), it = id ? trial!.scene.layout.byId.get(id) : undefined, start = id ? localAt(trial!.scene, id) : undefined;
1111
+ if (!trial || trial.diags.length || !id || !it || !start) return false;
1112
+ const b = it.box, par = it.parent, inHome = par ? home.scene.layout.byId.get(par.id) : undefined;
1113
+ // drawn in a container of its own, made with it: it could only be moved inside that
1114
+ if (par && !inHome) return false;
1115
+ endWay(); clearTimeout(relayout);
1116
+ const g: NonNullable<typeof drag> = {
1117
+ kind: 'pin', x0: at.x, y0: at.y, moved: true, name, id, start, shown: start, z0: b.z0, size: [b.x1 - b.x0, b.y1 - b.y0], origCd: home,
1118
+ // its container, as it was: what is drawn is moved to it (stillOn)
1119
+ 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 } : undefined,
1120
+ beside: besideOf(home, id, inHome), shifted: was?.shifted,
1121
+ fresh: { base: trial, name, path, plan, text },
1122
+ gridShown: was?.gridShown,
1123
+ };
1124
+ drag = g;
1125
+ // out of one container and into another: the view as it was, then the new one still
1126
+ unshift(g);
1127
+ try { g.fresh!.base = trialLayout(g, start).next; } catch { /* as the layout has it */ }
1128
+ stillOn(g, g.fresh!.base);
1129
+ void draw(g.fresh!.base);
1130
+ if (pinDrag() !== g) return false;
1131
+ }
1132
+ lastPin = { x: at.x, y: at.y, alt: at.alt };
1133
+ pinStep();
1134
+ return true;
1135
+ }
1136
+ /** the new thing off the canvas again: the drawing without it, the drag not over */
1137
+ function hideFresh() {
1138
+ const g = pinDrag();
1139
+ if (!g?.fresh) return;
1140
+ endWay(); clearTimeout(relayout);
1141
+ drag = undefined;
1142
+ lastKey = '';
1143
+ unshift(g);
1144
+ void draw(g.origCd!);
1145
+ paintNav();
1146
+ }
1147
+ async function endFresh(g: NonNullable<typeof drag>, commit: boolean, stale: boolean) {
1148
+ const f = g.fresh!, m = g.move;
1149
+ if (!commit || !m) {
1150
+ unshift(g);
1151
+ await draw(g.origCd!);
1152
+ redrawPending();
1153
+ return;
1154
+ }
1155
+ pendingAfterDrag = false;
1156
+ // where it is dropped, unless that is where the layout puts it anyway; on a taken cell, where the layout puts it
1157
+ let keep = g.keep ?? [];
1158
+ if (!g.invalid && (stale || !g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1] || g.keep === undefined)) try { keep = trialLayout(g).keep; } catch { keep = []; }
1159
+ // (the layout's own place needn't be on the grid: the same cell is the same place)
1160
+ 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];
1161
+ const pins: [string, [number, number]][] = g.invalid ? [] : [...(its || keep.length ? [[f.name, m.at] as [string, [number, number]]] : []), ...keep];
1162
+ const cmd = pins.length ? seqCmd(`${f.plan.label} at [${m.at.join(', ')}]${wayWords(g, keep)}`, [f.plan.add, pinsCmd(pins, '')]) : f.plan.add;
1163
+ if (g.invalid) unshift(g);
1164
+ if (!run(doc, { ...cmd, select: [f.path] }, 'canvas', opts.note)) { lastKey = ''; unshift(g); await draw(g.origCd!); return; }
1165
+ if (g.invalid) opts.note(`${f.name} added; that spot is taken, so the layout placed it`);
1166
+ doc.select([f.path], 'canvas');
1167
+ // its name, in the inline field above it; the drop and the name are one undo step
1168
+ rename(f.path, { joins: doc.undoId, at: lastPin });
873
1169
  }
874
1170
 
875
1171
  function up(e: PointerEvent) {
@@ -911,10 +1207,6 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
911
1207
  }
912
1208
  return out;
913
1209
  }
914
- const round = (v: number) => Math.round(v * 2) / 2;
915
- const snap = ([x, y]: [number, number]): [number, number] => [round(x), round(y)];
916
- const gridToScreen = (gx: number, gy: number): [number, number] => { const [ux, uy] = screenToGrid(1, 0), [vx, vy] = screenToGrid(0, 1); const det = ux * vy - uy * vx; return [(gx * vy - gy * vx) / det, (gy * ux - gx * uy) / det]; };
917
-
918
1210
  function wheel(e: WheelEvent) {
919
1211
  e.preventDefault();
920
1212
  const { x, y } = pageXY(e);
@@ -1041,110 +1333,21 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1041
1333
  }
1042
1334
  }
1043
1335
  // ---------- E11: the palette: add a resource by a click, or by a drag onto the canvas ----------
1044
- /** Where a drop lands, as a pin: the new thing laid out once (a trial), then moved from where the layout put it to
1045
- * the point, in its parent's frame and on the grid. Undefined: the spot is taken, or it can't be placed. */
1046
- function placeAt(name: string, add: Command, at: { x: number; y: number }): [number, number] | undefined {
1047
- if (!cd || !svg) return undefined;
1048
- const text = add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
1049
- let trial: D | undefined;
1050
- try { trial = K.trial(text, opts.theme); } catch { return undefined; }
1051
- if (!trial) return undefined;
1052
- const id = trial.pinId.get(name), item = id ? trial.scene.layout.byId.get(id) : undefined, start = id ? localAt(trial.scene, id) : undefined;
1053
- if (!item || !start) return undefined;
1054
- const b = item.box, par = item.parent;
1055
- // the drawing's coordinates are the projection's: the trial's centre and the drop point, in the same units
1056
- const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
1057
- const centre = [(cx - cy) * C * S, (cx + cy) * 0.5 * S - b.z0 * S], drop = toSvg(at.x, at.y);
1058
- const m = snapMove(start, screenToGrid(drop.x - centre[0], drop.y - centre[1]), 1, [b.x1 - b.x0, b.y1 - b.y0],
1059
- par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region) } : undefined);
1060
- const dx = m.at[0] - start[0], dy = m.at[1] - start[1];
1061
- const moved = { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy };
1062
- const siblings = (par ? par.children : trial.scene.layout.items.filter(i => !i.parent)).filter(i => i !== item).map(i => i.box);
1063
- return overlaps(moved, siblings) ? undefined : m.at;
1064
- }
1065
- /** The container (of the kind given) whose floor a point is on (its footprint, as drawn), if any. */
1066
- function containerAt(kind: string, at: { x: number; y: number }): string | undefined {
1067
- if (!cd) return undefined;
1068
- const p = toSvg(at.x, at.y);
1069
- if (flat) {
1070
- // 2D: the innermost panel of that kind under the point
1071
- for (const id of flat.panelsAt(p.x, p.y)) {
1072
- const name = [...cd.pinId].find(([, pid]) => pid === id)?.[0];
1073
- if (name && resourceOf(cd.pathOf.get(id) ?? '')?.kind === kind) return name;
1074
- }
1075
- return undefined;
1076
- }
1077
- const inside = (poly: [number, number][]) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > p.y) !== (yj > p.y) && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c; } return c; };
1078
- for (const [name, id] of cd.pinId) {
1079
- if (resourceOf(cd.pathOf.get(id) ?? '')?.kind !== kind) continue;
1080
- const item = cd.scene.layout.byId.get(id);
1081
- if (item && inside(floorOf(item.box))) return name;
1082
- }
1083
- return undefined;
1084
- }
1085
- /** (0.10.1) the objects whose drawn floor a point is on, innermost first: in 2D the panels under it; in 3D every placed
1086
- * thing whose floor holds the point, the deepest (then the smallest) first */
1087
- function objectsUnder(at: { x: number; y: number }): ObjectRef[] {
1088
- if (!cd) return [];
1089
- const p = toSvg(at.x, at.y);
1090
- const refOf = (id: string) => { const ptr = cd!.pathOf.get(id); const r = ptr === undefined ? undefined : resourceOf(ptr); return r && r.path === ptr ? r : undefined; };
1091
- if (flat) return flat.panelsAt(p.x, p.y).map(refOf).filter((r): r is ObjectRef => !!r);
1092
- const inside = (poly: [number, number][]) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > p.y) !== (yj > p.y) && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c; } return c; };
1093
- const depth = (i: { parent?: unknown }) => { let n = 0; for (let q = i.parent as { parent?: unknown } | undefined; q; q = q.parent as { parent?: unknown } | undefined) n++; return n; };
1094
- // what is drawn under the point, topmost (innermost) first, as the eye sees it; then any whose floor holds the point
1095
- const seen = new Map<string, ObjectRef>();
1096
- for (const e of fdoc().elementsFromPoint(at.x, at.y)) {
1097
- if (!svg?.contains(e)) continue;
1098
- for (let el = e.closest('[data-id]'); el; el = el.parentElement?.closest('[data-id]') ?? null) {
1099
- const r = refOf(el.getAttribute('data-id') ?? '');
1100
- if (r && !seen.has(r.path)) seen.set(r.path, r);
1101
- }
1102
- }
1103
- const hits: { r: ObjectRef; d: number; a: number }[] = [];
1104
- for (const [, id] of cd.pinId) {
1105
- const item = cd.scene.layout.byId.get(id), r = refOf(id);
1106
- 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) });
1107
- }
1108
- return [...seen.values(), ...hits.sort((x, y) => y.d - x.d || x.a - y.a).map(h => h.r)];
1109
- }
1110
- /** Add an object from the palette: dropped at a point, it is pinned there; dropped on a container the kit names, it
1111
- * is made inside it; else the layout places it. One command (one undo step); then it is selected and named. */
1336
+ /** Add an object from the palette, by a click or (where it isn't dragged itself: 2D, a container of its own) by a drop at
1337
+ * a point: into what holds it there, else the layout places it. One command (one undo step); then it is selected and named. */
1112
1338
  function addFromPalette(sec: string, at?: { x: number; y: number }, item?: PaletteItem): Path | undefined {
1113
1339
  if (!doc.doc.ok) { opts.note('Fix the YAML first', 'warn'); return undefined; }
1114
- const k = kindOf(sec);
1115
- // (0.10.0) a palette entry's preset: what it starts as, and the base of its name
1116
- const preset = item?.value?.() as Record<string, unknown> | undefined;
1117
- const what = item && preset !== undefined ? item.label.toLowerCase() : k.singular;
1118
- const name = freshName(doc.text, item?.name ?? k.singular);
1119
- const p = [...k.section, name] as Path;
1120
- let value = (preset ?? k.template()) as Record<string, unknown>;
1121
- let into: string | undefined;
1122
- const drop = at ? K.dropInto?.(sec) : undefined;
1123
- if (at && drop) {
1124
- const c = containerAt(drop.container, at);
1125
- // dropped into a container: what puts it there, and the preset's own keys over it
1126
- if (c) { into = c; value = { ...(drop.value(c) as Record<string, unknown>), ...(preset ?? {}) }; }
1127
- }
1128
- let intoLabel = into ? drop!.label(into) : '';
1129
- // (0.10.1) the domain's rule: the innermost object under the drop that holds it
1130
- if (at && !into && K.dropOnto) {
1131
- for (const t of objectsUnder(at)) {
1132
- const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
1133
- if (plan) { into = t.name; value = plan.value as Record<string, unknown>; intoLabel = plan.label ? ` ${plan.label}` : ` in ${t.name}`; break; }
1134
- }
1135
- }
1136
- const label = `Add ${what} ${name}${intoLabel}`;
1137
- const add = insertCmd(p.slice(0, -1), name, value, { label });
1138
- const pin = at && !into && mode === '3d' ? placeAt(name, add, at) : undefined;
1139
- const cmd = pin ? seqCmd(`${label} at [${pin.join(', ')}]`, [add, withPinsMoved(setCmd([PINS_KEY, 'layout', name], { at: pin }))]) : add;
1140
- if (!run(doc, { ...cmd, select: [p] }, 'canvas', opts.note)) return undefined;
1141
- 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`);
1340
+ const k = kindOf(sec), name = freshName(doc.text, item?.name ?? k.singular), p = [...k.section, name] as Path;
1341
+ const plan = freshPlan(sec, item, name, p, at && toSvg(at.x, at.y), cd);
1342
+ if (!run(doc, { ...plan.add, select: [p] }, 'canvas', opts.note)) return undefined;
1343
+ 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)' : ''}`);
1142
1344
  doc.select([p], 'canvas');
1143
1345
  // (0.12.5) its name, in the inline field above it; the drop and the name are one undo step
1144
1346
  rename(p, { joins: doc.undoId, at });
1145
1347
  return p;
1146
1348
  }
1147
1349
  const palette = h('div', { class: 'palette', role: 'toolbar', 'aria-label': T.palette, 'aria-orientation': 'vertical' });
1350
+ const drawLooks = K.looks?.(palette, () => (disposed ? undefined : doc.goodDoc.data), ui, opts.theme) ?? (() => {});
1148
1351
  // (0.11.0) sections: a header (a button, aria-expanded) over its entries; open: the section last added from (the
1149
1352
  // first, before any); the reader opens and closes the others as they like. The host's store may be off: guarded.
1150
1353
  const sections = new Map<string, { head: HTMLButtonElement; body: HTMLElement }>();
@@ -1153,7 +1356,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1153
1356
  try { const v = JSON.parse(opts.store?.get(PAL_KEY) ?? '{}') as { last?: unknown }; if (typeof v.last === 'string') lastSection = v.last; } catch { /* none */ }
1154
1357
  const named = [...new Set(ui.palette.map(i => i.section).filter((x): x is string => x !== undefined))];
1155
1358
  const openAtStart = lastSection !== undefined && named.includes(lastSection) ? lastSection : named[0];
1156
- const setOpen = (sec: string, open: boolean) => { const g = sections.get(sec); if (!g) return; g.head.setAttribute('aria-expanded', String(open)); g.body.hidden = !open; };
1359
+ const setOpen = (sec: string, open: boolean) => { const g = sections.get(sec); if (!g) return; g.head.setAttribute('aria-expanded', String(open)); g.body.hidden = !open; if (open) drawLooks(); };
1157
1360
  function sectionBody(sec: string): HTMLElement {
1158
1361
  const have = sections.get(sec);
1159
1362
  if (have) return have.body;
@@ -1199,6 +1402,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1199
1402
  }
1200
1403
  if (!words.length && before) { for (const [sec, open] of before) setOpen(sec, open); before = undefined; }
1201
1404
  none.hidden = shown > 0;
1405
+ drawLooks();
1202
1406
  none.textContent = shown ? '' : `Nothing matches "${search.value.trim()}"`;
1203
1407
  }
1204
1408
  const setDockW = (w: number, keep = true) => { const v = Math.round(Math.min(DOCK_MAX, Math.max(DOCK_MIN, w))); host.style.setProperty('--pal-w', `${v}px`); palGrip.setAttribute('aria-valuenow', String(v)); if (keep) { dockPref.w = v; saveDock(); } };
@@ -1259,19 +1463,35 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1259
1463
  e.preventDefault();
1260
1464
  try { b.setPointerCapture(e.pointerId); } catch { /* a synthetic pointer: the events come to the button anyway */ }
1261
1465
  const x0 = e.clientX, y0 = e.clientY;
1262
- let ghost: HTMLElement | undefined;
1466
+ let ghost: HTMLElement | undefined, dragged = false, real = false, frame = 0, last: PointerEvent | undefined;
1263
1467
  const over = (ev: PointerEvent) => { const r = stage.getBoundingClientRect(); 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)); };
1468
+ // the thing itself on the canvas (0.14.0: 3D), else its label
1469
+ const step = (ev: PointerEvent) => {
1470
+ const on = over(ev);
1471
+ real = on && dragFresh(sec, item, { x: ev.clientX, y: ev.clientY, alt: ev.altKey });
1472
+ if (!on || !real) hideFresh();
1473
+ if (!real) {
1474
+ if (!ghost) { ghost = h('div', { class: 'pal-ghost', 'aria-hidden': 'true' }, icon(ic), label); host.append(ghost); }
1475
+ const hr = host.getBoundingClientRect();
1476
+ ghost.style.left = `${ev.clientX - hr.left + 8}px`; ghost.style.top = `${ev.clientY - hr.top + 8}px`;
1477
+ ghost.classList.toggle('bad', !on);
1478
+ } else { ghost?.remove(); ghost = undefined; }
1479
+ };
1264
1480
  const mv = (ev: PointerEvent) => {
1265
- if (!ghost && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
1266
- if (!ghost) { ghost = h('div', { class: 'pal-ghost', 'aria-hidden': 'true' }, icon(ic), label); host.append(ghost); }
1267
- const hr = host.getBoundingClientRect();
1268
- ghost.style.left = `${ev.clientX - hr.left + 8}px`; ghost.style.top = `${ev.clientY - hr.top + 8}px`;
1269
- ghost.classList.toggle('bad', !over(ev));
1481
+ if (!dragged && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
1482
+ dragged = true;
1483
+ last = ev;
1484
+ if (frame) return;
1485
+ const go = () => { if (!frame) return; cancelAnimationFrame(frame); frame = 0; if (last) step(last); };
1486
+ frame = requestAnimationFrame(go); setTimeout(go, 32);
1270
1487
  };
1271
1488
  const done = (ev: PointerEvent, drop: boolean) => {
1272
1489
  b.removeEventListener('pointermove', mv); b.removeEventListener('pointerup', upH); b.removeEventListener('pointercancel', cancelH); removeEventListener('keydown', esc, true);
1273
- const dragged = !!ghost;
1490
+ cancelAnimationFrame(frame); frame = 0;
1491
+ if (drop && dragged) step(ev);
1274
1492
  ghost?.remove();
1493
+ if (real && pinDrag()?.fresh) { if (drop) usedSection(item); void endPin(drop); return; }
1494
+ hideFresh();
1275
1495
  if (!drop) return;
1276
1496
  if (!dragged) { usedSection(item); addFromPalette(sec, undefined, item); }
1277
1497
  else if (over(ev)) { usedSection(item); addFromPalette(sec, { x: ev.clientX, y: ev.clientY }, item); }
@@ -1398,9 +1618,9 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1398
1618
  });
1399
1619
 
1400
1620
  const base = {
1401
- addFromPalette, palette, groupSelection, startPick, objectsUnder, get linking() { return linking; },
1621
+ addFromPalette, palette, groupSelection, startPick, get linking() { return linking; },
1402
1622
  render, setTheme, paintOverlay, fit: fitItems, fitNext() { toFit = true; }, fitAll: fit, actual, zoomAt, itemsBox, routesBox, get moved() { return V.moved; }, settled, get zoom() { return V.zoom; },
1403
- dispose() { endMorph(); clearTimeout(relayout); V.dispose(); disposed = true; },
1623
+ dispose() { endMorph(); endWay(); clearTimeout(relayout); V.dispose(); disposed = true; },
1404
1624
  focus: () => stage.focus(),
1405
1625
  /** for the tests */
1406
1626
  get view() { return V.view; },