@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
@@ -14,6 +14,7 @@
14
14
  import { h, icon, type IconName } from './icons.ts';
15
15
  import { openMenu, type MenuItem } from './menu.ts';
16
16
  import { run, type Actions } from './actions.ts';
17
+ import { connectionsOf, nearestOn } from '../connections.ts';
17
18
  import { screenToGrid, localAt, boxSilhouette, floorOf, snapMove, overlaps, paddingOf, type Move } from '../../iso-objects/geometry.ts';
18
19
  import { regionKind, type KindCatalog } from '../../iso-objects/kinds.ts';
19
20
  import type { CompiledScene } from '../../iso-objects/compile.ts';
@@ -22,6 +23,7 @@ import type { EditorModel, Command } from '../model.ts';
22
23
  import type { Problem } from '../validate.ts';
23
24
  import { applyStep } from '../splice.ts';
24
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';
25
27
  import type { ObjectKindInfo, ObjectRef, ConnectPlan, GroupPlan } from '../adapter.ts';
26
28
  import { fromPointer, toPointer, type Path } from '../path.ts';
27
29
  import { buildSvg } from '../../iso-core/svg-dom.ts';
@@ -81,6 +83,12 @@ export interface CanvasUi {
81
83
  * its own at the canvas's left, with a search box filtering by label and section, resizable and collapsible; its
82
84
  * width and whether it is collapsed are kept in the host's store as `canvas-palette-dock`) */
83
85
  paletteLayout?: 'floating' | 'docked';
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) */
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';
84
92
  text: {
85
93
  stage: string; dragGroup: string; dragSelectTip: string; unreadable: string; palette: string;
86
94
  /** the end of a pin drag's hint */
@@ -110,6 +118,9 @@ export interface CanvasKit<M, D extends CanvasDrawing> {
110
118
  dropOnto?(target: ObjectRef, value: unknown, kind: string, data: unknown): { value: unknown; label?: string } | undefined;
111
119
  /** (0.10.0) the selection made into a new container (the adapter's group): Group, ⌘G, one undo step */
112
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;
113
124
  actions: Actions;
114
125
  /** what an object's own menu offers, beyond rename, duplicate and delete */
115
126
  objectItems(doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void): MenuItem[];
@@ -145,13 +156,16 @@ export interface CanvasOpts<M, D extends CanvasDrawing, A extends object = objec
145
156
  layer?: (ctx: CanvasCtx<D>) => CanvasLayer<A>;
146
157
  }
147
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
+
148
162
  const SVGNS = 'http://www.w3.org/2000/svg';
149
163
 
150
164
 
151
165
  export function canvasView<M, D extends CanvasDrawing, A extends object = object>(host: HTMLElement, doc: EditorModel, opts: CanvasOpts<M, D, A>) {
152
166
  const K = opts.kit, ui = K.ui, T = ui.text;
153
167
  const { setCmd, deleteCmd, insertCmd, insertItemCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
154
- const { deletePaths, renameDialog, duplicate, connected } = K.actions;
168
+ const { deletePaths, duplicate, connected } = K.actions;
155
169
  const resourceOf = (ptr: string) => K.objectOf(ptr);
156
170
  const kindOf = (k: string) => K.kinds.find(x => x.kind === k)!;
157
171
  const PINS_KEY = K.pins.key;
@@ -237,7 +251,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
237
251
  if (!s3) { showEmpty(T.unreadable); return; }
238
252
  const key = JSON.stringify(data);
239
253
  // nothing new to draw: repaint the marks, unless a drag is showing its grid (it repaints when it ends)
240
- if (key === lastKey && svg) { if (!pinDrag()) paintOverlay(); return; }
254
+ if (key === lastKey && svg) { if (!pinDrag()) paintOverlay(); if (toFit) { toFit = false; fitItems(); } return; }
241
255
  if (mode === '2d' && !flatImpl) {
242
256
  try { await loadFlat(); } catch (e) { mode = '3d'; paintNav(); opts.note(`The 2D view couldn't load: ${(e as Error).message}`, 'warn'); }
243
257
  }
@@ -246,10 +260,12 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
246
260
  if (next.diags.length) { showEmpty(`The canvas couldn't draw this: ${next.diags[0]}`); return; }
247
261
  lastKey = key;
248
262
  lastS3 = s3; lastData = data;
249
- 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
250
265
  await draw(next);
251
266
  if (cd!.pinNotes.length) opts.note(`Pins: ${cd!.pinNotes.join('; ')}`, 'warn');
252
267
  }
268
+ let toFit = false; // (0.12.5) the next drawing is another document's: fitted
253
269
  let lastS3: M | undefined, lastData: unknown, pendingAfterDrag = false;
254
270
  // ---------- the switch's morph (0.7.5): the 2D view's implementation runs it, over the stage ----------
255
271
  let morphFrom: { svg: SVGSVGElement; mode: '3d' | '2d' } | undefined;
@@ -308,7 +324,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
308
324
  svg = s;
309
325
  const [x, y, w, hh] = full;
310
326
  V.full = { x, y, w, h: hh };
311
- if (!V.view) { V.view = { ...V.full }; autoFit(); } else quietly(applyView);
327
+ if (toFit) { toFit = false; V.view = { ...V.full }; fitItems(); } else if (!V.view) { V.view = { ...V.full }; autoFit(); } else quietly(applyView);
312
328
  empty.hidden = true;
313
329
  layer?.drawn?.();
314
330
  if (pendingReveal && reveal(pendingReveal)) pendingReveal = undefined;
@@ -336,6 +352,12 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
336
352
  const live = layer?.extent?.() ?? [];
337
353
  return union([...ptrs.flatMap(p => elementsFor(p)).filter(e => e.getBBox().width || e.getBBox().height).map(boxOf), ...live]);
338
354
  }
355
+ /** (0.12.6) the connectors and their labels (not a step's marks on them, which a still doesn't show): Fit keeps them on the stage */
356
+ function routesBox() {
357
+ if (!cd || !svg) return undefined;
358
+ const els = Object.keys(cd.scene.rendered.paths).flatMap(id => [...svg!.querySelectorAll<SVGGraphicsElement>(`[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'));
359
+ return union(els.filter(e => e.getBBox().width || e.getBBox().height).map(boxOf));
360
+ }
339
361
  // (0.12.1) the view is the stage's: docked, the palette's pane shares the host, so the host is wider than what is
340
362
  // drawn (the scale, the pointer's place, a resize); floating, the stage is the host's whole area
341
363
  const docked = ui.paletteLayout === 'docked';
@@ -350,6 +372,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
350
372
  },
351
373
  onRezoom: () => paintOverlay(),
352
374
  itemsBox: () => itemsBox(),
375
+ alsoBox: () => routesBox(),
353
376
  marksShowing: () => !!layer?.showing?.(),
354
377
  });
355
378
  const { size, scale, quietly, applyView, toSvg, zoomAt, fit, fitItems, autoFit, actual, settled } = V;
@@ -399,6 +422,37 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
399
422
  return undefined;
400
423
  };
401
424
 
425
+ // (0.12.4) connections: the routes that are entries of the file's own (src/iso-editor/connections.ts)
426
+ const isRouteId = (id: string) => !!cd && Object.hasOwn(cd.scene.rendered.paths, id);
427
+ const connections = () => (cd ? connectionsOf(cd.pathOf, isRouteId, K.objectOf) : new Map<string, string>());
428
+ /** how near a connection, in the page's pixels, is on it */
429
+ const NEAR = 6;
430
+ /** the drawn thing under a place on the page: a connection within NEAR of it, unless a node is there (a node's always the
431
+ * one meant; a region's floor, or nothing, gives way) or a node hides that part of the connection */
432
+ const pathAt = (target: EventTarget | null, px: number, py: number): string | undefined => {
433
+ const direct = pathAtEvent(target);
434
+ const isNode = (el: Element | null): boolean => {
435
+ const id = el?.closest?.('[data-id]')?.getAttribute('data-id');
436
+ if (!id || !cd || isRouteId(id)) return false;
437
+ if (flat) { const q = toSvg(px, py); return !flat.panelsAt(q.x, q.y).includes(id) && cd.scene.layout.byId.has(id); }
438
+ return cd.scene.layout.byId.get(id)?.type === 'node';
439
+ };
440
+ const el = target as Element | null;
441
+ if (!cd || !svg || !el?.closest || (el !== svg && !svg.contains(el) && el !== stage) || isNode(el)) return direct;
442
+ const conns = connections();
443
+ if (!conns.size || (direct !== undefined && conns.has(direct))) return direct;
444
+ const at = toSvg(px, py), k = scale(), r = viewEl.getBoundingClientRect();
445
+ let best: { ptr: string; dist: number } | undefined;
446
+ for (const ptr of conns.keys()) for (const sh of outlinesFor(ptr)) {
447
+ if (sh.kind !== 'route') continue;
448
+ const q = nearestOn(sh.d, at.x, at.y);
449
+ if (!q || q.dist * k > NEAR || (best && q.dist >= best.dist)) continue;
450
+ if (isNode(fdoc().elementFromPoint(r.left + (q.x - V.view!.x) * k, r.top + (q.y - V.view!.y) * k))) continue;
451
+ best = { ptr, dist: q.dist };
452
+ }
453
+ return best ? best.ptr : direct;
454
+ };
455
+
402
456
  // ---------- the overlay: selection rings, hover, problem badges ----------
403
457
  /**
404
458
  * A resource's drawn shapes, isometric: a node (or a slab, a VM, a platform) is the silhouette of its box (the hexagon
@@ -526,8 +580,16 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
526
580
  kind: 'pan' | 'marquee' | 'pin' | 'click'; x0: number; y0: number; v0?: View; emptyClick?: boolean;
527
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
528
582
  start?: [number, number]; shown?: [number, number]; z0?: number; size?: [number, number];
529
- parent?: { w: number; d: number; pad: number; box: { x0: number; y0: number; x1: number; y1: number }; label: string };
530
- 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 };
531
593
  /** siblings that flow after the dragged item, pinned where they stand so the drag doesn't push them */
532
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;
533
595
  let spaceKeyDown = false;
@@ -535,10 +597,17 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
535
597
  stage.addEventListener('pointerdown', down);
536
598
  stage.addEventListener('pointermove', move);
537
599
  stage.addEventListener('pointerup', up);
538
- stage.addEventListener('pointercancel', up);
600
+ stage.addEventListener('pointercancel', e => { if (pinDrag()) void endPin(false); else up(e); });
539
601
  stage.addEventListener('wheel', wheel, { passive: false });
540
602
  stage.addEventListener('contextmenu', context);
541
- stage.addEventListener('dblclick', e => { const p = pathAtEvent(e.target); if (p !== undefined) opts.showInText(fromPointer(p)); });
603
+ stage.addEventListener('dblclick', e => {
604
+ // (0.12.5) what is under the pointer: the presses were captured, so a real double click's target is the stage
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));
610
+ });
542
611
  };
543
612
  // in the page, a pointer's coordinates are already the page's
544
613
  const pageXY = (e: PointerEvent | MouseEvent) => ({ x: e.clientX, y: e.clientY });
@@ -559,7 +628,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
559
628
  const pan = () => { drag = { kind: 'pan', x0: x, y0: y, v0: { ...V.view! } }; svg?.classList.add('panning'); e.preventDefault(); };
560
629
  if (e.button === 1 || spaceKeyDown) { pan(); return; }
561
630
  if (e.button !== 0) return;
562
- const ptr = pathAtEvent(e.target);
631
+ const ptr = pathAt(e.target, x, y);
563
632
  if (ptr === undefined) {
564
633
  // nothing under the pointer: Pan mode pans (⇧ or ⌘ draws a selection instead); Select mode draws a selection (the space key pans)
565
634
  const mod = e.shiftKey || e.metaKey || e.ctrlKey;
@@ -587,10 +656,9 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
587
656
  const start = localAt(cd.scene, id);
588
657
  if (item && start) {
589
658
  const b = item.box, par = item.parent;
590
- 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 }));
591
659
  drag = {
592
- 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,
593
- 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,
594
662
  origCd: cd,
595
663
  };
596
664
  }
@@ -606,7 +674,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
606
674
  return;
607
675
  }
608
676
  if (!drag) {
609
- const p = pathAtEvent(e.target);
677
+ const p = pathAt(e.target, x, y);
610
678
  if (p !== hoverId) { hoverId = p; paintOverlay(); }
611
679
  return;
612
680
  }
@@ -673,6 +741,16 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
673
741
  }
674
742
  let pinFrame = false, lastPin: { x: number; y: number; alt: boolean } | undefined, relayout = 0;
675
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;
676
754
  /** one step of a pin drag: snap, clamp, check, move the drawing, and lay it out again when the cell changes */
677
755
  function pinStep() {
678
756
  const g = pinDrag();
@@ -680,71 +758,201 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
680
758
  const k = scale();
681
759
  const step = lastPin.alt ? 0.5 : 1;
682
760
  g.step = step;
683
- const m = snapMove(g.start!, screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k), step, g.size!, g.parent);
684
- const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
685
- 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);
686
767
  const changed = !g.move || g.move.at[0] !== m.at[0] || g.move.at[1] !== m.at[1];
687
768
  g.move = m;
688
- 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;
689
772
  svg?.classList.add('dragging');
690
773
  svg?.classList.toggle('drag-bad', g.invalid);
691
774
  // at once: the drawn item (and what stands on it) moved by transform, from where the drawing has it
692
775
  shiftDragged(g.id!, [m.at[0] - g.shown![0], m.at[1] - g.shown![1]]);
693
776
  paintDrag(foot);
694
- const within = g.parent ? `within ${g.parent.label}` : 'on the canvas';
695
- 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);
696
778
  // then the real layout, with its routes and labels, once per cell (and only where it may drop)
697
- if (changed && !g.invalid && lastS3) {
698
- clearTimeout(relayout);
699
- relayout = window.setTimeout(async () => {
700
- const now = pinDrag();
701
- if (!now || now.invalid || !now.move) return;
702
- let next: D;
703
- try { ({ next, keep: now.keep } = trialLayout(now)); } catch { return; }
704
- if (pinDrag() !== now) return; // the drag ended meanwhile: don't draw a stale trial
705
- await draw(next);
706
- if (pinDrag() !== now) return;
707
- now.shown = now.move.at;
708
- shiftDragged(now.id!, [0, 0]);
709
- 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);
710
- }, 0);
711
- }
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);
712
903
  }
713
904
  /**
714
905
  * The drawing with the dragged item pinned at its move. Siblings placed after it (in the flow, or beside it) would move
715
906
  * with it; any that did, and can be pinned, are kept where they stood, and the drop pins them too.
716
907
  */
717
- function trialLayout(g: NonNullable<typeof drag>): { next: D; keep: [string, [number, number]][] } {
718
- const base = JSON.parse(JSON.stringify(lastData ?? {})) as Record<string, Record<string, Record<string, unknown>>>;
719
- // pins kept under the legacy key are read there; the trial puts them where the drop will (x-editor)
720
- if (K.pins.legacyOnly(base)) { base[PINS_KEY] = base[K.pins.legacyKey!]; delete base[K.pins.legacyKey!]; }
721
- base[PINS_KEY] ??= {}; base[PINS_KEY].layout ??= {};
722
- const pins = base[PINS_KEY].layout;
723
- pins[g.name!] = { at: g.move!.at };
724
- 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]][] } {
725
909
  const orig = g.origCd!, nameOf = new Map([...orig.pinId].map(([n, id]) => [id, n]));
726
- const me = orig.scene.layout.byId.get(g.id!)!;
727
- 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)]);
728
917
  const keep: [string, [number, number]][] = [];
729
- for (const sb of sibs) {
730
- if (sb === me) continue;
731
- const n = nameOf.get(sb.id), was = localAt(orig.scene, sb.id), now = next.scene.layout.byId.get(sb.id)?.box;
732
- if (!n || !was || !now || n in pins) continue;
733
- 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; };
734
931
  }
735
- if (keep.length) { for (const [n, at] of keep) pins[n] = { at }; next = K.draw(lastS3!, base, opts.theme); }
736
- 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
+ };
737
940
  }
738
941
  /** move a drawn item, and everything standing on it, by a grid offset (a transform: the next layout replaces it) */
739
942
  function shiftDragged(id: string, [gx, gy]: [number, number]) {
740
943
  if (!svg || !cd) return;
741
- 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;
742
950
  const ids = new Set([id]);
743
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; } }
744
952
  for (const el of svg.querySelectorAll<SVGElement>('[data-id]')) {
745
953
  if (!ids.has(el.getAttribute('data-id') ?? '')) continue;
746
954
  if (el.parentElement?.closest(`[data-id="${CSS.escape(el.getAttribute('data-id')!)}"]`)) continue;
747
- 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)})` : '');
748
956
  }
749
957
  }
750
958
  /** the drag's overlay: the grid on the parent's floor (half cells too, with ⌥), the drop target, the clamped edges */
@@ -772,10 +980,21 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
772
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');
773
981
  overlay.append(wrap);
774
982
  // the drop target: the footprint, accent where it may drop, red where it can't
775
- const t = d.createElementNS(SVGNS, 'polygon');
776
- t.setAttribute('class', `drop${g.invalid ? ' bad' : ''}`);
777
- 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(' '));
778
- 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
+ }
779
998
  // the parent's edges the move is held at
780
999
  if (g.parent && g.move) {
781
1000
  const pb = g.parent.box, c = g.move.clamped, pad = g.parent.pad;
@@ -787,11 +1006,25 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
787
1006
  }
788
1007
  }
789
1008
  /** end a pin drag: the drop commits one command; an overlap, a cancel or no move puts the drawing back */
1009
+ /** drops whose pin isn't written yet (the grid fading out first) */
1010
+ let dropping = 0;
790
1011
  async function endPin(commit: boolean) {
1012
+ if (!pinDrag()) return;
1013
+ dropping++;
1014
+ try { await endDrop(commit); } finally { dropping--; }
1015
+ }
1016
+ async function endDrop(commit: boolean) {
791
1017
  const g = pinDrag();
792
1018
  if (!g) return;
793
1019
  drag = undefined;
794
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
+ }
795
1028
  // the grid and the drop target fade out, then the drop
796
1029
  const shown = overlay ? [...overlay.querySelectorAll('.gridwrap, .drop, .edge')] : [];
797
1030
  if (shown.length) {
@@ -802,19 +1035,137 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
802
1035
  svg?.classList.remove('dragging', 'drag-bad');
803
1036
  paintNav();
804
1037
  const m = g.move;
1038
+ if (g.fresh) { await endFresh(g, commit, stale); return; }
805
1039
  const moved = m && (m.at[0] !== g.start![0] || m.at[1] !== g.start![1]);
806
1040
  if (commit && m && moved && !g.invalid) {
807
1041
  // the item, and the neighbours the move would have pushed, kept where they stand: one command, one undo step
808
1042
  const label = `Pin ${describe(fromPointer(g.ptr!))} at [${m.at.join(', ')}]`;
809
1043
  let keep = g.keep ?? [];
810
- 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 */ }
811
- 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);
812
- 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
813
1047
  return;
814
1048
  }
815
1049
  if (commit && g.invalid) opts.note(`${g.name} can't go there: it would overlap`, 'warn');
1050
+ unshift(g);
816
1051
  await draw(g.origCd!);
817
- 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 });
818
1169
  }
819
1170
 
820
1171
  function up(e: PointerEvent) {
@@ -856,10 +1207,6 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
856
1207
  }
857
1208
  return out;
858
1209
  }
859
- const round = (v: number) => Math.round(v * 2) / 2;
860
- const snap = ([x, y]: [number, number]): [number, number] => [round(x), round(y)];
861
- 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]; };
862
-
863
1210
  function wheel(e: WheelEvent) {
864
1211
  e.preventDefault();
865
1212
  const { x, y } = pageXY(e);
@@ -876,7 +1223,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
876
1223
  e.preventDefault();
877
1224
  const { x, y } = pageXY(e);
878
1225
  if (layer?.context?.(e, { x, y })) return;
879
- const ptr = pathAtEvent(e.target);
1226
+ const ptr = pathAt(e.target, x, y);
880
1227
  if (ptr !== undefined && !doc.selection.some(p => toPointer(p) === ptr)) doc.select([fromPointer(ptr)], 'canvas');
881
1228
  openMenu(menuItems(ptr), { x, y }, 'Canvas');
882
1229
  }
@@ -897,7 +1244,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
897
1244
  if (one) {
898
1245
  items.push(...K.objectItems(doc, one, 'canvas', opts.note));
899
1246
  if (items.length) items.push({ sep: true });
900
- items.push({ label: 'Rename…', icon: 'pencil', keys: 'F2', disabled: ro || !isRes, why: T.renameWhy, onSelect: () => renameDialog(doc, one, 'canvas', opts.note) });
1247
+ items.push({ label: 'Rename…', icon: 'pencil', keys: 'F2', disabled: ro || !isRes, why: T.renameWhy, onSelect: () => rename(one) });
901
1248
  items.push({ label: 'Duplicate', icon: 'copy', keys: '⌘D', disabled: ro || !isRes, why: T.duplicateWhy, onSelect: () => duplicate(doc, one, 'canvas', opts.note) });
902
1249
  const name = isRes ? resourceOf(toPointer(one))!.name : '';
903
1250
  const pinned = !!K.pins.of(doc.goodDoc.data)?.[name];
@@ -982,115 +1329,25 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
982
1329
  const p = [...k.section, name];
983
1330
  if (run(doc, insertCmd(p.slice(0, -1), name, k.template(), { label: `Add ${k.singular} ${name}` }), 'canvas', opts.note)) {
984
1331
  doc.select([p], 'canvas');
985
- renameDialog(doc, p, 'canvas', opts.note);
1332
+ rename(p, { joins: doc.undoId });
986
1333
  }
987
1334
  }
988
1335
  // ---------- E11: the palette: add a resource by a click, or by a drag onto the canvas ----------
989
- /** Where a drop lands, as a pin: the new thing laid out once (a trial), then moved from where the layout put it to
990
- * the point, in its parent's frame and on the grid. Undefined: the spot is taken, or it can't be placed. */
991
- function placeAt(name: string, add: Command, at: { x: number; y: number }): [number, number] | undefined {
992
- if (!cd || !svg) return undefined;
993
- const text = add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
994
- let trial: D | undefined;
995
- try { trial = K.trial(text, opts.theme); } catch { return undefined; }
996
- if (!trial) return undefined;
997
- const id = trial.pinId.get(name), item = id ? trial.scene.layout.byId.get(id) : undefined, start = id ? localAt(trial.scene, id) : undefined;
998
- if (!item || !start) return undefined;
999
- const b = item.box, par = item.parent;
1000
- // the drawing's coordinates are the projection's: the trial's centre and the drop point, in the same units
1001
- const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
1002
- const centre = [(cx - cy) * C * S, (cx + cy) * 0.5 * S - b.z0 * S], drop = toSvg(at.x, at.y);
1003
- const m = snapMove(start, screenToGrid(drop.x - centre[0], drop.y - centre[1]), 1, [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) } : undefined);
1005
- const dx = m.at[0] - start[0], dy = m.at[1] - start[1];
1006
- const moved = { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy };
1007
- const siblings = (par ? par.children : trial.scene.layout.items.filter(i => !i.parent)).filter(i => i !== item).map(i => i.box);
1008
- return overlaps(moved, siblings) ? undefined : m.at;
1009
- }
1010
- /** The container (of the kind given) whose floor a point is on (its footprint, as drawn), if any. */
1011
- function containerAt(kind: string, at: { x: number; y: number }): string | undefined {
1012
- if (!cd) return undefined;
1013
- const p = toSvg(at.x, at.y);
1014
- if (flat) {
1015
- // 2D: the innermost panel of that kind under the point
1016
- for (const id of flat.panelsAt(p.x, p.y)) {
1017
- const name = [...cd.pinId].find(([, pid]) => pid === id)?.[0];
1018
- if (name && resourceOf(cd.pathOf.get(id) ?? '')?.kind === kind) return name;
1019
- }
1020
- return undefined;
1021
- }
1022
- 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; };
1023
- for (const [name, id] of cd.pinId) {
1024
- if (resourceOf(cd.pathOf.get(id) ?? '')?.kind !== kind) continue;
1025
- const item = cd.scene.layout.byId.get(id);
1026
- if (item && inside(floorOf(item.box))) return name;
1027
- }
1028
- return undefined;
1029
- }
1030
- /** (0.10.1) the objects whose drawn floor a point is on, innermost first: in 2D the panels under it; in 3D every placed
1031
- * thing whose floor holds the point, the deepest (then the smallest) first */
1032
- function objectsUnder(at: { x: number; y: number }): ObjectRef[] {
1033
- if (!cd) return [];
1034
- const p = toSvg(at.x, at.y);
1035
- const refOf = (id: string) => { const ptr = cd!.pathOf.get(id); const r = ptr === undefined ? undefined : resourceOf(ptr); return r && r.path === ptr ? r : undefined; };
1036
- if (flat) return flat.panelsAt(p.x, p.y).map(refOf).filter((r): r is ObjectRef => !!r);
1037
- 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; };
1038
- 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; };
1039
- // what is drawn under the point, topmost (innermost) first, as the eye sees it; then any whose floor holds the point
1040
- const seen = new Map<string, ObjectRef>();
1041
- for (const e of fdoc().elementsFromPoint(at.x, at.y)) {
1042
- if (!svg?.contains(e)) continue;
1043
- for (let el = e.closest('[data-id]'); el; el = el.parentElement?.closest('[data-id]') ?? null) {
1044
- const r = refOf(el.getAttribute('data-id') ?? '');
1045
- if (r && !seen.has(r.path)) seen.set(r.path, r);
1046
- }
1047
- }
1048
- const hits: { r: ObjectRef; d: number; a: number }[] = [];
1049
- for (const [, id] of cd.pinId) {
1050
- const item = cd.scene.layout.byId.get(id), r = refOf(id);
1051
- 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) });
1052
- }
1053
- return [...seen.values(), ...hits.sort((x, y) => y.d - x.d || x.a - y.a).map(h => h.r)];
1054
- }
1055
- /** Add an object from the palette: dropped at a point, it is pinned there; dropped on a container the kit names, it
1056
- * 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. */
1057
1338
  function addFromPalette(sec: string, at?: { x: number; y: number }, item?: PaletteItem): Path | undefined {
1058
1339
  if (!doc.doc.ok) { opts.note('Fix the YAML first', 'warn'); return undefined; }
1059
- const k = kindOf(sec);
1060
- // (0.10.0) a palette entry's preset: what it starts as, and the base of its name
1061
- const preset = item?.value?.() as Record<string, unknown> | undefined;
1062
- const what = item && preset !== undefined ? item.label.toLowerCase() : k.singular;
1063
- const name = freshName(doc.text, item?.name ?? k.singular);
1064
- const p = [...k.section, name] as Path;
1065
- let value = (preset ?? k.template()) as Record<string, unknown>;
1066
- let into: string | undefined;
1067
- const drop = at ? K.dropInto?.(sec) : undefined;
1068
- if (at && drop) {
1069
- const c = containerAt(drop.container, at);
1070
- // dropped into a container: what puts it there, and the preset's own keys over it
1071
- if (c) { into = c; value = { ...(drop.value(c) as Record<string, unknown>), ...(preset ?? {}) }; }
1072
- }
1073
- let intoLabel = into ? drop!.label(into) : '';
1074
- // (0.10.1) the domain's rule: the innermost object under the drop that holds it
1075
- if (at && !into && K.dropOnto) {
1076
- for (const t of objectsUnder(at)) {
1077
- const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
1078
- if (plan) { into = t.name; value = plan.value as Record<string, unknown>; intoLabel = plan.label ? ` ${plan.label}` : ` in ${t.name}`; break; }
1079
- }
1080
- }
1081
- const label = `Add ${what} ${name}${intoLabel}`;
1082
- const add = insertCmd(p.slice(0, -1), name, value, { label });
1083
- const pin = at && !into && mode === '3d' ? placeAt(name, add, at) : undefined;
1084
- const cmd = pin ? seqCmd(`${label} at [${pin.join(', ')}]`, [add, withPinsMoved(setCmd([PINS_KEY, 'layout', name], { at: pin }))]) : add;
1085
- if (!run(doc, { ...cmd, select: [p] }, 'canvas', opts.note)) return undefined;
1086
- 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)' : ''}`);
1087
1344
  doc.select([p], 'canvas');
1088
- // (0.10.1) the canvas has the focus while the name is asked, so the dialog gives it back there (⌘Z works at once)
1089
- stage.focus({ preventScroll: true });
1090
- renameDialog(doc, p, 'canvas', opts.note);
1345
+ // (0.12.5) its name, in the inline field above it; the drop and the name are one undo step
1346
+ rename(p, { joins: doc.undoId, at });
1091
1347
  return p;
1092
1348
  }
1093
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) ?? (() => {});
1094
1351
  // (0.11.0) sections: a header (a button, aria-expanded) over its entries; open: the section last added from (the
1095
1352
  // first, before any); the reader opens and closes the others as they like. The host's store may be off: guarded.
1096
1353
  const sections = new Map<string, { head: HTMLButtonElement; body: HTMLElement }>();
@@ -1099,7 +1356,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1099
1356
  try { const v = JSON.parse(opts.store?.get(PAL_KEY) ?? '{}') as { last?: unknown }; if (typeof v.last === 'string') lastSection = v.last; } catch { /* none */ }
1100
1357
  const named = [...new Set(ui.palette.map(i => i.section).filter((x): x is string => x !== undefined))];
1101
1358
  const openAtStart = lastSection !== undefined && named.includes(lastSection) ? lastSection : named[0];
1102
- 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(); };
1103
1360
  function sectionBody(sec: string): HTMLElement {
1104
1361
  const have = sections.get(sec);
1105
1362
  if (have) return have.body;
@@ -1145,6 +1402,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1145
1402
  }
1146
1403
  if (!words.length && before) { for (const [sec, open] of before) setOpen(sec, open); before = undefined; }
1147
1404
  none.hidden = shown > 0;
1405
+ drawLooks();
1148
1406
  none.textContent = shown ? '' : `Nothing matches "${search.value.trim()}"`;
1149
1407
  }
1150
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(); } };
@@ -1205,19 +1463,35 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1205
1463
  e.preventDefault();
1206
1464
  try { b.setPointerCapture(e.pointerId); } catch { /* a synthetic pointer: the events come to the button anyway */ }
1207
1465
  const x0 = e.clientX, y0 = e.clientY;
1208
- let ghost: HTMLElement | undefined;
1466
+ let ghost: HTMLElement | undefined, dragged = false, real = false, frame = 0, last: PointerEvent | undefined;
1209
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
+ };
1210
1480
  const mv = (ev: PointerEvent) => {
1211
- if (!ghost && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
1212
- if (!ghost) { ghost = h('div', { class: 'pal-ghost', 'aria-hidden': 'true' }, icon(ic), label); host.append(ghost); }
1213
- const hr = host.getBoundingClientRect();
1214
- ghost.style.left = `${ev.clientX - hr.left + 8}px`; ghost.style.top = `${ev.clientY - hr.top + 8}px`;
1215
- 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);
1216
1487
  };
1217
1488
  const done = (ev: PointerEvent, drop: boolean) => {
1218
1489
  b.removeEventListener('pointermove', mv); b.removeEventListener('pointerup', upH); b.removeEventListener('pointercancel', cancelH); removeEventListener('keydown', esc, true);
1219
- const dragged = !!ghost;
1490
+ cancelAnimationFrame(frame); frame = 0;
1491
+ if (drop && dragged) step(ev);
1220
1492
  ghost?.remove();
1493
+ if (real && pinDrag()?.fresh) { if (drop) usedSection(item); void endPin(drop); return; }
1494
+ hideFresh();
1221
1495
  if (!drop) return;
1222
1496
  if (!dragged) { usedSection(item); addFromPalette(sec, undefined, item); }
1223
1497
  else if (over(ev)) { usedSection(item); addFromPalette(sec, { x: ev.clientX, y: ev.clientY }, item); }
@@ -1239,6 +1513,20 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1239
1513
  const only = x && Object.keys(x).length === 1;
1240
1514
  run(doc, { ...deleteCmd(only ? [key] : [key, 'layout']), label: 'Reset the layout' }, 'canvas', opts.note);
1241
1515
  }
1516
+ /** (0.12.5) name it, in the inline field above its drawing; Enter and Esc give the canvas the focus back (⌘Z works at once) */
1517
+ function rename(p: Path, o: { joins?: number; at?: { x: number; y: number } } = {}) {
1518
+ let path: Path | null = p;
1519
+ const off = doc.on(c => { if (path && c.remap) path = c.remap(path); });
1520
+ void K.actions.rename(doc, p, 'canvas', opts.note, {
1521
+ ...o, back: stage, late: stage, busy: () => !!drag || dropping > 0, bounds: () => stage.getBoundingClientRect(),
1522
+ place: () => {
1523
+ const b = path && V.view ? boxFor(path) : undefined;
1524
+ if (!b) return undefined;
1525
+ const r = viewEl.getBoundingClientRect(), k = scale();
1526
+ 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 };
1527
+ },
1528
+ }).finally(off);
1529
+ }
1242
1530
  function selectParent() {
1243
1531
  const up = new Map<string, Path>();
1244
1532
  for (const p of doc.selection) {
@@ -1269,10 +1557,11 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1269
1557
  case '@': case '2': if (e.shiftKey || e.key === '@') zoomToSelection(); else return; break;
1270
1558
  case 'Escape': if (linking) { linking = undefined; paintOverlay(); opts.note('Not connected'); break; } if (pinDrag()) { endPin(false); break; } doc.select([], 'canvas'); break;
1271
1559
  case 'Delete': case 'Backspace': if (sel.length && !ro) deletePaths(doc, sel, 'canvas', opts.note); break;
1272
- case 'F2': if (sel.length === 1 && !ro) renameDialog(doc, sel[0], 'canvas', opts.note); break;
1560
+ case 'F2': if (sel.length === 1 && !ro) rename(sel[0]); break;
1273
1561
  case 'ArrowUp': if (mod) { selectParent(); break; } return;
1274
1562
  case 'Tab': case 'ArrowRight': case 'ArrowLeft': case 'ArrowDown': {
1275
- // move through what is drawn, in the file's order
1563
+ // move through what is drawn, in the file's order: the objects, then (0.12.4) the connections
1564
+ drawn.push(...connections().keys());
1276
1565
  if (!drawn.length) return;
1277
1566
  const i = sel.length ? drawn.indexOf(toPointer(sel[0])) : -1;
1278
1567
  const back = e.key === 'ArrowLeft' || (e.key === 'Tab' && e.shiftKey);
@@ -1329,9 +1618,9 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1329
1618
  });
1330
1619
 
1331
1620
  const base = {
1332
- addFromPalette, palette, groupSelection, startPick, objectsUnder, get linking() { return linking; },
1333
- render, setTheme, paintOverlay, fit: fitItems, fitAll: fit, actual, zoomAt, itemsBox, get moved() { return V.moved; }, settled, get zoom() { return V.zoom; },
1334
- dispose() { endMorph(); clearTimeout(relayout); V.dispose(); disposed = true; },
1621
+ addFromPalette, palette, groupSelection, startPick, get linking() { return linking; },
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; },
1623
+ dispose() { endMorph(); endWay(); clearTimeout(relayout); V.dispose(); disposed = true; },
1335
1624
  focus: () => stage.focus(),
1336
1625
  /** for the tests */
1337
1626
  get view() { return V.view; },