@ruckc/truss-graph 1.24.0 → 1.26.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 +12 -8
- package/dist/layout.d.ts +6 -0
- package/dist/layout.js +19 -2
- package/dist/routing.d.ts +18 -2
- package/dist/routing.js +33 -6
- 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, spreadLabels, 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 {
|
|
@@ -245,9 +245,9 @@
|
|
|
245
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 [];
|
|
246
246
|
const pa = findPort(a, e.fromPort, 'out'), pb = findPort(b, e.toPort, 'in');
|
|
247
247
|
if (!pa || !pb) return [];
|
|
248
|
-
const r = routeEdge(routeType(e.type ?? edgeType), portAnchor(a, pa, portsOf(a)), portAnchor(b, pb, portsOf(b)), needsObstacles ? rects : []);
|
|
248
|
+
const r = routeEdge(routeType(e.type ?? edgeType), portAnchor(a, pa, portsOf(a)), portAnchor(b, pb, portsOf(b)), needsObstacles ? rects : [], labelSize(e, !!edgeLabel));
|
|
249
249
|
return [{ e, d: r.d, m: r.mid }];
|
|
250
|
-
}), (g) => (
|
|
250
|
+
}), (g) => labelSize(g.e, !!edgeLabel), needsObstacles ? rects : [])
|
|
251
251
|
);
|
|
252
252
|
const toGraph = (cx: number, cy: number) => {
|
|
253
253
|
const r = root.getBoundingClientRect();
|
|
@@ -271,13 +271,17 @@
|
|
|
271
271
|
}
|
|
272
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
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;
|
|
274
277
|
let measured = $state(false);
|
|
275
278
|
const widthFit = $derived.by(() => {
|
|
276
279
|
if (fitMode !== 'width' || !live.length || !rw) return null;
|
|
277
280
|
const { x0, y0, x1, y1 } = bounds();
|
|
281
|
+
const top = WIDTH_PAD + (interactive ? CONTROLS_BAND : 0);
|
|
278
282
|
// until the container is measured (server render, first paint) `rw` is a guess: stay at full size, left-aligned
|
|
279
283
|
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:
|
|
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) };
|
|
281
285
|
});
|
|
282
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
|
|
283
287
|
const view = $derived(widthFit ?? { k, tx, ty });
|
|
@@ -321,17 +325,17 @@
|
|
|
321
325
|
* after adding nodes ("expand neighbours"): `g.layout({ pin: existingIds })`.
|
|
322
326
|
*/
|
|
323
327
|
export function layout(opts: GraphLayoutOptions = {}) {
|
|
324
|
-
nodes = computeLayout(opts
|
|
328
|
+
nodes = computeLayout(opts);
|
|
325
329
|
onchange?.();
|
|
326
330
|
// the graph may be gone by the next frame (navigating away right after pressing the button)
|
|
327
331
|
if (!opts.pin?.length) requestAnimationFrame(() => { if (root?.isConnected) fit(); });
|
|
328
332
|
}
|
|
329
|
-
function computeLayout(pin
|
|
333
|
+
function computeLayout({ pin, gapX, gapY }: GraphLayoutOptions = {}): GraphNode[] {
|
|
330
334
|
// the layout spaces nodes by their size: hand it the card heights (wrapped labels), then keep only the positions
|
|
331
335
|
const sizedIn = nodes.map(sized);
|
|
332
336
|
const out = layoutMode === 'force' ? forceLayout(sizedIn, edges, { pin })
|
|
333
337
|
: layoutMode === 'radial' ? radialLayout(sizedIn, edges, { root: selected[0], pin })
|
|
334
|
-
: autoLayout(sizedIn, edges, { direction, pin });
|
|
338
|
+
: autoLayout(sizedIn, edges, { direction, pin, gapX, gapY, edgeLabel: !!edgeLabel });
|
|
335
339
|
const orig = new Map(nodes.map((n) => [n.id, n]));
|
|
336
340
|
return out.map((o) => ({ ...orig.get(o.id)!, x: o.x, y: o.y }));
|
|
337
341
|
}
|
|
@@ -381,7 +385,7 @@
|
|
|
381
385
|
function bgDown(e: PointerEvent) {
|
|
382
386
|
if ((e.target as HTMLElement).closest('.node, .controls, .edge-hit, .elabel, .minimap, .legend, .trg-overlay')) return;
|
|
383
387
|
selected = []; selectedEdge = undefined;
|
|
384
|
-
root.focus({ preventScroll: !interactive }); // a tall static graph must not jump the page when tapped
|
|
388
|
+
root.focus({ preventScroll: !interactive || !!widthFit }); // a tall static or width-fitted graph must not jump the page when tapped
|
|
385
389
|
if (!interactive) return; // no pan: the browser scrolls the page
|
|
386
390
|
const sx = e.clientX, sy = e.clientY, tx0 = tx, ty0 = ty;
|
|
387
391
|
panning = true;
|
package/dist/layout.d.ts
CHANGED
|
@@ -3,6 +3,11 @@ import { type GraphEdge, type GraphNode } from './types.js';
|
|
|
3
3
|
* Layered (Sugiyama-lite) auto layout: longest-path layering, one barycenter sweep to
|
|
4
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
|
+
* `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.
|
|
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.
|
|
8
13
|
*/
|
|
@@ -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
|
|
@@ -78,6 +81,11 @@ function placeAround(nodes, edges, pinned, want, probe, gap) {
|
|
|
78
81
|
* Layered (Sugiyama-lite) auto layout: longest-path layering, one barycenter sweep to
|
|
79
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.
|
|
80
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.
|
|
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.
|
|
83
91
|
*/
|
|
@@ -157,18 +165,27 @@ export function autoLayout(nodes, edges, opts = {}) {
|
|
|
157
165
|
});
|
|
158
166
|
const w = (n) => n.width ?? NODE_W;
|
|
159
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
|
+
}
|
|
160
177
|
const pos = new Map();
|
|
161
178
|
const span = (col) => col.reduce((a, n) => a + (direction === 'LR' ? h(n) : w(n)) + gapY, -gapY);
|
|
162
179
|
const tallest = Math.max(0, ...cols.filter(Boolean).map(span));
|
|
163
180
|
let offset = 0;
|
|
164
|
-
cols.forEach((col) => {
|
|
181
|
+
cols.forEach((col, ci) => {
|
|
165
182
|
const colSize = col.reduce((m, n) => Math.max(m, direction === 'LR' ? w(n) : h(n)), 0);
|
|
166
183
|
let cursor = (tallest - span(col)) / 2;
|
|
167
184
|
for (const n of col) {
|
|
168
185
|
pos.set(n.id, direction === 'LR' ? { x: offset, y: cursor } : { x: cursor, y: offset });
|
|
169
186
|
cursor += (direction === 'LR' ? h(n) : w(n)) + gapY;
|
|
170
187
|
}
|
|
171
|
-
offset += colSize + gapX;
|
|
188
|
+
offset += colSize + Math.max(gapX, need[ci]);
|
|
172
189
|
});
|
|
173
190
|
return nodes.map((n) => ({ ...n, ...pos.get(n.id) }));
|
|
174
191
|
}
|
package/dist/routing.d.ts
CHANGED
|
@@ -21,6 +21,10 @@ 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
|
+
type Box = {
|
|
25
|
+
w: number;
|
|
26
|
+
h: number;
|
|
27
|
+
};
|
|
24
28
|
/**
|
|
25
29
|
* Edge labels sit at the midpoint of their edge, and edges that fan out share their first segments, so the
|
|
26
30
|
* midpoints crowd together. Walks the items in order and slides each label along y (0, +1, -1, +2, ... steps of
|
|
@@ -32,6 +36,18 @@ export declare function spreadLabels<T extends {
|
|
|
32
36
|
}>(items: T[], size: (item: T) => {
|
|
33
37
|
w: number;
|
|
34
38
|
h: number;
|
|
35
|
-
} | null): T[];
|
|
39
|
+
} | null, obstacles?: Rect[]): T[];
|
|
40
|
+
/**
|
|
41
|
+
* Estimated size of an edge's label box: 180 x 32 for an `edgeLabel` snippet (any edge), else the text's width
|
|
42
|
+
* (`len * 6.8 + 16`) by 20 for a plain `label`, or null when the edge has none. Shared by label spreading and the
|
|
43
|
+
* layered layout (which widens a rank gap to fit the labels crossing it).
|
|
44
|
+
*/
|
|
45
|
+
export declare function labelSize(edge: {
|
|
46
|
+
label?: string;
|
|
47
|
+
}, snippet?: boolean): {
|
|
48
|
+
w: number;
|
|
49
|
+
h: number;
|
|
50
|
+
} | null;
|
|
36
51
|
/** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
|
|
37
|
-
export declare function routeEdge(type: EdgeType, a: Anchor, b: Anchor, obstacles?: Rect[]): Routed;
|
|
52
|
+
export declare function routeEdge(type: EdgeType, a: Anchor, b: Anchor, obstacles?: Rect[], label?: Box | null): Routed;
|
|
53
|
+
export {};
|
package/dist/routing.js
CHANGED
|
@@ -69,6 +69,23 @@ function midOf(pts) {
|
|
|
69
69
|
}
|
|
70
70
|
return pts.at(-1);
|
|
71
71
|
}
|
|
72
|
+
const overlaps = (c, s, o) => Math.abs(c.x - (o.x + o.w / 2)) < (o.w + s.w) / 2 && Math.abs(c.y - (o.y + o.h / 2)) < (o.h + s.h) / 2;
|
|
73
|
+
/**
|
|
74
|
+
* Where an orthogonal route's label goes: its midpoint, unless the label box there would cover a node (a self-loop or an
|
|
75
|
+
* aligned back-edge hugs its card). Then the label moves off the line, perpendicular to the segment, to whichever side
|
|
76
|
+
* (the outer one first) clears every node; it keeps the midpoint when neither does.
|
|
77
|
+
*/
|
|
78
|
+
function labelPoint(pts, size, obstacles) {
|
|
79
|
+
const m = midOf(pts);
|
|
80
|
+
if (!size || !obstacles.some((o) => overlaps(m, size, o)))
|
|
81
|
+
return m;
|
|
82
|
+
// the segment holding the midpoint is vertical when its ends share x (the midpoint always lies on a segment)
|
|
83
|
+
const k = pts.findIndex((p, i) => i > 0 && dist(pts[i - 1], m) + dist(m, p) < dist(pts[i - 1], p) + 0.01);
|
|
84
|
+
const vertical = Math.abs(pts[k].x - pts[k - 1].x) < 0.01;
|
|
85
|
+
const off = (vertical ? size.w : size.h) / 2 + 6;
|
|
86
|
+
const spots = [off, -off].map((d) => (vertical ? { x: m.x + d, y: m.y } : { x: m.x, y: m.y + d }));
|
|
87
|
+
return spots.find((c) => !obstacles.some((o) => overlaps(c, size, o))) ?? m;
|
|
88
|
+
}
|
|
72
89
|
const stubOf = (a, s) => ({ x: a.x + DIR[a.side].x * s, y: a.y + DIR[a.side].y * s });
|
|
73
90
|
// ---------- routers
|
|
74
91
|
function bezier(a, b) {
|
|
@@ -243,13 +260,15 @@ function clearPoints(a, b, obstacles) {
|
|
|
243
260
|
* its own height) until its box clears every label placed before it. `size` is null for an item without a label.
|
|
244
261
|
* Pure and deterministic; an item that finds no free spot within 12 tries keeps its own midpoint.
|
|
245
262
|
*/
|
|
246
|
-
export function spreadLabels(items, size) {
|
|
263
|
+
export function spreadLabels(items, size, obstacles = []) {
|
|
247
264
|
const placed = [];
|
|
248
265
|
return items.map((item) => {
|
|
249
266
|
const s = size(item);
|
|
250
267
|
if (!s)
|
|
251
268
|
return item;
|
|
252
|
-
|
|
269
|
+
// a slid label also steers clear of the nodes (a label kept at its routed midpoint is left as routed)
|
|
270
|
+
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)
|
|
271
|
+
|| (y !== item.m.y && obstacles.some((o) => overlaps({ x: item.m.x, y }, s, o)));
|
|
253
272
|
let y = item.m.y;
|
|
254
273
|
for (let k = 0; k < 12 && hit(y); k++)
|
|
255
274
|
y = item.m.y + (k % 2 ? -1 : 1) * Math.ceil((k + 1) / 2) * (s.h + 2);
|
|
@@ -259,22 +278,30 @@ export function spreadLabels(items, size) {
|
|
|
259
278
|
return y === item.m.y ? item : { ...item, m: { x: item.m.x, y } };
|
|
260
279
|
});
|
|
261
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* Estimated size of an edge's label box: 180 x 32 for an `edgeLabel` snippet (any edge), else the text's width
|
|
283
|
+
* (`len * 6.8 + 16`) by 20 for a plain `label`, or null when the edge has none. Shared by label spreading and the
|
|
284
|
+
* layered layout (which widens a rank gap to fit the labels crossing it).
|
|
285
|
+
*/
|
|
286
|
+
export function labelSize(edge, snippet = false) {
|
|
287
|
+
return snippet ? { w: 180, h: 32 } : edge.label ? { w: edge.label.length * 6.8 + 16, h: 20 } : null;
|
|
288
|
+
}
|
|
262
289
|
/** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
|
|
263
|
-
export function routeEdge(type, a, b, obstacles = []) {
|
|
290
|
+
export function routeEdge(type, a, b, obstacles = [], label = null) {
|
|
264
291
|
switch (type) {
|
|
265
292
|
case 'straight':
|
|
266
293
|
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 } };
|
|
267
294
|
case 'step': {
|
|
268
295
|
const p = clearPoints(a, b, obstacles);
|
|
269
|
-
return { d: pathOf(p, 0), mid:
|
|
296
|
+
return { d: pathOf(p, 0), mid: labelPoint(p, label, obstacles) };
|
|
270
297
|
}
|
|
271
298
|
case 'smoothstep': {
|
|
272
299
|
const p = clearPoints(a, b, obstacles);
|
|
273
|
-
return { d: pathOf(p, 12), mid:
|
|
300
|
+
return { d: pathOf(p, 12), mid: labelPoint(p, label, obstacles) };
|
|
274
301
|
}
|
|
275
302
|
case 'avoid': {
|
|
276
303
|
const p = avoidPoints(a, b, obstacles) ?? orthogonalPoints(a, b);
|
|
277
|
-
return { d: pathOf(p, 10), mid:
|
|
304
|
+
return { d: pathOf(p, 10), mid: labelPoint(p, label, obstacles) };
|
|
278
305
|
}
|
|
279
306
|
default:
|
|
280
307
|
return bezier(a, b);
|
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 = {
|