@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
@@ -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();
@@ -0,0 +1,53 @@
1
+ import { buildSvg } from "../../iso-core/svg-dom.js";
2
+ import { boxSilhouette } from "../../iso-objects/geometry.js";
3
+ import { applyStep } from "../splice.js";
4
+ import { h } from "./icons.js";
5
+ const paletteLooks = (K) => (palette, data, ui, theme) => {
6
+ palette.classList.add("looks");
7
+ let soon = 0;
8
+ return function draw() {
9
+ if (soon) return;
10
+ soon = window.setTimeout(() => {
11
+ soon = 0;
12
+ const b = [...palette.querySelectorAll(".pal-item:not([data-look])")].find((q) => !q.hidden && !q.closest("[hidden]")), d = data();
13
+ if (!b || !d) return;
14
+ const s = lookOf(K, ui.palette[Number(b.dataset.entry)], d, theme);
15
+ b.dataset.look = s ? "object" : "icon";
16
+ if (s) b.querySelector(".icon")?.replaceWith(h("span", { class: `${ui.rootClass} pal-look` }, s));
17
+ draw();
18
+ }, 0);
19
+ };
20
+ };
21
+ function lookOf(K, item, data, theme) {
22
+ const k = K.kinds.find((x) => x.kind === item.kind);
23
+ if (!k) return void 0;
24
+ const name = K.commands.freshName("", item.name ?? k.singular), path = [...k.section, name];
25
+ const bare = Object.entries(data ?? {}).filter(([, v]) => v === null || typeof v !== "object").map(([n, v]) => `${JSON.stringify(n)}: ${JSON.stringify(v)}
26
+ `).join("");
27
+ let d;
28
+ try {
29
+ d = K.trial(K.commands.insertCmd(path.slice(0, -1), name, item.value?.() ?? k.template()).build(bare).steps.reduce((t, st) => applyStep(t, st), bare), theme);
30
+ } catch {
31
+ }
32
+ const id = d?.pinId.get(name), it = id ? d.scene.layout.byId.get(id) : void 0;
33
+ if (!d || d.diags.length || !id || !it) return void 0;
34
+ const s = buildSvg(d.svg), all = [...s.querySelectorAll("[data-id]")];
35
+ if (!all.some((e) => e.getAttribute("data-id") === id)) return void 0;
36
+ for (const e of all) if (e.getAttribute("data-id") !== id) e.remove();
37
+ for (const e of s.querySelectorAll("text, title, desc, .g-labels, .g-floor")) e.remove();
38
+ const pts = boxSilhouette(it.box), xs = pts.map((q) => q[0]), ys = pts.map((q) => q[1]), m = 3;
39
+ s.setAttribute("viewBox", [Math.min(...xs) - m, Math.min(...ys) - m, Math.max(...xs) - Math.min(...xs) + 2 * m, Math.max(...ys) - Math.min(...ys) + 2 * m].map((v) => v.toFixed(1)).join(" "));
40
+ for (const a of ["width", "height", "role", "tabindex", "aria-label"]) s.removeAttribute(a);
41
+ for (const e of s.querySelectorAll("[tabindex]")) {
42
+ e.removeAttribute("tabindex");
43
+ e.removeAttribute("role");
44
+ }
45
+ s.setAttribute("preserveAspectRatio", "xMidYMid meet");
46
+ s.setAttribute("aria-hidden", "true");
47
+ s.setAttribute("focusable", "false");
48
+ s.classList.add("pal-scene");
49
+ return s;
50
+ }
51
+ export {
52
+ paletteLooks
53
+ };
@@ -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
+ };
@@ -1,3 +1,4 @@
1
+ import { paletteLooks } from "./palette-look.js";
1
2
  import { toPointer } from "../path.js";
2
3
  import { outline } from "../outline.js";
3
4
  import { commandsFor } from "../commands.js";
@@ -78,6 +79,8 @@ function setupFor(a, v, textPane) {
78
79
  newOrder: a.kinds.map((k) => k.kind),
79
80
  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
81
  ...v.paletteLayout === void 0 ? {} : { paletteLayout: v.paletteLayout },
82
+ ...v.doubleClick === void 0 ? {} : { doubleClick: v.doubleClick },
83
+ ...v.dragMotion === void 0 ? {} : { dragMotion: v.dragMotion },
81
84
  text: {
82
85
  stage: "The file, drawn: arrow keys and Tab move through what is drawn; + and \u2212 zoom, 0 fits",
83
86
  dragGroup: "A drag on nothing",
@@ -108,6 +111,7 @@ function setupFor(a, v, textPane) {
108
111
  return r.read === void 0 || r.diags.some((d) => d.severity === "error") ? void 0 : v.draw(r.read, r.read.data, theme);
109
112
  }
110
113
  };
114
+ if (v.paletteLook === "object") canvas.looks = paletteLooks(canvas);
111
115
  const kit = {
112
116
  async check(text) {
113
117
  const r = analyse(a, text, { fileName: v.fileName });
@@ -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.14.1",
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
+ }
@@ -0,0 +1,89 @@
1
+ // Making way for a dragged thing: which of the things beside it would step aside, and where to. Pure arithmetic on boxes in the
2
+ // container's own grid; the canvas says when (its dwell) and draws it (ui/drag-way.ts).
3
+ // - Only what the dragged thing's cells overlap, and what those then overlap, moves: at most MAX_CHAIN things, all the same way.
4
+ // - The fewest whole cells; among equals, the way the dragged thing was going; never back towards where it came from.
5
+ // - Clear of everything else and of the dragged thing, inside the container's margin. If there is no such place, undefined.
6
+
7
+ /** a drop that overlaps waits this long on one cell before anything shows (ms) */
8
+ export const DWELL_HINT = 150;
9
+ /** and this long, from the same start, before the things in its way give way (ms) */
10
+ export const DWELL_GIVE = 700;
11
+ /** what gave way goes back this long after the dragged thing no longer needs the place (ms) */
12
+ export const BACK_AFTER = 250;
13
+ /** a thing's glide to its place, or back (ms) */
14
+ export const GLIDE = 180;
15
+ /** the jiggle: how far (screen px), and how often (a second) */
16
+ export const JIGGLE = { px: 1.5, hz: 8 };
17
+ /** the most things that may step aside for one drop */
18
+ export const MAX_CHAIN = 3;
19
+
20
+ export interface Rect { x0: number; y0: number; x1: number; y1: number }
21
+ export interface Beside extends Rect {
22
+ id: string;
23
+ /** whether it may be pinned somewhere else */
24
+ movable: boolean;
25
+ }
26
+ export interface WayOptions {
27
+ /** where the dragged thing would be */
28
+ foot: Rect;
29
+ /** everything else in the container */
30
+ others: Beside[];
31
+ /** the way it was going: its last step, or from where it started */
32
+ going: [number, number];
33
+ /** what a thing that steps aside must stay in (the container, less its margin); none: anywhere */
34
+ bounds?: Rect;
35
+ max?: number;
36
+ }
37
+
38
+ const E = 1e-6;
39
+ export const hits = (a: Rect, b: Rect) => a.x0 < b.x1 - E && a.x1 > b.x0 + E && a.y0 < b.y1 - E && a.y1 > b.y0 + E;
40
+ const at = (b: Rect, [dx, dy]: [number, number]): Rect => ({ x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy });
41
+
42
+ /** The steps (whole cells) of what would move, by id; undefined: nothing can make way. */
43
+ export function makeWay({ foot, others, going, bounds, max = MAX_CHAIN }: WayOptions): Map<string, [number, number]> | undefined {
44
+ const first = others.filter(o => hits(o, foot));
45
+ if (!first.length) return new Map();
46
+ if (first.some(o => !o.movable)) return undefined;
47
+ const ways: [number, number][] = [[1, 0], [-1, 0], [0, 1], [0, -1]];
48
+ let best: { steps: Map<string, [number, number]>; cells: number; along: number } | undefined;
49
+ for (const w of ways) {
50
+ const along = w[0] * going[0] + w[1] * going[1];
51
+ // back to where it came from: against its larger component
52
+ if (along < 0 && Math.abs(along) >= Math.max(Math.abs(going[0]), Math.abs(going[1])) - E) continue;
53
+ const steps = push(foot, others, w, bounds, max);
54
+ if (!steps) continue;
55
+ const cells = [...steps.values()].reduce((n, [dx, dy]) => n + Math.abs(dx) + Math.abs(dy), 0);
56
+ if (!best || cells < best.cells || (cells === best.cells && along > best.along + E)) best = { steps, cells, along };
57
+ }
58
+ return best?.steps;
59
+ }
60
+ /** all that is in the way, pushed one way by whole cells until each is clear of what pushes it */
61
+ function push(foot: Rect, others: Beside[], w: [number, number], bounds: Rect | undefined, max: number): Map<string, [number, number]> | undefined {
62
+ const far = new Map<string, number>(); // cells, by id
63
+ const byId = new Map<string, Beside>(others.map(o => [o.id, o]));
64
+ const boxOf = (o: Beside) => at(o, [w[0] * (far.get(o.id) ?? 0), w[1] * (far.get(o.id) ?? 0)]);
65
+ // what pushes: the dragged thing first, then each that moved (again, if it moved again)
66
+ const queue: (string | undefined)[] = [undefined];
67
+ for (let guard = 0; queue.length; guard++) {
68
+ if (guard > 100) return undefined;
69
+ const id = queue.shift(), by = id === undefined ? foot : boxOf(byId.get(id)!);
70
+ for (const o of others) {
71
+ if (o.id === id) continue;
72
+ const b = boxOf(o);
73
+ if (!hits(b, by)) continue;
74
+ if (!o.movable) return undefined;
75
+ const gap = w[0] > 0 ? by.x1 - b.x0 : w[0] < 0 ? b.x1 - by.x0 : w[1] > 0 ? by.y1 - b.y0 : b.y1 - by.y0;
76
+ far.set(o.id, (far.get(o.id) ?? 0) + Math.max(1, Math.ceil(gap - E)));
77
+ if (far.size > max) return undefined;
78
+ if (!queue.includes(o.id)) queue.push(o.id);
79
+ }
80
+ }
81
+ const steps = new Map([...far].map(([id, n]) => [id, [w[0] * n, w[1] * n] as [number, number]]));
82
+ // clear of everything, the dragged thing too, and inside
83
+ for (const id of steps.keys()) {
84
+ const o = byId.get(id)!, b = boxOf(o);
85
+ if (hits(b, foot) || others.some(q => q.id !== id && hits(b, boxOf(q)))) return undefined;
86
+ if (bounds && (b.x0 < bounds.x0 - E || b.y0 < bounds.y0 - E || b.x1 > bounds.x1 + E || b.y1 > bounds.y1 + E)) return undefined;
87
+ }
88
+ return steps;
89
+ }
@@ -16,6 +16,8 @@ export interface Command {
16
16
  build(text: string): Splice;
17
17
  /** the paths it touched (for the views to refresh and reveal) */
18
18
  touched?: Path[];
19
+ /** (0.12.5) the label of the step it joined (apply's `joins`), given the step's own */
20
+ joined?(label: string): string;
19
21
  /** where a path is after the change (a rename moves paths); null when it no longer exists */
20
22
  remap?(p: Path): Path | null;
21
23
  /** the selection afterwards (default: the old one, remapped) */
@@ -119,8 +121,10 @@ export class EditorModel {
119
121
 
120
122
  // ---------- doing ----------
121
123
 
122
- /** Run a command: build it against the text, apply its steps, push it. Returns false if it changed nothing. */
123
- apply(cmd: Command, origin: Origin = 'api'): boolean {
124
+ /** Run a command: build it against the text, apply its steps, push it. Returns false if it changed nothing. `joins`
125
+ * (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
126
+ * wasn't saved at it (the saved text must stay a step of its own to come back to). */
127
+ apply(cmd: Command, origin: Origin = 'api', joins?: number): boolean {
124
128
  this.seal();
125
129
  const splice = cmd.build(this._text);
126
130
  if (!splice.steps.some(s => s.length)) return false;
@@ -129,7 +133,15 @@ export class EditorModel {
129
133
  const remap = cmd.remap ?? ((p: Path) => p);
130
134
  this.selection = cmd.select ?? this.selection.map(remap).filter((p): p is Path => p !== null);
131
135
  if (splice.fallback) this.fallbacks++;
132
- 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 });
136
+ const top = this.undoStack[this.undoStack.length - 1];
137
+ if (top && joins !== undefined && top.id === joins && !this.redoStack.length && top.id !== this.cleanId) {
138
+ top.label = cmd.joined?.(top.label) ?? top.label;
139
+ top.steps.push(...splice.steps);
140
+ top.inverse.unshift(...inverse);
141
+ top.after = { paths: this.selection, text: this.textSel };
142
+ top.time = this.now();
143
+ top.fallback ||= !!splice.fallback;
144
+ } 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 });
133
145
  this.emit({ kind: 'do', origin, label: cmd.label, steps: splice.steps, version: this._version, remap: cmd.remap });
134
146
  for (const fn of this.selListeners) fn({ paths: this.selection, origin });
135
147
  return true;
@@ -196,6 +208,8 @@ export class EditorModel {
196
208
 
197
209
  get canUndo() { return this.undoStack.length > 0; }
198
210
  get canRedo() { return this.redoStack.length > 0; }
211
+ /** the last undo step's id (what `apply` may join) */
212
+ get undoId() { return this.undoStack[this.undoStack.length - 1]?.id; }
199
213
  get undoLabel() { return this.undoStack[this.undoStack.length - 1]?.label; }
200
214
  get redoLabel() { return this.redoStack[this.redoStack.length - 1]?.label; }
201
215
 
@@ -1,10 +1,11 @@
1
1
  // Actions the canvas and the properties panel share (the tree has its own inline forms of the same commands): delete
2
- // with a references dialog, rename in a dialog, duplicate, select connected. What an object is and how it is named
2
+ // with a references dialog, rename in the inline field, duplicate, select connected. What an object is and how it is named
3
3
  // are the kit's (the domain's commands, objectOf, kinds and name rule); what each kind offers in its own menu is the
4
4
  // domain's too.
5
5
 
6
6
  import { h } from './icons.ts';
7
7
  import { ask } from './dialog.ts';
8
+ import { renameField, type RenameAt } from './rename.ts';
8
9
  import type { EditorModel, Command } from '../model.ts';
9
10
  import type { Commands } from '../commands.ts';
10
11
  import type { ObjectKindInfo, ObjectRef } from '../adapter.ts';
@@ -23,8 +24,8 @@ export interface ActionsKit {
23
24
  nameHint: string;
24
25
  }
25
26
 
26
- export function run(doc: EditorModel, c: Command, origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void): boolean {
27
- try { return doc.apply(c, origin); } catch (e) { note?.(String((e as Error).message), 'bad'); return false; }
27
+ export function run(doc: EditorModel, c: Command, origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void, joins?: number): boolean {
28
+ try { return doc.apply(c, origin, joins); } catch (e) { note?.(String((e as Error).message), 'bad'); return false; }
28
29
  }
29
30
 
30
31
  /** Several commands as one undo step. */
@@ -68,26 +69,22 @@ async function deletePaths(doc: EditorModel, paths: Path[], origin: 'canvas' | '
68
69
  return ok;
69
70
  }
70
71
 
71
- /** Rename in a dialog (the canvas has no inline field). */
72
- async function renameDialog(doc: EditorModel, path: Path, origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void): Promise<boolean> {
73
- const now = String(path[path.length - 1]);
74
- const input = h('input', { type: 'text', value: now, 'aria-label': 'New name', spellcheck: 'false', autocomplete: 'off', class: 'mono-input' });
75
- input.value = now;
76
- const why = h('p', { class: 'dlg-error', role: 'alert' });
72
+ /** Rename, in the inline field (rename.ts). `joins`: the undo step it becomes part of (an add's, so a drop and its name
73
+ * are one), when that is still the last one. */
74
+ async function rename(doc: EditorModel, path: Path, origin: 'canvas' | 'props' | 'menu', note: ((t: string, tone?: 'bad') => void) | undefined, at: RenameAt & { joins?: number }): Promise<boolean> {
75
+ const now = String(path[path.length - 1]), res = isRes(path);
76
+ let here: Path | null = path;
77
+ const off = doc.on(c => { if (here && c.remap) here = c.remap(here); });
77
78
  const used = () => kit.kinds.flatMap(k => Object.keys((getIn(doc.goodDoc.data, k.section) ?? {}) as Raw));
78
- const check = () => {
79
- const v = input.value.trim();
80
- const bad = !kit.nameRule.test(v) && isRes(path) ? kit.nameHint : v !== now && used().includes(v) ? `"${v}" is already used` : '';
81
- why.textContent = bad;
82
- return bad ? undefined : v;
83
- };
84
- input.addEventListener('input', check);
85
- 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 }]);
86
- setTimeout(() => { input.focus(); input.select(); }, 0);
87
- if (await go !== 'ok') return false;
88
- const v = check();
89
- if (!v || v === now) return false;
90
- return run(doc, isRes(path) ? renameCmd(path, v) : renameKeyCmd(path, v), origin, note);
79
+ let ok = false;
80
+ await renameField({
81
+ label: `Rename ${describe(path)}`, value: now,
82
+ wrong: v => (!v ? 'A name is needed' : v === now ? '' : res && !kit.nameRule.test(v) ? kit.nameHint : used().includes(v) ? `"${v}" is already used` : ''),
83
+ alive: () => !!here && getIn(doc.goodDoc.data, here) !== undefined,
84
+ commit: v => { if (here) ok = run(doc, { ...(res ? renameCmd(here, v) : renameKeyCmd(here, v)), joined: l => l.replace(` ${now}`, ` ${v}`) }, origin, note, at.joins); },
85
+ }, at);
86
+ off();
87
+ return ok;
91
88
  }
92
89
 
93
90
  const duplicate = (doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void) => {
@@ -114,6 +111,6 @@ function connected(doc: EditorModel, paths: Path[]): Path[] {
114
111
  return [...out.values()];
115
112
  }
116
113
 
117
- return { deletePaths, renameDialog, duplicate, connected };
114
+ return { deletePaths, rename, duplicate, connected };
118
115
  }
119
116
  export type Actions = ReturnType<typeof actionsFor>;
@@ -95,6 +95,12 @@ body[data-view="text"] .status .hint-mode { display: none; }
95
95
  .chip-add { width: auto !important; min-width: 80px; }
96
96
  .props-delete { margin-top: var(--sp-4); align-self: flex-start; }
97
97
  .mono-input { font-family: var(--mono); }
98
+ .rename-field { position: fixed; z-index: var(--z-menu); }
99
+ .rename-field > .rename-input { display: block; width: auto; max-width: calc(100vw - 16px); height: 26px; min-height: 26px; padding: 0 var(--sp-2); font-family: var(--mono); font-size: var(--fs-mono); text-align: center; box-shadow: var(--shadow-3); }
100
+ .rename-field.over > .rename-input { text-align: left; }
101
+ .rename-field > .rename-input[aria-invalid="true"] { border-color: var(--bad); }
102
+ .rename-field > .rename-error { position: absolute; top: 100%; left: 50%; translate: -50% 4px; width: max-content; max-width: 280px; margin: 0; padding: var(--sp-1) var(--sp-2); background: var(--surface); border: var(--bw) solid var(--bad); border-radius: var(--r-md); color: var(--bad); font-size: var(--fs-sm); line-height: 1.35; box-shadow: var(--shadow-2); }
103
+ .rename-field > .rename-error:empty { display: none; }
98
104
  #se-grip { height: 6px; margin: -3px 0; cursor: row-resize; z-index: 2; position: relative; }
99
105
  #se-grip:hover, #se-grip:focus-visible { background: color-mix(in srgb, var(--accent) 30%, transparent); }
100
106
  #se-problems { height: var(--problems-h, 160px); flex: none; overflow: auto; border-top: var(--bw) solid var(--line); background: var(--bg); font-size: var(--fs-sm); }
@@ -254,6 +260,10 @@ body.read-only .palette { display: none; }
254
260
  .pal-grip { flex: none; width: 6px; margin: 0 -3px; cursor: col-resize; z-index: 3; position: relative; }
255
261
  .pal-grip:hover, .pal-grip:focus-visible { background: color-mix(in srgb, var(--accent) 30%, transparent); outline: 0; }
256
262
  body.read-only .pal-dock, body.read-only .pal-grip { display: none; }
263
+ .palette.looks .pal-item { height: auto; min-height: 40px; }
264
+ .palette.looks .pal-look { display: block; flex: 0 0 44px; width: 44px; height: 36px; margin: 0; padding: 0; background: none; pointer-events: none; overflow: hidden; }
265
+ .palette.looks .pal-scene { display: block; width: 100%; height: 100%; }
266
+ .palette.looks .pal-item > .icon { margin: 0 15px; }
257
267
  .pal-ghost { position: absolute; z-index: 5; pointer-events: none; display: flex; align-items: center; gap: var(--sp-1); padding: 2px var(--sp-2); border: var(--bw) solid var(--accent); border-radius: var(--r-sm); background: var(--surface); color: var(--ink); font-size: var(--fs-sm); box-shadow: var(--shadow-2, none); }
258
268
  .pal-ghost .icon { width: 14px; height: 14px; }
259
269
  .pal-ghost.bad { border-color: var(--bad); color: var(--bad); }