@weasel-js/diagram 1.4.4 → 1.5.1

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.
@@ -0,0 +1,749 @@
1
+ import * as _weasel_js_core from '@weasel-js/core';
2
+ import { Path, Vec2, PoseDescriptor, SimulationNode, createSimulation } from '@weasel-js/core/math';
3
+
4
+ /**
5
+ * The shapes a built body can wear, as paths in the node's bounds.
6
+ *
7
+ * These are the flowchart vocabulary — a decision is a diamond, an I/O step a
8
+ * parallelogram, a terminator a stadium — plus `'rect'` for everything else and
9
+ * a `Path` escape hatch for a shape the vocabulary does not have. The path is
10
+ * built in world coordinates from the bounds it is given, the same way the
11
+ * kit's own `clipFromPose` factories are.
12
+ */
13
+
14
+ /** An axis-aligned box, in the shape `PoseDescriptor.getBounds` returns. */
15
+ interface Bounds {
16
+ x: number;
17
+ y: number;
18
+ width: number;
19
+ height: number;
20
+ }
21
+ /** A named flowchart shape, or a path a consumer built themselves. */
22
+ type Outline = 'rect' | 'diamond' | 'stadium' | 'parallelogram' | Path;
23
+ /** The path `outline` describes inside `bounds`. A zero-area box gives a
24
+ * zero-area rect rather than a degenerate polygon. */
25
+ declare function outlinePath(outline: Outline, bounds: Bounds): Path;
26
+ /**
27
+ * The largest axis-aligned box a shape's content can occupy without leaving
28
+ * the shape. Rows lay out in here, not in the bounds — a diamond's corners and
29
+ * a parallelogram's lean are outside its own box, and a label placed against
30
+ * the bounding box lands there and gets clipped away by the silhouette.
31
+ *
32
+ * Conservative rather than exact: the inscribed rect of a rhombus is exact,
33
+ * and a stadium reports the flat span between its rounded ends, which gives up
34
+ * a little height near them.
35
+ */
36
+ declare function contentBox(outline: Outline, bounds: Bounds): Bounds;
37
+ /**
38
+ * The box whose {@link contentBox} is at least `content` — the inverse, for
39
+ * sizing a node to what its rows measured.
40
+ *
41
+ * The stadium case is the only inexact one: its inset depends on the height it
42
+ * is solving for, so it assumes the wide orientation and adds one height's
43
+ * worth of end caps.
44
+ */
45
+ declare function boxForContent(outline: Outline, content: {
46
+ width: number;
47
+ height: number;
48
+ }): {
49
+ width: number;
50
+ height: number;
51
+ };
52
+
53
+ /**
54
+ * Where a port sits on its node, in **normalized bounds coordinates**:
55
+ * `(0, 0)` is the top-left corner of the node's AABB and `(1, 1)` the
56
+ * bottom-right. `COMPASS` names the eight positions almost everything wants.
57
+ *
58
+ * Normalized rather than absolute because a node's size is authored data that
59
+ * resize, align and distribute all write — a port fixed at an offset would
60
+ * drift off the shape the first time one of them ran.
61
+ */
62
+ interface PortAnchor {
63
+ u: number;
64
+ v: number;
65
+ }
66
+ /** One attachment point declared on a node. */
67
+ interface PortSpec {
68
+ /** Unique within the node. Edges name this, so it outlives a re-layout. */
69
+ id: string;
70
+ at: PortAnchor;
71
+ /** Consulted by a connect gesture's validity predicate. Uninterpreted here. */
72
+ type?: string;
73
+ /** The direction an edge leaves along, overriding the one the anchor
74
+ * implies. `null` means "no preferred direction" — a router goes straight
75
+ * at it. */
76
+ normal?: Vec2 | null;
77
+ }
78
+ /**
79
+ * The trait that makes an existing scene node a diagram participant.
80
+ *
81
+ * Attached to a node's `data`, not a node kind the plugin mints: a text block,
82
+ * an image, a path, a group or a plain rect all take part by carrying this,
83
+ * and nothing has to be authored through this package to be connectable.
84
+ */
85
+ interface DiagramNode {
86
+ /** Defaults to {@link DEFAULT_PORTS} — the four edge midpoints of the
87
+ * node's own bounds, which every node has. */
88
+ ports?: readonly PortSpec[];
89
+ /** Layout must not move this node. */
90
+ pinned?: boolean;
91
+ /** What the node is *drawn* as. Present on a built body; absent on a
92
+ * participant that already had a look of its own — a text block, an image,
93
+ * a path — which keeps whatever painter it already matched. */
94
+ outline?: Outline;
95
+ }
96
+ /** A port resolved against a node's current pose: where it is in world
97
+ * coordinates, and which way an edge leaves it. */
98
+ interface Port {
99
+ id: string;
100
+ /** The node this port belongs to. */
101
+ nodeId: string;
102
+ /** World point an edge attaches to. */
103
+ point: Vec2;
104
+ /** Unit vector pointing away from the node, or `null` when the port
105
+ * declared no direction. Rotated with the node. */
106
+ normal: Vec2 | null;
107
+ type?: string;
108
+ }
109
+
110
+ /** One line of body content. */
111
+ type Row =
112
+ /** Text. `label` is the node's name; `field` is a named value. */
113
+ {
114
+ kind: 'label';
115
+ text: string;
116
+ style?: RowTextStyle;
117
+ } | {
118
+ kind: 'field';
119
+ label: string;
120
+ value: string;
121
+ style?: RowTextStyle;
122
+ }
123
+ /** A row that carries ports on its own left and right edges — the
124
+ * visual-programming shape, where an operator's inputs line up with the
125
+ * rows they feed. */
126
+ | {
127
+ kind: 'ports';
128
+ left?: readonly RowPort[];
129
+ right?: readonly RowPort[];
130
+ height?: number;
131
+ }
132
+ /** Reserved space a consumer paints into. */
133
+ | {
134
+ kind: 'slot';
135
+ height: number;
136
+ id?: string;
137
+ };
138
+ /** A port declared on a row rather than on the node's perimeter. */
139
+ interface RowPort {
140
+ id: string;
141
+ /** Label shown beside it, and what the row measures against. */
142
+ label?: string;
143
+ type?: string;
144
+ }
145
+ /** The subset of a text style the body measures against. Deliberately small:
146
+ * a full `ResolvedTextStyle` belongs to whatever paints the row. */
147
+ interface RowTextStyle {
148
+ fontSize?: number;
149
+ fontFamily?: string;
150
+ bold?: boolean;
151
+ }
152
+ /** Measures one run of text. Returns its advance width and its line height. */
153
+ type MeasureRowText = (text: string, style: RowTextStyle) => {
154
+ width: number;
155
+ height: number;
156
+ };
157
+ interface BodySpec {
158
+ outline: Outline;
159
+ rows: readonly Row[];
160
+ /** Space between the outline and its rows. Default 8. */
161
+ padding?: number;
162
+ /** Space between adjacent rows. Default 4. */
163
+ gap?: number;
164
+ }
165
+ /** What {@link buildBody} emits: the `AddNodeSpec` fields it fills in. Named
166
+ * structurally rather than imported so a consumer whose scene is typed
167
+ * differently can still spread one. */
168
+ interface BodyNodeSpec<TData, TLayer extends string, TPose> {
169
+ kind: 'container' | 'leaf';
170
+ layer: TLayer;
171
+ pose: TPose;
172
+ data: TData;
173
+ id?: string;
174
+ parent?: string;
175
+ /** Set `false` on every leaf the builder emits: the innermost hit wins, so a
176
+ * row that answers a press is a body that cannot be dragged. */
177
+ pickable?: boolean;
178
+ }
179
+ /** The floor a body's content puts under its node's size. */
180
+ interface BodyFloor {
181
+ minWidth: number;
182
+ minHeight: number;
183
+ }
184
+ /** Where one row landed, in the same frame as the bounds it was laid out in.
185
+ * A `ports` row's own ports anchor to this box. */
186
+ interface RowBox extends Bounds {
187
+ row: Row;
188
+ index: number;
189
+ }
190
+ /** Where one row port's label sits, in the same frame as the row box it was
191
+ * laid out in. Its vertical center is also where the port itself attaches, so
192
+ * a label and the port it names cannot drift apart. */
193
+ interface RowPortBox extends Bounds {
194
+ port: RowPort;
195
+ side: 'left' | 'right';
196
+ /** Position within its own side, top to bottom. */
197
+ index: number;
198
+ }
199
+ /** Adapts the kit's `measureText` for a caller holding a 2D context. Pass the
200
+ * same context the renderer measures with, or the floor will not match what
201
+ * is painted. */
202
+ declare function canvasMeasure(ctx: {
203
+ measureText(text: string): {
204
+ width: number;
205
+ };
206
+ font: string;
207
+ }): MeasureRowText;
208
+ /**
209
+ * The smallest box `spec`'s rows fit in. A node's pose is maxed against this,
210
+ * never set to it.
211
+ */
212
+ declare function measureBody(spec: BodySpec, measure?: MeasureRowText): BodyFloor;
213
+ /**
214
+ * The authored size, grown to fit the body. Never shrinks: a row removed
215
+ * leaves the node the size the author last saw it at, which is the only
216
+ * behavior that survives a resize the author did on purpose.
217
+ */
218
+ declare function sizeToBody<TPose extends Bounds>(pose: TPose, floor: BodyFloor): TPose;
219
+ /** Where each row sits inside `bounds`, top to bottom. Rows keep their
220
+ * measured heights; the leftover goes unclaimed at the bottom rather than
221
+ * being distributed, so a row does not move when a sibling grows. */
222
+ declare function layoutBody(spec: BodySpec, bounds: Bounds, measure?: MeasureRowText): RowBox[];
223
+ /**
224
+ * Where each of a `ports` row's ports goes inside `box`, on the same terms
225
+ * `layoutBody` gives one box per row.
226
+ *
227
+ * Both sides are cut into the same number of slots — the longer side's count —
228
+ * so the nth input faces the nth output whichever side has more. A label box
229
+ * is as wide as its own text and pinned to its own edge of the row; an
230
+ * unlabeled port gets a zero-width box there, which is still where it attaches.
231
+ */
232
+ declare function layoutRowPorts(row: Extract<Row, {
233
+ kind: 'ports';
234
+ }>, box: Bounds, measure?: MeasureRowText): RowPortBox[];
235
+ /**
236
+ * The `DiagramNode` trait a built body implies: perimeter ports for the
237
+ * outline, plus one port per `ports`-row entry, anchored to that row's own
238
+ * left or right edge.
239
+ *
240
+ * Anchors are normalized against `bounds`, so they survive the node being
241
+ * resized — which is the whole reason `PortAnchor` is normalized.
242
+ *
243
+ * **A row port on a side takes that side's compass default with it.** Both sit
244
+ * on the same edge, and a row near the vertical middle puts one exactly on top
245
+ * of `w` or `e` — where the later region wins the hit and the other is
246
+ * grabbable nowhere. A body that declares where its inputs attach has said what
247
+ * that side is for.
248
+ */
249
+ declare function bodyTrait(spec: BodySpec, bounds: Bounds, measure?: MeasureRowText): DiagramNode;
250
+ /** The outline path for a built body at `bounds` — what paints it, and what a
251
+ * perimeter-hugging port will eventually be placed on. */
252
+ declare function bodyOutline(spec: BodySpec, bounds: Bounds): _weasel_js_core.Path;
253
+ /** What a built body's rows are handed to, one call per row.
254
+ *
255
+ * `text` is the row's content already formatted — a `label`'s own text, or a
256
+ * `field`'s `"label: value"` — so the common case needs no discrimination.
257
+ * Return `null` for a row the consumer paints itself; `ports` and `slot` rows
258
+ * arrive with `text` empty and are the usual ones to decline. */
259
+ type RowNodeData<TData> = (text: string, box: RowBox) => TData | null;
260
+ interface BuildBodyOptions<TData, TLayer extends string, TPose extends Bounds> {
261
+ layer: TLayer;
262
+ /** The container's id. Edges name it, so pass one for anything an edge or a
263
+ * layout `pin` will refer to. */
264
+ id?: string;
265
+ measure?: MeasureRowText;
266
+ /** The container's own data, given the trait the builder computed and the
267
+ * pose it was computed against. */
268
+ body: (trait: DiagramNode, pose: TPose) => TData;
269
+ /** One row's data, or `null` to leave that row undrawn. */
270
+ row: RowNodeData<TData>;
271
+ /** One row port's label, or `null` to leave it undrawn. Ports with no
272
+ * `label` are never offered. Omit to draw none — a body whose ports are
273
+ * named only for the width they claim needs nothing here. */
274
+ portLabel?: (text: string, box: RowPortBox) => TData | null;
275
+ }
276
+ /**
277
+ * The scene nodes a built body is: one container carrying the trait, and one
278
+ * leaf per row that wants drawing.
279
+ *
280
+ * Rows are ordinary scene nodes rather than something this package paints, so
281
+ * the kit's own text painter draws them and text editing, styling and
282
+ * selection work on them unchanged. The walk that places them is
283
+ * `layoutBody` — the same one `bodyTrait` anchors its row ports against, which
284
+ * is why a label and its ports cannot drift apart.
285
+ *
286
+ * The pose is `sizeToBody(at, measureBody(spec))`: the body measures a floor
287
+ * and the authored size is grown to clear it, never shrunk.
288
+ */
289
+ declare function buildBody<TData, TLayer extends string, TPose extends Bounds>(spec: BodySpec, at: TPose, opts: BuildBodyOptions<TData, TLayer, TPose>): {
290
+ pose: TPose;
291
+ specs: BodyNodeSpec<TData, TLayer, TPose>[];
292
+ };
293
+
294
+ /**
295
+ * Reading the `DiagramNode` trait off a scene node.
296
+ *
297
+ * Two ways to attach it, both of which this module's default reader answers:
298
+ *
299
+ * - **On the node.** `data.diagram` holds the trait. One node, one answer;
300
+ * what a connect gesture writes when the author drags a new edge.
301
+ * - **By kind.** A consumer declares once which data shapes take part, and
302
+ * every matching node gets the trait without being stamped. This mirrors
303
+ * `createNodeRouting` in the kit — a predicate over `data`, first match
304
+ * wins — and is the shape to reach for when the participants are a class
305
+ * of node rather than a hand-picked set.
306
+ *
307
+ * A reader is a plain function, so a consumer whose data lives somewhere else
308
+ * entirely passes their own and never touches either form.
309
+ */
310
+
311
+ /** The key on a node's `data` the default reader looks under. */
312
+ declare const DIAGRAM_TRAIT_KEY = "diagram";
313
+ /** All a reader looks at. Deliberately not `SceneNode`: naming `TPose` there
314
+ * would put it in a contravariant position for no gain, since nothing here
315
+ * reads a pose. */
316
+ interface DiagramNodeLike {
317
+ id: string;
318
+ kind: 'leaf' | 'container';
319
+ data: unknown;
320
+ }
321
+ /** Answers "is this node a diagram participant, and on what terms" — `null`
322
+ * for a node that takes no part. */
323
+ type DiagramNodeReader = (node: DiagramNodeLike) => DiagramNode | null;
324
+ /** One class of participant, declared once for every node whose data matches.
325
+ * Mirrors `NodeRoutingEntry`. */
326
+ interface DiagramNodeEntry {
327
+ /** Unique within a reader; the same vocabulary as `NodeRoutingEntry.name`. */
328
+ name: string;
329
+ matches: (data: unknown) => boolean;
330
+ /** The trait every matching node carries. A function when it varies with the
331
+ * node's own data — a pipeline stage whose ports come from its rows. */
332
+ trait: DiagramNode | ((data: unknown) => DiagramNode);
333
+ }
334
+ /** The trait on the node's own `data.diagram`, or `null`.
335
+ *
336
+ * An edge's trait lives under the same key, so `from` and `to` are what tells
337
+ * the two apart. Without that test an edge reads as a participant declaring
338
+ * no ports, and collects the four defaults on the degenerate pose an edge
339
+ * carries — four grabbable ports in the middle of nowhere. */
340
+ declare const dataKeyReader: DiagramNodeReader;
341
+ /**
342
+ * A reader over declared kinds. A trait on the node's own data still wins, so
343
+ * a single node can opt out of, or override, whatever its kind says.
344
+ *
345
+ * Throws on a duplicate `name`, for the reason `mergeContributions` does: a
346
+ * class of node silently losing its ports is what this registry exists to make
347
+ * loud.
348
+ */
349
+ declare function createDiagramNodes(entries: readonly DiagramNodeEntry[]): DiagramNodeReader;
350
+ /** The trait `node` carries, through `read` (default: its own `data.diagram`). */
351
+ declare function diagramNodeOf(node: DiagramNodeLike, read?: DiagramNodeReader): DiagramNode | null;
352
+ /** True when layout must leave this node where it is. */
353
+ declare function isPinned(node: DiagramNodeLike, read?: DiagramNodeReader): boolean;
354
+
355
+ /**
356
+ * Where a node's ports are, in world coordinates.
357
+ *
358
+ * A port is placed in the node's **unrotated** bounds, then carried through
359
+ * the pose's rotation — the same pivot every other kit reader uses, the AABB
360
+ * center. Bounds come from the pose descriptor rather than from `pose.width`
361
+ * and friends, so a node whose pose is a path, an ellipse or anything else a
362
+ * consumer wired is connectable on the same terms as a rect.
363
+ */
364
+
365
+ /** The eight anchors almost everything wants, named the way a compass is. */
366
+ declare const COMPASS: {
367
+ readonly nw: {
368
+ readonly u: 0;
369
+ readonly v: 0;
370
+ };
371
+ readonly n: {
372
+ readonly u: 0.5;
373
+ readonly v: 0;
374
+ };
375
+ readonly ne: {
376
+ readonly u: 1;
377
+ readonly v: 0;
378
+ };
379
+ readonly e: {
380
+ readonly u: 1;
381
+ readonly v: 0.5;
382
+ };
383
+ readonly se: {
384
+ readonly u: 1;
385
+ readonly v: 1;
386
+ };
387
+ readonly s: {
388
+ readonly u: 0.5;
389
+ readonly v: 1;
390
+ };
391
+ readonly sw: {
392
+ readonly u: 0;
393
+ readonly v: 1;
394
+ };
395
+ readonly w: {
396
+ readonly u: 0;
397
+ readonly v: 0.5;
398
+ };
399
+ };
400
+ /**
401
+ * What a node carrying no `ports` gets: the four edge midpoints of its own
402
+ * bounds. Every node has bounds, so every node is connectable without saying
403
+ * anything.
404
+ */
405
+ declare const DEFAULT_PORTS: readonly PortSpec[];
406
+ interface PortsOptions<TPose> {
407
+ /** Reads the AABB a port is placed in, and the node's rotation. Defaults to
408
+ * the kit's `AUTO_POSE_DESCRIPTOR`, which handles rect and path poses. */
409
+ geometry?: PoseDescriptor<TPose>;
410
+ /** How the `DiagramNode` trait is read off a node. */
411
+ read?: DiagramNodeReader;
412
+ }
413
+ /**
414
+ * Every port on `node`, resolved against `pose`.
415
+ *
416
+ * Pass the pose the node is **painted** at — `effectivePose(scene, node)` —
417
+ * not `node.pose`. A port that answers from the document pose while the node
418
+ * is mid-drag puts an edge somewhere the user can see the node is not.
419
+ */
420
+ declare function portsOf<TPose>(node: DiagramNodeLike, pose: TPose, opts?: PortsOptions<TPose>): Port[];
421
+ /** One named port, or `undefined` when the node has no such port. */
422
+ declare function portOf<TPose>(node: DiagramNodeLike, pose: TPose, portId: string, opts?: PortsOptions<TPose>): Port | undefined;
423
+
424
+ /**
425
+ * `Graph` — the adjacency index a layout runs over.
426
+ *
427
+ * The scene is the document, so there is no second graph kept in sync with it:
428
+ * this one is built from the scene on demand, used, and thrown away. Rebuilding
429
+ * per layout invocation is deliberate — a maintained index is a cache to
430
+ * invalidate on every add, delete, reparent and `dependsOn` edit, and layout is
431
+ * not on the hot path. Measure before changing that.
432
+ *
433
+ * A node's *identity* is its id and its *size* is its bounds; where it currently
434
+ * sits is here too, because a re-layout that ignores where things already are
435
+ * scrambles a diagram the author has arranged.
436
+ */
437
+
438
+ /** A scene node as the graph reads it. `dependsOn` is what an edge's two
439
+ * endpoints are: the edge trait names *ports*, and the nodes those ports are
440
+ * on are the dependencies the derivation already runs on. */
441
+ interface GraphNodeLike extends DiagramNodeLike {
442
+ dependsOn?: readonly string[] | 'children';
443
+ }
444
+ /** Where the graph gets its nodes. The same thunk shape the port affordance
445
+ * takes, so one source answers both. */
446
+ type GraphSource<TPose> = () => Iterable<{
447
+ node: GraphNodeLike;
448
+ pose: TPose;
449
+ }>;
450
+ /** One participant. */
451
+ interface GraphNode {
452
+ id: string;
453
+ /** Where it is now, in world coordinates. */
454
+ bounds: Bounds;
455
+ /** Layout must not move it. */
456
+ pinned: boolean;
457
+ }
458
+ /** One connection. `id` is the edge node's own id, so a caller can go back to
459
+ * the scene for its trait. */
460
+ interface GraphEdge {
461
+ id: string;
462
+ from: string;
463
+ to: string;
464
+ }
465
+ /**
466
+ * Nodes, edges, and the two adjacency reads a layout needs.
467
+ *
468
+ * Every list is in source order — render order, when the source is a scene —
469
+ * which is what a layout's tiebreaks resolve against. There is no RNG anywhere
470
+ * downstream of this, and this is where that starts.
471
+ */
472
+ interface Graph {
473
+ readonly nodes: readonly GraphNode[];
474
+ readonly edges: readonly GraphEdge[];
475
+ node(id: string): GraphNode | undefined;
476
+ /** Edges leaving `id`, in source order. */
477
+ outgoing(id: string): readonly GraphEdge[];
478
+ /** Edges arriving at `id`, in source order. */
479
+ incoming(id: string): readonly GraphEdge[];
480
+ }
481
+ interface BuildGraphOptions<TPose> {
482
+ read?: DiagramNodeReader;
483
+ geometry?: PoseDescriptor<TPose>;
484
+ }
485
+ /**
486
+ * Read a graph out of a source of scene nodes.
487
+ *
488
+ * A node is an edge if it carries the edge trait and names exactly two
489
+ * dependencies; a participant if the reader hands back a `DiagramNode`;
490
+ * neither, and it is not in the diagram at all. An edge whose endpoints are not
491
+ * both participants is dropped — a dangling edge should not be ranking
492
+ * anything.
493
+ */
494
+ declare function buildGraph<TPose>(source: GraphSource<TPose>, opts?: BuildGraphOptions<TPose>): Graph;
495
+
496
+ /**
497
+ * Layout: where the participants go.
498
+ *
499
+ * A layout is a pure function of the graph — no scene, no ops, no history. It
500
+ * hands back the new top-left for every node that **moves**, and a node already
501
+ * standing where the layout wants it is simply absent from the answer. That is
502
+ * what makes re-running a layout free rather than destructive, and it is the
503
+ * property the idempotence test asserts.
504
+ *
505
+ * Three rules keep re-layout non-destructive, and all three live here rather
506
+ * than in each algorithm:
507
+ *
508
+ * - **No RNG anywhere.** Every tiebreak falls back to the graph's own node
509
+ * order, which is the source's order — render order, for a scene.
510
+ * - **Within-rank order is seeded from where the nodes already are**, read
511
+ * off the cross axis, rather than from crossing-minimization. An author who
512
+ * dragged two boxes into an order gets that order back.
513
+ * - **A pin set nothing moves.** Pinned nodes are never in the result, and
514
+ * the rest of the layout is translated to sit around them.
515
+ *
516
+ * `layered` and `tree` are idempotent by construction: the second run reads the
517
+ * order the first run produced and computes the same slots. `force` is an
518
+ * iterative relaxation and makes no such claim — re-running it keeps relaxing.
519
+ */
520
+
521
+ /** Which way the ranks stack. `force` ignores it. */
522
+ type LayoutDirection = 'down' | 'up' | 'right' | 'left';
523
+ interface LayoutOptions {
524
+ /** Default `'down'`. */
525
+ direction?: LayoutDirection;
526
+ /** Between neighbors within a rank, in world units. Default 48. */
527
+ nodeGap?: number;
528
+ /** Between one rank and the next. Default 96. */
529
+ rankGap?: number;
530
+ /** Ids layout must not move, on top of whatever carries `pinned: true`. */
531
+ pin?: Iterable<string>;
532
+ /** How far a node has to move to be worth moving, in world units. Default
533
+ * `1e-6` — a float-noise floor, not a snapping quantum. Raise it to let a
534
+ * `force` pass that has stopped doing anything useful commit nothing. */
535
+ tolerance?: number;
536
+ }
537
+ /** The new top-left for each node that moves. A node that is already there is
538
+ * absent, so an empty result means "nothing to do". */
539
+ type LayoutResult = ReadonlyMap<string, Vec2>;
540
+ /** Every layout in this package has this shape, and so does a consumer's. */
541
+ type LayoutFn = (graph: Graph, opts?: LayoutOptions) => LayoutResult;
542
+ declare const DEFAULT_NODE_GAP = 48;
543
+ declare const DEFAULT_RANK_GAP = 96;
544
+ /** Which world axis carries ranks, which carries within-rank order, and
545
+ * whether ranks grow toward positive world coordinates. */
546
+ interface LayoutAxes {
547
+ rank: 'x' | 'y';
548
+ cross: 'x' | 'y';
549
+ /** `-1` for `'up'` and `'left'`, where the canonical frame is mirrored. */
550
+ sign: 1 | -1;
551
+ }
552
+ declare function axesFor(direction?: LayoutDirection): LayoutAxes;
553
+ /** A node's extent along one axis. */
554
+ declare function extent(bounds: Bounds, axis: 'x' | 'y'): number;
555
+ /** Every id layout must leave alone. */
556
+ declare function pinnedSet(graph: Graph, opts?: LayoutOptions): Set<string>;
557
+ /**
558
+ * A placement in the canonical `(cross, rank)` frame, before it is turned into
559
+ * world coordinates. `cross` and `rank` are the node's low corner along each.
560
+ */
561
+ interface Slot {
562
+ cross: number;
563
+ rank: number;
564
+ }
565
+ /**
566
+ * Turn canonical slots into the positions to write.
567
+ *
568
+ * Three steps, in order: map the canonical frame onto the world axes the
569
+ * direction names; translate the whole layout so it lands where the graph
570
+ * already is; drop everything that is pinned or that would not move.
571
+ *
572
+ * The translation is what makes the layout non-destructive, and it is chosen so
573
+ * that a second run lands on the same answer. With a pin, it is whatever keeps
574
+ * the first pinned node exactly where it is. Without one, it is whatever puts
575
+ * the layout's own bounding box where the graph's bounding box already starts —
576
+ * which the first run then makes true, so the second run computes the same
577
+ * translation and writes nothing.
578
+ */
579
+ declare function settle(graph: Graph, slots: ReadonlyMap<string, Slot>, opts?: LayoutOptions): LayoutResult;
580
+ /**
581
+ * {@link settle}'s second half, for a layout that already works in world
582
+ * coordinates — `force` does, since the integrator moves points around rather
583
+ * than filling slots.
584
+ */
585
+ declare function translated(graph: Graph, placed: ReadonlyMap<string, Vec2>, pinned: ReadonlySet<string>, tolerance?: number): LayoutResult;
586
+ /**
587
+ * Lay a list of nodes out along the cross axis, in the order given, and hand
588
+ * back each one's low corner plus the total span.
589
+ *
590
+ * Shared by `layered`'s ranks and `tree`'s sibling rows, which pack a row the
591
+ * same way and differ only in what decides the order.
592
+ */
593
+ declare function packAcross(nodes: readonly GraphNode[], axis: 'x' | 'y', gap: number): {
594
+ at: Map<string, number>;
595
+ span: number;
596
+ };
597
+ /** Order within a rank: where the nodes already sit on the cross axis, with
598
+ * graph order breaking a tie. Never a comparison that could reverse between
599
+ * two runs on the same input. */
600
+ declare function seededOrder(nodes: readonly GraphNode[], axis: 'x' | 'y', indexOf: (id: string) => number): GraphNode[];
601
+ /** Each node's position in `graph.nodes`, for tiebreaks. */
602
+ declare function graphOrder(graph: Graph): (id: string) => number;
603
+
604
+ /**
605
+ * `force` — relaxation, for a graph with no direction to read it in.
606
+ *
607
+ * Seeded from where the nodes already are rather than from a fresh random
608
+ * scatter: an author who has arranged half a diagram gets that arrangement
609
+ * relaxed, not replaced. There is no RNG in it at all — two coincident nodes
610
+ * are separated along a golden-angle spiral keyed to their index, which is what
611
+ * a random jiggle is for elsewhere.
612
+ *
613
+ * The integrator is the kit's own `createSimulation`, the same one
614
+ * `useSimulation` runs a frame at a time. Only the forces are local, and they
615
+ * are the naive O(n²) kind — right for the tens-to-hundreds of nodes an
616
+ * edge-per-scene-node diagram is already sized for, wrong for a 10k-node graph,
617
+ * which wants d3-force's Barnes–Hut through `useSimulation` and its own render
618
+ * layer.
619
+ *
620
+ * **This is the one layout that is not idempotent.** A relaxation re-run from
621
+ * its own output keeps relaxing; `direction` means nothing to it. Pins and the
622
+ * `tolerance` option are what keep a second pass from scrambling a settled
623
+ * diagram.
624
+ */
625
+
626
+ interface ForceOptions extends LayoutOptions {
627
+ /** Ticks to run. Default 300 — one full cooling schedule. */
628
+ iterations?: number;
629
+ /** Rest length of an edge, in world units. Default 160. */
630
+ linkDistance?: number;
631
+ /** How hard an edge pulls, 0..1. Default 0.35. */
632
+ linkStrength?: number;
633
+ /** Pairwise repulsion. Negative repels; default -3000. */
634
+ charge?: number;
635
+ /** How hard the graph is held around its own centroid. Default 0.02. */
636
+ gravity?: number;
637
+ /** Clear space kept between two boxes, in world units. Default 24. */
638
+ padding?: number;
639
+ }
640
+ interface Body extends SimulationNode {
641
+ id: string;
642
+ /** Half the node's box, so separation can work on the shape the author sees
643
+ * rather than on a point. */
644
+ hw: number;
645
+ hh: number;
646
+ }
647
+ /**
648
+ * The bodies and the force list, wound up and ready to tick.
649
+ *
650
+ * Shared by the one-shot `force` below and the live relaxation in `live.ts`,
651
+ * which ticks it a frame at a time. Two copies of a force list drift, and the
652
+ * only thing that would say so is the arrangement they produce.
653
+ */
654
+ interface ForceRelaxation {
655
+ bodies: Body[];
656
+ byId: Map<string, Body>;
657
+ /** Ids the caller must not move: declared pins, held as `fx`/`fy`. */
658
+ pinned: ReadonlySet<string>;
659
+ sim: ReturnType<typeof createSimulation<Body>>;
660
+ /** Where a body's node's top-left sits, given the body's center. */
661
+ placed(): Map<string, {
662
+ x: number;
663
+ y: number;
664
+ }>;
665
+ }
666
+ declare function forceRelaxation(graph: Graph, opts?: ForceOptions): ForceRelaxation;
667
+ declare const force: (graph: Graph, opts?: ForceOptions) => LayoutResult;
668
+
669
+ /**
670
+ * `layered` — ranks running one way, nodes running across.
671
+ *
672
+ * The flowchart / pipeline layout: an edge points from one rank to the next, so
673
+ * reading down the page is reading the order things happen in. Ranks come from
674
+ * longest-path layering, which puts every node as far along as its deepest
675
+ * predecessor allows.
676
+ *
677
+ * Cycles do not disqualify a graph. A depth-first walk in graph order names the
678
+ * edges that close a cycle, layering ignores those, and they draw as edges
679
+ * running back up the page — which is what a reader expects a loop to look
680
+ * like. Which edges get named depends only on the node order, so it is the same
681
+ * every run.
682
+ *
683
+ * This is not crossing-minimization: within a rank, nodes keep the order they
684
+ * already have on the cross axis. An author who dragged two branches into an
685
+ * order gets that order back, and re-running the layout is free.
686
+ */
687
+
688
+ /** Edge ids that close a cycle, found by a depth-first walk in graph order. */
689
+ declare function backEdges(graph: Graph): Set<string>;
690
+ /** Longest-path rank per node: one past its deepest predecessor. */
691
+ declare function ranksOf(graph: Graph, back: ReadonlySet<string>): Map<string, number>;
692
+ declare const layered: LayoutFn;
693
+
694
+ /**
695
+ * `tree` — a parent centered over the block its children occupy.
696
+ *
697
+ * The hierarchy layout: org charts, file trees, decision trees. Depth is the
698
+ * rank axis, so every child sits one band past its parent, and a subtree is
699
+ * packed as a solid block so two siblings' descendants never interleave.
700
+ *
701
+ * A graph that is not a tree still lays out. Roots are the nodes nothing points
702
+ * at, in graph order; a node reachable from two parents belongs to whichever
703
+ * the depth-first walk reaches first; and anything the walk never reaches — a
704
+ * disconnected part, or a pure cycle — becomes a root of its own. So the answer
705
+ * is always a forest, and which forest depends only on the node order.
706
+ *
707
+ * The block packing is deliberately not Reingold–Tilford: it never slides a
708
+ * deep subtree under a shallow neighbor's overhang. That costs horizontal
709
+ * space and buys an invariant an author can rely on — a subtree's extent is a
710
+ * rectangle, and dragging one never lands it inside another.
711
+ */
712
+
713
+ interface Forest {
714
+ roots: GraphNode[];
715
+ children: Map<string, GraphNode[]>;
716
+ depth: Map<string, number>;
717
+ }
718
+ /** The forest a depth-first walk in graph order finds. Exported because "which
719
+ * node ended up whose child" is the question anyone debugging a tree layout
720
+ * asks first. */
721
+ declare function forestOf(graph: Graph, crossAxis: 'x' | 'y'): Forest;
722
+ declare const tree: LayoutFn;
723
+
724
+ /** The outline as a closed polyline: `[x0, y0, x1, y1, …]`. */
725
+ declare function outlinePolyline(outline: Outline, bounds: Bounds): number[];
726
+ /**
727
+ * Where the ray from `center` through `point` last crosses `poly`, or `null`
728
+ * when it never does.
729
+ *
730
+ * The *last* crossing rather than the first: a concave outline can be crossed
731
+ * more than once, and the far side is the boundary an edge should attach to.
732
+ */
733
+ declare function rayHit(poly: readonly number[], center: {
734
+ x: number;
735
+ y: number;
736
+ }, point: {
737
+ x: number;
738
+ y: number;
739
+ }): {
740
+ x: number;
741
+ y: number;
742
+ } | null;
743
+ /**
744
+ * Every port moved onto `outline`. A port the ray misses — one at the node's
745
+ * dead center, with no direction to cast along — is left where it was.
746
+ */
747
+ declare function portsOnOutline(ports: readonly Port[], outline: Outline, bounds: Bounds): Port[];
748
+
749
+ export { forceRelaxation as $, type RowPort as A, type BodyFloor as B, COMPASS as C, type DiagramNodeLike as D, type RowPortBox as E, type ForceOptions as F, type GraphSource as G, type RowTextStyle as H, axesFor as I, backEdges as J, bodyOutline as K, type LayoutFn as L, type MeasureRowText as M, bodyTrait as N, type Outline as O, type Port as P, boxForContent as Q, type Row as R, type Slot as S, buildBody as T, buildGraph as U, canvasMeasure as V, contentBox as W, createDiagramNodes as X, dataKeyReader as Y, diagramNodeOf as Z, force as _, type PortsOptions as a, forestOf as a0, graphOrder as a1, isPinned as a2, layered as a3, layoutBody as a4, layoutRowPorts as a5, measureBody as a6, outlinePath as a7, outlinePolyline as a8, packAcross as a9, pinnedSet as aa, portOf as ab, portsOf as ac, portsOnOutline as ad, ranksOf as ae, rayHit as af, seededOrder as ag, settle as ah, sizeToBody as ai, translated as aj, tree as ak, extent as al, type DiagramNodeReader as b, type LayoutOptions as c, type LayoutResult as d, type Graph as e, type BodyNodeSpec as f, type BodySpec as g, type Bounds as h, type BuildBodyOptions as i, type BuildGraphOptions as j, DEFAULT_NODE_GAP as k, DEFAULT_PORTS as l, DEFAULT_RANK_GAP as m, DIAGRAM_TRAIT_KEY as n, type DiagramNode as o, type DiagramNodeEntry as p, type ForceRelaxation as q, type GraphEdge as r, type GraphNode as s, type GraphNodeLike as t, type LayoutAxes as u, type LayoutDirection as v, type PortAnchor as w, type PortSpec as x, type RowBox as y, type RowNodeData as z };