@ruckc/truss-graph 1.24.0 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Graph.svelte 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 {
@@ -247,7 +247,7 @@
247
247
  if (!pa || !pb) return [];
248
248
  const r = routeEdge(routeType(e.type ?? edgeType), portAnchor(a, pa, portsOf(a)), portAnchor(b, pb, portsOf(b)), needsObstacles ? rects : []);
249
249
  return [{ e, d: r.d, m: r.mid }];
250
- }), (g) => (edgeLabel ? { w: 180, h: 32 } : g.e.label ? { w: g.e.label.length * 6.8 + 16, h: 20 } : null))
250
+ }), (g) => labelSize(g.e, !!edgeLabel))
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: WIDTH_PAD - y0 * s, h: Math.ceil((y1 - y0) * s + WIDTH_PAD * 2) };
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.pin);
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?: string[]): GraphNode[] {
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
@@ -33,5 +33,16 @@ export declare function spreadLabels<T extends {
33
33
  w: number;
34
34
  h: number;
35
35
  } | null): T[];
36
+ /**
37
+ * Estimated size of an edge's label box: 180 x 32 for an `edgeLabel` snippet (any edge), else the text's width
38
+ * (`len * 6.8 + 16`) by 20 for a plain `label`, or null when the edge has none. Shared by label spreading and the
39
+ * layered layout (which widens a rank gap to fit the labels crossing it).
40
+ */
41
+ export declare function labelSize(edge: {
42
+ label?: string;
43
+ }, snippet?: boolean): {
44
+ w: number;
45
+ h: number;
46
+ } | null;
36
47
  /** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
37
48
  export declare function routeEdge(type: EdgeType, a: Anchor, b: Anchor, obstacles?: Rect[]): Routed;
package/dist/routing.js CHANGED
@@ -259,6 +259,14 @@ export function spreadLabels(items, size) {
259
259
  return y === item.m.y ? item : { ...item, m: { x: item.m.x, y } };
260
260
  });
261
261
  }
262
+ /**
263
+ * Estimated size of an edge's label box: 180 x 32 for an `edgeLabel` snippet (any edge), else the text's width
264
+ * (`len * 6.8 + 16`) by 20 for a plain `label`, or null when the edge has none. Shared by label spreading and the
265
+ * layered layout (which widens a rank gap to fit the labels crossing it).
266
+ */
267
+ export function labelSize(edge, snippet = false) {
268
+ return snippet ? { w: 180, h: 32 } : edge.label ? { w: edge.label.length * 6.8 + 16, h: 20 } : null;
269
+ }
262
270
  /** Route an edge between two anchors with the chosen method. `obstacles` is used by `avoid`, and by `step` / `smoothstep` to go around nodes. */
263
271
  export function routeEdge(type, a, b, obstacles = []) {
264
272
  switch (type) {
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 = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-graph",
3
- "version": "1.24.0",
3
+ "version": "1.25.0",
4
4
  "description": "Zero-dependency node/edge graph editor for Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",