@johnoscott/isometric-engine 0.12.3 → 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 (37) hide show
  1. package/EDITOR-GUIDE.md +1 -0
  2. package/README.md +1 -1
  3. package/assets/app.css +6 -0
  4. package/iso-editor.js +165 -165
  5. package/iso-render.js +82 -82
  6. package/iso-systems.js +79 -79
  7. package/js/iso-editor/commands.js +7 -0
  8. package/js/iso-editor/connections.js +24 -0
  9. package/js/iso-editor/model.js +17 -3
  10. package/js/iso-editor/ui/actions.js +22 -24
  11. package/js/iso-editor/ui/canvas.js +92 -12
  12. package/js/iso-editor/ui/mount.js +2 -1
  13. package/js/iso-editor/ui/props.js +2 -2
  14. package/js/iso-editor/ui/rename.js +114 -0
  15. package/js/iso-editor/ui/setup.js +1 -0
  16. package/js/iso-viewer/viewport.js +17 -5
  17. package/package.json +1 -1
  18. package/src/iso-editor/commands.ts +9 -0
  19. package/src/iso-editor/connections.ts +28 -0
  20. package/src/iso-editor/model.ts +17 -3
  21. package/src/iso-editor/ui/actions.ts +20 -23
  22. package/src/iso-editor/ui/app.css +6 -0
  23. package/src/iso-editor/ui/canvas.ts +84 -15
  24. package/src/iso-editor/ui/mount.ts +4 -3
  25. package/src/iso-editor/ui/props.ts +3 -3
  26. package/src/iso-editor/ui/rename.ts +105 -0
  27. package/src/iso-editor/ui/setup.ts +3 -0
  28. package/src/iso-viewer/viewport.ts +25 -5
  29. package/types/iso-editor/connections.d.ts +8 -0
  30. package/types/iso-editor/model.d.ts +8 -2
  31. package/types/iso-editor/ui/actions.d.ts +5 -2
  32. package/types/iso-editor/ui/canvas.d.ts +10 -1
  33. package/types/iso-editor/ui/mount.d.ts +6 -2
  34. package/types/iso-editor/ui/props.d.ts +1 -1
  35. package/types/iso-editor/ui/rename.d.ts +43 -0
  36. package/types/iso-editor/ui/setup.d.ts +2 -0
  37. 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
+ };
@@ -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,6 +263,11 @@ 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
  }
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
+ }
256
271
  const docked = ui.paletteLayout === "docked";
257
272
  const viewEl = docked ? stage : host;
258
273
  const V = viewport(viewEl, {
@@ -265,6 +280,7 @@ function canvasView(host, doc, opts) {
265
280
  },
266
281
  onRezoom: () => paintOverlay(),
267
282
  itemsBox: () => itemsBox(),
283
+ alsoBox: () => routesBox(),
268
284
  marksShowing: () => !!layer?.showing?.()
269
285
  });
270
286
  const { size, scale, quietly, applyView, toSvg, zoomAt, fit, fitItems, autoFit, actual, settled } = V;
@@ -314,6 +330,35 @@ function canvasView(host, doc, opts) {
314
330
  }
315
331
  return void 0;
316
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
+ };
317
362
  function outlinesFor(ptr) {
318
363
  if (!cd) return [];
319
364
  const out = [];
@@ -448,8 +493,10 @@ function canvasView(host, doc, opts) {
448
493
  stage.addEventListener("wheel", wheel, { passive: false });
449
494
  stage.addEventListener("contextmenu", context);
450
495
  stage.addEventListener("dblclick", (e) => {
451
- const p = pathAtEvent(e.target);
452
- 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));
453
500
  });
454
501
  };
455
502
  const pageXY = (e) => ({ x: e.clientX, y: e.clientY });
@@ -490,7 +537,7 @@ function canvasView(host, doc, opts) {
490
537
  return;
491
538
  }
492
539
  if (e.button !== 0) return;
493
- const ptr = pathAtEvent(e.target);
540
+ const ptr = pathAt(e.target, x, y);
494
541
  if (ptr === void 0) {
495
542
  const mod = e.shiftKey || e.metaKey || e.ctrlKey;
496
543
  if (nav.drag === "pan" && !mod) {
@@ -549,7 +596,7 @@ function canvasView(host, doc, opts) {
549
596
  return;
550
597
  }
551
598
  if (!drag) {
552
- const p = pathAtEvent(e.target);
599
+ const p = pathAt(e.target, x, y);
553
600
  if (p !== hoverId) {
554
601
  hoverId = p;
555
602
  paintOverlay();
@@ -756,7 +803,17 @@ function canvasView(host, doc, opts) {
756
803
  if (c.bottom) e(pb.x0, pb.y1 - pad, pb.x1, pb.y1 - pad);
757
804
  }
758
805
  }
806
+ let dropping = 0;
759
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) {
760
817
  const g = pinDrag();
761
818
  if (!g) return;
762
819
  drag = void 0;
@@ -864,7 +921,7 @@ function canvasView(host, doc, opts) {
864
921
  e.preventDefault();
865
922
  const { x, y } = pageXY(e);
866
923
  if (layer?.context?.(e, { x, y })) return;
867
- const ptr = pathAtEvent(e.target);
924
+ const ptr = pathAt(e.target, x, y);
868
925
  if (ptr !== void 0 && !doc.selection.some((p) => toPointer(p) === ptr)) doc.select([fromPointer(ptr)], "canvas");
869
926
  openMenu(menuItems(ptr), { x, y }, "Canvas");
870
927
  }
@@ -885,7 +942,7 @@ function canvasView(host, doc, opts) {
885
942
  if (one) {
886
943
  items.push(...K.objectItems(doc, one, "canvas", opts.note));
887
944
  if (items.length) items.push({ sep: true });
888
- items.push({ label: "Rename\u2026", icon: "pencil", keys: "F2", disabled: ro || !isRes, why: T.renameWhy, onSelect: () => renameDialog(doc, one, "canvas", opts.note) });
945
+ items.push({ label: "Rename\u2026", icon: "pencil", keys: "F2", disabled: ro || !isRes, why: T.renameWhy, onSelect: () => rename(one) });
889
946
  items.push({ label: "Duplicate", icon: "copy", keys: "\u2318D", disabled: ro || !isRes, why: T.duplicateWhy, onSelect: () => duplicate(doc, one, "canvas", opts.note) });
890
947
  const name = isRes ? resourceOf(toPointer(one)).name : "";
891
948
  const pinned = !!K.pins.of(doc.goodDoc.data)?.[name];
@@ -978,7 +1035,7 @@ function canvasView(host, doc, opts) {
978
1035
  const p = [...k.section, name];
979
1036
  if (run(doc, insertCmd(p.slice(0, -1), name, k.template(), { label: `Add ${k.singular} ${name}` }), "canvas", opts.note)) {
980
1037
  doc.select([p], "canvas");
981
- renameDialog(doc, p, "canvas", opts.note);
1038
+ rename(p, { joins: doc.undoId });
982
1039
  }
983
1040
  }
984
1041
  function placeAt(name, add, at) {
@@ -1109,8 +1166,7 @@ function canvasView(host, doc, opts) {
1109
1166
  if (!run(doc, { ...cmd, select: [p] }, "canvas", opts.note)) return void 0;
1110
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`);
1111
1168
  doc.select([p], "canvas");
1112
- stage.focus({ preventScroll: true });
1113
- renameDialog(doc, p, "canvas", opts.note);
1169
+ rename(p, { joins: doc.undoId, at });
1114
1170
  return p;
1115
1171
  }
1116
1172
  const palette = h("div", { class: "palette", role: "toolbar", "aria-label": T.palette, "aria-orientation": "vertical" });
@@ -1355,6 +1411,25 @@ function canvasView(host, doc, opts) {
1355
1411
  const only = x && Object.keys(x).length === 1;
1356
1412
  run(doc, { ...deleteCmd(only ? [key2] : [key2, "layout"]), label: "Reset the layout" }, "canvas", opts.note);
1357
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
+ }
1358
1433
  function selectParent() {
1359
1434
  const up2 = /* @__PURE__ */ new Map();
1360
1435
  for (const p of doc.selection) {
@@ -1421,7 +1496,7 @@ function canvasView(host, doc, opts) {
1421
1496
  if (sel.length && !ro) deletePaths(doc, sel, "canvas", opts.note);
1422
1497
  break;
1423
1498
  case "F2":
1424
- if (sel.length === 1 && !ro) renameDialog(doc, sel[0], "canvas", opts.note);
1499
+ if (sel.length === 1 && !ro) rename(sel[0]);
1425
1500
  break;
1426
1501
  case "ArrowUp":
1427
1502
  if (mod) {
@@ -1433,6 +1508,7 @@ function canvasView(host, doc, opts) {
1433
1508
  case "ArrowRight":
1434
1509
  case "ArrowLeft":
1435
1510
  case "ArrowDown": {
1511
+ drawn.push(...connections().keys());
1436
1512
  if (!drawn.length) return;
1437
1513
  const i = sel.length ? drawn.indexOf(toPointer(sel[0])) : -1;
1438
1514
  const back = e.key === "ArrowLeft" || e.key === "Tab" && e.shiftKey;
@@ -1518,10 +1594,14 @@ function canvasView(host, doc, opts) {
1518
1594
  setTheme,
1519
1595
  paintOverlay,
1520
1596
  fit: fitItems,
1597
+ fitNext() {
1598
+ toFit = true;
1599
+ },
1521
1600
  fitAll: fit,
1522
1601
  actual,
1523
1602
  zoomAt,
1524
1603
  itemsBox,
1604
+ routesBox,
1525
1605
  get moved() {
1526
1606
  return V.moved;
1527
1607
  },
@@ -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();
@@ -12,7 +12,7 @@ function propsPanel(body, doc, opts) {
12
12
  let focusInput = false;
13
13
  const K = opts.kit, ui = K.ui;
14
14
  const { setCmd, deleteCmd, insertItemCmd, referencesTo, describe } = K.commands;
15
- const { deletePaths, renameDialog } = K.actions;
15
+ const { deletePaths, rename } = K.actions;
16
16
  const kindOf = (k) => K.kinds.find((x) => x.kind === k);
17
17
  const singular = (k) => kindOf(k)?.singular ?? "item";
18
18
  const names = (s) => Object.keys(getIn(doc.goodDoc.data, kindOf(s)?.section ?? []) ?? {}).filter((k) => !k.startsWith("x-"));
@@ -47,7 +47,7 @@ function propsPanel(body, doc, opts) {
47
47
  }
48
48
  const head = h("div", { class: "sel-headrow" }, h("div", { class: "sel-title" }, describe(target)));
49
49
  const rn = h("button", { type: "button", class: "btn sm quiet icon-only", "aria-label": `Rename ${describe(target)}`, title: "Rename (F2)" }, icon("pencil"));
50
- rn.addEventListener("click", () => renameDialog(doc, target, "props", opts.note));
50
+ rn.addEventListener("click", () => void rename(doc, target, "props", opts.note, { over: true, place: () => head.isConnected ? head.firstElementChild.getBoundingClientRect() : void 0 }));
51
51
  head.append(rn);
52
52
  body.append(head);
53
53
  if (toPointer(p) !== r.path) pendingFocus = toPointer(p);
@@ -0,0 +1,114 @@
1
+ import { h } from "./icons.js";
2
+ import { layer } from "./layer.js";
3
+ let open;
4
+ const renameOpen = () => !!open;
5
+ function renameField(f, at) {
6
+ open?.close();
7
+ return new Promise((resolve) => {
8
+ const back = at.back ?? document.activeElement;
9
+ const id = `rename-${Math.random().toString(36).slice(2, 8)}`;
10
+ const input = h("input", { type: "text", class: "rename-input", "aria-label": f.label, "aria-describedby": id, spellcheck: "false", autocomplete: "off", autocapitalize: "off" });
11
+ const why = h("p", { class: "rename-error", role: "alert", id });
12
+ const box = h("div", { class: `rename-field${at.over ? " over" : ""}` }, input, why);
13
+ input.value = f.value;
14
+ const fitWidth = () => {
15
+ input.size = Math.max(8, Math.min(40, input.value.length + 1));
16
+ };
17
+ fitWidth();
18
+ layer().append(box);
19
+ let done = false, frame = 0, seen = at.at ? { left: at.at.x, top: at.at.y, width: 0, height: 0 } : void 0;
20
+ const put = () => {
21
+ const p = at.place();
22
+ if (p) seen = p;
23
+ const b = at.bounds?.() ?? { left: 0, top: 0, right: innerWidth, bottom: innerHeight }, r = input.getBoundingClientRect();
24
+ const t = seen ?? { left: (b.left + b.right) / 2, top: b.top + 48, width: 0, height: 0 };
25
+ const within = (v, lo, hi) => Math.max(lo, Math.min(v, Math.max(lo, hi)));
26
+ box.style.left = `${within(at.over ? t.left - 8 : t.left + t.width / 2 - r.width / 2, b.left + 4, b.right - r.width - 4)}px`;
27
+ box.style.top = `${within(at.over ? t.top + t.height / 2 - r.height / 2 : t.top - r.height - 8, b.top + 4, b.bottom - r.height - 4)}px`;
28
+ };
29
+ const follow = () => {
30
+ if (done) return;
31
+ if (f.alive && !f.alive()) {
32
+ end(void 0, false);
33
+ return;
34
+ }
35
+ put();
36
+ frame = requestAnimationFrame(follow);
37
+ };
38
+ const check = () => {
39
+ const bad = f.wrong(input.value.trim());
40
+ why.textContent = bad;
41
+ input.setAttribute("aria-invalid", String(!!bad));
42
+ return bad;
43
+ };
44
+ const good = () => {
45
+ const v = input.value.trim();
46
+ return v !== f.value && !f.wrong(v) ? v : void 0;
47
+ };
48
+ function end(v, focusBack, late = false) {
49
+ if (done) return;
50
+ done = true;
51
+ cancelAnimationFrame(frame);
52
+ removeEventListener("pointerdown", outside, true);
53
+ box.remove();
54
+ open = void 0;
55
+ if (focusBack && back?.isConnected) back.focus({ preventScroll: true });
56
+ const save = () => {
57
+ if (v !== void 0 && (!f.alive || f.alive())) f.commit(v);
58
+ resolve(v);
59
+ };
60
+ if (!late || v === void 0) {
61
+ save();
62
+ return;
63
+ }
64
+ const up = () => {
65
+ removeEventListener("pointerup", up, true);
66
+ removeEventListener("pointercancel", up, true);
67
+ setTimeout(wait, 0);
68
+ };
69
+ const wait = () => {
70
+ if (at.busy?.()) setTimeout(wait, 20);
71
+ else save();
72
+ };
73
+ addEventListener("pointerup", up, true);
74
+ addEventListener("pointercancel", up, true);
75
+ }
76
+ const outside = (e) => {
77
+ if (!box.contains(e.target)) end(good(), false, !!at.late?.contains(e.target));
78
+ };
79
+ addEventListener("pointerdown", outside, true);
80
+ input.addEventListener("input", () => {
81
+ fitWidth();
82
+ check();
83
+ });
84
+ input.addEventListener("keydown", (e) => {
85
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "s") {
86
+ end(good(), true);
87
+ return;
88
+ }
89
+ e.stopPropagation();
90
+ if (e.isComposing) return;
91
+ if (e.key === "Escape") {
92
+ e.preventDefault();
93
+ end(void 0, true);
94
+ }
95
+ if (e.key === "Enter") {
96
+ e.preventDefault();
97
+ const v = input.value.trim();
98
+ if (!check()) end(v === f.value ? void 0 : v, true);
99
+ }
100
+ });
101
+ input.addEventListener("keyup", (e) => e.stopPropagation());
102
+ input.addEventListener("blur", () => setTimeout(() => {
103
+ if (!done && document.hasFocus() && document.activeElement !== input && document.activeElement !== document.body) end(good(), false);
104
+ }, 0));
105
+ open = { close: () => end(void 0, false) };
106
+ follow();
107
+ input.focus({ preventScroll: true });
108
+ input.select();
109
+ });
110
+ }
111
+ export {
112
+ renameField,
113
+ renameOpen
114
+ };
@@ -78,6 +78,7 @@ function setupFor(a, v, textPane) {
78
78
  newOrder: a.kinds.map((k) => k.kind),
79
79
  palette: v.palette ? v.palette.map((e) => ({ kind: e.kind, label: e.label, icon: e.icon ?? icon(e.kind), name: e.name, ...e.section === void 0 ? {} : { section: e.section }, ...e.value === void 0 ? {} : { value: () => structuredClone(e.value) } })) : a.kinds.map((k) => ({ kind: k.kind, icon: icon(k.kind), label: k.singular[0].toUpperCase() + k.singular.slice(1) })),
80
80
  ...v.paletteLayout === void 0 ? {} : { paletteLayout: v.paletteLayout },
81
+ ...v.doubleClick === void 0 ? {} : { doubleClick: v.doubleClick },
81
82
  text: {
82
83
  stage: "The file, drawn: arrow keys and Tab move through what is drawn; + and \u2212 zoom, 0 fits",
83
84
  dragGroup: "A drag on nothing",
@@ -1,3 +1,16 @@
1
+ const INSET = 6;
2
+ function fitted(s, box, also) {
3
+ const pad = 24;
4
+ const most = (len, a0, a1, b0, b1) => Math.min((len - pad * 2) / (a1 - a0), ...b0 === void 0 || b1 === void 0 ? [] : [[b1 - b0, INSET * 2], [b1 - a0, pad + INSET], [a1 - b0, pad + INSET]].map(([d, edges]) => d > 0 ? (len - edges) / d : Infinity));
5
+ const k = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min(most(s.w, box.x, box.x + box.w, also?.x, also && also.x + also.w), most(s.h, box.y, box.y + box.h, also?.y, also && also.y + also.h))));
6
+ const middle = (len, a0, a1, b0, b1) => {
7
+ const c = (a0 + a1) / 2;
8
+ if (b0 === void 0 || b1 === void 0) return c;
9
+ const lo = b1 - (len / 2 - INSET) / k, hi = b0 + (len / 2 - INSET) / k;
10
+ return lo > hi ? (lo + hi) / 2 : Math.max(lo, Math.min(hi, c));
11
+ };
12
+ return { k, cx: middle(s.w, box.x, box.x + box.w, also?.x, also && also.x + also.w), cy: middle(s.h, box.y, box.y + box.h, also?.y, also && also.y + also.h) };
13
+ }
1
14
  const MIN_ZOOM = 0.1, MAX_ZOOM = 8;
2
15
  function viewport(host, o) {
3
16
  let view, full;
@@ -51,11 +64,9 @@ function viewport(host, o) {
51
64
  view = { x: p.x - (px - r.left) / nk, y: p.y - (py - r.top) / nk, w: s.w / nk, h: s.h / nk };
52
65
  applyView();
53
66
  }
54
- function fit(box = full) {
67
+ function fit(box = full, also) {
55
68
  if (!box) return;
56
- const s = size(), pad = 24;
57
- const k = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min((s.w - pad * 2) / box.w, (s.h - pad * 2) / box.h)));
58
- const cx = box.x + box.w / 2, cy = box.y + box.h / 2;
69
+ const s = size(), { k, cx, cy } = fitted(s, box, also);
59
70
  const next = { x: cx - s.w / k / 2, y: cy - s.h / k / 2, w: s.w / k, h: s.h / k };
60
71
  if (view && Math.abs(next.w / view.w - 1) < 1e-3 && Math.abs(next.h / view.h - 1) < 1e-3 && Math.abs(next.x - view.x) < next.w * 1e-3 && Math.abs(next.y - view.y) < next.h * 1e-3) {
61
72
  applyView();
@@ -72,7 +83,7 @@ function viewport(host, o) {
72
83
  if (key === last) break;
73
84
  last = key;
74
85
  const m = Math.max(24, Math.min(b.w, b.h) * 0.06);
75
- quietly(() => fit({ x: b.x - m, y: b.y - m, w: b.w + m * 2, h: b.h + m * 2 }));
86
+ quietly(() => fit({ x: b.x - m, y: b.y - m, w: b.w + m * 2, h: b.h + m * 2 }, o.alsoBox?.()));
76
87
  if (!o.marksShowing() || !paintedK || Math.abs(scale() / paintedK - 1) <= 0.02) break;
77
88
  cancelAnimationFrame(rezoom);
78
89
  rezoom = 0;
@@ -173,5 +184,6 @@ function viewport(host, o) {
173
184
  export {
174
185
  MAX_ZOOM,
175
186
  MIN_ZOOM,
187
+ fitted,
176
188
  viewport
177
189
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnoscott/isometric-engine",
3
- "version": "0.12.3",
3
+ "version": "0.12.6",
4
4
  "description": "A generic isometric diagram engine: render (L0–L2) and editor (L0–L3), with a 2D view and a YAML diagram format.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -132,6 +132,15 @@ export function commandsFor(a: CommandsAdapter) {
132
132
  const quote = now[0] === '"' || now[0] === "'" ? now[0] : undefined;
133
133
  edits.push({ start: range[0], end: range[1], text: quote === '"' ? JSON.stringify(v) : quote === "'" ? `'${v}'` : scalarText(v, { flow: true, indent: 0 }) });
134
134
  }
135
+ // (0.12.5) its pin is keyed by its name: it follows (a domain whose references include the pins has done it), so the
136
+ // thing stays where it was put. Not over a pin there already.
137
+ const data = dataOf(t) as Record<string, { layout?: Record<string, unknown> } | null> | undefined;
138
+ for (const k of [a.pins.key, a.pins.legacyKey]) {
139
+ const layout = k === undefined ? undefined : data?.[k]?.layout;
140
+ if (!layout || typeof layout !== 'object' || !Object.hasOwn(layout, from) || Object.hasOwn(layout, to)) continue;
141
+ const range = d.rangeOf([k!, 'layout', from], 'key');
142
+ 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 }) });
143
+ }
135
144
  return { steps: [edits] };
136
145
  },
137
146
  };
@@ -0,0 +1,28 @@
1
+ // Which of a drawing's routes are connections of the file's own: a route whose path is an entry of its own (not an object,
2
+ // not a key inside one, not a whole section), that nothing else in the drawing stands for. Only these are offered as
3
+ // connections (a wider place to click, the keyboard): elsewhere a route shows an object, or one of its settings. Pure.
4
+
5
+ import { fromPointer } from './path.ts';
6
+
7
+ /** path → route id, in the file's order as the drawing maps it */
8
+ export function connectionsOf(pathOf: ReadonlyMap<string, string>, isRoute: (id: string) => boolean, objectOf: (ptr: string) => unknown): Map<string, string> {
9
+ const uses = new Map<string, number>();
10
+ for (const p of pathOf.values()) uses.set(p, (uses.get(p) ?? 0) + 1);
11
+ const out = new Map<string, string>();
12
+ for (const [id, p] of pathOf) if (isRoute(id) && uses.get(p) === 1 && fromPointer(p).length >= 2 && objectOf(p) === undefined) out.set(p, id);
13
+ return out;
14
+ }
15
+
16
+ /** the nearest point of a polyline path ("M x,y L x,y …", the numbers taken in pairs) to a point */
17
+ export function nearestOn(d: string, x: number, y: number): { x: number; y: number; dist: number } | undefined {
18
+ const n = (d.match(/-?\d*\.?\d+(?:e-?\d+)?/gi) ?? []).map(Number), pts: [number, number][] = [];
19
+ for (let i = 0; i + 1 < n.length; i += 2) pts.push([n[i], n[i + 1]]);
20
+ let best: { x: number; y: number; dist: number } | undefined;
21
+ for (let i = 0; i + 1 < pts.length; i++) {
22
+ const [ax, ay] = pts[i], [bx, by] = pts[i + 1], l2 = (bx - ax) ** 2 + (by - ay) ** 2;
23
+ const t = l2 ? Math.max(0, Math.min(1, ((x - ax) * (bx - ax) + (y - ay) * (by - ay)) / l2)) : 0;
24
+ const px = ax + (bx - ax) * t, py = ay + (by - ay) * t, dist = Math.hypot(px - x, py - y);
25
+ if (!best || dist < best.dist) best = { x: px, y: py, dist };
26
+ }
27
+ return best;
28
+ }