@johnoscott/isometric-engine 0.9.0 → 0.10.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.
@@ -22,7 +22,7 @@ import type { EditorModel, Command } from '../model.ts';
22
22
  import type { Problem } from '../validate.ts';
23
23
  import { applyStep } from '../splice.ts';
24
24
  import { seqCmd, type Commands } from '../commands.ts';
25
- import type { ObjectKindInfo, ObjectRef } from '../adapter.ts';
25
+ import type { ObjectKindInfo, ObjectRef, ConnectPlan, GroupPlan } from '../adapter.ts';
26
26
  import { fromPointer, toPointer, type Path } from '../path.ts';
27
27
  import { buildSvg } from '../../iso-core/svg-dom.ts';
28
28
  import { viewport, type View } from '../../iso-viewer/viewport.ts';
@@ -74,13 +74,16 @@ export interface CanvasUi {
74
74
  rootClass: string; panKeyClass: string;
75
75
  /** the kinds the canvas's menu offers, in order */
76
76
  newOrder: string[];
77
- palette: { kind: string; icon: IconName; label: string }[];
77
+ /** the palette's entries: a kind, and (0.10.0) a preset: what a new one starts as (default: the kind's template) and
78
+ * the base of its fresh name (default: the kind's singular) */
79
+ palette: PaletteItem[];
78
80
  text: {
79
81
  stage: string; dragGroup: string; dragSelectTip: string; unreadable: string; palette: string;
80
82
  /** the end of a pin drag's hint */
81
83
  pinHint: string; renameWhy: string; duplicateWhy: string;
82
84
  };
83
85
  }
86
+ export interface PaletteItem { kind: string; icon: IconName; label: string; value?(): unknown; name?: string }
84
87
  /** what the canvas is given of the domain (M: the domain's reading of the file; D: its drawing) */
85
88
  export interface CanvasKit<M, D extends CanvasDrawing> {
86
89
  draw(model: M, data: unknown, theme: string): D;
@@ -89,7 +92,14 @@ export interface CanvasKit<M, D extends CanvasDrawing> {
89
92
  catalog: KindCatalog;
90
93
  objectOf(ptr: string): ObjectRef | undefined;
91
94
  kinds: ObjectKindInfo[];
92
- commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertCmd' | 'pinsCmd' | 'withPinsMoved' | 'describe' | 'freshName'>;
95
+ commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertCmd' | 'insertItemCmd' | 'pinsCmd' | 'withPinsMoved' | 'describe' | 'freshName'>;
96
+ /** (0.10.0) a connection drawn from one object to another (the adapter's connect): the canvas offers the gesture (a
97
+ * handle on a selected object, and "Connect to…") only when it is given */
98
+ connect?(from: ObjectRef, to: ObjectRef, data: unknown): ConnectPlan | undefined;
99
+ /** (0.10.1) a palette drop onto an object (the adapter's dropInto): the new thing inside it, asked innermost first */
100
+ dropOnto?(target: ObjectRef, value: unknown, kind: string, data: unknown): { value: unknown; label?: string } | undefined;
101
+ /** (0.10.0) the selection made into a new container (the adapter's group): Group, ⌘G, one undo step */
102
+ group?(members: ObjectRef[], data: unknown): GroupPlan | undefined;
93
103
  actions: Actions;
94
104
  /** what an object's own menu offers, beyond rename, duplicate and delete */
95
105
  objectItems(doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void): MenuItem[];
@@ -130,11 +140,14 @@ const SVGNS = 'http://www.w3.org/2000/svg';
130
140
 
131
141
  export function canvasView<M, D extends CanvasDrawing, A extends object = object>(host: HTMLElement, doc: EditorModel, opts: CanvasOpts<M, D, A>) {
132
142
  const K = opts.kit, ui = K.ui, T = ui.text;
133
- const { setCmd, deleteCmd, insertCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
143
+ const { setCmd, deleteCmd, insertCmd, insertItemCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
134
144
  const { deletePaths, renameDialog, duplicate, connected } = K.actions;
135
145
  const resourceOf = (ptr: string) => K.objectOf(ptr);
136
146
  const kindOf = (k: string) => K.kinds.find(x => x.kind === k)!;
137
147
  const PINS_KEY = K.pins.key;
148
+ /** (0.10.0) a connection being drawn: from what, the pointer (in the drawing's coordinates), what it is over; `pick`:
149
+ * started from the menu, so the next click ends it */
150
+ let linking: { from: ObjectRef; x?: number; y?: number; over?: string; pick?: boolean } | undefined;
138
151
  host.classList.add('canvas');
139
152
  // the stage holds the drawing, and takes the focus, the keys and the pointer
140
153
  const stage = h('div', { class: `${ui.rootClass} canvas-stage`, tabindex: '0', role: 'application', 'aria-label': T.stage });
@@ -438,6 +451,31 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
438
451
  };
439
452
  if (hoverId !== undefined && !doc.selection.some(p => toPointer(p) === hoverId)) draw(hoverId, 'hover');
440
453
  for (const p of doc.selection) draw(toPointer(p), 'ring');
454
+ // (0.10.0) connecting: a handle on the one selected object, and while a connection is drawn, its line and its target
455
+ const one = connectable();
456
+ const from = linking?.from ?? one;
457
+ const fb = from ? boxFor(fromPointer(from.path)) : undefined;
458
+ if (fb && K.connect) {
459
+ const k = scale(), hx = fb.x + fb.w + 10 / k, hy = fb.y + fb.h / 2;
460
+ if (linking && linking.x !== undefined && linking.y !== undefined) {
461
+ if (linking.over) draw(linking.over, 'hover');
462
+ const l = d.createElementNS(SVGNS, 'line');
463
+ l.setAttribute('class', `connect-line${linking.over ? ' ok' : ''}`);
464
+ l.setAttribute('x1', String(hx)); l.setAttribute('y1', String(hy)); l.setAttribute('x2', String(linking.x)); l.setAttribute('y2', String(linking.y));
465
+ overlay.append(l);
466
+ }
467
+ if (!linking) {
468
+ const c = d.createElementNS(SVGNS, 'circle');
469
+ c.setAttribute('class', 'connect-handle');
470
+ c.setAttribute('cx', String(hx)); c.setAttribute('cy', String(hy)); c.setAttribute('r', String(7 / k));
471
+ // the one mark that takes the pointer (through the CSSOM: a host's marks CSS may say none for the overlay)
472
+ c.style.pointerEvents = 'all'; c.style.cursor = 'crosshair';
473
+ const t = d.createElementNS(SVGNS, 'title');
474
+ t.textContent = `Drag to what ${from!.name} connects to`;
475
+ c.append(t);
476
+ overlay.append(c);
477
+ }
478
+ }
441
479
  // a badge on each drawn resource with problems
442
480
  const counts = new Map<string, { e: number; w: number }>();
443
481
  for (const pr of opts.problems()) {
@@ -497,6 +535,12 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
497
535
  stage.focus({ preventScroll: true });
498
536
  if (layer?.down?.(e)) return;
499
537
  const { x, y } = pageXY(e);
538
+ // (0.10.0) a press on the connect handle starts a connection; a click while one is picked ends it
539
+ if (e.button === 0 && linking?.pick) { e.preventDefault(); endConnect(pathAtEvent(e.target)); return; }
540
+ if (e.button === 0 && (e.target as Element | null)?.closest?.('.connect-handle')) {
541
+ const one = connectable();
542
+ if (one) { capture(e); e.preventDefault(); const p = toSvg(x, y); linking = { from: one, x: p.x, y: p.y }; paintOverlay(); return; }
543
+ }
500
544
  if (e.button === 0 || e.button === 1) capture(e);
501
545
  const pan = () => { drag = { kind: 'pan', x0: x, y0: y, v0: { ...V.view! } }; svg?.classList.add('panning'); e.preventDefault(); };
502
546
  if (e.button === 1 || spaceKeyDown) { pan(); return; }
@@ -540,6 +584,13 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
540
584
  }
541
585
  function move(e: PointerEvent) {
542
586
  const { x, y } = pageXY(e);
587
+ if (linking) {
588
+ const p = toSvg(x, y), under = pathAtEvent(document.elementFromPoint(x, y));
589
+ const r = under === undefined ? undefined : resourceOf(under);
590
+ linking = { ...linking, x: p.x, y: p.y, over: r && r.path !== linking.from.path ? r.path : undefined };
591
+ paintOverlay();
592
+ return;
593
+ }
543
594
  if (!drag) {
544
595
  const p = pathAtEvent(e.target);
545
596
  if (p !== hoverId) { hoverId = p; paintOverlay(); }
@@ -753,6 +804,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
753
804
  }
754
805
 
755
806
  function up(e: PointerEvent) {
807
+ if (linking && !linking.pick) { const { x, y } = pageXY(e); endConnect(pathAtEvent(document.elementFromPoint(x, y))); return; }
756
808
  const d0 = drag;
757
809
  drag = undefined;
758
810
  svg?.classList.remove('panning');
@@ -840,6 +892,9 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
840
892
  items.push({ label: 'Show in text', icon: 'code-xml', onSelect: () => opts.showInText(one) });
841
893
  items.push({ label: 'Show in tree', icon: 'list-tree', onSelect: () => opts.showInTree(one) });
842
894
  }
895
+ // (0.10.0) connect and group, where the domain says how
896
+ if (K.connect && one && isRes) items.push({ label: 'Connect to…', icon: 'link', desc: 'Then click what it connects to (Esc cancels)', disabled: ro, onSelect: () => startPick() });
897
+ if (K.group) items.push({ label: sel.length > 1 ? `Group ${sel.length} items` : 'Group', icon: 'box', keys: '⌘G', desc: 'Into a new container, as one step', disabled: ro || !members().length, why: 'Only objects are grouped', onSelect: groupSelection });
843
898
  items.push({ label: 'Select parent', icon: 'arrow-up-right', keys: '⌘↑', onSelect: selectParent });
844
899
  items.push({ label: 'Select connected', icon: 'link', desc: 'What refers to it, and what it refers to', onSelect: () => doc.select(connected(doc, sel), 'canvas') });
845
900
  items.push({ label: 'Zoom to selection', keys: '⇧2', onSelect: zoomToSelection });
@@ -847,6 +902,66 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
847
902
  items.push({ sep: true }, { label: sel.length > 1 ? `Delete ${sel.length} items` : 'Delete', icon: 'trash-2', keys: '⌫', danger: true, disabled: ro, onSelect: () => deletePaths(doc, sel, 'canvas', opts.note) });
848
903
  return items;
849
904
  }
905
+ // ---------- (0.10.0) connect and group, by the domain's plans ----------
906
+ /** the one selected object, if the domain connects and the file reads */
907
+ function connectable(): ObjectRef | undefined {
908
+ if (!K.connect || !doc.doc.ok || doc.selection.length !== 1) return undefined;
909
+ const ptr = toPointer(doc.selection[0]), r = resourceOf(ptr);
910
+ return r && r.path === ptr ? r : undefined;
911
+ }
912
+ function startPick() {
913
+ const from = connectable();
914
+ if (!from) return;
915
+ linking = { from, pick: true };
916
+ opts.note(`Click what ${from.name} connects to (Esc cancels)`);
917
+ paintOverlay();
918
+ }
919
+ /** end a connection on what is under the pointer: the domain's plan, written as one step */
920
+ function endConnect(ptr: string | undefined) {
921
+ const from = linking?.from;
922
+ linking = undefined;
923
+ paintOverlay();
924
+ if (!from || ptr === undefined) return;
925
+ const to = resourceOf(ptr);
926
+ if (!to || to.path === from.path) { opts.note('Not connected: drop it on another object', 'warn'); return; }
927
+ const data = doc.goodDoc.data;
928
+ const plan = K.connect?.(from, to, data);
929
+ if (!plan) { opts.note(`${from.name} and ${to.name} can't be connected`, 'warn'); return; }
930
+ const label = plan.label ?? `Connect ${from.name} to ${to.name}`;
931
+ let cmd: Command, path: Path;
932
+ if (plan.name !== undefined) {
933
+ const name = freshName(doc.text, plan.name);
934
+ cmd = insertCmd(plan.at, name, plan.value, { label });
935
+ path = [...plan.at, name];
936
+ } else {
937
+ const list = plan.at.reduce<unknown>((x, k) => (x && typeof x === 'object' ? (x as Record<string, unknown>)[k as string] : undefined), data);
938
+ path = [...plan.at, Array.isArray(list) ? list.length : 0];
939
+ cmd = insertItemCmd(plan.at, plan.value, undefined, label);
940
+ }
941
+ if (run(doc, { ...cmd, select: [path] }, 'canvas', opts.note)) doc.select([path], 'canvas');
942
+ }
943
+ /** the selection's objects (a key inside one counts as its object), once each */
944
+ function members(): ObjectRef[] {
945
+ const out = new Map<string, ObjectRef>();
946
+ for (const p of doc.selection) { const r = resourceOf(toPointer(p)); if (r) out.set(r.path, r); }
947
+ return [...out.values()];
948
+ }
949
+ /** the selection into a new container: the container, each member's change and its pin dropped (the layout places it
950
+ * in its new frame), as one command, one undo step */
951
+ function groupSelection() {
952
+ if (!K.group || !doc.doc.ok) return;
953
+ const ms = members();
954
+ if (!ms.length) { opts.note('Only objects are grouped', 'warn'); return; }
955
+ const plan = K.group(ms, doc.goodDoc.data);
956
+ if (!plan) { opts.note(ms.length > 1 ? `These ${ms.length} can't be grouped` : `${ms[0].name} can't be grouped`, 'warn'); return; }
957
+ const name = freshName(doc.text, plan.name);
958
+ const pins = K.pins.of(doc.goodDoc.data) ?? {};
959
+ const unpin = ms.filter(m => pins[m.name] !== undefined).map(m => withPinsMoved(deleteCmd([PINS_KEY, 'layout', m.name])));
960
+ const label = plan.label ?? `Group ${ms.length > 1 ? `${ms.length} items` : ms[0].name} into ${name}`;
961
+ const p = [...plan.at, name] as Path;
962
+ const cmd = seqCmd(label, [insertCmd(plan.at, name, plan.value, { label }), ...plan.members(name).map(m => setCmd(m.path, m.value)), ...unpin]);
963
+ if (run(doc, { ...cmd, select: [p] }, 'canvas', opts.note)) doc.select([p], 'canvas');
964
+ }
850
965
  function addResource(s: string) {
851
966
  const k = kindOf(s);
852
967
  const name = freshName(doc.text, k.singular);
@@ -898,33 +1013,73 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
898
1013
  }
899
1014
  return undefined;
900
1015
  }
1016
+ /** (0.10.1) the objects whose drawn floor a point is on, innermost first: in 2D the panels under it; in 3D every placed
1017
+ * thing whose floor holds the point, the deepest (then the smallest) first */
1018
+ function objectsUnder(at: { x: number; y: number }): ObjectRef[] {
1019
+ if (!cd) return [];
1020
+ const p = toSvg(at.x, at.y);
1021
+ const refOf = (id: string) => { const ptr = cd!.pathOf.get(id); const r = ptr === undefined ? undefined : resourceOf(ptr); return r && r.path === ptr ? r : undefined; };
1022
+ if (flat) return flat.panelsAt(p.x, p.y).map(refOf).filter((r): r is ObjectRef => !!r);
1023
+ const inside = (poly: [number, number][]) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > p.y) !== (yj > p.y) && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c; } return c; };
1024
+ const depth = (i: { parent?: unknown }) => { let n = 0; for (let q = i.parent as { parent?: unknown } | undefined; q; q = q.parent as { parent?: unknown } | undefined) n++; return n; };
1025
+ // what is drawn under the point, topmost (innermost) first, as the eye sees it; then any whose floor holds the point
1026
+ const seen = new Map<string, ObjectRef>();
1027
+ for (const e of fdoc().elementsFromPoint(at.x, at.y)) {
1028
+ if (!svg?.contains(e)) continue;
1029
+ for (let el = e.closest('[data-id]'); el; el = el.parentElement?.closest('[data-id]') ?? null) {
1030
+ const r = refOf(el.getAttribute('data-id') ?? '');
1031
+ if (r && !seen.has(r.path)) seen.set(r.path, r);
1032
+ }
1033
+ }
1034
+ const hits: { r: ObjectRef; d: number; a: number }[] = [];
1035
+ for (const [, id] of cd.pinId) {
1036
+ const item = cd.scene.layout.byId.get(id), r = refOf(id);
1037
+ if (item && r && !seen.has(r.path) && inside(floorOf(item.box))) hits.push({ r, d: depth(item), a: (item.box.x1 - item.box.x0) * (item.box.y1 - item.box.y0) });
1038
+ }
1039
+ return [...seen.values(), ...hits.sort((x, y) => y.d - x.d || x.a - y.a).map(h => h.r)];
1040
+ }
901
1041
  /** Add an object from the palette: dropped at a point, it is pinned there; dropped on a container the kit names, it
902
1042
  * is made inside it; else the layout places it. One command (one undo step); then it is selected and named. */
903
- function addFromPalette(sec: string, at?: { x: number; y: number }): Path | undefined {
1043
+ function addFromPalette(sec: string, at?: { x: number; y: number }, item?: PaletteItem): Path | undefined {
904
1044
  if (!doc.doc.ok) { opts.note('Fix the YAML first', 'warn'); return undefined; }
905
1045
  const k = kindOf(sec);
906
- const name = freshName(doc.text, k.singular);
1046
+ // (0.10.0) a palette entry's preset: what it starts as, and the base of its name
1047
+ const preset = item?.value?.() as Record<string, unknown> | undefined;
1048
+ const what = item && preset !== undefined ? item.label.toLowerCase() : k.singular;
1049
+ const name = freshName(doc.text, item?.name ?? k.singular);
907
1050
  const p = [...k.section, name] as Path;
908
- let value = k.template() as Record<string, unknown>;
1051
+ let value = (preset ?? k.template()) as Record<string, unknown>;
909
1052
  let into: string | undefined;
910
1053
  const drop = at ? K.dropInto?.(sec) : undefined;
911
1054
  if (at && drop) {
912
1055
  const c = containerAt(drop.container, at);
913
- if (c) { into = c; value = drop.value(c) as Record<string, unknown>; }
1056
+ // dropped into a container: what puts it there, and the preset's own keys over it
1057
+ if (c) { into = c; value = { ...(drop.value(c) as Record<string, unknown>), ...(preset ?? {}) }; }
1058
+ }
1059
+ let intoLabel = into ? drop!.label(into) : '';
1060
+ // (0.10.1) the domain's rule: the innermost object under the drop that holds it
1061
+ if (at && !into && K.dropOnto) {
1062
+ for (const t of objectsUnder(at)) {
1063
+ const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
1064
+ if (plan) { into = t.name; value = plan.value as Record<string, unknown>; intoLabel = plan.label ? ` ${plan.label}` : ` in ${t.name}`; break; }
1065
+ }
914
1066
  }
915
- const label = `Add ${k.singular} ${name}${into ? drop!.label(into) : ''}`;
1067
+ const label = `Add ${what} ${name}${intoLabel}`;
916
1068
  const add = insertCmd(p.slice(0, -1), name, value, { label });
917
1069
  const pin = at && !into && mode === '3d' ? placeAt(name, add, at) : undefined;
918
1070
  const cmd = pin ? seqCmd(`${label} at [${pin.join(', ')}]`, [add, withPinsMoved(setCmd([PINS_KEY, 'layout', name], { at: pin }))]) : add;
919
1071
  if (!run(doc, { ...cmd, select: [p] }, 'canvas', opts.note)) return undefined;
920
1072
  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`);
921
1073
  doc.select([p], 'canvas');
1074
+ // (0.10.1) the canvas has the focus while the name is asked, so the dialog gives it back there (⌘Z works at once)
1075
+ stage.focus({ preventScroll: true });
922
1076
  renameDialog(doc, p, 'canvas', opts.note);
923
1077
  return p;
924
1078
  }
925
1079
  const palette = h('div', { class: 'palette', role: 'toolbar', 'aria-label': T.palette, 'aria-orientation': 'vertical' });
926
- for (const { kind: sec, icon: ic, label } of ui.palette) {
927
- const b = h('button', { type: 'button', class: 'pal-item', 'data-section': sec, title: `Add ${label.toLowerCase()} (click), or drag it where it goes` }, icon(ic), h('span', { class: 'pal-label' }, label));
1080
+ ui.palette.forEach((item, idx) => {
1081
+ const { kind: sec, icon: ic, label } = item;
1082
+ 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));
928
1083
  b.addEventListener('pointerdown', e => {
929
1084
  if (e.button !== 0) return;
930
1085
  e.preventDefault();
@@ -944,17 +1099,17 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
944
1099
  const dragged = !!ghost;
945
1100
  ghost?.remove();
946
1101
  if (!drop) return;
947
- if (!dragged) addFromPalette(sec);
948
- else if (over(ev)) addFromPalette(sec, { x: ev.clientX, y: ev.clientY });
1102
+ if (!dragged) addFromPalette(sec, undefined, item);
1103
+ else if (over(ev)) addFromPalette(sec, { x: ev.clientX, y: ev.clientY }, item);
949
1104
  };
950
1105
  const upH = (ev: PointerEvent) => done(ev, true), cancelH = (ev: PointerEvent) => done(ev, false);
951
1106
  const esc = (ev: KeyboardEvent) => { if (ev.key === 'Escape') { ev.stopPropagation(); ev.preventDefault(); done(e, false); } };
952
1107
  b.addEventListener('pointermove', mv); b.addEventListener('pointerup', upH); b.addEventListener('pointercancel', cancelH); addEventListener('keydown', esc, true);
953
1108
  });
954
1109
  // the keyboard: Enter or the space key adds (the layout places it)
955
- b.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); addFromPalette(sec); } });
1110
+ b.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); addFromPalette(sec, undefined, item); } });
956
1111
  palette.append(b);
957
- }
1112
+ });
958
1113
  host.append(palette);
959
1114
 
960
1115
  function resetLayout() {
@@ -992,7 +1147,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
992
1147
  case '0': fitItems(); break;
993
1148
  case '1': actual(); break;
994
1149
  case '@': case '2': if (e.shiftKey || e.key === '@') zoomToSelection(); else return; break;
995
- case 'Escape': if (pinDrag()) { endPin(false); break; } doc.select([], 'canvas'); break;
1150
+ case 'Escape': if (linking) { linking = undefined; paintOverlay(); opts.note('Not connected'); break; } if (pinDrag()) { endPin(false); break; } doc.select([], 'canvas'); break;
996
1151
  case 'Delete': case 'Backspace': if (sel.length && !ro) deletePaths(doc, sel, 'canvas', opts.note); break;
997
1152
  case 'F2': if (sel.length === 1 && !ro) renameDialog(doc, sel[0], 'canvas', opts.note); break;
998
1153
  case 'ArrowUp': if (mod) { selectParent(); break; } return;
@@ -1013,6 +1168,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1013
1168
  default:
1014
1169
  if (mod && e.key.toLowerCase() === 'd' && sel.length === 1 && !ro) { duplicate(doc, sel[0], 'canvas', opts.note); break; }
1015
1170
  if (mod && e.key.toLowerCase() === 'a') { doc.select(drawn.map(fromPointer), 'canvas'); break; }
1171
+ if (mod && e.key.toLowerCase() === 'g' && K.group && sel.length && !ro) { groupSelection(); break; }
1016
1172
  return;
1017
1173
  }
1018
1174
  e.preventDefault();
@@ -1053,7 +1209,7 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1053
1209
  });
1054
1210
 
1055
1211
  const base = {
1056
- addFromPalette, palette,
1212
+ addFromPalette, palette, groupSelection, startPick, objectsUnder, get linking() { return linking; },
1057
1213
  render, setTheme, paintOverlay, fit: fitItems, fitAll: fit, actual, zoomAt, itemsBox, get moved() { return V.moved; }, settled, get zoom() { return V.zoom; },
1058
1214
  dispose() { endMorph(); clearTimeout(relayout); V.dispose(); disposed = true; },
1059
1215
  focus: () => stage.focus(),
@@ -1,6 +1,6 @@
1
1
  /* The canvas's own marks over the drawing (0.7.4), for the plain words (setup.ts: the root .iso-canvas, the pan key's
2
2
  class .pan-key): selection, hover, marquee, the drag's grid, drop target and edges,
3
- problem badges, and the canvas's cursors. On the skin's tokens: --iso-sel* default to --accent, --iso-bad and
3
+ problem badges, the connect handle and line (0.10.0), and the canvas's cursors. On the skin's tokens: --iso-sel* default to --accent, --iso-bad and
4
4
  --iso-warn to --bad and --warn; a host may set any of them on .iso-canvas. The package's assets/app.css carries
5
5
  this file after the layout, and it ships alone as assets/marks.css. (A domain with its own words styles its own.)
6
6
  Without any of it the marks are still harmless: the overlay's own attributes give no fill and take no pointer. */
@@ -27,6 +27,10 @@
27
27
  .iso-canvas .overlay .drop { fill: var(--iso-sel-fill); stroke: var(--iso-sel); stroke-width: 2; stroke-linejoin: round; vector-effect: non-scaling-stroke; }
28
28
  .iso-canvas .overlay .drop.bad { fill: color-mix(in srgb, var(--iso-bad) 18%, transparent); stroke: var(--iso-bad); }
29
29
  .iso-canvas .overlay .edge { fill: none; stroke: var(--iso-sel); stroke-width: 4; stroke-linecap: round; vector-effect: non-scaling-stroke; }
30
+ .iso-canvas .overlay .connect-handle { fill: var(--surface, #fff); stroke: var(--iso-sel); stroke-width: 2; vector-effect: non-scaling-stroke; pointer-events: all; cursor: crosshair; }
31
+ .iso-canvas .overlay .connect-handle:hover { fill: var(--iso-sel); }
32
+ .iso-canvas .overlay .connect-line { stroke: var(--iso-sel); stroke-width: 2; stroke-dasharray: 5 4; stroke-linecap: round; vector-effect: non-scaling-stroke; }
33
+ .iso-canvas .overlay .connect-line.ok { stroke-dasharray: none; }
30
34
  .iso-canvas .overlay .badge circle { fill: var(--iso-bad); stroke: none; }
31
35
  .iso-canvas .overlay .badge.warn circle { fill: var(--iso-warn); }
32
36
  .iso-canvas .overlay .badge text { fill: #fff; stroke: none; font-family: system-ui, sans-serif; font-weight: 600; text-anchor: middle; dominant-baseline: central; }
@@ -7,7 +7,7 @@
7
7
  // The text pane is given, not imported: Monaco is a big dependency, and a host without it still gets the canvas, the
8
8
  // tree and the panel.
9
9
 
10
- import type { DomainAdapter, FileRole } from '../adapter.ts';
10
+ import type { DomainAdapter, FileRole, ObjectRef } from '../adapter.ts';
11
11
  import type { Path } from '../path.ts';
12
12
  import { toPointer } from '../path.ts';
13
13
  import { outline } from '../outline.ts';
@@ -50,6 +50,9 @@ export interface DomainView<R, D extends CanvasDrawing> {
50
50
  icons?: Record<string, string>;
51
51
  words?: Partial<ShellWords>;
52
52
  keymap?: KeyGroup[];
53
+ /** (0.10.0) the palette's entries: presets of a kind, each with its label, icon, what a new one starts as (a copy of
54
+ * `value`; default: the kind's template) and the base of its fresh name. None: one entry per kind, as before */
55
+ palette?: { kind: string; label: string; icon?: string; value?: unknown; name?: string }[];
53
56
  /** the canvas's 2D view (0.6.0): a 3D | 2D switch; its link kinds' styles (the host's canvas CSS adds flatCss) */
54
57
  flat?: CanvasKit<R, D>['flat'];
55
58
  /** a layer over the canvas, and a part beside the views (A: their calls) */
@@ -102,7 +105,9 @@ export function setupFor<R, D extends CanvasDrawing>(a: DomainAdapter, v: Domain
102
105
  };
103
106
  const canvasUi: CanvasUi = {
104
107
  rootClass: 'iso-canvas', panKeyClass: 'pan-key', newOrder: a.kinds.map(k => k.kind),
105
- palette: a.kinds.map(k => ({ kind: k.kind, icon: icon(k.kind), label: k.singular[0].toUpperCase() + k.singular.slice(1) })),
108
+ palette: v.palette
109
+ ? v.palette.map(e => ({ kind: e.kind, label: e.label, icon: (e.icon ?? icon(e.kind)) as IconName, name: e.name, ...(e.value === undefined ? {} : { value: () => structuredClone(e.value) }) }))
110
+ : a.kinds.map(k => ({ kind: k.kind, icon: icon(k.kind), label: k.singular[0].toUpperCase() + k.singular.slice(1) })),
106
111
  text: {
107
112
  stage: 'The file, drawn: arrow keys and Tab move through what is drawn; + and − zoom, 0 fits', dragGroup: 'A drag on nothing',
108
113
  dragSelectTip: 'Drag draws a selection; hold the space key to pan', unreadable: 'The canvas draws a file that reads cleanly; fix the problems listed to see it.',
@@ -111,6 +116,9 @@ export function setupFor<R, D extends CanvasDrawing>(a: DomainAdapter, v: Domain
111
116
  };
112
117
  const canvas: CanvasKit<R, D> = {
113
118
  draw: v.draw, catalog: v.catalog, objectOf: a.objectOf, kinds: a.kinds, commands, actions, objectItems: () => [], pins, ui: canvasUi, flat: v.flat,
119
+ ...(a.connect ? { connect: (f: ObjectRef, t: ObjectRef, d: unknown) => a.connect!(f, t, d) } : {}),
120
+ ...(a.group ? { group: (m: ObjectRef[], d: unknown) => a.group!(m, d) } : {}),
121
+ ...(a.dropInto ? { dropOnto: (t: ObjectRef, v: unknown, k: string, d: unknown) => a.dropInto!(t, v, k, d) } : {}),
114
122
  trial: (text, theme) => { const r = read(text); return r.read === undefined || r.diags.some(d => d.severity === 'error') ? undefined : v.draw(r.read as R, (r.read as { data?: unknown }).data, theme); },
115
123
  };
116
124
  const kit: MountKit<R, undefined> = {
@@ -128,7 +136,8 @@ export function setupFor<R, D extends CanvasDrawing>(a: DomainAdapter, v: Domain
128
136
  return undefined;
129
137
  },
130
138
  extraLabel: () => ({ text: '', cls: '' }),
131
- keymap: v.keymap ?? PLAIN_KEYMAP,
139
+ // (0.10.0) the plain keymap says ⌘G where the domain groups
140
+ keymap: v.keymap ?? (a.group ? PLAIN_KEYMAP.map(g => (g.where === 'The tree and the canvas' ? { ...g, keys: [...g.keys, ['⌘G', 'Group the selection'] as [string, string]] } : g)) : PLAIN_KEYMAP),
132
141
  };
133
142
  const features: ShellFeatures & Record<string, unknown> = {
134
143
  canvas: { canvasView: (host: HTMLElement, doc: EditorModel, o: never) => canvasView<R, D, object>(host, doc, { ...(o as object), theme: v.theme, kit: canvas, layer: v.layer } as never) },
@@ -74,7 +74,7 @@ export interface RouteResult { routes: Routed[]; diags: Diag[] }
74
74
 
75
75
  /**
76
76
  * The search steps routing may take in one scene. The heaviest diagram in this repo takes about 57,000
77
- * (the session-messaging reproduction in repro/); a drawing with 40 more nodes took 11 million, and minutes. Past the budget,
77
+ * (the large drawing in corpus/messaging.yaml); a drawing with 40 more nodes took 11 million, and minutes. Past the budget,
78
78
  * the routes left are drawn as plain elbows and the scene says so, so a large diagram draws in about a second.
79
79
  */
80
80
  export const ROUTE_BUDGET = 500_000;
@@ -48,6 +48,26 @@ export interface ObjectRef {
48
48
  name: string;
49
49
  path: string;
50
50
  }
51
+ /** (0.10.0) what a connection drawn on the canvas writes: a value added to a list (`at`), or, with `name` (a base for a
52
+ * fresh one), to a map */
53
+ export interface ConnectPlan {
54
+ at: Path;
55
+ value: unknown;
56
+ name?: string;
57
+ label?: string;
58
+ }
59
+ /** (0.10.0) the selection made into a new container: where it goes (`at`, a map), the base of its fresh name, its
60
+ * value, and, given the name it got, what changes in each member (each a set) */
61
+ export interface GroupPlan {
62
+ at: Path;
63
+ name: string;
64
+ value: unknown;
65
+ members(name: string): {
66
+ path: Path;
67
+ value: unknown;
68
+ }[];
69
+ label?: string;
70
+ }
51
71
  /** what the domain's reader says of a text */
52
72
  export interface ReadOutcome {
53
73
  diags: Diag[];
@@ -113,6 +133,19 @@ export interface DomainAdapter {
113
133
  } | undefined;
114
134
  /** what a completion list says of an extra word in a slot */
115
135
  extraDetail?(word: string, data: unknown): string | undefined;
136
+ /** (0.10.0) a connection drawn from one object to another: what to add, or undefined (these two don't connect). None:
137
+ * the canvas offers no connect gesture */
138
+ connect?(from: ObjectRef, to: ObjectRef, data: unknown): ConnectPlan | undefined;
139
+ /** (0.10.0) the selected objects grouped into a new container, as one step; undefined: these can't be. None: the
140
+ * canvas offers no Group */
141
+ group?(members: ObjectRef[], data: unknown): GroupPlan | undefined;
142
+ /** (0.10.1) a new object of `kind` (its value as the palette made it) dropped onto `target`: its value put inside the
143
+ * target, and the words for it ("in subnet app"), or undefined (the target doesn't hold it). The canvas asks what is
144
+ * under the drop, innermost first; none: a drop is pinned where it lands */
145
+ dropInto?(target: ObjectRef, value: unknown, kind: string, data: unknown): {
146
+ value: unknown;
147
+ label?: string;
148
+ } | undefined;
116
149
  /** the top-level key order: where a new section goes */
117
150
  topOrder: readonly string[];
118
151
  /** the layout pins: the key they live under, a legacy key read too, and whether a file has only the legacy one */
@@ -1,4 +1,4 @@
1
- export type { FileRole, ObjectKindInfo, RefSlot, Ref, ObjectRef, ReadOutcome, DomainAdapter } from './adapter.js';
1
+ export type { FileRole, ObjectKindInfo, RefSlot, Ref, ObjectRef, ReadOutcome, DomainAdapter, ConnectPlan, GroupPlan } from './adapter.js';
2
2
  export { toPointer, fromPointer, parentOf, isPrefix, samePath } from './path.js';
3
3
  export type { Seg, Path } from './path.js';
4
4
  export { EditorDoc, completionContext } from './doc.js';
@@ -43,7 +43,7 @@ export { propsPanel } from './ui/props.js';
43
43
  export type { PropsUi, PropsKit, PropsOpts } from './ui/props.js';
44
44
  export type { Box as CanvasBox, Outline, CanvasCtx, CanvasLayer } from './ui/canvas-layer.js';
45
45
  export { canvasView } from './ui/canvas.js';
46
- export type { CanvasDrawing, DropInto, CanvasUi, CanvasKit, CanvasOpts, FlatCanvas, FlatDrawn } from './ui/canvas.js';
46
+ export type { CanvasDrawing, DropInto, CanvasUi, CanvasKit, CanvasOpts, FlatCanvas, FlatDrawn, PaletteItem } from './ui/canvas.js';
47
47
  export { flatCanvas } from './ui/flat-canvas.js';
48
48
  export type { PartCtx, Attention, EditorPart } from './ui/part.js';
49
49
  export type { Checked, MountKit } from './ui/mount-kit.js';
@@ -7,7 +7,7 @@ import type { CompiledScene } from '../../iso-objects/compile.js';
7
7
  import type { EditorModel } from '../model.js';
8
8
  import type { Problem } from '../validate.js';
9
9
  import { type Commands } from '../commands.js';
10
- import type { ObjectKindInfo, ObjectRef } from '../adapter.js';
10
+ import type { ObjectKindInfo, ObjectRef, ConnectPlan, GroupPlan } from '../adapter.js';
11
11
  import { type Path } from '../path.js';
12
12
  import { type View } from '../../iso-viewer/viewport.js';
13
13
  import type { CanvasCtx, CanvasLayer } from './canvas-layer.js';
@@ -83,11 +83,9 @@ export interface CanvasUi {
83
83
  panKeyClass: string;
84
84
  /** the kinds the canvas's menu offers, in order */
85
85
  newOrder: string[];
86
- palette: {
87
- kind: string;
88
- icon: IconName;
89
- label: string;
90
- }[];
86
+ /** the palette's entries: a kind, and (0.10.0) a preset: what a new one starts as (default: the kind's template) and
87
+ * the base of its fresh name (default: the kind's singular) */
88
+ palette: PaletteItem[];
91
89
  text: {
92
90
  stage: string;
93
91
  dragGroup: string;
@@ -100,6 +98,13 @@ export interface CanvasUi {
100
98
  duplicateWhy: string;
101
99
  };
102
100
  }
101
+ export interface PaletteItem {
102
+ kind: string;
103
+ icon: IconName;
104
+ label: string;
105
+ value?(): unknown;
106
+ name?: string;
107
+ }
103
108
  /** what the canvas is given of the domain (M: the domain's reading of the file; D: its drawing) */
104
109
  export interface CanvasKit<M, D extends CanvasDrawing> {
105
110
  draw(model: M, data: unknown, theme: string): D;
@@ -108,7 +113,17 @@ export interface CanvasKit<M, D extends CanvasDrawing> {
108
113
  catalog: KindCatalog;
109
114
  objectOf(ptr: string): ObjectRef | undefined;
110
115
  kinds: ObjectKindInfo[];
111
- commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertCmd' | 'pinsCmd' | 'withPinsMoved' | 'describe' | 'freshName'>;
116
+ commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertCmd' | 'insertItemCmd' | 'pinsCmd' | 'withPinsMoved' | 'describe' | 'freshName'>;
117
+ /** (0.10.0) a connection drawn from one object to another (the adapter's connect): the canvas offers the gesture (a
118
+ * handle on a selected object, and "Connect to…") only when it is given */
119
+ connect?(from: ObjectRef, to: ObjectRef, data: unknown): ConnectPlan | undefined;
120
+ /** (0.10.1) a palette drop onto an object (the adapter's dropInto): the new thing inside it, asked innermost first */
121
+ dropOnto?(target: ObjectRef, value: unknown, kind: string, data: unknown): {
122
+ value: unknown;
123
+ label?: string;
124
+ } | undefined;
125
+ /** (0.10.0) the selection made into a new container (the adapter's group): Group, ⌘G, one undo step */
126
+ group?(members: ObjectRef[], data: unknown): GroupPlan | undefined;
112
127
  actions: Actions;
113
128
  /** what an object's own menu offers, beyond rename, duplicate and delete */
114
129
  objectItems(doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void): MenuItem[];
@@ -161,8 +176,21 @@ export declare function canvasView<M, D extends CanvasDrawing, A extends object
161
176
  addFromPalette: (sec: string, at?: {
162
177
  x: number;
163
178
  y: number;
164
- }) => Path | undefined;
179
+ }, item?: PaletteItem) => Path | undefined;
165
180
  palette: HTMLDivElement;
181
+ groupSelection: () => void;
182
+ startPick: () => void;
183
+ objectsUnder: (at: {
184
+ x: number;
185
+ y: number;
186
+ }) => ObjectRef[];
187
+ readonly linking: {
188
+ from: ObjectRef;
189
+ x?: number;
190
+ y?: number;
191
+ over?: string;
192
+ pick?: boolean;
193
+ } | undefined;
166
194
  render: (s3: M | undefined, data: unknown) => Promise<void>;
167
195
  setTheme: (_t: 'light' | 'dark') => void;
168
196
  paintOverlay: () => void;
@@ -26,6 +26,15 @@ export interface DomainView<R, D extends CanvasDrawing> {
26
26
  icons?: Record<string, string>;
27
27
  words?: Partial<ShellWords>;
28
28
  keymap?: KeyGroup[];
29
+ /** (0.10.0) the palette's entries: presets of a kind, each with its label, icon, what a new one starts as (a copy of
30
+ * `value`; default: the kind's template) and the base of its fresh name. None: one entry per kind, as before */
31
+ palette?: {
32
+ kind: string;
33
+ label: string;
34
+ icon?: string;
35
+ value?: unknown;
36
+ name?: string;
37
+ }[];
29
38
  /** the canvas's 2D view (0.6.0): a 3D | 2D switch; its link kinds' styles (the host's canvas CSS adds flatCss) */
30
39
  flat?: CanvasKit<R, D>['flat'];
31
40
  /** a layer over the canvas, and a part beside the views (A: their calls) */
@@ -44,7 +44,7 @@ export interface RouteResult {
44
44
  }
45
45
  /**
46
46
  * The search steps routing may take in one scene. The heaviest diagram in this repo takes about 57,000
47
- * (the session-messaging reproduction in repro/); a drawing with 40 more nodes took 11 million, and minutes. Past the budget,
47
+ * (the large drawing in corpus/messaging.yaml); a drawing with 40 more nodes took 11 million, and minutes. Past the budget,
48
48
  * the routes left are drawn as plain elbows and the scene says so, so a large diagram draws in about a second.
49
49
  */
50
50
  export declare const ROUTE_BUDGET = 500000;