@ruckc/truss-graph 1.23.1 → 1.25.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 +117 -34
- package/dist/Graph.svelte.d.ts +8 -0
- package/dist/layout.d.ts +7 -1
- package/dist/layout.js +48 -11
- package/dist/routing.d.ts +24 -1
- package/dist/routing.js +52 -4
- package/dist/types.d.ts +4 -0
- 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, labelSize, 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) => labelSize(g.e, !!edgeLabel))
|
|
206
251
|
);
|
|
207
252
|
const toGraph = (cx: number, cy: number) => {
|
|
208
253
|
const r = root.getBoundingClientRect();
|
|
@@ -217,12 +262,30 @@
|
|
|
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
|
+
// the zoom controls float over the top-right corner (8px in, about 32px tall): an interactive width fit starts the content
|
|
275
|
+
// below them, so the last column never sits under the buttons. A static graph has no controls and needs no band.
|
|
276
|
+
const CONTROLS_BAND = 48;
|
|
277
|
+
let measured = $state(false);
|
|
278
|
+
const widthFit = $derived.by(() => {
|
|
279
|
+
if (fitMode !== 'width' || !live.length || !rw) return null;
|
|
280
|
+
const { x0, y0, x1, y1 } = bounds();
|
|
281
|
+
const top = WIDTH_PAD + (interactive ? CONTROLS_BAND : 0);
|
|
282
|
+
// until the container is measured (server render, first paint) `rw` is a guess: stay at full size, left-aligned
|
|
283
|
+
const s = measured ? Math.min(1, Math.max(minK, (rw - WIDTH_PAD * 2) / (x1 - x0))) : 1;
|
|
284
|
+
return { k: s, tx: measured ? (rw - (x1 - x0) * s) / 2 - x0 * s : WIDTH_PAD - x0, ty: top - y0 * s, h: Math.ceil((y1 - y0) * s + top + WIDTH_PAD) };
|
|
285
|
+
});
|
|
286
|
+
// what is drawn: the width fit straight from the derived value (so server-rendered markup is already right), else the pan and zoom state
|
|
287
|
+
const view = $derived(widthFit ?? { k, tx, ty });
|
|
288
|
+
$effect(() => { if (widthFit) ({ k, tx, ty } = widthFit); });
|
|
226
289
|
/** Pan (keeping the zoom) so the middle of the graph is in the middle of the view. */
|
|
227
290
|
export function center() {
|
|
228
291
|
if (!live.length || !root) return;
|
|
@@ -262,17 +325,22 @@
|
|
|
262
325
|
* after adding nodes ("expand neighbours"): `g.layout({ pin: existingIds })`.
|
|
263
326
|
*/
|
|
264
327
|
export function layout(opts: GraphLayoutOptions = {}) {
|
|
265
|
-
nodes = computeLayout(opts
|
|
328
|
+
nodes = computeLayout(opts);
|
|
266
329
|
onchange?.();
|
|
267
330
|
// the graph may be gone by the next frame (navigating away right after pressing the button)
|
|
268
331
|
if (!opts.pin?.length) requestAnimationFrame(() => { if (root?.isConnected) fit(); });
|
|
269
332
|
}
|
|
270
|
-
function computeLayout(pin
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
333
|
+
function computeLayout({ pin, gapX, gapY }: GraphLayoutOptions = {}): GraphNode[] {
|
|
334
|
+
// the layout spaces nodes by their size: hand it the card heights (wrapped labels), then keep only the positions
|
|
335
|
+
const sizedIn = nodes.map(sized);
|
|
336
|
+
const out = layoutMode === 'force' ? forceLayout(sizedIn, edges, { pin })
|
|
337
|
+
: layoutMode === 'radial' ? radialLayout(sizedIn, edges, { root: selected[0], pin })
|
|
338
|
+
: autoLayout(sizedIn, edges, { direction, pin, gapX, gapY, edgeLabel: !!edgeLabel });
|
|
339
|
+
const orig = new Map(nodes.map((n) => [n.id, n]));
|
|
340
|
+
return out.map((o) => ({ ...orig.get(o.id)!, x: o.x, y: o.y }));
|
|
274
341
|
}
|
|
275
342
|
function zoomAt(factor: number, cx: number, cy: number) {
|
|
343
|
+
if (!interactive) return;
|
|
276
344
|
const nk = Math.min(2.5, Math.max(minK, k * factor));
|
|
277
345
|
tx = cx - (cx - tx) * (nk / k);
|
|
278
346
|
ty = cy - (cy - ty) * (nk / k);
|
|
@@ -288,7 +356,8 @@
|
|
|
288
356
|
const r = root.getBoundingClientRect();
|
|
289
357
|
zoomAt(Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015)), e.clientX - r.left, e.clientY - r.top);
|
|
290
358
|
};
|
|
291
|
-
|
|
359
|
+
measured = true;
|
|
360
|
+
if (interactive) root.addEventListener('wheel', wheel, { passive: false });
|
|
292
361
|
if (layoutMode !== 'layered' && nodes.length) nodes = computeLayout();
|
|
293
362
|
if (fitOnMount) fit();
|
|
294
363
|
// Popovers a node opens in `fixed` mode would sit inside the transformed canvas, which makes the canvas (not
|
|
@@ -316,7 +385,8 @@
|
|
|
316
385
|
function bgDown(e: PointerEvent) {
|
|
317
386
|
if ((e.target as HTMLElement).closest('.node, .controls, .edge-hit, .elabel, .minimap, .legend, .trg-overlay')) return;
|
|
318
387
|
selected = []; selectedEdge = undefined;
|
|
319
|
-
root.focus();
|
|
388
|
+
root.focus({ preventScroll: !interactive || !!widthFit }); // a tall static or width-fitted graph must not jump the page when tapped
|
|
389
|
+
if (!interactive) return; // no pan: the browser scrolls the page
|
|
320
390
|
const sx = e.clientX, sy = e.clientY, tx0 = tx, ty0 = ty;
|
|
321
391
|
panning = true;
|
|
322
392
|
const move = (ev: PointerEvent) => { tx = tx0 + ev.clientX - sx; ty = ty0 + ev.clientY - sy; };
|
|
@@ -331,10 +401,11 @@
|
|
|
331
401
|
const t = e.target as HTMLElement;
|
|
332
402
|
if (t.closest('.port')) return;
|
|
333
403
|
e.stopPropagation();
|
|
404
|
+
if (!interactive) return; // static: a touch that starts a page scroll must not select; the click does (see nodeClick)
|
|
334
405
|
selectedEdge = undefined;
|
|
335
406
|
if (e.shiftKey || e.ctrlKey || e.metaKey) selected = selected.includes(n.id) ? selected.filter((i) => i !== n.id) : [...selected, n.id];
|
|
336
407
|
else if (!selected.includes(n.id)) selected = [n.id];
|
|
337
|
-
if (!
|
|
408
|
+
if (!edit || t.closest(INTERACTIVE)) return;
|
|
338
409
|
const ids = [...selected], sx = e.clientX, sy = e.clientY;
|
|
339
410
|
let moved = false;
|
|
340
411
|
const move = (ev: PointerEvent) => {
|
|
@@ -361,7 +432,11 @@
|
|
|
361
432
|
let suppressClick = false, keyMenuAt = -Infinity;
|
|
362
433
|
// controls inside custom nodes and the node's own badges handle their own clicks
|
|
363
434
|
const ownsEvent = (e: Event) => !!(e.target as HTMLElement).closest(`.port, .expander, ${INTERACTIVE}`);
|
|
364
|
-
function nodeClick(e: MouseEvent, n: GraphNode) {
|
|
435
|
+
function nodeClick(e: MouseEvent, n: GraphNode) {
|
|
436
|
+
if (suppressClick || ownsEvent(e)) return;
|
|
437
|
+
if (!interactive) { selected = [n.id]; selectedEdge = undefined; }
|
|
438
|
+
onnodeclick?.(n, e);
|
|
439
|
+
}
|
|
365
440
|
function nodeDblClick(e: MouseEvent, n: GraphNode) { if (!ownsEvent(e)) onnodedblclick?.(n, e); }
|
|
366
441
|
function nodeMenu(e: MouseEvent, n: GraphNode) {
|
|
367
442
|
if (!onnodecontextmenu || ownsEvent(e)) return;
|
|
@@ -385,7 +460,7 @@
|
|
|
385
460
|
const valid = (from: { node: string; port: string }, to: { node: string; port: string }) =>
|
|
386
461
|
from.node !== to.node && (isValidConnection?.(from, to) ?? true);
|
|
387
462
|
function portDown(e: PointerEvent, n: GraphNode, p: GraphPort) {
|
|
388
|
-
if (!connectable || !
|
|
463
|
+
if (!connectable || !edit) return;
|
|
389
464
|
e.stopPropagation();
|
|
390
465
|
e.preventDefault();
|
|
391
466
|
const g0 = toGraph(e.clientX, e.clientY);
|
|
@@ -423,7 +498,7 @@
|
|
|
423
498
|
});
|
|
424
499
|
|
|
425
500
|
function remove() {
|
|
426
|
-
if (!
|
|
501
|
+
if (!edit) return;
|
|
427
502
|
if (selectedEdge) edges = edges.filter((e) => e.id !== selectedEdge);
|
|
428
503
|
if (selected.length) {
|
|
429
504
|
edges = edges.filter((e) => !selected.includes(e.from) && !selected.includes(e.to));
|
|
@@ -471,10 +546,13 @@
|
|
|
471
546
|
}
|
|
472
547
|
function goTo(n: GraphNode) {
|
|
473
548
|
selected = [n.id]; selectedEdge = undefined;
|
|
549
|
+
if (interactive) panInto(n);
|
|
550
|
+
tick().then(() => root?.querySelector<HTMLElement>(`.node[data-id="${CSS.escape(n.id)}"]`)?.focus());
|
|
551
|
+
}
|
|
552
|
+
function panInto(n: GraphNode) {
|
|
474
553
|
const pad = 32, sx = n.x * k + tx, sy = n.y * k + ty, sw = W(n) * k, sh = H(n) * k;
|
|
475
554
|
if (sx < pad) tx += pad - sx; else if (sx + sw > rw - pad) tx -= sx + sw - (rw - pad);
|
|
476
555
|
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
556
|
}
|
|
479
557
|
function onKey(e: KeyboardEvent) {
|
|
480
558
|
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 +566,7 @@
|
|
|
488
566
|
}
|
|
489
567
|
const step = e.shiftKey ? 32 : 8;
|
|
490
568
|
const mv = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
|
|
491
|
-
if (mv && !
|
|
569
|
+
if (mv && !edit) {
|
|
492
570
|
const cur = (e.target as HTMLElement).closest<HTMLElement>('.node')?.dataset.id ?? selected[0];
|
|
493
571
|
const next = neighbour(cur ? byId.get(cur) : undefined, e.key);
|
|
494
572
|
if (!next) return;
|
|
@@ -500,12 +578,12 @@
|
|
|
500
578
|
if (collapsed.includes(id)) expand(id);
|
|
501
579
|
else if (childrenOf.get(id)?.length) collapse(id);
|
|
502
580
|
else return;
|
|
503
|
-
} else if (mv && selected.length &&
|
|
581
|
+
} else if (mv && selected.length && edit) {
|
|
504
582
|
nodes = nodes.map((n) => (selected.includes(n.id) ? { ...n, x: n.x + mv[0], y: n.y + mv[1] } : n));
|
|
505
583
|
} 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();
|
|
584
|
+
else if (interactive && (e.key === '+' || e.key === '=')) zoomCenter(1.2);
|
|
585
|
+
else if (interactive && e.key === '-') zoomCenter(1 / 1.2);
|
|
586
|
+
else if (interactive && e.key === '0') fit();
|
|
509
587
|
else if (e.key === 'Escape') { selected = []; selectedEdge = undefined; }
|
|
510
588
|
else return;
|
|
511
589
|
e.preventDefault();
|
|
@@ -514,13 +592,13 @@
|
|
|
514
592
|
|
|
515
593
|
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
|
|
516
594
|
<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}
|
|
595
|
+
{...rest} class={'trg ' + klass} bind:this={root} bind:clientWidth={rw} bind:clientHeight={rh} role="application" tabindex="0" data-panning={panning} data-static={!interactive}
|
|
596
|
+
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.')}
|
|
597
|
+
style:height={widthFit ? px(widthFit.h) : typeof height === 'number' ? `${height}px` : height}
|
|
598
|
+
style:--tx={px(view.tx)} style:--ty={px(view.ty)} style:--k={view.k} style:--trg-lines={Math.max(1, labelLines)}
|
|
521
599
|
onpointerdown={bgDown} onkeydown={onKey}
|
|
522
600
|
>
|
|
523
|
-
<div class="viewport" bind:this={viewport} style:transform="translate({tx}px, {ty}px) scale({k})">
|
|
601
|
+
<div class="viewport" bind:this={viewport} style:transform="translate({view.tx}px, {view.ty}px) scale({view.k})">
|
|
524
602
|
<svg class="edges" width="1" height="1">
|
|
525
603
|
<defs>
|
|
526
604
|
<marker id="trg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
|
|
@@ -583,7 +661,7 @@
|
|
|
583
661
|
<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
662
|
style:left="{a.x - n.x}px" style:top="{a.y - n.y}px"></span>
|
|
585
663
|
{:else}
|
|
586
|
-
<span class="port" role="presentation" data-side={p.side} data-connectable={connectable &&
|
|
664
|
+
<span class="port" role="presentation" data-side={p.side} data-connectable={connectable && edit} onpointerdown={(e) => portDown(e, n, p)}
|
|
587
665
|
style:left="{a.x - n.x}px" style:top="{a.y - n.y}px"></span>
|
|
588
666
|
{/if}
|
|
589
667
|
{#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 +710,14 @@
|
|
|
632
710
|
<!-- node-attached overlays (HoverCard, Popover) are lifted here, outside the transformed canvas -->
|
|
633
711
|
<div class="trg-overlay" bind:this={overlay}></div>
|
|
634
712
|
|
|
713
|
+
{#if interactive}
|
|
635
714
|
<div class="controls" role="toolbar" aria-label="Graph controls">
|
|
636
715
|
<Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label="Zoom in" onclick={() => zoomCenter(1.2)} />
|
|
637
716
|
<Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label="Zoom out" onclick={() => zoomCenter(1 / 1.2)} />
|
|
638
717
|
<Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label="Fit to view" onclick={() => fit()} />
|
|
639
|
-
{#if
|
|
718
|
+
{#if edit}<Button variant="minimal" intent="neutral" size="sm" icon="refresh" aria-label="Auto layout" onclick={() => layout()} />{/if}
|
|
640
719
|
</div>
|
|
720
|
+
{/if}
|
|
641
721
|
</div>
|
|
642
722
|
|
|
643
723
|
<style>
|
|
@@ -664,6 +744,8 @@
|
|
|
664
744
|
}
|
|
665
745
|
.trg-overlay { position: absolute; left: 0; top: 0; width: 0; height: 0; }
|
|
666
746
|
.trg[data-panning='true'] { cursor: grabbing; }
|
|
747
|
+
/* static: touches and wheels belong to the page, which scrolls through the graph */
|
|
748
|
+
.trg[data-static='true'] { touch-action: auto; cursor: default; }
|
|
667
749
|
.trg:focus-visible { box-shadow: var(--tr-focus-ring); border-color: var(--tr-primary); }
|
|
668
750
|
.viewport { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
|
|
669
751
|
.edges { position: absolute; left: 0; top: 0; overflow: visible; pointer-events: none; }
|
|
@@ -739,8 +821,9 @@
|
|
|
739
821
|
.custom { width: 100%; min-width: 0; }
|
|
740
822
|
.custom.fill { height: 100%; }
|
|
741
823
|
.content { flex: 1; min-width: 0; padding: 0 12px 0 16px; line-height: 1.25; }
|
|
742
|
-
.label {
|
|
743
|
-
.
|
|
824
|
+
.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; }
|
|
825
|
+
.label { font-weight: 600; color: var(--tr-on-surface); }
|
|
826
|
+
.subtitle { font-size: var(--tr-text-sm); color: var(--tr-on-surface-variant); }
|
|
744
827
|
|
|
745
828
|
.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
829
|
.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,12 @@
|
|
|
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
|
+
*
|
|
6
|
+
* `gapX` is the minimum space between ranks (columns in LR, rows in TB), `gapY` the space between nodes inside a rank.
|
|
7
|
+
* A rank gap grows to fit the widest label of the edges crossing it (`labelSize`; pass `edgeLabel` when the graph
|
|
8
|
+
* renders an `edgeLabel` snippet), plus a margin; a gap no edge labels stays at `gapX`. A multi-rank edge counts in
|
|
9
|
+
* the middle gap it spans, where its label sits.
|
|
5
10
|
*
|
|
6
11
|
* `pin` (node ids) makes it incremental: pinned nodes keep their exact position and every other node is placed
|
|
7
12
|
* in the column after (or before) its placed neighbours, nudged along the column until it overlaps nothing.
|
|
@@ -11,6 +16,7 @@ export declare function autoLayout(nodes: GraphNode[], edges: GraphEdge[], opts?
|
|
|
11
16
|
gapY?: number;
|
|
12
17
|
direction?: 'LR' | 'TB';
|
|
13
18
|
pin?: Iterable<string>;
|
|
19
|
+
edgeLabel?: boolean;
|
|
14
20
|
}): GraphNode[];
|
|
15
21
|
/**
|
|
16
22
|
* Force-directed layout (Fruchterman-Reingold). Deterministic for a given `seed`; repulsion is
|
package/dist/layout.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { labelSize } from './routing.js';
|
|
1
2
|
import { NODE_H, NODE_W } from './types.js';
|
|
2
3
|
/** Ids from `pin` that exist in `nodes`, or null when none do (the layout then runs from scratch). */
|
|
3
4
|
function pinnedIn(nodes, pin) {
|
|
@@ -10,6 +11,8 @@ function pinnedIn(nodes, pin) {
|
|
|
10
11
|
return out.size ? out : null;
|
|
11
12
|
}
|
|
12
13
|
const PAD = 16;
|
|
14
|
+
/** Clear space kept on each side of an edge label inside its rank gap. */
|
|
15
|
+
const LABEL_MARGIN = 12;
|
|
13
16
|
/**
|
|
14
17
|
* Incremental placement: pinned nodes are returned untouched; every other node is placed near the nodes it is
|
|
15
18
|
* connected to (`want` picks the spot from its already-placed neighbours), then nudged along `probe` until it
|
|
@@ -76,7 +79,12 @@ function placeAround(nodes, edges, pinned, want, probe, gap) {
|
|
|
76
79
|
}
|
|
77
80
|
/**
|
|
78
81
|
* Layered (Sugiyama-lite) auto layout: longest-path layering, one barycenter sweep to
|
|
79
|
-
* reduce crossings, columns centred vertically. Cycle-safe. Returns new node objects.
|
|
82
|
+
* 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.
|
|
83
|
+
*
|
|
84
|
+
* `gapX` is the minimum space between ranks (columns in LR, rows in TB), `gapY` the space between nodes inside a rank.
|
|
85
|
+
* A rank gap grows to fit the widest label of the edges crossing it (`labelSize`; pass `edgeLabel` when the graph
|
|
86
|
+
* renders an `edgeLabel` snippet), plus a margin; a gap no edge labels stays at `gapX`. A multi-rank edge counts in
|
|
87
|
+
* the middle gap it spans, where its label sits.
|
|
80
88
|
*
|
|
81
89
|
* `pin` (node ids) makes it incremental: pinned nodes keep their exact position and every other node is placed
|
|
82
90
|
* in the column after (or before) its placed neighbours, nudged along the column until it overlaps nothing.
|
|
@@ -103,20 +111,40 @@ export function autoLayout(nodes, edges, opts = {}) {
|
|
|
103
111
|
return placeAround(nodes, edges, pinned, want, probe, gapX);
|
|
104
112
|
}
|
|
105
113
|
const ids = new Set(nodes.map((n) => n.id));
|
|
106
|
-
|
|
114
|
+
// Cycles: a depth-first walk in input order (sources first, then whatever is left) finds the back-edges, those
|
|
115
|
+
// pointing at a node still on the walk's stack. Ranking ignores them, so the forward order stays intact and the
|
|
116
|
+
// layers do not shift; they are routed around the side by `routeEdge`.
|
|
117
|
+
const outs = new Map(nodes.map((n) => [n.id, []]));
|
|
118
|
+
const hasIn = new Set();
|
|
107
119
|
for (const e of edges)
|
|
108
|
-
if (ids.has(e.from) && ids.has(e.to) && e.from !== e.to)
|
|
109
|
-
|
|
120
|
+
if (ids.has(e.from) && ids.has(e.to) && e.from !== e.to) {
|
|
121
|
+
outs.get(e.from).push(e.to);
|
|
122
|
+
hasIn.add(e.to);
|
|
123
|
+
}
|
|
124
|
+
const preds = new Map(nodes.map((n) => [n.id, []]));
|
|
125
|
+
const state = new Map(); // 1 = on the stack, 2 = done
|
|
126
|
+
const walk = (id) => {
|
|
127
|
+
state.set(id, 1);
|
|
128
|
+
for (const to of outs.get(id)) {
|
|
129
|
+
if (state.get(to) === 1)
|
|
130
|
+
continue; // back-edge
|
|
131
|
+
preds.get(to).push(id);
|
|
132
|
+
if (!state.has(to))
|
|
133
|
+
walk(to);
|
|
134
|
+
}
|
|
135
|
+
state.set(id, 2);
|
|
136
|
+
};
|
|
137
|
+
for (const n of nodes)
|
|
138
|
+
if (!hasIn.has(n.id) && !state.has(n.id))
|
|
139
|
+
walk(n.id);
|
|
140
|
+
for (const n of nodes)
|
|
141
|
+
if (!state.has(n.id))
|
|
142
|
+
walk(n.id);
|
|
110
143
|
const layer = new Map();
|
|
111
|
-
const visiting = new Set();
|
|
112
144
|
const depth = (id) => {
|
|
113
145
|
if (layer.has(id))
|
|
114
146
|
return layer.get(id);
|
|
115
|
-
if (visiting.has(id))
|
|
116
|
-
return 0; // break cycles
|
|
117
|
-
visiting.add(id);
|
|
118
147
|
const d = preds.get(id).reduce((m, p) => Math.max(m, depth(p) + 1), 0);
|
|
119
|
-
visiting.delete(id);
|
|
120
148
|
layer.set(id, d);
|
|
121
149
|
return d;
|
|
122
150
|
};
|
|
@@ -137,18 +165,27 @@ export function autoLayout(nodes, edges, opts = {}) {
|
|
|
137
165
|
});
|
|
138
166
|
const w = (n) => n.width ?? NODE_W;
|
|
139
167
|
const h = (n) => n.height ?? NODE_H;
|
|
168
|
+
// rank gaps: gapX, or more where the labels of the edges crossing it need the room (their extent along the rank axis)
|
|
169
|
+
const need = new Array(cols.length).fill(0);
|
|
170
|
+
for (const e of edges) {
|
|
171
|
+
const a = layer.get(e.from), b = layer.get(e.to), size = labelSize(e, opts.edgeLabel);
|
|
172
|
+
if (a == null || b == null || b <= a || !size)
|
|
173
|
+
continue;
|
|
174
|
+
const g = Math.floor((a + b - 1) / 2);
|
|
175
|
+
need[g] = Math.max(need[g], (direction === 'LR' ? size.w : size.h) + LABEL_MARGIN * 2);
|
|
176
|
+
}
|
|
140
177
|
const pos = new Map();
|
|
141
178
|
const span = (col) => col.reduce((a, n) => a + (direction === 'LR' ? h(n) : w(n)) + gapY, -gapY);
|
|
142
179
|
const tallest = Math.max(0, ...cols.filter(Boolean).map(span));
|
|
143
180
|
let offset = 0;
|
|
144
|
-
cols.forEach((col) => {
|
|
181
|
+
cols.forEach((col, ci) => {
|
|
145
182
|
const colSize = col.reduce((m, n) => Math.max(m, direction === 'LR' ? w(n) : h(n)), 0);
|
|
146
183
|
let cursor = (tallest - span(col)) / 2;
|
|
147
184
|
for (const n of col) {
|
|
148
185
|
pos.set(n.id, direction === 'LR' ? { x: offset, y: cursor } : { x: cursor, y: offset });
|
|
149
186
|
cursor += (direction === 'LR' ? h(n) : w(n)) + gapY;
|
|
150
187
|
}
|
|
151
|
-
offset += colSize + gapX;
|
|
188
|
+
offset += colSize + Math.max(gapX, need[ci]);
|
|
152
189
|
});
|
|
153
190
|
return nodes.map((n) => ({ ...n, ...pos.get(n.id) }));
|
|
154
191
|
}
|
package/dist/routing.d.ts
CHANGED
|
@@ -21,5 +21,28 @@ 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
|
+
/**
|
|
37
|
+
* Estimated size of an edge's label box: 180 x 32 for an `edgeLabel` snippet (any edge), else the text's width
|
|
38
|
+
* (`len * 6.8 + 16`) by 20 for a plain `label`, or null when the edge has none. Shared by label spreading and the
|
|
39
|
+
* layered layout (which widens a rank gap to fit the labels crossing it).
|
|
40
|
+
*/
|
|
41
|
+
export declare function labelSize(edge: {
|
|
42
|
+
label?: string;
|
|
43
|
+
}, snippet?: boolean): {
|
|
44
|
+
w: number;
|
|
45
|
+
h: number;
|
|
46
|
+
} | null;
|
|
47
|
+
/** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
|
|
25
48
|
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,62 @@ 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
|
+
/**
|
|
263
|
+
* Estimated size of an edge's label box: 180 x 32 for an `edgeLabel` snippet (any edge), else the text's width
|
|
264
|
+
* (`len * 6.8 + 16`) by 20 for a plain `label`, or null when the edge has none. Shared by label spreading and the
|
|
265
|
+
* layered layout (which widens a rank gap to fit the labels crossing it).
|
|
266
|
+
*/
|
|
267
|
+
export function labelSize(edge, snippet = false) {
|
|
268
|
+
return snippet ? { w: 180, h: 32 } : edge.label ? { w: edge.label.length * 6.8 + 16, h: 20 } : null;
|
|
269
|
+
}
|
|
270
|
+
/** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
|
|
223
271
|
export function routeEdge(type, a, b, obstacles = []) {
|
|
224
272
|
switch (type) {
|
|
225
273
|
case 'straight':
|
|
226
274
|
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
275
|
case 'step': {
|
|
228
|
-
const p =
|
|
276
|
+
const p = clearPoints(a, b, obstacles);
|
|
229
277
|
return { d: pathOf(p, 0), mid: midOf(p) };
|
|
230
278
|
}
|
|
231
279
|
case 'smoothstep': {
|
|
232
|
-
const p =
|
|
280
|
+
const p = clearPoints(a, b, obstacles);
|
|
233
281
|
return { d: pathOf(p, 12), mid: midOf(p) };
|
|
234
282
|
}
|
|
235
283
|
case 'avoid': {
|
package/dist/types.d.ts
CHANGED
|
@@ -15,6 +15,10 @@ export type GraphLegend = {
|
|
|
15
15
|
export type GraphLayoutOptions = {
|
|
16
16
|
/** Ids that keep their position; every other node is placed near its neighbours. No fit-to-view afterwards, so the viewport stays put. */
|
|
17
17
|
pin?: string[];
|
|
18
|
+
/** Minimum space between layers for the layered layout (default 90); a layer gap still grows to fit the edge labels crossing it. */
|
|
19
|
+
gapX?: number;
|
|
20
|
+
/** Space between nodes inside a layer for the layered layout (default 28). */
|
|
21
|
+
gapY?: number;
|
|
18
22
|
};
|
|
19
23
|
export type EdgeType = 'bezier' | 'straight' | 'step' | 'smoothstep' | 'avoid';
|
|
20
24
|
export type GraphPort = {
|