@ruckc/truss-graph 1.23.0 → 1.24.0
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.
- package/dist/Graph.svelte +111 -32
- package/dist/Graph.svelte.d.ts +8 -0
- package/dist/layout.d.ts +1 -1
- package/dist/layout.js +29 -9
- package/dist/routing.d.ts +13 -1
- package/dist/routing.js +44 -4
- package/package.json +1 -1
package/dist/Graph.svelte
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import type { HTMLAttributes } from 'svelte/elements';
|
|
4
4
|
import { Button } from '@ruckc/truss-ui';
|
|
5
5
|
import { autoLayout, forceLayout, radialLayout } from './layout.js';
|
|
6
|
-
import { defaultPorts, opposite, portAnchor, routeEdge, type Anchor, type Rect } from './routing.js';
|
|
6
|
+
import { defaultPorts, opposite, portAnchor, routeEdge, spreadLabels, type Anchor, type Rect } from './routing.js';
|
|
7
7
|
import { NODE_H, NODE_W, type EdgeType, type GraphEdge, type GraphLayout, type GraphLayoutOptions, type GraphLegend, type GraphNode, type GraphPort, type HighlightDirection, type NodeCtx, type NodeKind, type NodeRenderer } from './types.js';
|
|
8
8
|
|
|
9
9
|
let {
|
|
@@ -23,8 +23,12 @@
|
|
|
23
23
|
connectable = true,
|
|
24
24
|
editable = true,
|
|
25
25
|
fitOnMount = true,
|
|
26
|
+
fit: fitMode = 'both',
|
|
27
|
+
interactive = true,
|
|
28
|
+
labelLines = 2,
|
|
26
29
|
minimap = false,
|
|
27
30
|
minimapPosition = 'bottom-right',
|
|
31
|
+
minimapMinWidth = 480,
|
|
28
32
|
nodeTypes,
|
|
29
33
|
node,
|
|
30
34
|
body,
|
|
@@ -68,9 +72,17 @@
|
|
|
68
72
|
/** Allow moving and deleting. */
|
|
69
73
|
editable?: boolean;
|
|
70
74
|
fitOnMount?: boolean;
|
|
75
|
+
/** What `fit()` and `fitOnMount` fit. `both` (default) fits the whole graph into the box. `width` fits it to the container's width (never enlarging past 100%) and sizes the box's height to the content at that scale, ignoring `height`, so the page scrolls rather than the graph. Re-fits when the container is resized. */
|
|
76
|
+
fit?: 'both' | 'width';
|
|
77
|
+
/** Set false for a static, scroll-through graph: no pan, zoom, drag or connect, no controls or minimap, and `touch-action` is left to the browser, so touches and wheels scroll the page. Node clicks (`onnodeclick`), keyboard focus and Enter still work. Pair with `fit="width"` on touch screens. */
|
|
78
|
+
interactive?: boolean;
|
|
79
|
+
/** Lines the default card's label and subtitle wrap onto before an ellipsis (default 2; 1 truncates on one line). The card grows to fit, and the layout and edges follow, unless the node sets its own `height`. */
|
|
80
|
+
labelLines?: number;
|
|
71
81
|
/** Overview panel showing every node and the current viewport; click or drag it to pan. */
|
|
72
82
|
minimap?: boolean;
|
|
73
83
|
minimapPosition?: 'bottom-right' | 'bottom-left';
|
|
84
|
+
/** The minimap is hidden while the graph is narrower than this many pixels, so it does not cover nodes on phones (default 480). 0 always shows it. */
|
|
85
|
+
minimapMinWidth?: number;
|
|
74
86
|
/** Custom node components by `node.type`. Each is a snippet receiving `{ node, selected, dragging, update }` and draws the whole node. */
|
|
75
87
|
nodeTypes?: Record<string, NodeRenderer>;
|
|
76
88
|
/** Custom component for every node that has no matching `nodeTypes` entry. */
|
|
@@ -93,6 +105,8 @@
|
|
|
93
105
|
onnodecontextmenu?: (node: GraphNode, event: MouseEvent | KeyboardEvent) => void;
|
|
94
106
|
} = $props();
|
|
95
107
|
|
|
108
|
+
// a static graph never edits, whatever `editable` says
|
|
109
|
+
const edit = $derived(editable && interactive);
|
|
96
110
|
let root: HTMLDivElement;
|
|
97
111
|
let viewport: HTMLDivElement;
|
|
98
112
|
let overlay: HTMLDivElement;
|
|
@@ -106,7 +120,7 @@
|
|
|
106
120
|
// ---- minimap geometry: world bounds = nodes ∪ viewport (so the viewport box is always visible)
|
|
107
121
|
const MW = 184, MH = 124;
|
|
108
122
|
const mm = $derived.by(() => {
|
|
109
|
-
if (!minimap || !rw) return null;
|
|
123
|
+
if (!minimap || !interactive || !rw || rw < minimapMinWidth) return null;
|
|
110
124
|
const vx = -tx / k, vy = -ty / k, vw = rw / k, vh = rh / k;
|
|
111
125
|
let x0 = vx, y0 = vy, x1 = vx + vw, y1 = vy + vh;
|
|
112
126
|
for (const n of live) { x0 = Math.min(x0, n.x); y0 = Math.min(y0, n.y); x1 = Math.max(x1, n.x + W(n)); y1 = Math.max(y1, n.y + H(n)); }
|
|
@@ -131,7 +145,36 @@
|
|
|
131
145
|
}
|
|
132
146
|
|
|
133
147
|
const W = (n: GraphNode) => n.width ?? NODE_W;
|
|
134
|
-
const H = (n: GraphNode) => n.height ?? NODE_H;
|
|
148
|
+
const H = (n: GraphNode) => n.height ?? autoH(n) ?? NODE_H;
|
|
149
|
+
// ---- default-card height: label and subtitle wrap to `labelLines` lines, so a long title needs a taller card. Estimated
|
|
150
|
+
// from character widths (no DOM measuring: SSR-safe, and the layout can use it before anything is rendered).
|
|
151
|
+
const LABEL_CH = 7.6, LABEL_LH = 18, SUB_CH = 6.4, SUB_LH = 16, CARD_PAD = 20, CARD_INSET = 28;
|
|
152
|
+
function wrapped(text: string, avail: number, ch: number): number {
|
|
153
|
+
const per = Math.max(1, Math.floor(avail / ch));
|
|
154
|
+
let lines = 1, used = 0;
|
|
155
|
+
for (const word of text.split(/\s+/).filter(Boolean)) {
|
|
156
|
+
const len = word.length;
|
|
157
|
+
if (len > per) { lines += used ? 1 : 0; lines += Math.ceil(len / per) - 1; used = len % per || per; }
|
|
158
|
+
else if (!used) used = len;
|
|
159
|
+
else if (used + 1 + len <= per) used += 1 + len;
|
|
160
|
+
else { lines++; used = len; }
|
|
161
|
+
}
|
|
162
|
+
return lines;
|
|
163
|
+
}
|
|
164
|
+
const heights = new Map<string, number>();
|
|
165
|
+
function autoH(n: GraphNode): number | undefined {
|
|
166
|
+
if (rendererOf(n) || (n.shape && n.shape !== 'rect')) return undefined;
|
|
167
|
+
const w = W(n), key = `${w}|${labelLines}|${n.label}|${n.subtitle ?? ''}`;
|
|
168
|
+
let h = heights.get(key);
|
|
169
|
+
if (h === undefined) {
|
|
170
|
+
const avail = w - CARD_INSET, max = Math.max(1, labelLines);
|
|
171
|
+
const text = Math.min(max, wrapped(n.label, avail, LABEL_CH)) * LABEL_LH + (n.subtitle ? Math.min(max, wrapped(n.subtitle, avail, SUB_CH)) * SUB_LH : 0);
|
|
172
|
+
h = Math.max(NODE_H, Math.ceil(text + CARD_PAD));
|
|
173
|
+
if (heights.size > 2000) heights.clear();
|
|
174
|
+
heights.set(key, h);
|
|
175
|
+
}
|
|
176
|
+
return h === NODE_H ? undefined : h;
|
|
177
|
+
}
|
|
135
178
|
const portsOf = (n: GraphNode): GraphPort[] => n.ports ?? defaultPorts(n, direction);
|
|
136
179
|
// ---- reachability, collapsing, edge-kind filter
|
|
137
180
|
const adjacency = (from: 'from' | 'to') => {
|
|
@@ -178,12 +221,14 @@
|
|
|
178
221
|
/** Zoomed far out on a big graph: nodes are drawn as plain tiles without content or ports. */
|
|
179
222
|
const lod = $derived(big && k < 0.3);
|
|
180
223
|
|
|
181
|
-
|
|
224
|
+
// cards that grew to fit their text carry that height, so edges, routing and the minimap meet the card
|
|
225
|
+
const sized = (n: GraphNode) => { const h = n.height == null ? autoH(n) : undefined; return h ? { ...n, height: h } : n; };
|
|
226
|
+
const shown = $derived(live.map((n) => sized(drag?.ids.includes(n.id) ? { ...n, x: n.x + drag.dx, y: n.y + drag.dy } : n)));
|
|
182
227
|
const byId = $derived(new Map(shown.map((n) => [n.id, n])));
|
|
183
228
|
const visible = $derived(big ? shown.filter((n) => n.x + W(n) >= vx0 && n.x <= vx1 && n.y + H(n) >= vy0 && n.y <= vy1) : shown);
|
|
184
229
|
const rects = $derived<Rect[]>(shown.map((n) => ({ id: n.id, x: n.x, y: n.y, w: W(n), h: H(n) })));
|
|
185
|
-
// obstacle-
|
|
186
|
-
const needsObstacles = $derived(!big
|
|
230
|
+
// obstacle-aware routing is O(nodes) per edge: large graphs fall back to the cheap, obstacle-blind routers
|
|
231
|
+
const needsObstacles = $derived(!big);
|
|
187
232
|
// strings built in script: interpolating them in markup would add unreachable `?? ''` branches
|
|
188
233
|
const px = (v: number) => `${v}px`;
|
|
189
234
|
const edgeAria = (e: GraphEdge) => `Edge ${e.from} to ${e.to}`;
|
|
@@ -194,7 +239,7 @@
|
|
|
194
239
|
return ps.find((p) => p.kind === kind && (id == null || p.id === id)) ?? ps.find((p) => p.kind === kind);
|
|
195
240
|
};
|
|
196
241
|
const geo = $derived(
|
|
197
|
-
liveEdges.flatMap((e) => {
|
|
242
|
+
spreadLabels(liveEdges.flatMap((e) => {
|
|
198
243
|
const a = byId.get(e.from), b = byId.get(e.to);
|
|
199
244
|
if (!a || !b) return [];
|
|
200
245
|
if (big && (Math.max(a.x + W(a), b.x + W(b)) < vx0 || Math.min(a.x, b.x) > vx1 || Math.max(a.y + H(a), b.y + H(b)) < vy0 || Math.min(a.y, b.y) > vy1)) return [];
|
|
@@ -202,7 +247,7 @@
|
|
|
202
247
|
if (!pa || !pb) return [];
|
|
203
248
|
const r = routeEdge(routeType(e.type ?? edgeType), portAnchor(a, pa, portsOf(a)), portAnchor(b, pb, portsOf(b)), needsObstacles ? rects : []);
|
|
204
249
|
return [{ e, d: r.d, m: r.mid }];
|
|
205
|
-
})
|
|
250
|
+
}), (g) => (edgeLabel ? { w: 180, h: 32 } : g.e.label ? { w: g.e.label.length * 6.8 + 16, h: 20 } : null))
|
|
206
251
|
);
|
|
207
252
|
const toGraph = (cx: number, cy: number) => {
|
|
208
253
|
const r = root.getBoundingClientRect();
|
|
@@ -217,12 +262,26 @@
|
|
|
217
262
|
/** Zoom and pan so every visible node is in view. */
|
|
218
263
|
export function fit(padding = 48) {
|
|
219
264
|
if (!live.length || !root) return;
|
|
265
|
+
if (widthFit) { ({ k, tx, ty } = widthFit); return; }
|
|
220
266
|
const { x0, y0, x1, y1 } = bounds();
|
|
221
267
|
const { width, height: hh } = root.getBoundingClientRect();
|
|
222
268
|
k = Math.min(1.5, Math.max(minK, Math.min((width - padding * 2) / (x1 - x0), (hh - padding * 2) / (y1 - y0))));
|
|
223
269
|
tx = (width - (x1 - x0) * k) / 2 - x0 * k;
|
|
224
270
|
ty = (hh - (y1 - y0) * k) / 2 - y0 * k;
|
|
225
271
|
}
|
|
272
|
+
// `fit="width"`: scale to the container's width and size the box to the content, so the page scrolls instead of the graph
|
|
273
|
+
const WIDTH_PAD = 16;
|
|
274
|
+
let measured = $state(false);
|
|
275
|
+
const widthFit = $derived.by(() => {
|
|
276
|
+
if (fitMode !== 'width' || !live.length || !rw) return null;
|
|
277
|
+
const { x0, y0, x1, y1 } = bounds();
|
|
278
|
+
// until the container is measured (server render, first paint) `rw` is a guess: stay at full size, left-aligned
|
|
279
|
+
const s = measured ? Math.min(1, Math.max(minK, (rw - WIDTH_PAD * 2) / (x1 - x0))) : 1;
|
|
280
|
+
return { k: s, tx: measured ? (rw - (x1 - x0) * s) / 2 - x0 * s : WIDTH_PAD - x0, ty: WIDTH_PAD - y0 * s, h: Math.ceil((y1 - y0) * s + WIDTH_PAD * 2) };
|
|
281
|
+
});
|
|
282
|
+
// what is drawn: the width fit straight from the derived value (so server-rendered markup is already right), else the pan and zoom state
|
|
283
|
+
const view = $derived(widthFit ?? { k, tx, ty });
|
|
284
|
+
$effect(() => { if (widthFit) ({ k, tx, ty } = widthFit); });
|
|
226
285
|
/** Pan (keeping the zoom) so the middle of the graph is in the middle of the view. */
|
|
227
286
|
export function center() {
|
|
228
287
|
if (!live.length || !root) return;
|
|
@@ -268,11 +327,16 @@
|
|
|
268
327
|
if (!opts.pin?.length) requestAnimationFrame(() => { if (root?.isConnected) fit(); });
|
|
269
328
|
}
|
|
270
329
|
function computeLayout(pin?: string[]): GraphNode[] {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
330
|
+
// the layout spaces nodes by their size: hand it the card heights (wrapped labels), then keep only the positions
|
|
331
|
+
const sizedIn = nodes.map(sized);
|
|
332
|
+
const out = layoutMode === 'force' ? forceLayout(sizedIn, edges, { pin })
|
|
333
|
+
: layoutMode === 'radial' ? radialLayout(sizedIn, edges, { root: selected[0], pin })
|
|
334
|
+
: autoLayout(sizedIn, edges, { direction, pin });
|
|
335
|
+
const orig = new Map(nodes.map((n) => [n.id, n]));
|
|
336
|
+
return out.map((o) => ({ ...orig.get(o.id)!, x: o.x, y: o.y }));
|
|
274
337
|
}
|
|
275
338
|
function zoomAt(factor: number, cx: number, cy: number) {
|
|
339
|
+
if (!interactive) return;
|
|
276
340
|
const nk = Math.min(2.5, Math.max(minK, k * factor));
|
|
277
341
|
tx = cx - (cx - tx) * (nk / k);
|
|
278
342
|
ty = cy - (cy - ty) * (nk / k);
|
|
@@ -288,7 +352,8 @@
|
|
|
288
352
|
const r = root.getBoundingClientRect();
|
|
289
353
|
zoomAt(Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015)), e.clientX - r.left, e.clientY - r.top);
|
|
290
354
|
};
|
|
291
|
-
|
|
355
|
+
measured = true;
|
|
356
|
+
if (interactive) root.addEventListener('wheel', wheel, { passive: false });
|
|
292
357
|
if (layoutMode !== 'layered' && nodes.length) nodes = computeLayout();
|
|
293
358
|
if (fitOnMount) fit();
|
|
294
359
|
// Popovers a node opens in `fixed` mode would sit inside the transformed canvas, which makes the canvas (not
|
|
@@ -316,7 +381,8 @@
|
|
|
316
381
|
function bgDown(e: PointerEvent) {
|
|
317
382
|
if ((e.target as HTMLElement).closest('.node, .controls, .edge-hit, .elabel, .minimap, .legend, .trg-overlay')) return;
|
|
318
383
|
selected = []; selectedEdge = undefined;
|
|
319
|
-
root.focus();
|
|
384
|
+
root.focus({ preventScroll: !interactive }); // a tall static graph must not jump the page when tapped
|
|
385
|
+
if (!interactive) return; // no pan: the browser scrolls the page
|
|
320
386
|
const sx = e.clientX, sy = e.clientY, tx0 = tx, ty0 = ty;
|
|
321
387
|
panning = true;
|
|
322
388
|
const move = (ev: PointerEvent) => { tx = tx0 + ev.clientX - sx; ty = ty0 + ev.clientY - sy; };
|
|
@@ -331,10 +397,11 @@
|
|
|
331
397
|
const t = e.target as HTMLElement;
|
|
332
398
|
if (t.closest('.port')) return;
|
|
333
399
|
e.stopPropagation();
|
|
400
|
+
if (!interactive) return; // static: a touch that starts a page scroll must not select; the click does (see nodeClick)
|
|
334
401
|
selectedEdge = undefined;
|
|
335
402
|
if (e.shiftKey || e.ctrlKey || e.metaKey) selected = selected.includes(n.id) ? selected.filter((i) => i !== n.id) : [...selected, n.id];
|
|
336
403
|
else if (!selected.includes(n.id)) selected = [n.id];
|
|
337
|
-
if (!
|
|
404
|
+
if (!edit || t.closest(INTERACTIVE)) return;
|
|
338
405
|
const ids = [...selected], sx = e.clientX, sy = e.clientY;
|
|
339
406
|
let moved = false;
|
|
340
407
|
const move = (ev: PointerEvent) => {
|
|
@@ -361,7 +428,11 @@
|
|
|
361
428
|
let suppressClick = false, keyMenuAt = -Infinity;
|
|
362
429
|
// controls inside custom nodes and the node's own badges handle their own clicks
|
|
363
430
|
const ownsEvent = (e: Event) => !!(e.target as HTMLElement).closest(`.port, .expander, ${INTERACTIVE}`);
|
|
364
|
-
function nodeClick(e: MouseEvent, n: GraphNode) {
|
|
431
|
+
function nodeClick(e: MouseEvent, n: GraphNode) {
|
|
432
|
+
if (suppressClick || ownsEvent(e)) return;
|
|
433
|
+
if (!interactive) { selected = [n.id]; selectedEdge = undefined; }
|
|
434
|
+
onnodeclick?.(n, e);
|
|
435
|
+
}
|
|
365
436
|
function nodeDblClick(e: MouseEvent, n: GraphNode) { if (!ownsEvent(e)) onnodedblclick?.(n, e); }
|
|
366
437
|
function nodeMenu(e: MouseEvent, n: GraphNode) {
|
|
367
438
|
if (!onnodecontextmenu || ownsEvent(e)) return;
|
|
@@ -385,7 +456,7 @@
|
|
|
385
456
|
const valid = (from: { node: string; port: string }, to: { node: string; port: string }) =>
|
|
386
457
|
from.node !== to.node && (isValidConnection?.(from, to) ?? true);
|
|
387
458
|
function portDown(e: PointerEvent, n: GraphNode, p: GraphPort) {
|
|
388
|
-
if (!connectable || !
|
|
459
|
+
if (!connectable || !edit) return;
|
|
389
460
|
e.stopPropagation();
|
|
390
461
|
e.preventDefault();
|
|
391
462
|
const g0 = toGraph(e.clientX, e.clientY);
|
|
@@ -423,7 +494,7 @@
|
|
|
423
494
|
});
|
|
424
495
|
|
|
425
496
|
function remove() {
|
|
426
|
-
if (!
|
|
497
|
+
if (!edit) return;
|
|
427
498
|
if (selectedEdge) edges = edges.filter((e) => e.id !== selectedEdge);
|
|
428
499
|
if (selected.length) {
|
|
429
500
|
edges = edges.filter((e) => !selected.includes(e.from) && !selected.includes(e.to));
|
|
@@ -471,10 +542,13 @@
|
|
|
471
542
|
}
|
|
472
543
|
function goTo(n: GraphNode) {
|
|
473
544
|
selected = [n.id]; selectedEdge = undefined;
|
|
545
|
+
if (interactive) panInto(n);
|
|
546
|
+
tick().then(() => root?.querySelector<HTMLElement>(`.node[data-id="${CSS.escape(n.id)}"]`)?.focus());
|
|
547
|
+
}
|
|
548
|
+
function panInto(n: GraphNode) {
|
|
474
549
|
const pad = 32, sx = n.x * k + tx, sy = n.y * k + ty, sw = W(n) * k, sh = H(n) * k;
|
|
475
550
|
if (sx < pad) tx += pad - sx; else if (sx + sw > rw - pad) tx -= sx + sw - (rw - pad);
|
|
476
551
|
if (sy < pad) ty += pad - sy; else if (sy + sh > rh - pad) ty -= sy + sh - (rh - pad);
|
|
477
|
-
tick().then(() => root?.querySelector<HTMLElement>(`.node[data-id="${CSS.escape(n.id)}"]`)?.focus());
|
|
478
552
|
}
|
|
479
553
|
function onKey(e: KeyboardEvent) {
|
|
480
554
|
if ((e.target as HTMLElement).closest('input, textarea, select, [contenteditable="true"], .trg-overlay')) return; // typing inside a node, or a card lifted out of one
|
|
@@ -488,7 +562,7 @@
|
|
|
488
562
|
}
|
|
489
563
|
const step = e.shiftKey ? 32 : 8;
|
|
490
564
|
const mv = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
|
|
491
|
-
if (mv && !
|
|
565
|
+
if (mv && !edit) {
|
|
492
566
|
const cur = (e.target as HTMLElement).closest<HTMLElement>('.node')?.dataset.id ?? selected[0];
|
|
493
567
|
const next = neighbour(cur ? byId.get(cur) : undefined, e.key);
|
|
494
568
|
if (!next) return;
|
|
@@ -500,12 +574,12 @@
|
|
|
500
574
|
if (collapsed.includes(id)) expand(id);
|
|
501
575
|
else if (childrenOf.get(id)?.length) collapse(id);
|
|
502
576
|
else return;
|
|
503
|
-
} else if (mv && selected.length &&
|
|
577
|
+
} else if (mv && selected.length && edit) {
|
|
504
578
|
nodes = nodes.map((n) => (selected.includes(n.id) ? { ...n, x: n.x + mv[0], y: n.y + mv[1] } : n));
|
|
505
579
|
} else if (e.key === 'Delete' || e.key === 'Backspace') remove();
|
|
506
|
-
else if (e.key === '+' || e.key === '=') zoomCenter(1.2);
|
|
507
|
-
else if (e.key === '-') zoomCenter(1 / 1.2);
|
|
508
|
-
else if (e.key === '0') fit();
|
|
580
|
+
else if (interactive && (e.key === '+' || e.key === '=')) zoomCenter(1.2);
|
|
581
|
+
else if (interactive && e.key === '-') zoomCenter(1 / 1.2);
|
|
582
|
+
else if (interactive && e.key === '0') fit();
|
|
509
583
|
else if (e.key === 'Escape') { selected = []; selectedEdge = undefined; }
|
|
510
584
|
else return;
|
|
511
585
|
e.preventDefault();
|
|
@@ -514,13 +588,13 @@
|
|
|
514
588
|
|
|
515
589
|
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
|
|
516
590
|
<div
|
|
517
|
-
{...rest} class={'trg ' + klass} bind:this={root} bind:clientWidth={rw} bind:clientHeight={rh} role="application" tabindex="0" data-panning={panning}
|
|
518
|
-
aria-label={rest['aria-label'] ?? (editable ? 'Graph editor. Arrow keys move selected nodes, Delete removes, plus and minus zoom, 0 fits to view.' : 'Graph. Arrow keys move between nodes, Enter collapses or expands, plus and minus zoom, 0 fits to view.')}
|
|
519
|
-
style:height={typeof height === 'number' ? `${height}px` : height}
|
|
520
|
-
style:--tx={px(tx)} style:--ty={px(ty)} style:--k={k}
|
|
591
|
+
{...rest} class={'trg ' + klass} bind:this={root} bind:clientWidth={rw} bind:clientHeight={rh} role="application" tabindex="0" data-panning={panning} data-static={!interactive}
|
|
592
|
+
aria-label={rest['aria-label'] ?? (!interactive ? 'Graph. Arrow keys move between nodes, Enter collapses or expands.' : editable ? 'Graph editor. Arrow keys move selected nodes, Delete removes, plus and minus zoom, 0 fits to view.' : 'Graph. Arrow keys move between nodes, Enter collapses or expands, plus and minus zoom, 0 fits to view.')}
|
|
593
|
+
style:height={widthFit ? px(widthFit.h) : typeof height === 'number' ? `${height}px` : height}
|
|
594
|
+
style:--tx={px(view.tx)} style:--ty={px(view.ty)} style:--k={view.k} style:--trg-lines={Math.max(1, labelLines)}
|
|
521
595
|
onpointerdown={bgDown} onkeydown={onKey}
|
|
522
596
|
>
|
|
523
|
-
<div class="viewport" bind:this={viewport} style:transform="translate({tx}px, {ty}px) scale({k})">
|
|
597
|
+
<div class="viewport" bind:this={viewport} style:transform="translate({view.tx}px, {view.ty}px) scale({view.k})">
|
|
524
598
|
<svg class="edges" width="1" height="1">
|
|
525
599
|
<defs>
|
|
526
600
|
<marker id="trg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
|
|
@@ -583,7 +657,7 @@
|
|
|
583
657
|
<span class="port" data-side={p.side} data-port-in={n.id} data-port-id={p.id} data-hot={link?.over?.node === n.id && link.over.port === p.id}
|
|
584
658
|
style:left="{a.x - n.x}px" style:top="{a.y - n.y}px"></span>
|
|
585
659
|
{:else}
|
|
586
|
-
<span class="port" role="presentation" data-side={p.side} data-connectable={connectable &&
|
|
660
|
+
<span class="port" role="presentation" data-side={p.side} data-connectable={connectable && edit} onpointerdown={(e) => portDown(e, n, p)}
|
|
587
661
|
style:left="{a.x - n.x}px" style:top="{a.y - n.y}px"></span>
|
|
588
662
|
{/if}
|
|
589
663
|
{#if p.label}<span class="plabel" data-side={p.side} style:left="{a.x - n.x}px" style:top="{a.y - n.y}px">{p.label}</span>{/if}
|
|
@@ -632,12 +706,14 @@
|
|
|
632
706
|
<!-- node-attached overlays (HoverCard, Popover) are lifted here, outside the transformed canvas -->
|
|
633
707
|
<div class="trg-overlay" bind:this={overlay}></div>
|
|
634
708
|
|
|
709
|
+
{#if interactive}
|
|
635
710
|
<div class="controls" role="toolbar" aria-label="Graph controls">
|
|
636
711
|
<Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label="Zoom in" onclick={() => zoomCenter(1.2)} />
|
|
637
712
|
<Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label="Zoom out" onclick={() => zoomCenter(1 / 1.2)} />
|
|
638
713
|
<Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label="Fit to view" onclick={() => fit()} />
|
|
639
|
-
{#if
|
|
714
|
+
{#if edit}<Button variant="minimal" intent="neutral" size="sm" icon="refresh" aria-label="Auto layout" onclick={() => layout()} />{/if}
|
|
640
715
|
</div>
|
|
716
|
+
{/if}
|
|
641
717
|
</div>
|
|
642
718
|
|
|
643
719
|
<style>
|
|
@@ -664,6 +740,8 @@
|
|
|
664
740
|
}
|
|
665
741
|
.trg-overlay { position: absolute; left: 0; top: 0; width: 0; height: 0; }
|
|
666
742
|
.trg[data-panning='true'] { cursor: grabbing; }
|
|
743
|
+
/* static: touches and wheels belong to the page, which scrolls through the graph */
|
|
744
|
+
.trg[data-static='true'] { touch-action: auto; cursor: default; }
|
|
667
745
|
.trg:focus-visible { box-shadow: var(--tr-focus-ring); border-color: var(--tr-primary); }
|
|
668
746
|
.viewport { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
|
|
669
747
|
.edges { position: absolute; left: 0; top: 0; overflow: visible; pointer-events: none; }
|
|
@@ -739,8 +817,9 @@
|
|
|
739
817
|
.custom { width: 100%; min-width: 0; }
|
|
740
818
|
.custom.fill { height: 100%; }
|
|
741
819
|
.content { flex: 1; min-width: 0; padding: 0 12px 0 16px; line-height: 1.25; }
|
|
742
|
-
.label {
|
|
743
|
-
.
|
|
820
|
+
.label, .subtitle { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--trg-lines, 2); line-clamp: var(--trg-lines, 2); overflow: hidden; overflow-wrap: anywhere; }
|
|
821
|
+
.label { font-weight: 600; color: var(--tr-on-surface); }
|
|
822
|
+
.subtitle { font-size: var(--tr-text-sm); color: var(--tr-on-surface-variant); }
|
|
744
823
|
|
|
745
824
|
.port { position: absolute; z-index: 3; width: 12px; height: 12px; margin: -6px 0 0 -6px; border-radius: 50%; background: var(--tr-surface-container-highest); border: 2px solid var(--tr-outline); box-sizing: border-box; transition: transform var(--tr-dur-fast) var(--tr-ease); }
|
|
746
825
|
.port[data-connectable='true'] { cursor: crosshair; }
|
package/dist/Graph.svelte.d.ts
CHANGED
|
@@ -31,9 +31,17 @@ type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class
|
|
|
31
31
|
/** Allow moving and deleting. */
|
|
32
32
|
editable?: boolean;
|
|
33
33
|
fitOnMount?: boolean;
|
|
34
|
+
/** What `fit()` and `fitOnMount` fit. `both` (default) fits the whole graph into the box. `width` fits it to the container's width (never enlarging past 100%) and sizes the box's height to the content at that scale, ignoring `height`, so the page scrolls rather than the graph. Re-fits when the container is resized. */
|
|
35
|
+
fit?: 'both' | 'width';
|
|
36
|
+
/** Set false for a static, scroll-through graph: no pan, zoom, drag or connect, no controls or minimap, and `touch-action` is left to the browser, so touches and wheels scroll the page. Node clicks (`onnodeclick`), keyboard focus and Enter still work. Pair with `fit="width"` on touch screens. */
|
|
37
|
+
interactive?: boolean;
|
|
38
|
+
/** Lines the default card's label and subtitle wrap onto before an ellipsis (default 2; 1 truncates on one line). The card grows to fit, and the layout and edges follow, unless the node sets its own `height`. */
|
|
39
|
+
labelLines?: number;
|
|
34
40
|
/** Overview panel showing every node and the current viewport; click or drag it to pan. */
|
|
35
41
|
minimap?: boolean;
|
|
36
42
|
minimapPosition?: 'bottom-right' | 'bottom-left';
|
|
43
|
+
/** The minimap is hidden while the graph is narrower than this many pixels, so it does not cover nodes on phones (default 480). 0 always shows it. */
|
|
44
|
+
minimapMinWidth?: number;
|
|
37
45
|
/** Custom node components by `node.type`. Each is a snippet receiving `{ node, selected, dragging, update }` and draws the whole node. */
|
|
38
46
|
nodeTypes?: Record<string, NodeRenderer>;
|
|
39
47
|
/** Custom component for every node that has no matching `nodeTypes` entry. */
|
package/dist/layout.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type GraphEdge, type GraphNode } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Layered (Sugiyama-lite) auto layout: longest-path layering, one barycenter sweep to
|
|
4
|
-
* reduce crossings, columns centred vertically. Cycle-safe. Returns new node objects.
|
|
4
|
+
* reduce crossings, columns centred vertically. Cycle-safe: back-edges (found by a depth-first walk in input order) are left out of the ranking, so loops keep the forward order. Returns new node objects.
|
|
5
5
|
*
|
|
6
6
|
* `pin` (node ids) makes it incremental: pinned nodes keep their exact position and every other node is placed
|
|
7
7
|
* in the column after (or before) its placed neighbours, nudged along the column until it overlaps nothing.
|
package/dist/layout.js
CHANGED
|
@@ -76,7 +76,7 @@ function placeAround(nodes, edges, pinned, want, probe, gap) {
|
|
|
76
76
|
}
|
|
77
77
|
/**
|
|
78
78
|
* Layered (Sugiyama-lite) auto layout: longest-path layering, one barycenter sweep to
|
|
79
|
-
* reduce crossings, columns centred vertically. Cycle-safe. Returns new node objects.
|
|
79
|
+
* reduce crossings, columns centred vertically. Cycle-safe: back-edges (found by a depth-first walk in input order) are left out of the ranking, so loops keep the forward order. Returns new node objects.
|
|
80
80
|
*
|
|
81
81
|
* `pin` (node ids) makes it incremental: pinned nodes keep their exact position and every other node is placed
|
|
82
82
|
* in the column after (or before) its placed neighbours, nudged along the column until it overlaps nothing.
|
|
@@ -103,20 +103,40 @@ export function autoLayout(nodes, edges, opts = {}) {
|
|
|
103
103
|
return placeAround(nodes, edges, pinned, want, probe, gapX);
|
|
104
104
|
}
|
|
105
105
|
const ids = new Set(nodes.map((n) => n.id));
|
|
106
|
-
|
|
106
|
+
// Cycles: a depth-first walk in input order (sources first, then whatever is left) finds the back-edges, those
|
|
107
|
+
// pointing at a node still on the walk's stack. Ranking ignores them, so the forward order stays intact and the
|
|
108
|
+
// layers do not shift; they are routed around the side by `routeEdge`.
|
|
109
|
+
const outs = new Map(nodes.map((n) => [n.id, []]));
|
|
110
|
+
const hasIn = new Set();
|
|
107
111
|
for (const e of edges)
|
|
108
|
-
if (ids.has(e.from) && ids.has(e.to) && e.from !== e.to)
|
|
109
|
-
|
|
112
|
+
if (ids.has(e.from) && ids.has(e.to) && e.from !== e.to) {
|
|
113
|
+
outs.get(e.from).push(e.to);
|
|
114
|
+
hasIn.add(e.to);
|
|
115
|
+
}
|
|
116
|
+
const preds = new Map(nodes.map((n) => [n.id, []]));
|
|
117
|
+
const state = new Map(); // 1 = on the stack, 2 = done
|
|
118
|
+
const walk = (id) => {
|
|
119
|
+
state.set(id, 1);
|
|
120
|
+
for (const to of outs.get(id)) {
|
|
121
|
+
if (state.get(to) === 1)
|
|
122
|
+
continue; // back-edge
|
|
123
|
+
preds.get(to).push(id);
|
|
124
|
+
if (!state.has(to))
|
|
125
|
+
walk(to);
|
|
126
|
+
}
|
|
127
|
+
state.set(id, 2);
|
|
128
|
+
};
|
|
129
|
+
for (const n of nodes)
|
|
130
|
+
if (!hasIn.has(n.id) && !state.has(n.id))
|
|
131
|
+
walk(n.id);
|
|
132
|
+
for (const n of nodes)
|
|
133
|
+
if (!state.has(n.id))
|
|
134
|
+
walk(n.id);
|
|
110
135
|
const layer = new Map();
|
|
111
|
-
const visiting = new Set();
|
|
112
136
|
const depth = (id) => {
|
|
113
137
|
if (layer.has(id))
|
|
114
138
|
return layer.get(id);
|
|
115
|
-
if (visiting.has(id))
|
|
116
|
-
return 0; // break cycles
|
|
117
|
-
visiting.add(id);
|
|
118
139
|
const d = preds.get(id).reduce((m, p) => Math.max(m, depth(p) + 1), 0);
|
|
119
|
-
visiting.delete(id);
|
|
120
140
|
layer.set(id, d);
|
|
121
141
|
return d;
|
|
122
142
|
};
|
package/dist/routing.d.ts
CHANGED
|
@@ -21,5 +21,17 @@ export declare const opposite: (s: Side) => Side;
|
|
|
21
21
|
export declare function defaultPorts(n: GraphNode, direction?: 'LR' | 'TB'): GraphPort[];
|
|
22
22
|
/** Where a port sits on its node; several ports on one side are spread evenly. */
|
|
23
23
|
export declare function portAnchor(n: GraphNode, port: GraphPort, ports: GraphPort[]): Anchor;
|
|
24
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* Edge labels sit at the midpoint of their edge, and edges that fan out share their first segments, so the
|
|
26
|
+
* midpoints crowd together. Walks the items in order and slides each label along y (0, +1, -1, +2, ... steps of
|
|
27
|
+
* its own height) until its box clears every label placed before it. `size` is null for an item without a label.
|
|
28
|
+
* Pure and deterministic; an item that finds no free spot within 12 tries keeps its own midpoint.
|
|
29
|
+
*/
|
|
30
|
+
export declare function spreadLabels<T extends {
|
|
31
|
+
m: Pt;
|
|
32
|
+
}>(items: T[], size: (item: T) => {
|
|
33
|
+
w: number;
|
|
34
|
+
h: number;
|
|
35
|
+
} | null): T[];
|
|
36
|
+
/** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
|
|
25
37
|
export declare function routeEdge(type: EdgeType, a: Anchor, b: Anchor, obstacles?: Rect[]): Routed;
|
package/dist/routing.js
CHANGED
|
@@ -82,6 +82,9 @@ function bezier(a, b) {
|
|
|
82
82
|
}
|
|
83
83
|
/** Orthogonal route with short stubs leaving/entering perpendicular to each node side. */
|
|
84
84
|
function orthogonalPoints(a, b, stub = 24) {
|
|
85
|
+
// facing sides with less than two stubs between them: shrink the stubs to fit, so the route never overshoots into a loop
|
|
86
|
+
if (a.side === opposite(b.side))
|
|
87
|
+
stub = Math.min(stub, Math.max(DIR[a.side].x * (b.x - a.x) + DIR[a.side].y * (b.y - a.y), 0) / 2);
|
|
85
88
|
const p1 = stubOf(a, stub), q1 = stubOf(b, stub);
|
|
86
89
|
const mid = [];
|
|
87
90
|
if (horiz(a.side) && horiz(b.side)) {
|
|
@@ -108,7 +111,7 @@ function orthogonalPoints(a, b, stub = 24) {
|
|
|
108
111
|
mid.push({ x: p1.x, y }, { x: q1.x, y });
|
|
109
112
|
}
|
|
110
113
|
else {
|
|
111
|
-
const x = Math.abs(a.x - b.x) < 20 ? a.x +
|
|
114
|
+
const x = Math.abs(a.x - b.x) < 20 ? Math.max(a.x, b.x) + 114 : (a.x + b.x) / 2; // aligned back edge: round the side of a default-width node
|
|
112
115
|
mid.push({ x, y: p1.y }, { x, y: q1.y });
|
|
113
116
|
}
|
|
114
117
|
}
|
|
@@ -219,17 +222,54 @@ function avoidPoints(a, b, obstacles, margin = 14, stub = 26) {
|
|
|
219
222
|
}
|
|
220
223
|
return simplify([a, ...path.reverse(), b]);
|
|
221
224
|
}
|
|
222
|
-
/**
|
|
225
|
+
/** True when any segment of the polyline passes through the inside of an obstacle (touching the border is fine). */
|
|
226
|
+
function crossesAny(pts, obstacles) {
|
|
227
|
+
for (let i = 1; i < pts.length; i++) {
|
|
228
|
+
const x0 = Math.min(pts[i - 1].x, pts[i].x), x1 = Math.max(pts[i - 1].x, pts[i].x);
|
|
229
|
+
const y0 = Math.min(pts[i - 1].y, pts[i].y), y1 = Math.max(pts[i - 1].y, pts[i].y);
|
|
230
|
+
if (obstacles.some((o) => x1 > o.x + 1 && x0 < o.x + o.w - 1 && y1 > o.y + 1 && y0 < o.y + o.h - 1))
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
/** Orthogonal route that, given obstacles, is re-routed around them whenever the plain route would cross one. */
|
|
236
|
+
function clearPoints(a, b, obstacles) {
|
|
237
|
+
const p = orthogonalPoints(a, b);
|
|
238
|
+
return obstacles.length && crossesAny(p, obstacles) ? avoidPoints(a, b, obstacles) ?? p : p;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Edge labels sit at the midpoint of their edge, and edges that fan out share their first segments, so the
|
|
242
|
+
* midpoints crowd together. Walks the items in order and slides each label along y (0, +1, -1, +2, ... steps of
|
|
243
|
+
* its own height) until its box clears every label placed before it. `size` is null for an item without a label.
|
|
244
|
+
* Pure and deterministic; an item that finds no free spot within 12 tries keeps its own midpoint.
|
|
245
|
+
*/
|
|
246
|
+
export function spreadLabels(items, size) {
|
|
247
|
+
const placed = [];
|
|
248
|
+
return items.map((item) => {
|
|
249
|
+
const s = size(item);
|
|
250
|
+
if (!s)
|
|
251
|
+
return item;
|
|
252
|
+
const hit = (y) => placed.some((p) => Math.abs(p.x - item.m.x) < (p.w + s.w) / 2 && Math.abs(p.y - y) < (p.h + s.h) / 2);
|
|
253
|
+
let y = item.m.y;
|
|
254
|
+
for (let k = 0; k < 12 && hit(y); k++)
|
|
255
|
+
y = item.m.y + (k % 2 ? -1 : 1) * Math.ceil((k + 1) / 2) * (s.h + 2);
|
|
256
|
+
if (hit(y))
|
|
257
|
+
y = item.m.y;
|
|
258
|
+
placed.push({ x: item.m.x, y, ...s });
|
|
259
|
+
return y === item.m.y ? item : { ...item, m: { x: item.m.x, y } };
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
/** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
|
|
223
263
|
export function routeEdge(type, a, b, obstacles = []) {
|
|
224
264
|
switch (type) {
|
|
225
265
|
case 'straight':
|
|
226
266
|
return { d: `M${a.x},${a.y} L${b.x},${b.y}`, mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } };
|
|
227
267
|
case 'step': {
|
|
228
|
-
const p =
|
|
268
|
+
const p = clearPoints(a, b, obstacles);
|
|
229
269
|
return { d: pathOf(p, 0), mid: midOf(p) };
|
|
230
270
|
}
|
|
231
271
|
case 'smoothstep': {
|
|
232
|
-
const p =
|
|
272
|
+
const p = clearPoints(a, b, obstacles);
|
|
233
273
|
return { d: pathOf(p, 12), mid: midOf(p) };
|
|
234
274
|
}
|
|
235
275
|
case 'avoid': {
|