@ruckc/truss-graph 1.6.0 → 1.8.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 +127 -33
- package/dist/Graph.svelte.d.ts +12 -2
- package/dist/index.d.ts +1 -1
- package/dist/layout.d.ts +12 -0
- package/dist/layout.js +186 -17
- package/dist/routing.js +2 -2
- package/dist/types.d.ts +11 -0
- package/package.json +1 -1
package/dist/Graph.svelte
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { Button } from '@ruckc/truss-ui';
|
|
4
4
|
import { autoLayout, forceLayout, radialLayout } from './layout.js';
|
|
5
5
|
import { defaultPorts, opposite, portAnchor, routeEdge, type Anchor, type Rect } from './routing.js';
|
|
6
|
-
import { NODE_H, NODE_W, type EdgeType, type GraphEdge, type GraphLayout, type GraphLegend, type GraphNode, type GraphPort, type HighlightDirection, type NodeCtx, type NodeKind, type NodeRenderer } from './types.js';
|
|
6
|
+
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';
|
|
7
7
|
|
|
8
8
|
let {
|
|
9
9
|
nodes = $bindable([]),
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
direction = 'LR',
|
|
18
18
|
layout: layoutMode = 'layered',
|
|
19
19
|
legend,
|
|
20
|
+
categories,
|
|
20
21
|
connectable = true,
|
|
21
22
|
editable = true,
|
|
22
23
|
fitOnMount = true,
|
|
@@ -28,7 +29,11 @@
|
|
|
28
29
|
edgeLabel,
|
|
29
30
|
isValidConnection,
|
|
30
31
|
onconnect,
|
|
31
|
-
onchange
|
|
32
|
+
onchange,
|
|
33
|
+
onnodeclick,
|
|
34
|
+
onnodedblclick,
|
|
35
|
+
onnodehover,
|
|
36
|
+
onnodecontextmenu
|
|
32
37
|
}: {
|
|
33
38
|
nodes?: GraphNode[];
|
|
34
39
|
edges?: GraphEdge[];
|
|
@@ -48,6 +53,8 @@
|
|
|
48
53
|
layout?: GraphLayout;
|
|
49
54
|
/** Key for node and edge kinds. `true` derives it from the kinds in use; or pass labels per kind. Edge entries toggle `hiddenEdgeKinds`. */
|
|
50
55
|
legend?: boolean | GraphLegend;
|
|
56
|
+
/** Names for `node.category` (index = category), used by the legend. Missing names read "Category N". */
|
|
57
|
+
categories?: string[];
|
|
51
58
|
/** Drag from an output port to an input port to create edges. */
|
|
52
59
|
connectable?: boolean;
|
|
53
60
|
/** Allow moving and deleting. */
|
|
@@ -68,9 +75,19 @@
|
|
|
68
75
|
isValidConnection?: (from: { node: string; port: string }, to: { node: string; port: string }) => boolean;
|
|
69
76
|
onconnect?: (edge: GraphEdge) => void;
|
|
70
77
|
onchange?: () => void;
|
|
78
|
+
/** A node was clicked (also Enter on a focused node). Selection has already updated; call `event.preventDefault()` on an Enter press to skip the collapse toggle. Clicks that end a drag, and clicks on ports, expander badges or controls inside custom nodes, do not count. */
|
|
79
|
+
onnodeclick?: (node: GraphNode, event: MouseEvent | KeyboardEvent) => void;
|
|
80
|
+
/** A node was double-clicked. A double-click also fires `onnodeclick` twice first, as the browser does; the graph itself has no double-click action. */
|
|
81
|
+
onnodedblclick?: (node: GraphNode, event: MouseEvent) => void;
|
|
82
|
+
/** The pointer entered a node, or `null` when it left. */
|
|
83
|
+
onnodehover?: (node: GraphNode | null) => void;
|
|
84
|
+
/** Right-click, or ContextMenu / Shift+F10 on a focused node. The native menu is suppressed when this is set (except over inputs and links inside custom nodes). */
|
|
85
|
+
onnodecontextmenu?: (node: GraphNode, event: MouseEvent | KeyboardEvent) => void;
|
|
71
86
|
} = $props();
|
|
72
87
|
|
|
73
88
|
let root: HTMLDivElement;
|
|
89
|
+
let viewport: HTMLDivElement;
|
|
90
|
+
let overlay: HTMLDivElement;
|
|
74
91
|
let tx = $state(0), ty = $state(0), k = $state(1);
|
|
75
92
|
let drag = $state<{ ids: string[]; dx: number; dy: number } | null>(null);
|
|
76
93
|
let link = $state<{ from: string; port: string; x: number; y: number; over?: { node: string; port: string } } | null>(null);
|
|
@@ -145,10 +162,11 @@
|
|
|
145
162
|
const BIG = 150, CELL = 320;
|
|
146
163
|
const big = $derived(live.length > BIG);
|
|
147
164
|
const minK = $derived(big ? 0.04 : 0.2);
|
|
148
|
-
|
|
149
|
-
const
|
|
150
|
-
const
|
|
151
|
-
const
|
|
165
|
+
// the window is only read when `big` (see `visible` and `geo`), so these need no small-graph fallback
|
|
166
|
+
const vx0 = $derived(Math.floor(-tx / k / CELL - 1) * CELL);
|
|
167
|
+
const vy0 = $derived(Math.floor(-ty / k / CELL - 1) * CELL);
|
|
168
|
+
const vx1 = $derived(Math.ceil((rw - tx) / k / CELL + 1) * CELL);
|
|
169
|
+
const vy1 = $derived(Math.ceil((rh - ty) / k / CELL + 1) * CELL);
|
|
152
170
|
/** Zoomed far out on a big graph: nodes are drawn as plain tiles without content or ports. */
|
|
153
171
|
const lod = $derived(big && k < 0.3);
|
|
154
172
|
|
|
@@ -158,6 +176,9 @@
|
|
|
158
176
|
const rects = $derived<Rect[]>(shown.map((n) => ({ id: n.id, x: n.x, y: n.y, w: W(n), h: H(n) })));
|
|
159
177
|
// obstacle-avoiding routing is O(nodes) per edge: large graphs fall back to the cheap smoothstep router
|
|
160
178
|
const needsObstacles = $derived(!big && (edgeType === 'avoid' || edges.some((e) => e.type === 'avoid')));
|
|
179
|
+
// strings built in script: interpolating them in markup would add unreachable `?? ''` branches
|
|
180
|
+
const px = (v: number) => `${v}px`;
|
|
181
|
+
const edgeAria = (e: GraphEdge) => `Edge ${e.from} to ${e.to}`;
|
|
161
182
|
const routeType = (t: EdgeType): EdgeType => (big && t === 'avoid' ? 'smoothstep' : t);
|
|
162
183
|
|
|
163
184
|
const findPort = (n: GraphNode, id: string | undefined, kind: 'in' | 'out') => {
|
|
@@ -227,17 +248,21 @@
|
|
|
227
248
|
if (selected.some((s) => gone.has(s))) selected = selected.filter((s) => !gone.has(s));
|
|
228
249
|
}
|
|
229
250
|
export function expand(id: string) { if (collapsed.includes(id)) collapsed = collapsed.filter((c) => c !== id); }
|
|
230
|
-
/**
|
|
231
|
-
|
|
232
|
-
|
|
251
|
+
/**
|
|
252
|
+
* Re-run the `layout` algorithm over all nodes, then fit. With `{ pin }` it is incremental: those ids keep their
|
|
253
|
+
* position, the other nodes are placed near their neighbours, and the viewport is left alone (no fit). Use it
|
|
254
|
+
* after adding nodes ("expand neighbours"): `g.layout({ pin: existingIds })`.
|
|
255
|
+
*/
|
|
256
|
+
export function layout(opts: GraphLayoutOptions = {}) {
|
|
257
|
+
nodes = computeLayout(opts.pin);
|
|
233
258
|
onchange?.();
|
|
234
259
|
// the graph may be gone by the next frame (navigating away right after pressing the button)
|
|
235
|
-
requestAnimationFrame(() => { if (root?.isConnected) fit(); });
|
|
260
|
+
if (!opts.pin?.length) requestAnimationFrame(() => { if (root?.isConnected) fit(); });
|
|
236
261
|
}
|
|
237
|
-
function computeLayout(): GraphNode[] {
|
|
238
|
-
if (layoutMode === 'force') return forceLayout(nodes, edges);
|
|
239
|
-
if (layoutMode === 'radial') return radialLayout(nodes, edges, { root: selected[0] });
|
|
240
|
-
return autoLayout(nodes, edges, { direction });
|
|
262
|
+
function computeLayout(pin?: string[]): GraphNode[] {
|
|
263
|
+
if (layoutMode === 'force') return forceLayout(nodes, edges, { pin });
|
|
264
|
+
if (layoutMode === 'radial') return radialLayout(nodes, edges, { root: selected[0], pin });
|
|
265
|
+
return autoLayout(nodes, edges, { direction, pin });
|
|
241
266
|
}
|
|
242
267
|
function zoomAt(factor: number, cx: number, cy: number) {
|
|
243
268
|
const nk = Math.min(2.5, Math.max(minK, k * factor));
|
|
@@ -250,7 +275,7 @@
|
|
|
250
275
|
onMount(() => {
|
|
251
276
|
const wheel = (e: WheelEvent) => {
|
|
252
277
|
// let scrollable content inside custom nodes scroll normally
|
|
253
|
-
if ((e.target as HTMLElement).closest('.nowheel')) return;
|
|
278
|
+
if ((e.target as HTMLElement).closest('.nowheel, .trg-overlay')) return;
|
|
254
279
|
e.preventDefault();
|
|
255
280
|
const r = root.getBoundingClientRect();
|
|
256
281
|
zoomAt(Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015)), e.clientX - r.left, e.clientY - r.top);
|
|
@@ -258,12 +283,27 @@
|
|
|
258
283
|
root.addEventListener('wheel', wheel, { passive: false });
|
|
259
284
|
if (layoutMode !== 'layered' && nodes.length) nodes = computeLayout();
|
|
260
285
|
if (fitOnMount) fit();
|
|
261
|
-
|
|
286
|
+
// Popovers a node opens in `fixed` mode would sit inside the transformed canvas, which makes the canvas (not
|
|
287
|
+
// the page) their containing block and scales them. Move them to a layer outside it, then re-place them.
|
|
288
|
+
const lift = () => {
|
|
289
|
+
const found = viewport.querySelectorAll('.tr-popover[data-fixed="true"]');
|
|
290
|
+
for (const el of found) overlay.append(el);
|
|
291
|
+
if (found.length) overlay.dispatchEvent(new Event('scroll')); // Popover re-places itself on scroll
|
|
292
|
+
};
|
|
293
|
+
const mo = new MutationObserver(lift);
|
|
294
|
+
mo.observe(viewport, { childList: true, subtree: true });
|
|
295
|
+
lift();
|
|
296
|
+
return () => { root.removeEventListener('wheel', wheel); mo.disconnect(); };
|
|
297
|
+
});
|
|
298
|
+
// lifted overlays follow their anchor while the canvas pans and zooms
|
|
299
|
+
$effect(() => {
|
|
300
|
+
void tx; void ty; void k;
|
|
301
|
+
if (overlay?.firstElementChild) overlay.dispatchEvent(new Event('scroll'));
|
|
262
302
|
});
|
|
263
303
|
|
|
264
304
|
// ---- background: pan + clear selection
|
|
265
305
|
function bgDown(e: PointerEvent) {
|
|
266
|
-
if ((e.target as HTMLElement).closest('.node, .controls, .edge-hit, .elabel, .minimap, .legend')) return;
|
|
306
|
+
if ((e.target as HTMLElement).closest('.node, .controls, .edge-hit, .elabel, .minimap, .legend, .trg-overlay')) return;
|
|
267
307
|
selected = []; selectedEdge = undefined;
|
|
268
308
|
root.focus();
|
|
269
309
|
const sx = e.clientX, sy = e.clientY, tx0 = tx, ty0 = ty;
|
|
@@ -297,6 +337,8 @@
|
|
|
297
337
|
window.removeEventListener('pointerup', up);
|
|
298
338
|
if (drag) {
|
|
299
339
|
const d = drag;
|
|
340
|
+
suppressClick = true; // the click that ends a drag is not a node click
|
|
341
|
+
setTimeout(() => (suppressClick = false));
|
|
300
342
|
nodes = nodes.map((m) => (d.ids.includes(m.id) ? { ...m, x: Math.round(m.x + d.dx), y: Math.round(m.y + d.dy) } : m));
|
|
301
343
|
drag = null;
|
|
302
344
|
onchange?.();
|
|
@@ -305,6 +347,17 @@
|
|
|
305
347
|
window.addEventListener('pointermove', move);
|
|
306
348
|
window.addEventListener('pointerup', up);
|
|
307
349
|
}
|
|
350
|
+
let suppressClick = false, keyMenuAt = -Infinity;
|
|
351
|
+
// controls inside custom nodes and the node's own badges handle their own clicks
|
|
352
|
+
const ownsEvent = (e: Event) => !!(e.target as HTMLElement).closest(`.port, .expander, ${INTERACTIVE}`);
|
|
353
|
+
function nodeClick(e: MouseEvent, n: GraphNode) { if (!suppressClick && !ownsEvent(e)) onnodeclick?.(n, e); }
|
|
354
|
+
function nodeDblClick(e: MouseEvent, n: GraphNode) { if (!ownsEvent(e)) onnodedblclick?.(n, e); }
|
|
355
|
+
function nodeMenu(e: MouseEvent, n: GraphNode) {
|
|
356
|
+
if (!onnodecontextmenu || ownsEvent(e)) return;
|
|
357
|
+
e.preventDefault();
|
|
358
|
+
// a keyboard menu press already reported through onKey; browsers then also fire `contextmenu`
|
|
359
|
+
if (performance.now() - keyMenuAt > 300) onnodecontextmenu(n, e);
|
|
360
|
+
}
|
|
308
361
|
function updateNode(id: string, patch: Partial<GraphNode>) {
|
|
309
362
|
nodes = nodes.map((n) => (n.id === id ? { ...n, ...patch } : n));
|
|
310
363
|
onchange?.();
|
|
@@ -371,12 +424,19 @@
|
|
|
371
424
|
|
|
372
425
|
// ---- legend
|
|
373
426
|
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
427
|
+
// Graph-local copy of the chart palette: `--trc-s1..8` when the charts stylesheet is loaded, built-in values otherwise
|
|
428
|
+
const SLOTS = 8;
|
|
429
|
+
const slotVar = (c: number) => `var(--trg-s${((Math.trunc(c) % SLOTS) + SLOTS) % SLOTS + 1})`;
|
|
430
|
+
const colorOf = (n: GraphNode) => n.color ?? (n.category == null ? undefined : slotVar(n.category));
|
|
374
431
|
const legendData = $derived.by(() => {
|
|
375
432
|
if (!legend) return null;
|
|
376
433
|
const kinds = (xs: { kind?: NodeKind }[]) => [...new Set(xs.map((x) => x.kind ?? 'neutral'))];
|
|
377
|
-
|
|
434
|
+
// coloured nodes are not described by their kind
|
|
435
|
+
const nodeRows = legend === true ? kinds(live.filter((n) => colorOf(n) == null)).map((x) => [x, cap(x)] as [string, string]) : Object.entries(legend.nodes ?? {}) as [string, string][];
|
|
378
436
|
const edgeRows = legend === true ? kinds(edges).map((x) => [x, cap(x)] as [string, string]) : Object.entries(legend.edges ?? {}) as [string, string][];
|
|
379
|
-
|
|
437
|
+
const used = legend === true || legend.categories !== false ? [...new Set(live.filter((n) => n.color == null && n.category != null).map((n) => n.category!))].sort((a, b) => a - b) : [];
|
|
438
|
+
const catRows = used.map((c) => [c, categories?.[c] ?? `Category ${c + 1}`] as [number, string]);
|
|
439
|
+
return nodeRows.length || edgeRows.length || catRows.length ? { nodeRows, edgeRows, catRows } : null;
|
|
380
440
|
});
|
|
381
441
|
const toggleEdgeKind = (kind: string) => (hiddenEdgeKinds = hiddenEdgeKinds.includes(kind) ? hiddenEdgeKinds.filter((x) => x !== kind) : [...hiddenEdgeKinds, kind]);
|
|
382
442
|
|
|
@@ -405,7 +465,15 @@
|
|
|
405
465
|
tick().then(() => root?.querySelector<HTMLElement>(`.node[data-id="${CSS.escape(n.id)}"]`)?.focus());
|
|
406
466
|
}
|
|
407
467
|
function onKey(e: KeyboardEvent) {
|
|
408
|
-
if ((e.target as HTMLElement).closest('input, textarea, select, [contenteditable="true"]')) return; // typing inside a node
|
|
468
|
+
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
|
|
469
|
+
const on = e.target as HTMLElement;
|
|
470
|
+
const focused = on.classList.contains('node') ? byId.get(on.dataset.id!)! : undefined;
|
|
471
|
+
if (focused && onnodecontextmenu && (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey))) {
|
|
472
|
+
keyMenuAt = performance.now();
|
|
473
|
+
onnodecontextmenu(focused, e);
|
|
474
|
+
e.preventDefault();
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
409
477
|
const step = e.shiftKey ? 32 : 8;
|
|
410
478
|
const mv = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
|
|
411
479
|
if (mv && !editable) {
|
|
@@ -413,8 +481,10 @@
|
|
|
413
481
|
const next = neighbour(cur ? byId.get(cur) : undefined, e.key);
|
|
414
482
|
if (!next) return;
|
|
415
483
|
goTo(next);
|
|
416
|
-
} else if (e.key === 'Enter' &&
|
|
417
|
-
|
|
484
|
+
} else if (e.key === 'Enter' && focused) {
|
|
485
|
+
onnodeclick?.(focused, e);
|
|
486
|
+
if (e.defaultPrevented) return; // the handler took the key: no collapse toggle
|
|
487
|
+
const id = focused.id;
|
|
418
488
|
if (collapsed.includes(id)) expand(id);
|
|
419
489
|
else if (childrenOf.get(id)?.length) collapse(id);
|
|
420
490
|
else return;
|
|
@@ -435,10 +505,10 @@
|
|
|
435
505
|
class="trg" bind:this={root} bind:clientWidth={rw} bind:clientHeight={rh} role="application" tabindex="0" data-panning={panning}
|
|
436
506
|
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.'}
|
|
437
507
|
style:height={typeof height === 'number' ? `${height}px` : height}
|
|
438
|
-
style:--tx=
|
|
508
|
+
style:--tx={px(tx)} style:--ty={px(ty)} style:--k={k}
|
|
439
509
|
onpointerdown={bgDown} onkeydown={onKey}
|
|
440
510
|
>
|
|
441
|
-
<div class="viewport" style:transform="translate({tx}px, {ty}px) scale({k})">
|
|
511
|
+
<div class="viewport" bind:this={viewport} style:transform="translate({tx}px, {ty}px) scale({k})">
|
|
442
512
|
<svg class="edges" width="1" height="1">
|
|
443
513
|
<defs>
|
|
444
514
|
<marker id="trg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
|
|
@@ -450,7 +520,7 @@
|
|
|
450
520
|
<path class="line" d={g.d} marker-end="url(#trg-arrow)" />
|
|
451
521
|
{#if !lod}
|
|
452
522
|
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
|
|
453
|
-
<path class="edge-hit" d={g.d} role="img" aria-label=
|
|
523
|
+
<path class="edge-hit" d={g.d} role="img" aria-label={edgeAria(g.e)} onclick={(ev) => { ev.stopPropagation(); selected = []; selectedEdge = g.e.id; root.focus(); }} />
|
|
454
524
|
{/if}
|
|
455
525
|
{#if lod}
|
|
456
526
|
<!-- labels are unreadable this far out -->
|
|
@@ -473,12 +543,15 @@
|
|
|
473
543
|
{@const render = rendererOf(n)}
|
|
474
544
|
{@const bare = !!render && n.chrome !== true}
|
|
475
545
|
{@const ports = lod ? [] : portsOf(n)}
|
|
546
|
+
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
|
|
476
547
|
<div
|
|
477
548
|
class="node" role="group" tabindex="0" aria-label="{n.label}{n.subtitle ? `, ${n.subtitle}` : ''}"
|
|
478
549
|
data-id={n.id} data-kind={n.kind ?? 'neutral'} data-shape={n.shape && n.shape !== 'rect' ? n.shape : undefined} data-bare={bare} data-selected={selected.includes(n.id)} data-dragging={!!drag?.ids.includes(n.id)}
|
|
479
550
|
data-dim={hl ? !hl.has(n.id) : undefined} data-collapsed={hiding.counts.has(n.id) ? true : undefined}
|
|
480
|
-
style:left=
|
|
481
|
-
|
|
551
|
+
style:left={px(n.x)} style:top={px(n.y)} style:width={px(W(n))} style:height={px(H(n))}
|
|
552
|
+
style:--c={colorOf(n)}
|
|
553
|
+
onpointerdown={(e) => nodeDown(e, n)} onclick={(e) => nodeClick(e, n)} ondblclick={(e) => nodeDblClick(e, n)} oncontextmenu={(e) => nodeMenu(e, n)}
|
|
554
|
+
onpointerenter={() => onnodehover?.(n)} onpointerleave={() => onnodehover?.(null)}
|
|
482
555
|
>
|
|
483
556
|
{#if lod}
|
|
484
557
|
<!-- tile only -->
|
|
@@ -504,7 +577,8 @@
|
|
|
504
577
|
{#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}
|
|
505
578
|
{/each}
|
|
506
579
|
{#if !lod && hiding.counts.has(n.id)}
|
|
507
|
-
|
|
580
|
+
{@const hidden = hiding.counts.get(n.id)!}
|
|
581
|
+
<button type="button" class="expander nodrag" aria-label={`Expand ${n.label}, ${hidden} hidden`} onclick={(e) => { e.stopPropagation(); expand(n.id); }}>{`+${hidden}`}</button>
|
|
508
582
|
{/if}
|
|
509
583
|
</div>
|
|
510
584
|
{/each}
|
|
@@ -515,11 +589,12 @@
|
|
|
515
589
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
|
516
590
|
<svg width={mm.w} height={mm.h} role="img" aria-label="Minimap: drag to pan the view" onpointerdown={mmPan}>
|
|
517
591
|
{#each big ? [] : geo as g (g.e.id)}
|
|
518
|
-
|
|
519
|
-
{
|
|
592
|
+
<!-- `geo` only holds edges whose two ends are both in `byId` -->
|
|
593
|
+
{@const a = byId.get(g.e.from)!}{@const bn = byId.get(g.e.to)!}
|
|
594
|
+
<line class="mme" x1={(a.x + W(a) / 2 - mm.x0) * mm.sc} y1={(a.y + H(a) / 2 - mm.y0) * mm.sc} x2={(bn.x + W(bn) / 2 - mm.x0) * mm.sc} y2={(bn.y + H(bn) / 2 - mm.y0) * mm.sc} />
|
|
520
595
|
{/each}
|
|
521
596
|
{#each shown as n (n.id)}
|
|
522
|
-
<rect class="mmn" data-kind={n.kind ?? 'neutral'} data-selected={selected.includes(n.id)} x={(n.x - mm.x0) * mm.sc} y={(n.y - mm.y0) * mm.sc} width={Math.max(2, W(n) * mm.sc)} height={Math.max(2, H(n) * mm.sc)} rx="1.5" />
|
|
597
|
+
<rect class="mmn" data-kind={n.kind ?? 'neutral'} style:fill={colorOf(n)} data-selected={selected.includes(n.id)} x={(n.x - mm.x0) * mm.sc} y={(n.y - mm.y0) * mm.sc} width={Math.max(2, W(n) * mm.sc)} height={Math.max(2, H(n) * mm.sc)} rx="1.5" />
|
|
523
598
|
{/each}
|
|
524
599
|
<rect class="mmv" x={mm.view.x} y={mm.view.y} width={mm.view.w} height={mm.view.h} />
|
|
525
600
|
</svg>
|
|
@@ -531,19 +606,25 @@
|
|
|
531
606
|
{#each legendData.nodeRows as [kind, label] (kind)}
|
|
532
607
|
<span class="lg-item"><span class="lg-node" data-kind={kind}></span>{label}</span>
|
|
533
608
|
{/each}
|
|
609
|
+
{#each legendData.catRows as [cat, label] (cat)}
|
|
610
|
+
<span class="lg-item"><span class="lg-node" style:--c={slotVar(cat)}></span>{label}</span>
|
|
611
|
+
{/each}
|
|
534
612
|
{#each legendData.edgeRows as [kind, label] (kind)}
|
|
535
|
-
<button type="button" class="lg-item lg-edge" data-kind={kind} aria-pressed={!hiddenEdgeKinds.includes(kind)} title=
|
|
613
|
+
<button type="button" class="lg-item lg-edge" data-kind={kind} aria-pressed={!hiddenEdgeKinds.includes(kind)} title={`Show or hide ${label} edges`} onclick={() => toggleEdgeKind(kind)}>
|
|
536
614
|
<span class="lg-line"></span>{label}
|
|
537
615
|
</button>
|
|
538
616
|
{/each}
|
|
539
617
|
</div>
|
|
540
618
|
{/if}
|
|
541
619
|
|
|
620
|
+
<!-- node-attached overlays (HoverCard, Popover) are lifted here, outside the transformed canvas -->
|
|
621
|
+
<div class="trg-overlay" bind:this={overlay}></div>
|
|
622
|
+
|
|
542
623
|
<div class="controls" role="toolbar" aria-label="Graph controls">
|
|
543
624
|
<Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label="Zoom in" onclick={() => zoomCenter(1.2)} />
|
|
544
625
|
<Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label="Zoom out" onclick={() => zoomCenter(1 / 1.2)} />
|
|
545
626
|
<Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label="Fit to view" onclick={() => fit()} />
|
|
546
|
-
{#if editable}<Button variant="minimal" intent="neutral" size="sm" icon="refresh" aria-label="Auto layout" onclick={layout} />{/if}
|
|
627
|
+
{#if editable}<Button variant="minimal" intent="neutral" size="sm" icon="refresh" aria-label="Auto layout" onclick={() => layout()} />{/if}
|
|
547
628
|
</div>
|
|
548
629
|
</div>
|
|
549
630
|
|
|
@@ -556,7 +637,20 @@
|
|
|
556
637
|
background-size: calc(var(--grid) * var(--k)) calc(var(--grid) * var(--k));
|
|
557
638
|
background-position: var(--tx) var(--ty);
|
|
558
639
|
border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-md);
|
|
640
|
+
--trg-s1: var(--trc-s1, #2a78d6); --trg-s2: var(--trc-s2, #eb6834); --trg-s3: var(--trc-s3, #1baf7a); --trg-s4: var(--trc-s4, #eda100);
|
|
641
|
+
--trg-s5: var(--trc-s5, #e87ba4); --trg-s6: var(--trc-s6, #008300); --trg-s7: var(--trc-s7, #6250d6); --trg-s8: var(--trc-s8, #e34948);
|
|
642
|
+
}
|
|
643
|
+
@media (prefers-color-scheme: dark) {
|
|
644
|
+
:global(:root:not([data-theme='light'])) .trg {
|
|
645
|
+
--trg-s1: var(--trc-s1, #3987e5); --trg-s2: var(--trc-s2, #d95926); --trg-s3: var(--trc-s3, #199e70); --trg-s4: var(--trc-s4, #c98500);
|
|
646
|
+
--trg-s5: var(--trc-s5, #d55181); --trg-s6: var(--trc-s6, #008300); --trg-s7: var(--trc-s7, #9085e9); --trg-s8: var(--trc-s8, #e66767);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
:global(:root[data-theme='dark']) .trg {
|
|
650
|
+
--trg-s1: var(--trc-s1, #3987e5); --trg-s2: var(--trc-s2, #d95926); --trg-s3: var(--trc-s3, #199e70); --trg-s4: var(--trc-s4, #c98500);
|
|
651
|
+
--trg-s5: var(--trc-s5, #d55181); --trg-s6: var(--trc-s6, #008300); --trg-s7: var(--trc-s7, #9085e9); --trg-s8: var(--trc-s8, #e66767);
|
|
559
652
|
}
|
|
653
|
+
.trg-overlay { position: absolute; left: 0; top: 0; width: 0; height: 0; }
|
|
560
654
|
.trg[data-panning='true'] { cursor: grabbing; }
|
|
561
655
|
.trg:focus-visible { box-shadow: var(--tr-focus-ring); border-color: var(--tr-primary); }
|
|
562
656
|
.viewport { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
|
package/dist/Graph.svelte.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Snippet } from 'svelte';
|
|
2
|
-
import { type EdgeType, type GraphEdge, type GraphLayout, type GraphLegend, type GraphNode, type HighlightDirection, type NodeRenderer } from './types.js';
|
|
2
|
+
import { type EdgeType, type GraphEdge, type GraphLayout, type GraphLayoutOptions, type GraphLegend, type GraphNode, type HighlightDirection, type NodeRenderer } from './types.js';
|
|
3
3
|
type $$ComponentProps = {
|
|
4
4
|
nodes?: GraphNode[];
|
|
5
5
|
edges?: GraphEdge[];
|
|
@@ -19,6 +19,8 @@ type $$ComponentProps = {
|
|
|
19
19
|
layout?: GraphLayout;
|
|
20
20
|
/** Key for node and edge kinds. `true` derives it from the kinds in use; or pass labels per kind. Edge entries toggle `hiddenEdgeKinds`. */
|
|
21
21
|
legend?: boolean | GraphLegend;
|
|
22
|
+
/** Names for `node.category` (index = category), used by the legend. Missing names read "Category N". */
|
|
23
|
+
categories?: string[];
|
|
22
24
|
/** Drag from an output port to an input port to create edges. */
|
|
23
25
|
connectable?: boolean;
|
|
24
26
|
/** Allow moving and deleting. */
|
|
@@ -45,6 +47,14 @@ type $$ComponentProps = {
|
|
|
45
47
|
}) => boolean;
|
|
46
48
|
onconnect?: (edge: GraphEdge) => void;
|
|
47
49
|
onchange?: () => void;
|
|
50
|
+
/** A node was clicked (also Enter on a focused node). Selection has already updated; call `event.preventDefault()` on an Enter press to skip the collapse toggle. Clicks that end a drag, and clicks on ports, expander badges or controls inside custom nodes, do not count. */
|
|
51
|
+
onnodeclick?: (node: GraphNode, event: MouseEvent | KeyboardEvent) => void;
|
|
52
|
+
/** A node was double-clicked. A double-click also fires `onnodeclick` twice first, as the browser does; the graph itself has no double-click action. */
|
|
53
|
+
onnodedblclick?: (node: GraphNode, event: MouseEvent) => void;
|
|
54
|
+
/** The pointer entered a node, or `null` when it left. */
|
|
55
|
+
onnodehover?: (node: GraphNode | null) => void;
|
|
56
|
+
/** Right-click, or ContextMenu / Shift+F10 on a focused node. The native menu is suppressed when this is set (except over inputs and links inside custom nodes). */
|
|
57
|
+
onnodecontextmenu?: (node: GraphNode, event: MouseEvent | KeyboardEvent) => void;
|
|
48
58
|
};
|
|
49
59
|
declare const Graph: import("svelte").Component<$$ComponentProps, {
|
|
50
60
|
fit: (padding?: number) => void;
|
|
@@ -56,7 +66,7 @@ declare const Graph: import("svelte").Component<$$ComponentProps, {
|
|
|
56
66
|
clearHighlight: () => void;
|
|
57
67
|
collapse: (id: string) => void;
|
|
58
68
|
expand: (id: string) => void;
|
|
59
|
-
layout: () => void;
|
|
69
|
+
layout: (opts?: GraphLayoutOptions) => void;
|
|
60
70
|
}, "collapsed" | "selected" | "nodes" | "edges" | "selectedEdge" | "hiddenEdgeKinds">;
|
|
61
71
|
type Graph = ReturnType<typeof Graph>;
|
|
62
72
|
export default Graph;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { default as Graph } from './Graph.svelte';
|
|
2
2
|
export { autoLayout, forceLayout, radialLayout } from './layout.js';
|
|
3
3
|
export { routeEdge, portAnchor, defaultPorts } from './routing.js';
|
|
4
|
-
export type { GraphNode, GraphEdge, GraphPort, NodeKind, NodeCtx, NodeRenderer, EdgeType, Side, NodeShape, GraphLayout, GraphLegend, HighlightDirection } from './types.js';
|
|
4
|
+
export type { GraphNode, GraphEdge, GraphPort, NodeKind, NodeCtx, NodeRenderer, EdgeType, Side, NodeShape, GraphLayout, GraphLegend, HighlightDirection, GraphLayoutOptions } from './types.js';
|
package/dist/layout.d.ts
CHANGED
|
@@ -2,30 +2,42 @@ 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
4
|
* reduce crossings, columns centred vertically. Cycle-safe. Returns new node objects.
|
|
5
|
+
*
|
|
6
|
+
* `pin` (node ids) makes it incremental: pinned nodes keep their exact position and every other node is placed
|
|
7
|
+
* in the column after (or before) its placed neighbours, nudged along the column until it overlaps nothing.
|
|
5
8
|
*/
|
|
6
9
|
export declare function autoLayout(nodes: GraphNode[], edges: GraphEdge[], opts?: {
|
|
7
10
|
gapX?: number;
|
|
8
11
|
gapY?: number;
|
|
9
12
|
direction?: 'LR' | 'TB';
|
|
13
|
+
pin?: Iterable<string>;
|
|
10
14
|
}): GraphNode[];
|
|
11
15
|
/**
|
|
12
16
|
* Force-directed layout (Fruchterman-Reingold). Deterministic for a given `seed`; repulsion is
|
|
13
17
|
* computed through a uniform grid so large graphs (1000+ nodes) stay fast. Ends with a rectangle
|
|
14
18
|
* overlap-removal pass. Returns new node objects.
|
|
19
|
+
*
|
|
20
|
+
* `pin` (node ids) makes it incremental: pinned nodes stay exactly where they are (still pushing and pulling
|
|
21
|
+
* the rest), new nodes start next to their neighbours and settle around them; the result is not re-centred.
|
|
15
22
|
*/
|
|
16
23
|
export declare function forceLayout(nodes: GraphNode[], edges: GraphEdge[], opts?: {
|
|
17
24
|
iterations?: number;
|
|
18
25
|
seed?: number;
|
|
19
26
|
spacing?: number;
|
|
20
27
|
gravity?: number;
|
|
28
|
+
pin?: Iterable<string>;
|
|
21
29
|
}): GraphNode[];
|
|
22
30
|
/**
|
|
23
31
|
* Radial layout: the `root` (default: the first node with no incoming edge) in the centre, every
|
|
24
32
|
* other node on a ring by its distance from the root (edges treated as undirected). Subtrees get
|
|
25
33
|
* angular wedges proportional to their leaf count; unreachable components hang off the root.
|
|
34
|
+
*
|
|
35
|
+
* `pin` (node ids) makes it incremental: pinned nodes keep their position and every other node is placed on the
|
|
36
|
+
* far side of its placed neighbour (away from the pinned nodes' centre), siblings fanned out around it.
|
|
26
37
|
*/
|
|
27
38
|
export declare function radialLayout(nodes: GraphNode[], edges: GraphEdge[], opts?: {
|
|
28
39
|
root?: string;
|
|
29
40
|
ringGap?: number;
|
|
30
41
|
spacing?: number;
|
|
42
|
+
pin?: Iterable<string>;
|
|
31
43
|
}): GraphNode[];
|
package/dist/layout.js
CHANGED
|
@@ -1,10 +1,107 @@
|
|
|
1
1
|
import { NODE_H, NODE_W } from './types.js';
|
|
2
|
+
/** Ids from `pin` that exist in `nodes`, or null when none do (the layout then runs from scratch). */
|
|
3
|
+
function pinnedIn(nodes, pin) {
|
|
4
|
+
if (!pin)
|
|
5
|
+
return null;
|
|
6
|
+
const ids = new Set(nodes.map((n) => n.id)), out = new Set();
|
|
7
|
+
for (const id of pin)
|
|
8
|
+
if (ids.has(id))
|
|
9
|
+
out.add(id);
|
|
10
|
+
return out.size ? out : null;
|
|
11
|
+
}
|
|
12
|
+
const PAD = 16;
|
|
13
|
+
/**
|
|
14
|
+
* Incremental placement: pinned nodes are returned untouched; every other node is placed near the nodes it is
|
|
15
|
+
* connected to (`want` picks the spot from its already-placed neighbours), then nudged along `probe` until it
|
|
16
|
+
* overlaps nothing. Nodes with no placed neighbour (and no path to one) stack to the right of everything placed.
|
|
17
|
+
* Deterministic: node and edge order decide everything.
|
|
18
|
+
*/
|
|
19
|
+
function placeAround(nodes, edges, pinned, want, probe, gap) {
|
|
20
|
+
const out = new Map();
|
|
21
|
+
for (const n of nodes)
|
|
22
|
+
if (pinned.has(n.id))
|
|
23
|
+
out.set(n.id, { ...n });
|
|
24
|
+
const nbrs = new Map(nodes.map((n) => [n.id, []]));
|
|
25
|
+
for (const e of edges)
|
|
26
|
+
if (nbrs.has(e.from) && nbrs.has(e.to) && e.from !== e.to) {
|
|
27
|
+
nbrs.get(e.from).push(e.to);
|
|
28
|
+
nbrs.get(e.to).push(e.from);
|
|
29
|
+
}
|
|
30
|
+
const kids = new Map();
|
|
31
|
+
const clear = (n, at) => {
|
|
32
|
+
for (const m of out.values()) {
|
|
33
|
+
const a = sizeOf(n), b = sizeOf(m);
|
|
34
|
+
if (at.x < m.x + b.w + PAD && m.x < at.x + a.w + PAD && at.y < m.y + b.h + PAD && m.y < at.y + a.h + PAD)
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
return true;
|
|
38
|
+
};
|
|
39
|
+
const vertical = (k, at, n) => {
|
|
40
|
+
const step = sizeOf(n).h + PAD;
|
|
41
|
+
return { x: at.x, y: at.y + (k % 2 ? Math.ceil(k / 2) : -(k / 2)) * step };
|
|
42
|
+
};
|
|
43
|
+
let rest = nodes.filter((n) => !pinned.has(n.id));
|
|
44
|
+
while (rest.length) {
|
|
45
|
+
const ready = rest.filter((n) => nbrs.get(n.id).some((i) => out.has(i)));
|
|
46
|
+
for (const n of ready.length ? ready : [rest[0]]) {
|
|
47
|
+
const placed = nbrs.get(n.id).map((i) => out.get(i)).filter((m) => !!m);
|
|
48
|
+
let at, find = probe;
|
|
49
|
+
if (placed.length) {
|
|
50
|
+
const sib = kids.get(placed[0].id) ?? 0;
|
|
51
|
+
kids.set(placed[0].id, sib + 1);
|
|
52
|
+
at = want(n, placed, sib);
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
let right = -Infinity, top = Infinity;
|
|
56
|
+
for (const m of out.values()) {
|
|
57
|
+
right = Math.max(right, m.x + sizeOf(m).w);
|
|
58
|
+
top = Math.min(top, m.y);
|
|
59
|
+
}
|
|
60
|
+
at = { x: right + gap, y: top };
|
|
61
|
+
find = vertical;
|
|
62
|
+
}
|
|
63
|
+
let spot = at;
|
|
64
|
+
for (let k = 0; k < 80; k++) {
|
|
65
|
+
const c = find(k, at, n);
|
|
66
|
+
if (clear(n, c)) {
|
|
67
|
+
spot = c;
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
out.set(n.id, { ...n, x: Math.round(spot.x), y: Math.round(spot.y) });
|
|
72
|
+
}
|
|
73
|
+
rest = rest.filter((n) => !out.has(n.id));
|
|
74
|
+
}
|
|
75
|
+
return nodes.map((n) => out.get(n.id));
|
|
76
|
+
}
|
|
2
77
|
/**
|
|
3
78
|
* Layered (Sugiyama-lite) auto layout: longest-path layering, one barycenter sweep to
|
|
4
79
|
* reduce crossings, columns centred vertically. Cycle-safe. Returns new node objects.
|
|
80
|
+
*
|
|
81
|
+
* `pin` (node ids) makes it incremental: pinned nodes keep their exact position and every other node is placed
|
|
82
|
+
* in the column after (or before) its placed neighbours, nudged along the column until it overlaps nothing.
|
|
5
83
|
*/
|
|
6
84
|
export function autoLayout(nodes, edges, opts = {}) {
|
|
7
85
|
const { gapX = 90, gapY = 28, direction = 'LR' } = opts;
|
|
86
|
+
const pinned = pinnedIn(nodes, opts.pin);
|
|
87
|
+
if (pinned) {
|
|
88
|
+
const lr = direction === 'LR';
|
|
89
|
+
const along = (n) => (lr ? n.x : n.y), across = (n) => (lr ? n.y : n.x);
|
|
90
|
+
const alongSize = (n) => (lr ? sizeOf(n).w : sizeOf(n).h), acrossSize = (n) => (lr ? sizeOf(n).h : sizeOf(n).w);
|
|
91
|
+
const forward = new Set(edges.map((e) => `${e.from}>${e.to}`));
|
|
92
|
+
const want = (n, placed) => {
|
|
93
|
+
const before = placed.filter((p) => forward.has(`${p.id}>${n.id}`));
|
|
94
|
+
const set = before.length ? before : placed;
|
|
95
|
+
const mid = set.reduce((a, p) => a + across(p) + acrossSize(p) / 2, 0) / set.length - acrossSize(n) / 2;
|
|
96
|
+
const a = before.length ? Math.max(...before.map((p) => along(p) + alongSize(p))) + gapX : Math.min(...set.map(along)) - gapX - alongSize(n);
|
|
97
|
+
return lr ? { x: a, y: mid } : { x: mid, y: a };
|
|
98
|
+
};
|
|
99
|
+
const probe = (k, at, n) => {
|
|
100
|
+
const d = (k % 2 ? Math.ceil(k / 2) : -(k / 2)) * (acrossSize(n) + gapY);
|
|
101
|
+
return lr ? { x: at.x, y: at.y + d } : { x: at.x + d, y: at.y };
|
|
102
|
+
};
|
|
103
|
+
return placeAround(nodes, edges, pinned, want, probe, gapX);
|
|
104
|
+
}
|
|
8
105
|
const ids = new Set(nodes.map((n) => n.id));
|
|
9
106
|
const preds = new Map(nodes.map((n) => [n.id, []]));
|
|
10
107
|
for (const e of edges)
|
|
@@ -45,8 +142,6 @@ export function autoLayout(nodes, edges, opts = {}) {
|
|
|
45
142
|
const tallest = Math.max(0, ...cols.filter(Boolean).map(span));
|
|
46
143
|
let offset = 0;
|
|
47
144
|
cols.forEach((col) => {
|
|
48
|
-
if (!col)
|
|
49
|
-
return;
|
|
50
145
|
const colSize = col.reduce((m, n) => Math.max(m, direction === 'LR' ? w(n) : h(n)), 0);
|
|
51
146
|
let cursor = (tallest - span(col)) / 2;
|
|
52
147
|
for (const n of col) {
|
|
@@ -103,6 +198,9 @@ function normalise(nodes, cx, cy) {
|
|
|
103
198
|
* Force-directed layout (Fruchterman-Reingold). Deterministic for a given `seed`; repulsion is
|
|
104
199
|
* computed through a uniform grid so large graphs (1000+ nodes) stay fast. Ends with a rectangle
|
|
105
200
|
* overlap-removal pass. Returns new node objects.
|
|
201
|
+
*
|
|
202
|
+
* `pin` (node ids) makes it incremental: pinned nodes stay exactly where they are (still pushing and pulling
|
|
203
|
+
* the rest), new nodes start next to their neighbours and settle around them; the result is not re-centred.
|
|
106
204
|
*/
|
|
107
205
|
export function forceLayout(nodes, edges, opts = {}) {
|
|
108
206
|
const n = nodes.length;
|
|
@@ -113,16 +211,58 @@ export function forceLayout(nodes, edges, opts = {}) {
|
|
|
113
211
|
const rand = rng(seed);
|
|
114
212
|
const k = spacing;
|
|
115
213
|
const pairs = pairsOf(nodes, edges);
|
|
214
|
+
const pin = pinnedIn(nodes, opts.pin);
|
|
215
|
+
const fixed = nodes.map((nd) => !!pin?.has(nd.id));
|
|
116
216
|
const px = new Float64Array(n), py = new Float64Array(n);
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
217
|
+
let gx0 = 0, gy0 = 0; // gravity pulls towards the pinned nodes' centroid (the origin on a fresh layout)
|
|
218
|
+
if (pin) {
|
|
219
|
+
let c = 0;
|
|
220
|
+
nodes.forEach((nd, i) => { if (fixed[i]) {
|
|
221
|
+
px[i] = nd.x + sizeOf(nd).w / 2;
|
|
222
|
+
py[i] = nd.y + sizeOf(nd).h / 2;
|
|
223
|
+
gx0 += px[i];
|
|
224
|
+
gy0 += py[i];
|
|
225
|
+
c++;
|
|
226
|
+
} });
|
|
227
|
+
gx0 /= c;
|
|
228
|
+
gy0 /= c;
|
|
229
|
+
// new nodes start beside the neighbours that are already placed, a few rounds so chains of new nodes follow
|
|
230
|
+
const adj = nodes.map(() => []);
|
|
231
|
+
for (const [a, b] of pairs) {
|
|
232
|
+
adj[a].push(b);
|
|
233
|
+
adj[b].push(a);
|
|
234
|
+
}
|
|
235
|
+
const done = [...fixed];
|
|
236
|
+
let left = fixed.filter((f) => !f).length, fresh = 0;
|
|
237
|
+
while (left) {
|
|
238
|
+
const ready = nodes.map((_, i) => i).filter((i) => !done[i] && adj[i].some((j) => done[j]));
|
|
239
|
+
const batch = ready.length ? ready : [done.indexOf(false)];
|
|
240
|
+
for (const i of batch) {
|
|
241
|
+
const near = adj[i].filter((j) => done[j]);
|
|
242
|
+
if (near.length) {
|
|
243
|
+
px[i] = near.reduce((a, j) => a + px[j], 0) / near.length + (rand() - 0.5) * k * 0.6;
|
|
244
|
+
py[i] = near.reduce((a, j) => a + py[j], 0) / near.length + (rand() - 0.5) * k * 0.6;
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
const r = k * 0.55 * Math.sqrt(++fresh + 1), a = fresh * 2.399963;
|
|
248
|
+
px[i] = gx0 + r * Math.cos(a);
|
|
249
|
+
py[i] = gy0 + r * Math.sin(a);
|
|
250
|
+
}
|
|
251
|
+
done[i] = true;
|
|
252
|
+
left--;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
122
255
|
}
|
|
256
|
+
else
|
|
257
|
+
for (let i = 0; i < n; i++) {
|
|
258
|
+
// phyllotaxis start: even coverage, seeded jitter breaks symmetry
|
|
259
|
+
const r = k * 0.55 * Math.sqrt(i + 1), a = i * 2.399963 + (rand() - 0.5) * 0.4;
|
|
260
|
+
px[i] = r * Math.cos(a);
|
|
261
|
+
py[i] = r * Math.sin(a);
|
|
262
|
+
}
|
|
123
263
|
const dx = new Float64Array(n), dy = new Float64Array(n);
|
|
124
264
|
const cutoff = k * 2.5;
|
|
125
|
-
const t0 = k * 1.5;
|
|
265
|
+
const t0 = pin ? k * 0.5 : k * 1.5;
|
|
126
266
|
for (let it = 0; it < iterations; it++) {
|
|
127
267
|
dx.fill(0);
|
|
128
268
|
dy.fill(0);
|
|
@@ -172,19 +312,23 @@ export function forceLayout(nodes, edges, opts = {}) {
|
|
|
172
312
|
}
|
|
173
313
|
const t = t0 * (1 - it / iterations) + 1;
|
|
174
314
|
for (let i = 0; i < n; i++) {
|
|
175
|
-
|
|
176
|
-
|
|
315
|
+
if (fixed[i])
|
|
316
|
+
continue;
|
|
317
|
+
dx[i] -= (px[i] - gx0) * gravity;
|
|
318
|
+
dy[i] -= (py[i] - gy0) * gravity;
|
|
177
319
|
const len = Math.hypot(dx[i], dy[i]) || 1;
|
|
178
320
|
const step = Math.min(len, t);
|
|
179
321
|
px[i] += (dx[i] / len) * step;
|
|
180
322
|
py[i] += (dy[i] / len) * step;
|
|
181
323
|
}
|
|
182
324
|
}
|
|
183
|
-
removeOverlaps(nodes, px, py);
|
|
184
|
-
|
|
325
|
+
removeOverlaps(nodes, px, py, 16, pin ? fixed : undefined);
|
|
326
|
+
if (!pin)
|
|
327
|
+
return normalise(nodes, px, py);
|
|
328
|
+
return nodes.map((nd, i) => (fixed[i] ? { ...nd } : { ...nd, x: Math.round(px[i] - sizeOf(nd).w / 2), y: Math.round(py[i] - sizeOf(nd).h / 2) }));
|
|
185
329
|
}
|
|
186
330
|
/** Push apart any rectangles that still overlap (grid-accelerated, bounded passes). */
|
|
187
|
-
function removeOverlaps(nodes, px, py, pad = 16) {
|
|
331
|
+
function removeOverlaps(nodes, px, py, pad = 16, fixed) {
|
|
188
332
|
const n = nodes.length;
|
|
189
333
|
const sz = nodes.map(sizeOf);
|
|
190
334
|
const cell = Math.max(...sz.map((s) => Math.max(s.w, s.h))) + pad;
|
|
@@ -210,16 +354,19 @@ function removeOverlaps(nodes, px, py, pad = 16) {
|
|
|
210
354
|
const px2 = (sz[i].w + sz[j].w) / 2 + pad - Math.abs(ex), py2 = (sz[i].h + sz[j].h) / 2 + pad - Math.abs(ey);
|
|
211
355
|
if (px2 <= 0 || py2 <= 0)
|
|
212
356
|
continue;
|
|
357
|
+
if (fixed?.[i] && fixed[j])
|
|
358
|
+
continue; // two pinned nodes stay put, even when they overlap
|
|
213
359
|
moved = true;
|
|
360
|
+
const wi = fixed?.[j] ? 2 : fixed?.[i] ? 0 : 1, wj = fixed?.[i] ? 2 : fixed?.[j] ? 0 : 1; // the free one takes the whole push
|
|
214
361
|
if (px2 < py2) {
|
|
215
362
|
const s = (ex >= 0 ? 1 : -1) * (px2 / 2 + 0.5);
|
|
216
|
-
px[i] -= s;
|
|
217
|
-
px[j] += s;
|
|
363
|
+
px[i] -= s * wi;
|
|
364
|
+
px[j] += s * wj;
|
|
218
365
|
}
|
|
219
366
|
else {
|
|
220
367
|
const s = (ey >= 0 ? 1 : -1) * (py2 / 2 + 0.5);
|
|
221
|
-
py[i] -= s;
|
|
222
|
-
py[j] += s;
|
|
368
|
+
py[i] -= s * wi;
|
|
369
|
+
py[j] += s * wj;
|
|
223
370
|
}
|
|
224
371
|
}
|
|
225
372
|
}
|
|
@@ -232,12 +379,34 @@ function removeOverlaps(nodes, px, py, pad = 16) {
|
|
|
232
379
|
* Radial layout: the `root` (default: the first node with no incoming edge) in the centre, every
|
|
233
380
|
* other node on a ring by its distance from the root (edges treated as undirected). Subtrees get
|
|
234
381
|
* angular wedges proportional to their leaf count; unreachable components hang off the root.
|
|
382
|
+
*
|
|
383
|
+
* `pin` (node ids) makes it incremental: pinned nodes keep their position and every other node is placed on the
|
|
384
|
+
* far side of its placed neighbour (away from the pinned nodes' centre), siblings fanned out around it.
|
|
235
385
|
*/
|
|
236
386
|
export function radialLayout(nodes, edges, opts = {}) {
|
|
237
387
|
const n = nodes.length;
|
|
238
388
|
if (!n)
|
|
239
389
|
return [];
|
|
240
390
|
const { ringGap = 240, spacing = 200 } = opts;
|
|
391
|
+
const pinned = pinnedIn(nodes, opts.pin);
|
|
392
|
+
if (pinned) {
|
|
393
|
+
const pn = nodes.filter((nd) => pinned.has(nd.id));
|
|
394
|
+
const gx = pn.reduce((a, nd) => a + nd.x + sizeOf(nd).w / 2, 0) / pn.length, gy = pn.reduce((a, nd) => a + nd.y + sizeOf(nd).h / 2, 0) / pn.length;
|
|
395
|
+
const delta = spacing / ringGap;
|
|
396
|
+
const want = (nd, placed, sibling) => {
|
|
397
|
+
const c = { x: placed[0].x + sizeOf(placed[0]).w / 2, y: placed[0].y + sizeOf(placed[0]).h / 2 };
|
|
398
|
+
const away = Math.hypot(c.x - gx, c.y - gy) > 1;
|
|
399
|
+
const base = away ? Math.atan2(c.y - gy, c.x - gx) : 0;
|
|
400
|
+
const a = base + (away ? (sibling % 2 ? 1 : -1) * Math.ceil(sibling / 2) * delta : sibling * 2.399963);
|
|
401
|
+
const s = sizeOf(nd);
|
|
402
|
+
return { x: c.x + ringGap * Math.cos(a) - s.w / 2, y: c.y + ringGap * Math.sin(a) - s.h / 2 };
|
|
403
|
+
};
|
|
404
|
+
const probe = (k, at, nd) => {
|
|
405
|
+
const s = sizeOf(nd), cx = at.x + s.w / 2 - gx, cy = at.y + s.h / 2 - gy, d = Math.hypot(cx, cy) || 1;
|
|
406
|
+
return { x: at.x + (cx / d) * 60 * k, y: at.y + (cy / d) * 60 * k };
|
|
407
|
+
};
|
|
408
|
+
return placeAround(nodes, edges, pinned, want, probe, ringGap);
|
|
409
|
+
}
|
|
241
410
|
const adj = nodes.map(() => []);
|
|
242
411
|
const hasIn = new Array(n).fill(false);
|
|
243
412
|
for (const [a, b] of pairsOf(nodes, edges)) {
|
package/dist/routing.js
CHANGED
|
@@ -188,8 +188,8 @@ function avoidPoints(a, b, obstacles, margin = 14, stub = 26) {
|
|
|
188
188
|
while (heap.length) {
|
|
189
189
|
const [, gc, x, y, d] = pop();
|
|
190
190
|
const k = key(x, y, d);
|
|
191
|
-
if (gc >
|
|
192
|
-
continue;
|
|
191
|
+
if (gc > best.get(k))
|
|
192
|
+
continue; // every queued state has a recorded cost
|
|
193
193
|
if (x === g.x && y === g.y) {
|
|
194
194
|
goalKey = k;
|
|
195
195
|
break;
|
package/dist/types.d.ts
CHANGED
|
@@ -8,6 +8,13 @@ export type HighlightDirection = 'up' | 'down' | 'both';
|
|
|
8
8
|
export type GraphLegend = {
|
|
9
9
|
nodes?: Partial<Record<NodeKind, string>>;
|
|
10
10
|
edges?: Partial<Record<NodeKind, string>>;
|
|
11
|
+
/** Show a row per `category` in use (default true). Names come from the `categories` prop on <Graph>. */
|
|
12
|
+
categories?: boolean;
|
|
13
|
+
};
|
|
14
|
+
/** Options of `layout()` on <Graph>. */
|
|
15
|
+
export type GraphLayoutOptions = {
|
|
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
|
+
pin?: string[];
|
|
11
18
|
};
|
|
12
19
|
export type EdgeType = 'bezier' | 'straight' | 'step' | 'smoothstep' | 'avoid';
|
|
13
20
|
export type GraphPort = {
|
|
@@ -24,6 +31,10 @@ export type GraphNode = {
|
|
|
24
31
|
label: string;
|
|
25
32
|
subtitle?: string;
|
|
26
33
|
kind?: NodeKind;
|
|
34
|
+
/** Any CSS colour for the node's accent (card stripe, circle outline, diamond, minimap tile). Wins over `category` and `kind`. */
|
|
35
|
+
color?: string;
|
|
36
|
+
/** Index (from 0) into the chart categorical palette (8 slots, wrapping). Wins over `kind`; named by the `categories` prop and listed in the legend. */
|
|
37
|
+
category?: number;
|
|
27
38
|
/** Outline of the default card (default `rect`). Circle and diamond centre their text, so give them a fitting width and height. */
|
|
28
39
|
shape?: NodeShape;
|
|
29
40
|
/** Picks a renderer from the `nodeTypes` registry on <Graph>. */
|