@johnoscott/isometric-engine 0.10.1 → 0.12.6

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 (56) hide show
  1. package/EDITOR-GUIDE.md +12 -1
  2. package/README.md +1 -1
  3. package/assets/app.css +37 -0
  4. package/assets/icons.svg +1 -1
  5. package/iso-editor.js +182 -182
  6. package/iso-render.js +105 -105
  7. package/iso-systems.js +108 -108
  8. package/js/iso-editor/commands.js +7 -0
  9. package/js/iso-editor/connections.js +24 -0
  10. package/js/iso-editor/doc.js +4 -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 +277 -20
  14. package/js/iso-editor/ui/mount.js +2 -1
  15. package/js/iso-editor/ui/plain-icons.js +2 -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 +3 -1
  19. package/js/iso-objects/board.js +6 -1
  20. package/js/iso-objects/scene.js +3 -2
  21. package/js/iso-viewer/index.js +4 -1
  22. package/js/iso-viewer/viewport.js +17 -5
  23. package/package.json +92 -92
  24. package/src/iso-core/compile-schema.ts +3 -1
  25. package/src/iso-editor/commands.ts +9 -0
  26. package/src/iso-editor/connections.ts +28 -0
  27. package/src/iso-editor/doc.ts +6 -0
  28. package/src/iso-editor/model.ts +17 -3
  29. package/src/iso-editor/ui/actions.ts +20 -23
  30. package/src/iso-editor/ui/app.css +37 -0
  31. package/src/iso-editor/ui/canvas.ts +214 -25
  32. package/src/iso-editor/ui/mount.ts +4 -3
  33. package/src/iso-editor/ui/plain-icons.ts +2 -0
  34. package/src/iso-editor/ui/props.ts +3 -3
  35. package/src/iso-editor/ui/rename.ts +105 -0
  36. package/src/iso-editor/ui/setup.ts +9 -2
  37. package/src/iso-objects/board.ts +6 -2
  38. package/src/iso-objects/scene.ts +4 -2
  39. package/src/iso-viewer/index.ts +2 -2
  40. package/src/iso-viewer/morph.ts +5 -2
  41. package/src/iso-viewer/viewport.ts +25 -5
  42. package/types/iso-core/compile-schema.d.ts +2 -2
  43. package/types/iso-editor/connections.d.ts +8 -0
  44. package/types/iso-editor/model.d.ts +8 -2
  45. package/types/iso-editor/ui/actions.d.ts +5 -2
  46. package/types/iso-editor/ui/canvas.d.ts +18 -1
  47. package/types/iso-editor/ui/monaco-entry.d.ts +2 -0
  48. package/types/iso-editor/ui/mount.d.ts +6 -2
  49. package/types/iso-editor/ui/props.d.ts +1 -1
  50. package/types/iso-editor/ui/rename.d.ts +43 -0
  51. package/types/iso-editor/ui/setup.d.ts +6 -0
  52. package/types/iso-systems/validate.d.ts +4 -0
  53. package/types/iso-viewer/bundle.d.ts +1 -0
  54. package/types/iso-viewer/index.d.ts +2 -2
  55. package/types/iso-viewer/morph.d.ts +6 -3
  56. package/types/iso-viewer/viewport.d.ts +13 -1
@@ -116,6 +116,13 @@ function commandsFor(a) {
116
116
  const quote = now[0] === '"' || now[0] === "'" ? now[0] : void 0;
117
117
  edits.push({ start: range[0], end: range[1], text: quote === '"' ? JSON.stringify(v) : quote === "'" ? `'${v}'` : scalarText(v, { flow: true, indent: 0 }) });
118
118
  }
119
+ const data = dataOf(t);
120
+ for (const k of [a.pins.key, a.pins.legacyKey]) {
121
+ const layout = k === void 0 ? void 0 : data?.[k]?.layout;
122
+ if (!layout || typeof layout !== "object" || !Object.hasOwn(layout, from) || Object.hasOwn(layout, to)) continue;
123
+ const range = d.rangeOf([k, "layout", from], "key");
124
+ if (range && !edits.some((e) => e.start < range[1] && range[0] < e.end)) edits.push({ start: range[0], end: range[1], text: scalarText(to, { flow: true, indent: 0 }) });
125
+ }
119
126
  return { steps: [edits] };
120
127
  }
121
128
  };
@@ -0,0 +1,24 @@
1
+ import { fromPointer } from "./path.js";
2
+ function connectionsOf(pathOf, isRoute, objectOf) {
3
+ const uses = /* @__PURE__ */ new Map();
4
+ for (const p of pathOf.values()) uses.set(p, (uses.get(p) ?? 0) + 1);
5
+ const out = /* @__PURE__ */ new Map();
6
+ for (const [id, p] of pathOf) if (isRoute(id) && uses.get(p) === 1 && fromPointer(p).length >= 2 && objectOf(p) === void 0) out.set(p, id);
7
+ return out;
8
+ }
9
+ function nearestOn(d, x, y) {
10
+ const n = (d.match(/-?\d*\.?\d+(?:e-?\d+)?/gi) ?? []).map(Number), pts = [];
11
+ for (let i = 0; i + 1 < n.length; i += 2) pts.push([n[i], n[i + 1]]);
12
+ let best;
13
+ for (let i = 0; i + 1 < pts.length; i++) {
14
+ const [ax, ay] = pts[i], [bx, by] = pts[i + 1], l2 = (bx - ax) ** 2 + (by - ay) ** 2;
15
+ const t = l2 ? Math.max(0, Math.min(1, ((x - ax) * (bx - ax) + (y - ay) * (by - ay)) / l2)) : 0;
16
+ const px = ax + (bx - ax) * t, py = ay + (by - ay) * t, dist = Math.hypot(px - x, py - y);
17
+ if (!best || dist < best.dist) best = { x: px, y: py, dist };
18
+ }
19
+ return best;
20
+ }
21
+ export {
22
+ connectionsOf,
23
+ nearestOn
24
+ };
@@ -145,6 +145,10 @@ function parentByIndent(d, lineStart, indent, forList = false) {
145
145
  if (a.where === "key") return a.path.slice(0, -1);
146
146
  if (line.slice(ind).startsWith("- ")) return a.path.slice(0, -1);
147
147
  }
148
+ if (!forList && /^- /.test(line.slice(ind)) && ind + 2 === indent) {
149
+ const a = d.at(s + ind + 2);
150
+ if (a.where === "key") return a.path.slice(0, -1);
151
+ }
148
152
  if (ind < indent || forList && ind <= indent && /:\s*$/.test(line)) {
149
153
  const m = /^(\s*)(- )?([^\s:#][^:#]*?)\s*:/.exec(line);
150
154
  if (m) {
@@ -71,8 +71,10 @@ class EditorModel {
71
71
  this._version++;
72
72
  }
73
73
  // ---------- doing ----------
74
- /** Run a command: build it against the text, apply its steps, push it. Returns false if it changed nothing. */
75
- apply(cmd, origin = "api") {
74
+ /** Run a command: build it against the text, apply its steps, push it. Returns false if it changed nothing. `joins`
75
+ * (0.12.5): the id of an undo step it is part of, when that is the last one, nothing was undone since and the file
76
+ * wasn't saved at it (the saved text must stay a step of its own to come back to). */
77
+ apply(cmd, origin = "api", joins) {
76
78
  this.seal();
77
79
  const splice = cmd.build(this._text);
78
80
  if (!splice.steps.some((s) => s.length)) return false;
@@ -81,7 +83,15 @@ class EditorModel {
81
83
  const remap = cmd.remap ?? ((p) => p);
82
84
  this.selection = cmd.select ?? this.selection.map(remap).filter((p) => p !== null);
83
85
  if (splice.fallback) this.fallbacks++;
84
- this.push({ id: this.nextId++, label: cmd.label, origin, steps: splice.steps, inverse, before, after: { paths: this.selection, text: this.textSel }, time: this.now(), fallback: !!splice.fallback, open: false });
86
+ const top = this.undoStack[this.undoStack.length - 1];
87
+ if (top && joins !== void 0 && top.id === joins && !this.redoStack.length && top.id !== this.cleanId) {
88
+ top.label = cmd.joined?.(top.label) ?? top.label;
89
+ top.steps.push(...splice.steps);
90
+ top.inverse.unshift(...inverse);
91
+ top.after = { paths: this.selection, text: this.textSel };
92
+ top.time = this.now();
93
+ top.fallback ||= !!splice.fallback;
94
+ } else this.push({ id: this.nextId++, label: cmd.label, origin, steps: splice.steps, inverse, before, after: { paths: this.selection, text: this.textSel }, time: this.now(), fallback: !!splice.fallback, open: false });
85
95
  this.emit({ kind: "do", origin, label: cmd.label, steps: splice.steps, version: this._version, remap: cmd.remap });
86
96
  for (const fn of this.selListeners) fn({ paths: this.selection, origin });
87
97
  return true;
@@ -161,6 +171,10 @@ class EditorModel {
161
171
  get canRedo() {
162
172
  return this.redoStack.length > 0;
163
173
  }
174
+ /** the last undo step's id (what `apply` may join) */
175
+ get undoId() {
176
+ return this.undoStack[this.undoStack.length - 1]?.id;
177
+ }
164
178
  get undoLabel() {
165
179
  return this.undoStack[this.undoStack.length - 1]?.label;
166
180
  }
@@ -1,11 +1,12 @@
1
1
  import { h } from "./icons.js";
2
2
  import { ask } from "./dialog.js";
3
+ import { renameField } from "./rename.js";
3
4
  import { applyStep } from "../splice.js";
4
5
  import { fromPointer, isPrefix, toPointer } from "../path.js";
5
6
  const getIn = (o, p) => p.reduce((x, k) => x && typeof x === "object" ? x[k] : void 0, o);
6
- function run(doc, c, origin, note) {
7
+ function run(doc, c, origin, note, joins) {
7
8
  try {
8
- return doc.apply(c, origin);
9
+ return doc.apply(c, origin, joins);
9
10
  } catch (e) {
10
11
  note?.(String(e.message), "bad");
11
12
  return false;
@@ -59,28 +60,25 @@ function actionsFor(kit) {
59
60
  if (ok) doc.select([], origin);
60
61
  return ok;
61
62
  }
62
- async function renameDialog(doc, path, origin, note) {
63
- const now = String(path[path.length - 1]);
64
- const input = h("input", { type: "text", value: now, "aria-label": "New name", spellcheck: "false", autocomplete: "off", class: "mono-input" });
65
- input.value = now;
66
- const why = h("p", { class: "dlg-error", role: "alert" });
63
+ async function rename(doc, path, origin, note, at) {
64
+ const now = String(path[path.length - 1]), res = isRes(path);
65
+ let here = path;
66
+ const off = doc.on((c) => {
67
+ if (here && c.remap) here = c.remap(here);
68
+ });
67
69
  const used = () => kit.kinds.flatMap((k) => Object.keys(getIn(doc.goodDoc.data, k.section) ?? {}));
68
- const check = () => {
69
- const v2 = input.value.trim();
70
- const bad = !kit.nameRule.test(v2) && isRes(path) ? kit.nameHint : v2 !== now && used().includes(v2) ? `"${v2}" is already used` : "";
71
- why.textContent = bad;
72
- return bad ? void 0 : v2;
73
- };
74
- input.addEventListener("input", check);
75
- const go = ask(`Rename ${describe(path)}`, [h("label", { class: "field" }, h("span", null, "Name"), input), why, isRes(path) ? h("p", { class: "sub" }, "Every reference to it is renamed too.") : ""], [{ label: "Cancel", value: "cancel" }, { label: "Rename", value: "ok", primary: true }]);
76
- setTimeout(() => {
77
- input.focus();
78
- input.select();
79
- }, 0);
80
- if (await go !== "ok") return false;
81
- const v = check();
82
- if (!v || v === now) return false;
83
- return run(doc, isRes(path) ? renameCmd(path, v) : renameKeyCmd(path, v), origin, note);
70
+ let ok = false;
71
+ await renameField({
72
+ label: `Rename ${describe(path)}`,
73
+ value: now,
74
+ wrong: (v) => !v ? "A name is needed" : v === now ? "" : res && !kit.nameRule.test(v) ? kit.nameHint : used().includes(v) ? `"${v}" is already used` : "",
75
+ alive: () => !!here && getIn(doc.goodDoc.data, here) !== void 0,
76
+ commit: (v) => {
77
+ if (here) ok = run(doc, { ...res ? renameCmd(here, v) : renameKeyCmd(here, v), joined: (l) => l.replace(` ${now}`, ` ${v}`) }, origin, note, at.joins);
78
+ }
79
+ }, at);
80
+ off();
81
+ return ok;
84
82
  }
85
83
  const duplicate = (doc, path, origin, note) => {
86
84
  const c = duplicateCmd(path);
@@ -107,7 +105,7 @@ function actionsFor(kit) {
107
105
  }
108
106
  return [...out.values()];
109
107
  }
110
- return { deletePaths, renameDialog, duplicate, connected };
108
+ return { deletePaths, rename, duplicate, connected };
111
109
  }
112
110
  export {
113
111
  actionsFor,
@@ -1,6 +1,7 @@
1
1
  import { h, icon } from "./icons.js";
2
2
  import { openMenu } from "./menu.js";
3
3
  import { run } from "./actions.js";
4
+ import { connectionsOf, nearestOn } from "../connections.js";
4
5
  import { screenToGrid, localAt, boxSilhouette, floorOf, snapMove, overlaps, paddingOf } from "../../iso-objects/geometry.js";
5
6
  import { regionKind } from "../../iso-objects/kinds.js";
6
7
  import { iso, C, S } from "../../iso-core/kernel.js";
@@ -13,7 +14,7 @@ const SVGNS = "http://www.w3.org/2000/svg";
13
14
  function canvasView(host, doc, opts) {
14
15
  const K = opts.kit, ui = K.ui, T = ui.text;
15
16
  const { setCmd, deleteCmd, insertCmd, insertItemCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
16
- const { deletePaths, renameDialog, duplicate, connected } = K.actions;
17
+ const { deletePaths, duplicate, connected } = K.actions;
17
18
  const resourceOf = (ptr) => K.objectOf(ptr);
18
19
  const kindOf = (k) => K.kinds.find((x) => x.kind === k);
19
20
  const PINS_KEY = K.pins.key;
@@ -118,6 +119,10 @@ function canvasView(host, doc, opts) {
118
119
  const key2 = JSON.stringify(data);
119
120
  if (key2 === lastKey && svg) {
120
121
  if (!pinDrag()) paintOverlay();
122
+ if (toFit) {
123
+ toFit = false;
124
+ fitItems();
125
+ }
121
126
  return;
122
127
  }
123
128
  if (mode === "2d" && !flatImpl) {
@@ -150,6 +155,7 @@ function canvasView(host, doc, opts) {
150
155
  await draw(next);
151
156
  if (cd.pinNotes.length) opts.note(`Pins: ${cd.pinNotes.join("; ")}`, "warn");
152
157
  }
158
+ let toFit = false;
153
159
  let lastS3, lastData, pendingAfterDrag = false;
154
160
  let morphFrom;
155
161
  let morphing;
@@ -222,7 +228,11 @@ function canvasView(host, doc, opts) {
222
228
  svg = s;
223
229
  const [x, y, w, hh] = full;
224
230
  V.full = { x, y, w, h: hh };
225
- if (!V.view) {
231
+ if (toFit) {
232
+ toFit = false;
233
+ V.view = { ...V.full };
234
+ fitItems();
235
+ } else if (!V.view) {
226
236
  V.view = { ...V.full };
227
237
  autoFit();
228
238
  } else quietly(applyView);
@@ -253,7 +263,14 @@ function canvasView(host, doc, opts) {
253
263
  const live = layer?.extent?.() ?? [];
254
264
  return union([...ptrs.flatMap((p) => elementsFor(p)).filter((e) => e.getBBox().width || e.getBBox().height).map(boxOf), ...live]);
255
265
  }
256
- const V = viewport(host, {
266
+ function routesBox() {
267
+ if (!cd || !svg) return void 0;
268
+ const els = Object.keys(cd.scene.rendered.paths).flatMap((id) => [...svg.querySelectorAll(`[data-id="${CSS.escape(id)}"], [data-hl="${CSS.escape(id)}"], [data-for="${CSS.escape(id)}"]`)]).filter((e) => !e.closest(".pre, .overlay, .g-marks, .g-badges, .g-anim"));
269
+ return union(els.filter((e) => e.getBBox().width || e.getBBox().height).map(boxOf));
270
+ }
271
+ const docked = ui.paletteLayout === "docked";
272
+ const viewEl = docked ? stage : host;
273
+ const V = viewport(viewEl, {
257
274
  svg: () => svg,
258
275
  onApply: (k) => {
259
276
  svg.classList.toggle("zoom-near", k >= 1);
@@ -263,6 +280,7 @@ function canvasView(host, doc, opts) {
263
280
  },
264
281
  onRezoom: () => paintOverlay(),
265
282
  itemsBox: () => itemsBox(),
283
+ alsoBox: () => routesBox(),
266
284
  marksShowing: () => !!layer?.showing?.()
267
285
  });
268
286
  const { size, scale, quietly, applyView, toSvg, zoomAt, fit, fitItems, autoFit, actual, settled } = V;
@@ -312,6 +330,35 @@ function canvasView(host, doc, opts) {
312
330
  }
313
331
  return void 0;
314
332
  };
333
+ const isRouteId = (id) => !!cd && Object.hasOwn(cd.scene.rendered.paths, id);
334
+ const connections = () => cd ? connectionsOf(cd.pathOf, isRouteId, K.objectOf) : /* @__PURE__ */ new Map();
335
+ const NEAR = 6;
336
+ const pathAt = (target, px, py) => {
337
+ const direct = pathAtEvent(target);
338
+ const isNode = (el2) => {
339
+ const id = el2?.closest?.("[data-id]")?.getAttribute("data-id");
340
+ if (!id || !cd || isRouteId(id)) return false;
341
+ if (flat) {
342
+ const q = toSvg(px, py);
343
+ return !flat.panelsAt(q.x, q.y).includes(id) && cd.scene.layout.byId.has(id);
344
+ }
345
+ return cd.scene.layout.byId.get(id)?.type === "node";
346
+ };
347
+ const el = target;
348
+ if (!cd || !svg || !el?.closest || el !== svg && !svg.contains(el) && el !== stage || isNode(el)) return direct;
349
+ const conns = connections();
350
+ if (!conns.size || direct !== void 0 && conns.has(direct)) return direct;
351
+ const at = toSvg(px, py), k = scale(), r = viewEl.getBoundingClientRect();
352
+ let best;
353
+ for (const ptr of conns.keys()) for (const sh of outlinesFor(ptr)) {
354
+ if (sh.kind !== "route") continue;
355
+ const q = nearestOn(sh.d, at.x, at.y);
356
+ if (!q || q.dist * k > NEAR || best && q.dist >= best.dist) continue;
357
+ if (isNode(fdoc().elementFromPoint(r.left + (q.x - V.view.x) * k, r.top + (q.y - V.view.y) * k))) continue;
358
+ best = { ptr, dist: q.dist };
359
+ }
360
+ return best ? best.ptr : direct;
361
+ };
315
362
  function outlinesFor(ptr) {
316
363
  if (!cd) return [];
317
364
  const out = [];
@@ -446,8 +493,10 @@ function canvasView(host, doc, opts) {
446
493
  stage.addEventListener("wheel", wheel, { passive: false });
447
494
  stage.addEventListener("contextmenu", context);
448
495
  stage.addEventListener("dblclick", (e) => {
449
- const p = pathAtEvent(e.target);
450
- if (p !== void 0) opts.showInText(fromPointer(p));
496
+ const p = pathAt(e.target === stage ? fdoc().elementFromPoint(e.clientX, e.clientY) : e.target, e.clientX, e.clientY);
497
+ if (p === void 0) return;
498
+ if (ui.doubleClick === "rename" && doc.doc.ok && resourceOf(p)?.path === p) rename(fromPointer(p));
499
+ else opts.showInText(fromPointer(p));
451
500
  });
452
501
  };
453
502
  const pageXY = (e) => ({ x: e.clientX, y: e.clientY });
@@ -488,7 +537,7 @@ function canvasView(host, doc, opts) {
488
537
  return;
489
538
  }
490
539
  if (e.button !== 0) return;
491
- const ptr = pathAtEvent(e.target);
540
+ const ptr = pathAt(e.target, x, y);
492
541
  if (ptr === void 0) {
493
542
  const mod = e.shiftKey || e.metaKey || e.ctrlKey;
494
543
  if (nav.drag === "pan" && !mod) {
@@ -547,7 +596,7 @@ function canvasView(host, doc, opts) {
547
596
  return;
548
597
  }
549
598
  if (!drag) {
550
- const p = pathAtEvent(e.target);
599
+ const p = pathAt(e.target, x, y);
551
600
  if (p !== hoverId) {
552
601
  hoverId = p;
553
602
  paintOverlay();
@@ -754,7 +803,17 @@ function canvasView(host, doc, opts) {
754
803
  if (c.bottom) e(pb.x0, pb.y1 - pad, pb.x1, pb.y1 - pad);
755
804
  }
756
805
  }
806
+ let dropping = 0;
757
807
  async function endPin(commit) {
808
+ if (!pinDrag()) return;
809
+ dropping++;
810
+ try {
811
+ await endDrop(commit);
812
+ } finally {
813
+ dropping--;
814
+ }
815
+ }
816
+ async function endDrop(commit) {
758
817
  const g = pinDrag();
759
818
  if (!g) return;
760
819
  drag = void 0;
@@ -862,7 +921,7 @@ function canvasView(host, doc, opts) {
862
921
  e.preventDefault();
863
922
  const { x, y } = pageXY(e);
864
923
  if (layer?.context?.(e, { x, y })) return;
865
- const ptr = pathAtEvent(e.target);
924
+ const ptr = pathAt(e.target, x, y);
866
925
  if (ptr !== void 0 && !doc.selection.some((p) => toPointer(p) === ptr)) doc.select([fromPointer(ptr)], "canvas");
867
926
  openMenu(menuItems(ptr), { x, y }, "Canvas");
868
927
  }
@@ -883,7 +942,7 @@ function canvasView(host, doc, opts) {
883
942
  if (one) {
884
943
  items.push(...K.objectItems(doc, one, "canvas", opts.note));
885
944
  if (items.length) items.push({ sep: true });
886
- items.push({ label: "Rename\u2026", icon: "pencil", keys: "F2", disabled: ro || !isRes, why: T.renameWhy, onSelect: () => renameDialog(doc, one, "canvas", opts.note) });
945
+ items.push({ label: "Rename\u2026", icon: "pencil", keys: "F2", disabled: ro || !isRes, why: T.renameWhy, onSelect: () => rename(one) });
887
946
  items.push({ label: "Duplicate", icon: "copy", keys: "\u2318D", disabled: ro || !isRes, why: T.duplicateWhy, onSelect: () => duplicate(doc, one, "canvas", opts.note) });
888
947
  const name = isRes ? resourceOf(toPointer(one)).name : "";
889
948
  const pinned = !!K.pins.of(doc.goodDoc.data)?.[name];
@@ -976,7 +1035,7 @@ function canvasView(host, doc, opts) {
976
1035
  const p = [...k.section, name];
977
1036
  if (run(doc, insertCmd(p.slice(0, -1), name, k.template(), { label: `Add ${k.singular} ${name}` }), "canvas", opts.note)) {
978
1037
  doc.select([p], "canvas");
979
- renameDialog(doc, p, "canvas", opts.note);
1038
+ rename(p, { joins: doc.undoId });
980
1039
  }
981
1040
  }
982
1041
  function placeAt(name, add, at) {
@@ -1107,11 +1166,178 @@ function canvasView(host, doc, opts) {
1107
1166
  if (!run(doc, { ...cmd, select: [p] }, "canvas", opts.note)) return void 0;
1108
1167
  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`);
1109
1168
  doc.select([p], "canvas");
1110
- stage.focus({ preventScroll: true });
1111
- renameDialog(doc, p, "canvas", opts.note);
1169
+ rename(p, { joins: doc.undoId, at });
1112
1170
  return p;
1113
1171
  }
1114
1172
  const palette = h("div", { class: "palette", role: "toolbar", "aria-label": T.palette, "aria-orientation": "vertical" });
1173
+ const sections = /* @__PURE__ */ new Map();
1174
+ const PAL_KEY = "canvas-palette";
1175
+ let lastSection;
1176
+ try {
1177
+ const v = JSON.parse(opts.store?.get(PAL_KEY) ?? "{}");
1178
+ if (typeof v.last === "string") lastSection = v.last;
1179
+ } catch {
1180
+ }
1181
+ const named = [...new Set(ui.palette.map((i) => i.section).filter((x) => x !== void 0))];
1182
+ const openAtStart = lastSection !== void 0 && named.includes(lastSection) ? lastSection : named[0];
1183
+ const setOpen = (sec, open) => {
1184
+ const g = sections.get(sec);
1185
+ if (!g) return;
1186
+ g.head.setAttribute("aria-expanded", String(open));
1187
+ g.body.hidden = !open;
1188
+ };
1189
+ function sectionBody(sec) {
1190
+ const have = sections.get(sec);
1191
+ if (have) return have.body;
1192
+ const id = `pal-sec-${sections.size}-${Math.random().toString(36).slice(2, 8)}`;
1193
+ const head = h("button", { type: "button", class: "pal-head", "aria-expanded": "false", "aria-controls": id, "data-section-head": sec }, icon("chevron-right", "pal-chev"), h("span", { class: "pal-head-label" }, sec));
1194
+ const body = h("div", { class: "pal-body", id, role: "group", "aria-label": sec, "data-section-body": sec });
1195
+ head.addEventListener("click", () => setOpen(sec, head.getAttribute("aria-expanded") !== "true"));
1196
+ palette.append(h("div", { class: "pal-section", "data-pal-section": sec }, head, body));
1197
+ sections.set(sec, { head, body });
1198
+ setOpen(sec, sec === openAtStart);
1199
+ return body;
1200
+ }
1201
+ const DOCK_KEY = "canvas-palette-dock";
1202
+ const dockPref = {};
1203
+ try {
1204
+ const v = JSON.parse(opts.store?.get(DOCK_KEY) ?? "{}");
1205
+ if (typeof v.w === "number" && Number.isFinite(v.w)) dockPref.w = v.w;
1206
+ if (v.collapsed === true) dockPref.collapsed = true;
1207
+ } catch {
1208
+ }
1209
+ const saveDock = () => {
1210
+ try {
1211
+ opts.store?.set(DOCK_KEY, JSON.stringify(dockPref));
1212
+ } catch {
1213
+ }
1214
+ };
1215
+ const DOCK_MIN = 160, DOCK_MAX = 440;
1216
+ const palHome = docked ? h("aside", { class: "pal-dock", "aria-label": "Palette" }) : palette;
1217
+ const palGrip = h("div", { class: "pal-grip", role: "separator", "aria-orientation": "vertical", "aria-label": "Resize the palette", tabindex: "0" });
1218
+ const search = h("input", { type: "search", class: "pal-search", placeholder: "Search", "aria-label": "Search the palette", autocomplete: "off", spellcheck: "false" });
1219
+ const none = h("p", { class: "pal-none", role: "status", hidden: "" });
1220
+ const collapseBtn = h("button", { type: "button", class: "btn sm quiet icon-only pal-collapse", "aria-expanded": "true", "aria-label": "Collapse the palette", title: "Collapse the palette" }, icon("chevron-left"));
1221
+ const visibleItems = () => [...palette.querySelectorAll(".pal-item")].filter((b) => !b.hidden && !b.closest("[hidden]"));
1222
+ let before;
1223
+ function filter() {
1224
+ const words = search.value.toLowerCase().split(/\s+/).filter(Boolean);
1225
+ if (words.length && !before) before = new Map([...sections].map(([k, g]) => [k, g.head.getAttribute("aria-expanded") === "true"]));
1226
+ let shown = 0;
1227
+ for (const b of palette.querySelectorAll(".pal-item")) {
1228
+ const item = ui.palette[Number(b.dataset.entry)];
1229
+ const hay = `${item.label} ${item.section ?? ""}`.toLowerCase();
1230
+ b.hidden = !words.every((w) => hay.includes(w));
1231
+ if (!b.hidden) shown++;
1232
+ }
1233
+ for (const [sec, g] of sections) {
1234
+ const any = [...g.body.querySelectorAll(".pal-item")].some((b) => !b.hidden);
1235
+ g.head.parentElement.hidden = words.length > 0 && !any;
1236
+ if (words.length) setOpen(sec, any);
1237
+ }
1238
+ if (!words.length && before) {
1239
+ for (const [sec, open] of before) setOpen(sec, open);
1240
+ before = void 0;
1241
+ }
1242
+ none.hidden = shown > 0;
1243
+ none.textContent = shown ? "" : `Nothing matches "${search.value.trim()}"`;
1244
+ }
1245
+ const setDockW = (w, keep = true) => {
1246
+ const v = Math.round(Math.min(DOCK_MAX, Math.max(DOCK_MIN, w)));
1247
+ host.style.setProperty("--pal-w", `${v}px`);
1248
+ palGrip.setAttribute("aria-valuenow", String(v));
1249
+ if (keep) {
1250
+ dockPref.w = v;
1251
+ saveDock();
1252
+ }
1253
+ };
1254
+ const setCollapsed = (c, keep = true) => {
1255
+ host.classList.toggle("pal-collapsed", c);
1256
+ collapseBtn.setAttribute("aria-expanded", String(!c));
1257
+ const say = c ? "Show the palette" : "Collapse the palette";
1258
+ collapseBtn.setAttribute("aria-label", say);
1259
+ collapseBtn.title = say;
1260
+ collapseBtn.replaceChildren(icon(c ? "chevron-right" : "chevron-left"));
1261
+ if (keep) {
1262
+ if (c) dockPref.collapsed = true;
1263
+ else delete dockPref.collapsed;
1264
+ saveDock();
1265
+ }
1266
+ };
1267
+ if (docked) {
1268
+ host.classList.add("pal-docked");
1269
+ palette.classList.add("pal-list");
1270
+ palHome.append(h("div", { class: "pal-dock-head" }, collapseBtn, h("label", { class: "pal-search-wrap" }, icon("search"), search)), palette, none);
1271
+ palGrip.setAttribute("aria-valuemin", String(DOCK_MIN));
1272
+ palGrip.setAttribute("aria-valuemax", String(DOCK_MAX));
1273
+ setDockW(dockPref.w ?? 220, false);
1274
+ setCollapsed(!!dockPref.collapsed, false);
1275
+ collapseBtn.addEventListener("click", () => {
1276
+ setCollapsed(!host.classList.contains("pal-collapsed"));
1277
+ if (!host.classList.contains("pal-collapsed")) search.focus();
1278
+ });
1279
+ search.addEventListener("input", filter);
1280
+ search.addEventListener("keydown", (e) => {
1281
+ if (e.key === "Escape" && search.value) {
1282
+ e.preventDefault();
1283
+ e.stopPropagation();
1284
+ search.value = "";
1285
+ filter();
1286
+ } else if (e.key === "ArrowDown") {
1287
+ const first = visibleItems()[0];
1288
+ if (first) {
1289
+ e.preventDefault();
1290
+ first.focus();
1291
+ }
1292
+ } else if (e.key === "Enter") {
1293
+ const first = visibleItems()[0];
1294
+ if (first) {
1295
+ e.preventDefault();
1296
+ first.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
1297
+ }
1298
+ }
1299
+ });
1300
+ palette.addEventListener("keydown", (e) => {
1301
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
1302
+ const all = [...palette.querySelectorAll(".pal-head, .pal-item")].filter((b) => !b.hidden && !b.parentElement?.closest("[hidden]") && (b.classList.contains("pal-head") || !b.closest(".pal-body[hidden]")));
1303
+ const i = all.indexOf(document.activeElement);
1304
+ if (i < 0) return;
1305
+ e.preventDefault();
1306
+ if (e.key === "ArrowUp" && i === 0) search.focus();
1307
+ else all[Math.min(all.length - 1, Math.max(0, i + (e.key === "ArrowDown" ? 1 : -1)))].focus();
1308
+ });
1309
+ palGrip.addEventListener("pointerdown", (e) => {
1310
+ if (e.button !== 0) return;
1311
+ try {
1312
+ palGrip.setPointerCapture(e.pointerId);
1313
+ } catch {
1314
+ }
1315
+ const x0 = e.clientX, w0 = palHome.getBoundingClientRect().width;
1316
+ const mv = (ev) => setDockW(w0 + ev.clientX - x0, false);
1317
+ const up2 = (ev) => {
1318
+ palGrip.removeEventListener("pointermove", mv);
1319
+ palGrip.removeEventListener("pointerup", up2);
1320
+ setDockW(w0 + ev.clientX - x0);
1321
+ };
1322
+ palGrip.addEventListener("pointermove", mv);
1323
+ palGrip.addEventListener("pointerup", up2);
1324
+ });
1325
+ palGrip.addEventListener("keydown", (e) => {
1326
+ const d = e.key === "ArrowLeft" ? -16 : e.key === "ArrowRight" ? 16 : 0;
1327
+ if (d) {
1328
+ e.preventDefault();
1329
+ setDockW(palHome.getBoundingClientRect().width + d);
1330
+ }
1331
+ });
1332
+ }
1333
+ const usedSection = (item) => {
1334
+ if (item.section === void 0 || item.section === lastSection) return;
1335
+ lastSection = item.section;
1336
+ try {
1337
+ opts.store?.set(PAL_KEY, JSON.stringify({ last: lastSection }));
1338
+ } catch {
1339
+ }
1340
+ };
1115
1341
  ui.palette.forEach((item, idx) => {
1116
1342
  const { kind: sec, icon: ic, label } = item;
1117
1343
  const b = h("button", { type: "button", class: "pal-item", "data-section": sec, "data-entry": String(idx), title: `Add ${label.toLowerCase()} (click), or drag it where it goes` }, icon(ic), h("span", { class: "pal-label" }, label));
@@ -1126,7 +1352,7 @@ function canvasView(host, doc, opts) {
1126
1352
  let ghost;
1127
1353
  const over = (ev) => {
1128
1354
  const r = stage.getBoundingClientRect();
1129
- return ev.clientX >= r.left && ev.clientX <= r.right && ev.clientY >= r.top && ev.clientY <= r.bottom && !palette.contains(document.elementFromPoint(ev.clientX, ev.clientY));
1355
+ 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));
1130
1356
  };
1131
1357
  const mv = (ev) => {
1132
1358
  if (!ghost && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
@@ -1147,8 +1373,13 @@ function canvasView(host, doc, opts) {
1147
1373
  const dragged = !!ghost;
1148
1374
  ghost?.remove();
1149
1375
  if (!drop) return;
1150
- if (!dragged) addFromPalette(sec, void 0, item);
1151
- else if (over(ev)) addFromPalette(sec, { x: ev.clientX, y: ev.clientY }, item);
1376
+ if (!dragged) {
1377
+ usedSection(item);
1378
+ addFromPalette(sec, void 0, item);
1379
+ } else if (over(ev)) {
1380
+ usedSection(item);
1381
+ addFromPalette(sec, { x: ev.clientX, y: ev.clientY }, item);
1382
+ }
1152
1383
  };
1153
1384
  const upH = (ev) => done(ev, true), cancelH = (ev) => done(ev, false);
1154
1385
  const esc = (ev) => {
@@ -1166,18 +1397,39 @@ function canvasView(host, doc, opts) {
1166
1397
  b.addEventListener("keydown", (e) => {
1167
1398
  if (e.key === "Enter" || e.key === " ") {
1168
1399
  e.preventDefault();
1400
+ usedSection(item);
1169
1401
  addFromPalette(sec, void 0, item);
1170
1402
  }
1171
1403
  });
1172
- palette.append(b);
1404
+ (item.section === void 0 ? palette : sectionBody(item.section)).append(b);
1173
1405
  });
1174
- host.append(palette);
1406
+ if (docked) host.prepend(palHome, palGrip);
1407
+ else host.append(palette);
1175
1408
  function resetLayout() {
1176
1409
  const key2 = K.pins.keyOf(doc.goodDoc.data);
1177
1410
  const x = doc.goodDoc.data?.[key2];
1178
1411
  const only = x && Object.keys(x).length === 1;
1179
1412
  run(doc, { ...deleteCmd(only ? [key2] : [key2, "layout"]), label: "Reset the layout" }, "canvas", opts.note);
1180
1413
  }
1414
+ function rename(p, o = {}) {
1415
+ let path = p;
1416
+ const off = doc.on((c) => {
1417
+ if (path && c.remap) path = c.remap(path);
1418
+ });
1419
+ void K.actions.rename(doc, p, "canvas", opts.note, {
1420
+ ...o,
1421
+ back: stage,
1422
+ late: stage,
1423
+ busy: () => !!drag || dropping > 0,
1424
+ bounds: () => stage.getBoundingClientRect(),
1425
+ place: () => {
1426
+ const b = path && V.view ? boxFor(path) : void 0;
1427
+ if (!b) return void 0;
1428
+ const r = viewEl.getBoundingClientRect(), k = scale();
1429
+ 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 };
1430
+ }
1431
+ }).finally(off);
1432
+ }
1181
1433
  function selectParent() {
1182
1434
  const up2 = /* @__PURE__ */ new Map();
1183
1435
  for (const p of doc.selection) {
@@ -1244,7 +1496,7 @@ function canvasView(host, doc, opts) {
1244
1496
  if (sel.length && !ro) deletePaths(doc, sel, "canvas", opts.note);
1245
1497
  break;
1246
1498
  case "F2":
1247
- if (sel.length === 1 && !ro) renameDialog(doc, sel[0], "canvas", opts.note);
1499
+ if (sel.length === 1 && !ro) rename(sel[0]);
1248
1500
  break;
1249
1501
  case "ArrowUp":
1250
1502
  if (mod) {
@@ -1256,6 +1508,7 @@ function canvasView(host, doc, opts) {
1256
1508
  case "ArrowRight":
1257
1509
  case "ArrowLeft":
1258
1510
  case "ArrowDown": {
1511
+ drawn.push(...connections().keys());
1259
1512
  if (!drawn.length) return;
1260
1513
  const i = sel.length ? drawn.indexOf(toPointer(sel[0])) : -1;
1261
1514
  const back = e.key === "ArrowLeft" || e.key === "Tab" && e.shiftKey;
@@ -1269,7 +1522,7 @@ function canvasView(host, doc, opts) {
1269
1522
  if (e.key === "F10" && !e.shiftKey) return;
1270
1523
  {
1271
1524
  const b = unionBox(sel);
1272
- const r = host.getBoundingClientRect();
1525
+ const r = viewEl.getBoundingClientRect();
1273
1526
  const k = scale();
1274
1527
  openMenu(menuItems(sel.length ? toPointer(sel[0]) : void 0), b ? { x: r.left + (b.x + b.w - V.view.x) * k, y: r.top + (b.y - V.view.y) * k } : { x: r.left + 40, y: r.top + 40 }, "Canvas");
1275
1528
  }
@@ -1341,10 +1594,14 @@ function canvasView(host, doc, opts) {
1341
1594
  setTheme,
1342
1595
  paintOverlay,
1343
1596
  fit: fitItems,
1597
+ fitNext() {
1598
+ toFit = true;
1599
+ },
1344
1600
  fitAll: fit,
1345
1601
  actual,
1346
1602
  zoomAt,
1347
1603
  itemsBox,
1604
+ routesBox,
1348
1605
  get moved() {
1349
1606
  return V.moved;
1350
1607
  },
@@ -1390,7 +1647,7 @@ function canvasView(host, doc, opts) {
1390
1647
  boxFor,
1391
1648
  pageXYOf: (p) => {
1392
1649
  const b = boxFor(p);
1393
- const r = host.getBoundingClientRect();
1650
+ const r = viewEl.getBoundingClientRect();
1394
1651
  const k = scale();
1395
1652
  return b && V.view ? { x: r.left + (b.x + b.w / 2 - V.view.x) * k, y: r.top + (b.y + b.h / 2 - V.view.y) * k } : void 0;
1396
1653
  }
@@ -707,8 +707,9 @@ function mountEditor(el, opts, S) {
707
707
  return {
708
708
  internal,
709
709
  getText: () => doc.text,
710
- setText(text) {
710
+ setText(text, o = {}) {
711
711
  hideBanner();
712
+ if (o.fit && !disposed) canvas.fitNext?.();
712
713
  doc.load(text);
713
714
  doc.markClean();
714
715
  paintTitle();