@ruckc/truss-graph 1.7.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 +110 -22
- 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 -15
- 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);
|
|
@@ -231,17 +248,21 @@
|
|
|
231
248
|
if (selected.some((s) => gone.has(s))) selected = selected.filter((s) => !gone.has(s));
|
|
232
249
|
}
|
|
233
250
|
export function expand(id: string) { if (collapsed.includes(id)) collapsed = collapsed.filter((c) => c !== id); }
|
|
234
|
-
/**
|
|
235
|
-
|
|
236
|
-
|
|
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);
|
|
237
258
|
onchange?.();
|
|
238
259
|
// the graph may be gone by the next frame (navigating away right after pressing the button)
|
|
239
|
-
requestAnimationFrame(() => { if (root?.isConnected) fit(); });
|
|
260
|
+
if (!opts.pin?.length) requestAnimationFrame(() => { if (root?.isConnected) fit(); });
|
|
240
261
|
}
|
|
241
|
-
function computeLayout(): GraphNode[] {
|
|
242
|
-
if (layoutMode === 'force') return forceLayout(nodes, edges);
|
|
243
|
-
if (layoutMode === 'radial') return radialLayout(nodes, edges, { root: selected[0] });
|
|
244
|
-
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 });
|
|
245
266
|
}
|
|
246
267
|
function zoomAt(factor: number, cx: number, cy: number) {
|
|
247
268
|
const nk = Math.min(2.5, Math.max(minK, k * factor));
|
|
@@ -254,7 +275,7 @@
|
|
|
254
275
|
onMount(() => {
|
|
255
276
|
const wheel = (e: WheelEvent) => {
|
|
256
277
|
// let scrollable content inside custom nodes scroll normally
|
|
257
|
-
if ((e.target as HTMLElement).closest('.nowheel')) return;
|
|
278
|
+
if ((e.target as HTMLElement).closest('.nowheel, .trg-overlay')) return;
|
|
258
279
|
e.preventDefault();
|
|
259
280
|
const r = root.getBoundingClientRect();
|
|
260
281
|
zoomAt(Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015)), e.clientX - r.left, e.clientY - r.top);
|
|
@@ -262,12 +283,27 @@
|
|
|
262
283
|
root.addEventListener('wheel', wheel, { passive: false });
|
|
263
284
|
if (layoutMode !== 'layered' && nodes.length) nodes = computeLayout();
|
|
264
285
|
if (fitOnMount) fit();
|
|
265
|
-
|
|
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'));
|
|
266
302
|
});
|
|
267
303
|
|
|
268
304
|
// ---- background: pan + clear selection
|
|
269
305
|
function bgDown(e: PointerEvent) {
|
|
270
|
-
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;
|
|
271
307
|
selected = []; selectedEdge = undefined;
|
|
272
308
|
root.focus();
|
|
273
309
|
const sx = e.clientX, sy = e.clientY, tx0 = tx, ty0 = ty;
|
|
@@ -301,6 +337,8 @@
|
|
|
301
337
|
window.removeEventListener('pointerup', up);
|
|
302
338
|
if (drag) {
|
|
303
339
|
const d = drag;
|
|
340
|
+
suppressClick = true; // the click that ends a drag is not a node click
|
|
341
|
+
setTimeout(() => (suppressClick = false));
|
|
304
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));
|
|
305
343
|
drag = null;
|
|
306
344
|
onchange?.();
|
|
@@ -309,6 +347,17 @@
|
|
|
309
347
|
window.addEventListener('pointermove', move);
|
|
310
348
|
window.addEventListener('pointerup', up);
|
|
311
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
|
+
}
|
|
312
361
|
function updateNode(id: string, patch: Partial<GraphNode>) {
|
|
313
362
|
nodes = nodes.map((n) => (n.id === id ? { ...n, ...patch } : n));
|
|
314
363
|
onchange?.();
|
|
@@ -375,12 +424,19 @@
|
|
|
375
424
|
|
|
376
425
|
// ---- legend
|
|
377
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));
|
|
378
431
|
const legendData = $derived.by(() => {
|
|
379
432
|
if (!legend) return null;
|
|
380
433
|
const kinds = (xs: { kind?: NodeKind }[]) => [...new Set(xs.map((x) => x.kind ?? 'neutral'))];
|
|
381
|
-
|
|
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][];
|
|
382
436
|
const edgeRows = legend === true ? kinds(edges).map((x) => [x, cap(x)] as [string, string]) : Object.entries(legend.edges ?? {}) as [string, string][];
|
|
383
|
-
|
|
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;
|
|
384
440
|
});
|
|
385
441
|
const toggleEdgeKind = (kind: string) => (hiddenEdgeKinds = hiddenEdgeKinds.includes(kind) ? hiddenEdgeKinds.filter((x) => x !== kind) : [...hiddenEdgeKinds, kind]);
|
|
386
442
|
|
|
@@ -409,7 +465,15 @@
|
|
|
409
465
|
tick().then(() => root?.querySelector<HTMLElement>(`.node[data-id="${CSS.escape(n.id)}"]`)?.focus());
|
|
410
466
|
}
|
|
411
467
|
function onKey(e: KeyboardEvent) {
|
|
412
|
-
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
|
+
}
|
|
413
477
|
const step = e.shiftKey ? 32 : 8;
|
|
414
478
|
const mv = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
|
|
415
479
|
if (mv && !editable) {
|
|
@@ -417,8 +481,10 @@
|
|
|
417
481
|
const next = neighbour(cur ? byId.get(cur) : undefined, e.key);
|
|
418
482
|
if (!next) return;
|
|
419
483
|
goTo(next);
|
|
420
|
-
} else if (e.key === 'Enter' &&
|
|
421
|
-
|
|
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;
|
|
422
488
|
if (collapsed.includes(id)) expand(id);
|
|
423
489
|
else if (childrenOf.get(id)?.length) collapse(id);
|
|
424
490
|
else return;
|
|
@@ -442,7 +508,7 @@
|
|
|
442
508
|
style:--tx={px(tx)} style:--ty={px(ty)} style:--k={k}
|
|
443
509
|
onpointerdown={bgDown} onkeydown={onKey}
|
|
444
510
|
>
|
|
445
|
-
<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})">
|
|
446
512
|
<svg class="edges" width="1" height="1">
|
|
447
513
|
<defs>
|
|
448
514
|
<marker id="trg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
|
|
@@ -477,12 +543,15 @@
|
|
|
477
543
|
{@const render = rendererOf(n)}
|
|
478
544
|
{@const bare = !!render && n.chrome !== true}
|
|
479
545
|
{@const ports = lod ? [] : portsOf(n)}
|
|
546
|
+
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
|
|
480
547
|
<div
|
|
481
548
|
class="node" role="group" tabindex="0" aria-label="{n.label}{n.subtitle ? `, ${n.subtitle}` : ''}"
|
|
482
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)}
|
|
483
550
|
data-dim={hl ? !hl.has(n.id) : undefined} data-collapsed={hiding.counts.has(n.id) ? true : undefined}
|
|
484
551
|
style:left={px(n.x)} style:top={px(n.y)} style:width={px(W(n))} style:height={px(H(n))}
|
|
485
|
-
|
|
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)}
|
|
486
555
|
>
|
|
487
556
|
{#if lod}
|
|
488
557
|
<!-- tile only -->
|
|
@@ -525,7 +594,7 @@
|
|
|
525
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} />
|
|
526
595
|
{/each}
|
|
527
596
|
{#each shown as n (n.id)}
|
|
528
|
-
<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" />
|
|
529
598
|
{/each}
|
|
530
599
|
<rect class="mmv" x={mm.view.x} y={mm.view.y} width={mm.view.w} height={mm.view.h} />
|
|
531
600
|
</svg>
|
|
@@ -537,6 +606,9 @@
|
|
|
537
606
|
{#each legendData.nodeRows as [kind, label] (kind)}
|
|
538
607
|
<span class="lg-item"><span class="lg-node" data-kind={kind}></span>{label}</span>
|
|
539
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}
|
|
540
612
|
{#each legendData.edgeRows as [kind, label] (kind)}
|
|
541
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)}>
|
|
542
614
|
<span class="lg-line"></span>{label}
|
|
@@ -545,11 +617,14 @@
|
|
|
545
617
|
</div>
|
|
546
618
|
{/if}
|
|
547
619
|
|
|
620
|
+
<!-- node-attached overlays (HoverCard, Popover) are lifted here, outside the transformed canvas -->
|
|
621
|
+
<div class="trg-overlay" bind:this={overlay}></div>
|
|
622
|
+
|
|
548
623
|
<div class="controls" role="toolbar" aria-label="Graph controls">
|
|
549
624
|
<Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label="Zoom in" onclick={() => zoomCenter(1.2)} />
|
|
550
625
|
<Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label="Zoom out" onclick={() => zoomCenter(1 / 1.2)} />
|
|
551
626
|
<Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label="Fit to view" onclick={() => fit()} />
|
|
552
|
-
{#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}
|
|
553
628
|
</div>
|
|
554
629
|
</div>
|
|
555
630
|
|
|
@@ -562,7 +637,20 @@
|
|
|
562
637
|
background-size: calc(var(--grid) * var(--k)) calc(var(--grid) * var(--k));
|
|
563
638
|
background-position: var(--tx) var(--ty);
|
|
564
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);
|
|
565
652
|
}
|
|
653
|
+
.trg-overlay { position: absolute; left: 0; top: 0; width: 0; height: 0; }
|
|
566
654
|
.trg[data-panning='true'] { cursor: grabbing; }
|
|
567
655
|
.trg:focus-visible { box-shadow: var(--tr-focus-ring); border-color: var(--tr-primary); }
|
|
568
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)
|
|
@@ -101,6 +198,9 @@ function normalise(nodes, cx, cy) {
|
|
|
101
198
|
* Force-directed layout (Fruchterman-Reingold). Deterministic for a given `seed`; repulsion is
|
|
102
199
|
* computed through a uniform grid so large graphs (1000+ nodes) stay fast. Ends with a rectangle
|
|
103
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.
|
|
104
204
|
*/
|
|
105
205
|
export function forceLayout(nodes, edges, opts = {}) {
|
|
106
206
|
const n = nodes.length;
|
|
@@ -111,16 +211,58 @@ export function forceLayout(nodes, edges, opts = {}) {
|
|
|
111
211
|
const rand = rng(seed);
|
|
112
212
|
const k = spacing;
|
|
113
213
|
const pairs = pairsOf(nodes, edges);
|
|
214
|
+
const pin = pinnedIn(nodes, opts.pin);
|
|
215
|
+
const fixed = nodes.map((nd) => !!pin?.has(nd.id));
|
|
114
216
|
const px = new Float64Array(n), py = new Float64Array(n);
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
+
}
|
|
120
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
|
+
}
|
|
121
263
|
const dx = new Float64Array(n), dy = new Float64Array(n);
|
|
122
264
|
const cutoff = k * 2.5;
|
|
123
|
-
const t0 = k * 1.5;
|
|
265
|
+
const t0 = pin ? k * 0.5 : k * 1.5;
|
|
124
266
|
for (let it = 0; it < iterations; it++) {
|
|
125
267
|
dx.fill(0);
|
|
126
268
|
dy.fill(0);
|
|
@@ -170,19 +312,23 @@ export function forceLayout(nodes, edges, opts = {}) {
|
|
|
170
312
|
}
|
|
171
313
|
const t = t0 * (1 - it / iterations) + 1;
|
|
172
314
|
for (let i = 0; i < n; i++) {
|
|
173
|
-
|
|
174
|
-
|
|
315
|
+
if (fixed[i])
|
|
316
|
+
continue;
|
|
317
|
+
dx[i] -= (px[i] - gx0) * gravity;
|
|
318
|
+
dy[i] -= (py[i] - gy0) * gravity;
|
|
175
319
|
const len = Math.hypot(dx[i], dy[i]) || 1;
|
|
176
320
|
const step = Math.min(len, t);
|
|
177
321
|
px[i] += (dx[i] / len) * step;
|
|
178
322
|
py[i] += (dy[i] / len) * step;
|
|
179
323
|
}
|
|
180
324
|
}
|
|
181
|
-
removeOverlaps(nodes, px, py);
|
|
182
|
-
|
|
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) }));
|
|
183
329
|
}
|
|
184
330
|
/** Push apart any rectangles that still overlap (grid-accelerated, bounded passes). */
|
|
185
|
-
function removeOverlaps(nodes, px, py, pad = 16) {
|
|
331
|
+
function removeOverlaps(nodes, px, py, pad = 16, fixed) {
|
|
186
332
|
const n = nodes.length;
|
|
187
333
|
const sz = nodes.map(sizeOf);
|
|
188
334
|
const cell = Math.max(...sz.map((s) => Math.max(s.w, s.h))) + pad;
|
|
@@ -208,16 +354,19 @@ function removeOverlaps(nodes, px, py, pad = 16) {
|
|
|
208
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);
|
|
209
355
|
if (px2 <= 0 || py2 <= 0)
|
|
210
356
|
continue;
|
|
357
|
+
if (fixed?.[i] && fixed[j])
|
|
358
|
+
continue; // two pinned nodes stay put, even when they overlap
|
|
211
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
|
|
212
361
|
if (px2 < py2) {
|
|
213
362
|
const s = (ex >= 0 ? 1 : -1) * (px2 / 2 + 0.5);
|
|
214
|
-
px[i] -= s;
|
|
215
|
-
px[j] += s;
|
|
363
|
+
px[i] -= s * wi;
|
|
364
|
+
px[j] += s * wj;
|
|
216
365
|
}
|
|
217
366
|
else {
|
|
218
367
|
const s = (ey >= 0 ? 1 : -1) * (py2 / 2 + 0.5);
|
|
219
|
-
py[i] -= s;
|
|
220
|
-
py[j] += s;
|
|
368
|
+
py[i] -= s * wi;
|
|
369
|
+
py[j] += s * wj;
|
|
221
370
|
}
|
|
222
371
|
}
|
|
223
372
|
}
|
|
@@ -230,12 +379,34 @@ function removeOverlaps(nodes, px, py, pad = 16) {
|
|
|
230
379
|
* Radial layout: the `root` (default: the first node with no incoming edge) in the centre, every
|
|
231
380
|
* other node on a ring by its distance from the root (edges treated as undirected). Subtrees get
|
|
232
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.
|
|
233
385
|
*/
|
|
234
386
|
export function radialLayout(nodes, edges, opts = {}) {
|
|
235
387
|
const n = nodes.length;
|
|
236
388
|
if (!n)
|
|
237
389
|
return [];
|
|
238
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
|
+
}
|
|
239
410
|
const adj = nodes.map(() => []);
|
|
240
411
|
const hasIn = new Array(n).fill(false);
|
|
241
412
|
for (const [a, b] of pairsOf(nodes, edges)) {
|
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>. */
|