@slashsuite/ui-react 0.13.1 → 0.13.3

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.
@@ -82,6 +82,6 @@ Left out, the part takes the nearest loading layout's or part's; `false` opts it
82
82
  - FlowDirection: `"down" | "right"`. `down` reads from the top, `right` from the start edge.
83
83
  - FlowLayout: `{ width: number; height: number; nodes: readonly FlowNodeBox[]; groups: readonly (FlowBox & { name: string })[]; edges: readonly FlowEdgePath[] }`. The whole diagram as laid out, in one coordinate space: `width` and `height`, a box per node and per group, and a path per arrow. `FlowDiagram` hands it to `overlay`.
84
84
  - FlowNodeBox: `{ x: number; y: number; width: number; height: number; id: string }`. A node as laid out: its `id` and its box. A group's box (`group`) is the frame round its nodes.
85
- - FlowEdgePath: `{ from: string; to: string; index: number; points: readonly FlowPoint[]; path: string; labelAt: FlowPoint | null }`. An arrow as laid out: the `from` and `to` ids, its place in `edges` (`index`), the points dagre routed it through, the SVG path drawn through them (it ends on the target's edge, at the arrowhead's tip) and its label's centre when it has one.
85
+ - FlowEdgePath: `{ from: string; to: string; index: number; points: readonly FlowPoint[]; path: string; labelAt: FlowPoint | null }`. An arrow as laid out: the `from` and `to` ids, its place in `edges` (`index`), the corners of its square route (it leaves the source's side facing the way it goes, turns only between ranks, and ends on the target's edge, at the arrowhead's tip), the SVG path through them and its label's centre when it has one.
86
86
  - FlowBox: `{ x: number; y: number; width: number; height: number }`. Where a node or a group sits, its top left corner and its size, in CSS pixels.
87
87
  - FlowPoint: `{ x: number; y: number }`. A point in the diagram's own space, in CSS pixels from its top left corner.
@@ -29,6 +29,7 @@ import { StateMachine } from "@slashsuite/ui-react";
29
29
  - Give it `states` (`{ id, label, kind, owner }`), `transitions` (`{ from, to, event }`) and `items` (`{ id, label, state, href }`), plain data with no layout: it is drawn like a `FlowDiagram`.
30
30
  - `kind` says what a state is: `human` for a state waiting on a person (the warn tone), `failed` for an error (danger), `terminal` for done (muted), `initial` for the start. Each is also a tag in words. Leave the rest `normal`.
31
31
  - `owner` is the role or lane that acts in a state, a tag on its box.
32
+ - Keep a state's `label` short: every box is drawn one size, so the boxes line up, and a long label wraps inside it and makes every box a line taller.
32
33
  - An item's `id` is its short ref, shown by its dot; its `label` is the full name, its tooltip and what a screen reader says. Give `href` and the dot is a link.
33
34
  - Change an item's `state` and its dot runs along the arrow to its new box; there is nothing to call.
34
35
  - `active` rings the one state that is current, for a machine with one thing in it.
@@ -60,13 +61,13 @@ import { StateMachine } from "@slashsuite/ui-react";
60
61
 
61
62
  ### Accessibility
62
63
  - The drawing is an image named by `label`, with the count of states and transitions; the box round it is a group named by `label`, and takes the keyboard focus so a machine that scrolls can be scrolled with the arrow keys.
63
- - Each dot is named by its item's label and its state (`Fix the login, in Review`), and takes the focus; one with `href` is a link. A box with more than nine shows a `+N` button that shows the rest.
64
+ - Each dot is named by its item's label and its state (`Fix the login, in Review`), and takes the focus; one with `href` is a link. A box with more than six shows a `+N` button that shows the rest.
64
65
  - A visually hidden list after it carries every state, its tags and the transitions out of it, as `FlowDiagram`'s does.
65
66
  - With reduced motion a dot moves to its new state at once, with no run.
66
67
 
67
68
  ### Props
68
69
  ### StateMachine
69
- A state machine, drawn, with the things moving through it: each state a box, each transition an arrow named by its event, laid out like a `FlowDiagram`. A state's `kind` sets its look and a tag that says it: `human` takes the warn tone, `failed` the danger tone, `terminal` is muted, and `initial` is tagged start. Its `owner` is a tag beside it. Each of the `items` is a coloured dot with its short `id`, in the box of its `state`, which counts them; a box shows up to nine and a `+N` for the rest. The dot's name and tooltip is its full `label`, and with an `href` it is a link. An item whose state is not in the machine goes in a box of its own, "Not in any state", so nothing is dropped. When an item's state changes, its dot runs along the arrow between the two (straight across when there is none); with reduced motion it moves at once. `active` rings the one state that is current. `fromXState` makes `states` and `transitions` from an xstate machine.
70
+ A state machine, drawn, with the things moving through it: each state a box, each transition an arrow named by its event, laid out like a `FlowDiagram`. A state's `kind` sets its look and a tag that says it: `human` takes the warn tone, `failed` the danger tone, `terminal` is muted, and `initial` is tagged start. Its `owner` is a tag beside it. Every box is one size, the label wrapping inside it, and the boxes sit close. Each of the `items` is a coloured dot with its short `id`, in the box of its `state`, which counts them; a box shows up to six and a `+N` for the rest. The dot's name and tooltip is its full `label`, and with an `href` it is a link. An item whose state is not in the machine goes in a box of its own, "Not in any state", so nothing is dropped. When an item's state changes, its dot runs along the arrow between the two (straight across when there is none); with reduced motion it moves at once. `active` rings the one state that is current. `fromXState` makes `states` and `transitions` from an xstate machine.
70
71
  - active: string. The `id` of the one state to ring as current.
71
72
  - id: string. The root element's `id`: an anchor, or the target of a `for` or an `aria-describedby`.
72
73
  - items: readonly StateMachineItem[] (default []). The things in the machine, each in the state its `state` names.
@@ -77,9 +77,11 @@ export type ViewNode = Omit<FlowNode, "tone"> & {
77
77
  * `canvas` ref and the layout `drawn`. Unlike `overlay`, the layer is read by a screen reader and its
78
78
  * children may take the pointer (`pointer-events-auto`), so they can be links. With a layer, the
79
79
  * image is the drawing alone and the scrolling box round it is a group named by `label`. With `fit`,
80
- * a drawing wider than its room is shrunk to the room's width instead of scrolling. Internal.
80
+ * a drawing wider than its room is shrunk to the room's width instead of scrolling. With `uniform`
81
+ * (laid out by `useFlowLayout`'s `uniform`), every box fills its slot: its label wraps to the box's
82
+ * width and its content sits at the bottom. Internal.
81
83
  */
82
- export declare function FlowView({ label, nodes, edges, active, overlay, layer, canvas, drawn, fit, ...rest }: {
84
+ export declare function FlowView({ label, nodes, edges, active, overlay, layer, canvas, drawn, fit, uniform, ...rest }: {
83
85
  label: string;
84
86
  nodes: readonly ViewNode[];
85
87
  edges: readonly FlowEdge[];
@@ -89,4 +91,5 @@ export declare function FlowView({ label, nodes, edges, active, overlay, layer,
89
91
  canvas: ReturnType<typeof useFlowLayout>["canvas"];
90
92
  drawn: FlowLayout;
91
93
  fit?: boolean | undefined;
94
+ uniform?: boolean | undefined;
92
95
  } & Passthrough): ReactElement;
@@ -1,21 +1,8 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useId } from "react";
3
- import { TONE_SURFACE, TONE_TEXT } from "./Callout.js";
4
- import { cx } from "./cx.js";
3
+ import { FlowBoxView } from "./flowBox.js";
5
4
  import { Bone, BusyLabel, busy, useLoading } from "./skeleton.js";
6
- import { edgeKey, nodeKey, useFit, useFlowLayout } from "./useFlowLayout.js";
7
- /** A box's frame by tone: the Callout's soft surfaces, a white box for `neutral`, a grey one for `muted`. */
8
- const NODE_TONE = {
9
- ...TONE_SURFACE,
10
- neutral: "border-slate-300 bg-white",
11
- muted: "border-slate-200 bg-slate-50",
12
- };
13
- /** A box's ink by tone; `neutral` is the primary ink, `muted` the quiet one. */
14
- const NODE_INK = {
15
- ...TONE_TEXT,
16
- neutral: "text-slate-900",
17
- muted: "text-slate-500",
18
- };
5
+ import { edgeKey, useFit, useFlowLayout } from "./useFlowLayout.js";
19
6
  /**
20
7
  * Boxes joined by arrows, laid out for you: a flow, a pipeline, a state machine. Give it the
21
8
  * `nodes` and the `edges` between them and it places every box in ranks `direction` (`down` or
@@ -47,9 +34,11 @@ export function FlowDiagram({ label, nodes, edges, direction = "down", active, o
47
34
  * `canvas` ref and the layout `drawn`. Unlike `overlay`, the layer is read by a screen reader and its
48
35
  * children may take the pointer (`pointer-events-auto`), so they can be links. With a layer, the
49
36
  * image is the drawing alone and the scrolling box round it is a group named by `label`. With `fit`,
50
- * a drawing wider than its room is shrunk to the room's width instead of scrolling. Internal.
37
+ * a drawing wider than its room is shrunk to the room's width instead of scrolling. With `uniform`
38
+ * (laid out by `useFlowLayout`'s `uniform`), every box fills its slot: its label wraps to the box's
39
+ * width and its content sits at the bottom. Internal.
51
40
  */
52
- export function FlowView({ label, nodes, edges, active, overlay, layer, canvas, drawn, fit = false, ...rest }) {
41
+ export function FlowView({ label, nodes, edges, active, overlay, layer, canvas, drawn, fit = false, uniform = false, ...rest }) {
53
42
  const { frame, scale } = useFit(fit ? drawn.width : 0);
54
43
  const known = new Set(nodes.map((n) => n.id));
55
44
  const shown = edges.flatMap((edge, index) => known.has(edge.from) && known.has(edge.to) ? [{ edge, index }] : []);
@@ -57,7 +46,7 @@ export function FlowView({ label, nodes, edges, active, overlay, layer, canvas,
57
46
  role: "img",
58
47
  "aria-label": `${label}: ${count(known.size, "box", "boxes")} and ${count(shown.length, "arrow", "arrows")}`,
59
48
  };
60
- const drawing = _jsx(FlowCanvas, { drawn: drawn, nodes: nodes, edges: shown, active: active });
49
+ const drawing = (_jsx(FlowCanvas, { drawn: drawn, nodes: nodes, edges: shown, active: active, uniform: uniform }));
61
50
  return (_jsxs("div", { ...rest, className: "flex min-w-0 flex-col", children: [_jsx("div", { ...(layer ? { role: "group", "aria-label": label } : image),
62
51
  // A diagram wider than its room scrolls, so it takes the focus for the arrow keys.
63
52
  tabIndex: 0, ref: frame, className: "max-w-full overflow-auto rounded-lg outline-offset-2 focus-visible:outline-2 focus-visible:outline-violet-600", children: _jsx("div", { className: "mx-auto", style: { width: drawn.width * scale, height: drawn.height * scale }, children: _jsxs("div", { ref: canvas, className: "relative origin-top-left", style: {
@@ -69,7 +58,7 @@ export function FlowView({ label, nodes, edges, active, overlay, layer, canvas,
69
58
  /** `1 box`, `3 boxes`. */
70
59
  const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
71
60
  /** The drawing itself: the group frames, the arrows, their labels and the boxes. */
72
- function FlowCanvas({ drawn, nodes, edges, active, }) {
61
+ function FlowCanvas({ drawn, nodes, edges, active, uniform, }) {
73
62
  const marker = `flow-arrow-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
74
63
  const byId = new Map(nodes.map((n) => [n.id, n]));
75
64
  const paths = new Map(drawn.edges.map((e) => [e.index, e]));
@@ -78,18 +67,13 @@ function FlowCanvas({ drawn, nodes, edges, active, }) {
78
67
  return edge.label && at ? (_jsx("span", { "data-measure": edgeKey(index), className: "absolute -translate-x-1/2 -translate-y-1/2 whitespace-nowrap rounded bg-white px-1 text-xs text-slate-600", style: { left: at.x, top: at.y }, children: edge.label }, index)) : null;
79
68
  }), drawn.nodes.map((b) => {
80
69
  const node = byId.get(b.id);
81
- return node ? (_jsx(FlowBoxView, { box: b, node: node, active: active === b.id }, b.id)) : null;
70
+ return node ? (_jsx(FlowBoxView, { box: b, node: node, active: active === b.id, uniform: uniform }, b.id)) : null;
82
71
  })] }));
83
72
  }
84
73
  /** Every arrow as an SVG path, with its arrowhead. */
85
74
  function FlowArrows({ drawn, marker }) {
86
75
  return (_jsxs("svg", { width: drawn.width, height: drawn.height, className: "absolute inset-0 overflow-visible text-slate-400", children: [_jsx("defs", { children: _jsx("marker", { id: marker, viewBox: "0 0 10 10", refX: "9", refY: "5", markerWidth: "8", markerHeight: "8", markerUnits: "userSpaceOnUse", orient: "auto-start-reverse", children: _jsx("path", { d: "M0,0L10,5L0,10z", fill: "currentColor" }) }) }), drawn.edges.map((e) => (_jsx("path", { d: e.path, fill: "none", stroke: "currentColor", strokeWidth: 1.5, markerEnd: `url(#${marker})` }, e.index)))] }));
87
76
  }
88
- /** One box, placed: its label and content, sized by them, centred in the slot the layout gave it. */
89
- function FlowBoxView({ box, node, active, }) {
90
- const tone = node.tone ?? "neutral";
91
- return (_jsx("div", { className: "absolute flex items-center justify-center", style: { left: box.x, top: box.y, width: box.width, height: box.height }, children: _jsxs("div", { "data-measure": nodeKey(box.id), className: cx("w-max max-w-72 shrink-0 rounded-lg border px-3 py-2 text-sm", NODE_TONE[tone], NODE_INK[tone], active && "outline-2 outline-offset-2 outline-violet-600"), children: [_jsx("div", { className: "font-medium", children: node.label }), node.content != null && _jsx("div", { className: "mt-2", children: node.content })] }) }));
92
- }
93
77
  /** The diagram as text for a screen reader: each box, its content, and the arrows out of it. */
94
78
  function FlowList({ label, nodes, edges, active, }) {
95
79
  const names = new Map(nodes.map((n) => [n.id, n.label]));
@@ -40,10 +40,11 @@ export type StateMachineItem = {
40
40
  * A state machine, drawn, with the things moving through it: each state a box, each transition an
41
41
  * arrow named by its event, laid out like a `FlowDiagram`. A state's `kind` sets its look and a tag
42
42
  * that says it: `human` takes the warn tone, `failed` the danger tone, `terminal` is muted, and
43
- * `initial` is tagged start. Its `owner` is a tag beside it.
43
+ * `initial` is tagged start. Its `owner` is a tag beside it. Every box is one size, the label wrapping
44
+ * inside it, and the boxes sit close.
44
45
  *
45
46
  * Each of the `items` is a coloured dot with its short `id`, in the box of its `state`, which
46
- * counts them; a box shows up to nine and a `+N` for the rest. The dot's name and tooltip is its
47
+ * counts them; a box shows up to six and a `+N` for the rest. The dot's name and tooltip is its
47
48
  * full `label`, and with an `href` it is a link. An item whose state is not in the machine goes in
48
49
  * a box of its own, "Not in any state", so nothing is dropped. When an item's state changes, its
49
50
  * dot runs along the arrow between the two (straight across when there is none); with reduced
@@ -3,7 +3,7 @@ import { useState } from "react";
3
3
  import { FlowView } from "./FlowDiagram.js";
4
4
  import { Pill } from "./Pill.js";
5
5
  import { Bone, BusyLabel, busy, useLoading } from "./skeleton.js";
6
- import { boxContentSize, dotArea, dotLayer, placeOf, slotsFor, UNPLACED, useMoves, } from "./stateMachineDots.js";
6
+ import { boxContentSize, MACHINE_SPACING, dotArea, dotLayer, placeOf, slotsFor, UNPLACED, useMoves, } from "./stateMachineDots.js";
7
7
  import { useFlowLayout } from "./useFlowLayout.js";
8
8
  /** Each kind's box tone, and the tag that says it in words. */
9
9
  const KIND_TONE = {
@@ -88,10 +88,11 @@ function useOpenBoxes(opened) {
88
88
  * A state machine, drawn, with the things moving through it: each state a box, each transition an
89
89
  * arrow named by its event, laid out like a `FlowDiagram`. A state's `kind` sets its look and a tag
90
90
  * that says it: `human` takes the warn tone, `failed` the danger tone, `terminal` is muted, and
91
- * `initial` is tagged start. Its `owner` is a tag beside it.
91
+ * `initial` is tagged start. Its `owner` is a tag beside it. Every box is one size, the label wrapping
92
+ * inside it, and the boxes sit close.
92
93
  *
93
94
  * Each of the `items` is a coloured dot with its short `id`, in the box of its `state`, which
94
- * counts them; a box shows up to nine and a `+N` for the rest. The dot's name and tooltip is its
95
+ * counts them; a box shows up to six and a `+N` for the rest. The dot's name and tooltip is its
95
96
  * full `label`, and with an `href` it is a link. An item whose state is not in the machine goes in
96
97
  * a box of its own, "Not in any state", so nothing is dropped. When an item's state changes, its
97
98
  * dot runs along the arrow between the two (straight across when there is none); with reduced
@@ -107,10 +108,13 @@ export function StateMachine({ label, states, transitions, items = [], active, l
107
108
  const inBox = itemsByBox(items, known);
108
109
  const nodes = boxesFor(states, inBox, open);
109
110
  const edges = transitions.map((t) => ({ from: t.from, to: t.to, label: t.event }));
110
- const { canvas, drawn } = useFlowLayout(nodes, edges, "down");
111
+ const { canvas, drawn } = useFlowLayout(nodes, edges, "down", {
112
+ uniform: true,
113
+ spacing: MACHINE_SPACING,
114
+ });
111
115
  if (waiting && states.length === 0) {
112
116
  return (_jsxs("figure", { ...rest, ...busy(owner, waiting), "aria-label": label, className: "flex flex-col", children: [_jsx(Bone, { shape: "block h-48 rounded-lg" }), _jsx(BusyLabel, { owner: owner, loading: waiting, label: loadingLabel })] }));
113
117
  }
114
118
  const names = new Map(nodes.map((n) => [n.id, n.label]));
115
- return (_jsx(FlowView, { ...rest, label: label, nodes: nodes, edges: edges, active: active, layer: (layout) => dotLayer(layout, { inBox, names, open, toggle, moves, done }), canvas: canvas, drawn: drawn, fit: true }));
119
+ return (_jsx(FlowView, { ...rest, label: label, nodes: nodes, edges: edges, active: active, layer: (layout) => dotLayer(layout, { inBox, names, open, toggle, moves, done }), canvas: canvas, drawn: drawn, fit: true, uniform: true }));
116
120
  }
@@ -0,0 +1,15 @@
1
+ /** One box of a `FlowDiagram` or a `StateMachine`, placed. Internal. */
2
+ import type { ReactElement } from "react";
3
+ import type { ViewNode } from "./FlowDiagram.js";
4
+ import type { FlowNodeBox } from "./flowLayout.js";
5
+ /**
6
+ * One box, placed: its label and content, sized by them, centred in the slot the layout gave it.
7
+ * A `uniform` box fills its slot instead, its label measured alone and wrapped to the box's width,
8
+ * its content at the bottom.
9
+ */
10
+ export declare function FlowBoxView({ box, node, active, uniform, }: {
11
+ box: FlowNodeBox;
12
+ node: ViewNode;
13
+ active: boolean;
14
+ uniform: boolean;
15
+ }): ReactElement;
@@ -0,0 +1,25 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { TONE_SURFACE, TONE_TEXT } from "./Callout.js";
3
+ import { cx } from "./cx.js";
4
+ import { contentKey, labelKey, nodeKey } from "./useFlowLayout.js";
5
+ /** A box's frame by tone: the Callout's soft surfaces, a white box for `neutral`, a grey one for `muted`. */
6
+ const NODE_TONE = {
7
+ ...TONE_SURFACE,
8
+ neutral: "border-slate-300 bg-white",
9
+ muted: "border-slate-200 bg-slate-50",
10
+ };
11
+ /** A box's ink by tone; `neutral` is the primary ink, `muted` the quiet one. */
12
+ const NODE_INK = {
13
+ ...TONE_TEXT,
14
+ neutral: "text-slate-900",
15
+ muted: "text-slate-500",
16
+ };
17
+ /**
18
+ * One box, placed: its label and content, sized by them, centred in the slot the layout gave it.
19
+ * A `uniform` box fills its slot instead, its label measured alone and wrapped to the box's width,
20
+ * its content at the bottom.
21
+ */
22
+ export function FlowBoxView({ box, node, active, uniform, }) {
23
+ const tone = node.tone ?? "neutral";
24
+ return (_jsx("div", { className: "absolute flex items-center justify-center", style: { left: box.x, top: box.y, width: box.width, height: box.height }, children: _jsxs("div", { ...(uniform ? {} : { "data-measure": nodeKey(box.id) }), className: cx("rounded-lg border px-3 py-2 text-sm", uniform ? "flex size-full flex-col" : "w-max max-w-72 shrink-0", NODE_TONE[tone], NODE_INK[tone], active && "outline-2 outline-offset-2 outline-violet-600"), children: [_jsx("div", { ...(uniform ? { "data-measure": labelKey(box.id) } : {}), className: cx("font-medium", uniform && "break-words"), children: node.label }), node.content != null && (_jsx("div", { ...(uniform ? { "data-measure": contentKey(box.id) } : {}), className: uniform ? "mt-auto pt-2" : "mt-2", children: node.content }))] }) }));
25
+ }
@@ -17,9 +17,10 @@ export type FlowNodeBox = FlowBox & {
17
17
  id: string;
18
18
  };
19
19
  /**
20
- * An arrow as laid out: the `from` and `to` ids, its place in `edges` (`index`), the points dagre
21
- * routed it through, the SVG path drawn through them (it ends on the target's edge, at the
22
- * arrowhead's tip) and its label's centre when it has one.
20
+ * An arrow as laid out: the `from` and `to` ids, its place in `edges` (`index`), the corners of its
21
+ * square route (it leaves the source's side facing the way it goes, turns only between ranks, and
22
+ * ends on the target's edge, at the arrowhead's tip), the SVG path through them and its label's
23
+ * centre when it has one.
23
24
  */
24
25
  export type FlowEdgePath = {
25
26
  from: string;
@@ -60,9 +61,14 @@ export type LayoutEdge = {
60
61
  };
61
62
  /** `down` reads from the top, `right` from the start edge. */
62
63
  export type FlowDirection = "down" | "right";
64
+ /** The gaps dagre keeps: between boxes in a rank, between ranks, and between arrows in a rank. */
65
+ export type FlowSpacing = {
66
+ node: number;
67
+ rank: number;
68
+ edge: number;
69
+ };
63
70
  /**
64
71
  * Lays the nodes and arrows out with dagre. An arrow whose end is not a node is left out, so a
65
72
  * typo draws no stray box. Pure: the same input gives the same layout.
66
73
  */
67
- export declare function layoutFlow(nodes: readonly LayoutNode[], edges: readonly LayoutEdge[], direction: FlowDirection): FlowLayout;
68
- export declare function stepPath(points: readonly FlowPoint[], direction: FlowDirection, lane?: number): string;
74
+ export declare function layoutFlow(nodes: readonly LayoutNode[], edges: readonly LayoutEdge[], direction: FlowDirection, spacing?: FlowSpacing): FlowLayout;
@@ -1,14 +1,17 @@
1
1
  /**
2
- * The layout behind `FlowDiagram`: dagre places the boxes and routes the arrows, then this file
3
- * turns its output into what the component draws. Internal: only the geometry types are exported
2
+ * The layout behind `FlowDiagram`: dagre places the boxes and gives each arrow a route,
3
+ * `flowRoute` draws the arrows round the boxes along it, and this file turns the result into what
4
+ * the component draws. Internal: only the geometry types are exported
4
5
  * from the package, for `FlowDiagram`'s `overlay`.
5
6
  */
6
7
  import { Graph, layout } from "@dagrejs/dagre";
8
+ import { routeEdges, squarePath } from "./flowRoute.js";
7
9
  /** Space round the drawing, between boxes in a rank, and between ranks. */
8
10
  const MARGIN = 16;
9
11
  const NODE_GAP = 32;
10
12
  const RANK_GAP = 48;
11
13
  const EDGE_GAP = 16;
14
+ const LOOSE = { node: NODE_GAP, rank: RANK_GAP, edge: EDGE_GAP };
12
15
  /** A group's dagre id, kept apart from every node id. */
13
16
  const groupKey = (name) => `\u0000group:${name}`;
14
17
  const round = (n) => Math.round(n * 10) / 10;
@@ -16,7 +19,7 @@ const round = (n) => Math.round(n * 10) / 10;
16
19
  * Lays the nodes and arrows out with dagre. An arrow whose end is not a node is left out, so a
17
20
  * typo draws no stray box. Pure: the same input gives the same layout.
18
21
  */
19
- export function layoutFlow(nodes, edges, direction) {
22
+ export function layoutFlow(nodes, edges, direction, spacing = LOOSE) {
20
23
  const groups = [...new Set(nodes.flatMap((n) => (n.group ? [n.group] : [])))];
21
24
  const g = new Graph({
22
25
  multigraph: true,
@@ -24,9 +27,9 @@ export function layoutFlow(nodes, edges, direction) {
24
27
  });
25
28
  g.setGraph({
26
29
  rankdir: direction === "right" ? "LR" : "TB",
27
- nodesep: NODE_GAP,
28
- ranksep: RANK_GAP,
29
- edgesep: EDGE_GAP,
30
+ nodesep: spacing.node,
31
+ ranksep: spacing.rank,
32
+ edgesep: spacing.edge,
30
33
  marginx: MARGIN,
31
34
  marginy: MARGIN,
32
35
  });
@@ -45,61 +48,78 @@ export function layoutFlow(nodes, edges, direction) {
45
48
  g.setEdge(e.from, e.to, e.label ? { width: e.label.width, height: e.label.height, labelpos: "c" } : {}, String(index));
46
49
  }
47
50
  layout(g);
48
- const box = (key) => {
51
+ return routeLayout(g, { ids, groups, kept }, direction === "right");
52
+ }
53
+ /**
54
+ * Routes dagre's laid-out graph round its boxes and labels (`flowRoute`) and reads it back in the
55
+ * diagram's own space, rounded. `across` is true when the diagram is ranked right.
56
+ */
57
+ function routeLayout(g, { ids, groups, kept }, across) {
58
+ /** Turns a point or box into rank-down space, and back: ranked right, x and y swap. */
59
+ const turn = (p) => (across ? { x: p.y, y: p.x } : p);
60
+ const turnBox = (b) => across ? { x: b.y, y: b.x, width: b.height, height: b.width } : b;
61
+ const raw = (key) => {
49
62
  const { x = 0, y = 0, width = 0, height = 0 } = g.node(key);
50
- return {
51
- x: round(x - width / 2),
52
- y: round(y - height / 2),
53
- width: round(width),
54
- height: round(height),
55
- };
63
+ return turnBox({ x: x - width / 2, y: y - height / 2, width, height });
64
+ };
65
+ const routes = kept.map(({ e, index }) => ({
66
+ e,
67
+ index,
68
+ routed: g.edge(e.from, e.to, String(index)),
69
+ }));
70
+ const labelAt = routes.map(({ e, routed }) => e.label && routed.x !== undefined && routed.y !== undefined
71
+ ? turn({ x: routed.x, y: routed.y })
72
+ : null);
73
+ const labels = routes.flatMap(({ e }, i) => {
74
+ const at = labelAt[i];
75
+ if (!e.label || !at)
76
+ return [];
77
+ const size = turnBox({ x: 0, y: 0, width: e.label.width, height: e.label.height });
78
+ return [
79
+ {
80
+ x: at.x - size.width / 2,
81
+ y: at.y - size.height / 2,
82
+ width: size.width,
83
+ height: size.height,
84
+ },
85
+ ];
86
+ });
87
+ const { lines, shift, grow } = routeEdges(new Map([...ids].map((id) => [id, raw(id)])), labels, routes.map(({ e, routed }) => ({
88
+ from: e.from,
89
+ to: e.to,
90
+ points: (routed.points ?? []).map(turn),
91
+ })));
92
+ /** A box from rank-down space, moved past any widened gap, back in the diagram's space. */
93
+ const place = (b) => {
94
+ const top = shift(b.y);
95
+ const bottom = shift(b.y + b.height);
96
+ const out = turnBox({ x: b.x, y: top, width: b.width, height: bottom - top });
97
+ return { x: round(out.x), y: round(out.y), width: round(out.width), height: round(out.height) };
56
98
  };
57
99
  const graph = g.graph();
100
+ const size = turn({ x: graph.width ?? 0, y: graph.height ?? 0 });
101
+ const grown = turn({ x: size.x, y: size.y + grow });
58
102
  return {
59
- width: Math.ceil(graph.width ?? 0),
60
- height: Math.ceil(graph.height ?? 0),
61
- nodes: [...ids].map((id) => ({ id, ...box(id) })),
62
- groups: groups.map((name) => ({ name, ...box(groupKey(name)) })),
63
- edges: kept.map(({ e, index }) => {
64
- const routed = g.edge(e.from, e.to, String(index));
65
- const points = (routed.points ?? []).map((p) => ({ x: round(p.x), y: round(p.y) }));
103
+ width: Math.ceil(grown.x),
104
+ height: Math.ceil(grown.y),
105
+ nodes: [...ids].map((id) => ({ id, ...place(raw(id)) })),
106
+ groups: groups.map((name) => ({ name, ...place(raw(groupKey(name))) })),
107
+ edges: routes.map(({ e, index }, i) => {
108
+ const points = (lines[i] ?? []).map((p) => {
109
+ const out = turn(p);
110
+ return { x: round(out.x), y: round(out.y) };
111
+ });
112
+ const at = labelAt[i];
66
113
  return {
67
114
  from: e.from,
68
115
  to: e.to,
69
116
  index,
70
117
  points,
71
- path: stepPath(points, direction, LANES[index % LANES.length]),
72
- labelAt: e.label && routed.x !== undefined && routed.y !== undefined
73
- ? { x: round(routed.x), y: round(routed.y) }
118
+ path: squarePath(points),
119
+ labelAt: at
120
+ ? (({ x, y }) => ({ x: round(x), y: round(y) }))(turn({ x: at.x, y: shift(at.y) }))
74
121
  : null,
75
122
  };
76
123
  }),
77
124
  };
78
125
  }
79
- /**
80
- * A square path through dagre's route points: each step leaves along the rank `direction`, turns
81
- * once at `lane` of the way across (0.5 is halfway), and arrives along it again, so every arrow is
82
- * made of straight runs at right angles and ends exactly on the last point, where its arrowhead
83
- * sits. Arrows between the same two ranks take different lanes, so their cross runs do not overlap.
84
- */
85
- /** Where each arrow turns between two ranks, by its index: spread so parallel runs stay apart. */
86
- const LANES = [0.5, 0.3, 0.7, 0.4, 0.6];
87
- export function stepPath(points, direction, lane = 0.5) {
88
- const [first, ...rest] = points;
89
- if (!first)
90
- return "";
91
- let d = `M${first.x},${first.y}`;
92
- let from = first;
93
- for (const to of rest) {
94
- if (direction === "right") {
95
- const mid = round(from.x + (to.x - from.x) * lane);
96
- d += `H${mid}V${to.y}H${to.x}`;
97
- }
98
- else {
99
- const mid = round(from.y + (to.y - from.y) * lane);
100
- d += `V${mid}H${to.x}V${to.y}`;
101
- }
102
- from = to;
103
- }
104
- return d;
105
- }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * How `FlowDiagram`'s arrows are drawn round its boxes, after dagre has placed them. Internal.
3
+ *
4
+ * dagre ranks the boxes and gives each arrow a route: a point on the source, one point in every
5
+ * rank it passes (each clear of the boxes in that rank) and a point on the target. Drawn as square
6
+ * steps that turn halfway between two points, an arrow can turn inside a rank of tall boxes and run
7
+ * through one, and an arrow that leaves a box's side runs along its border. So this routes every
8
+ * arrow again, in the rank direction:
9
+ *
10
+ * - it leaves its source through the side facing its next point and enters its target through the
11
+ * side facing its last one, at ports spread along that side, so no two arrows share a port and
12
+ * none runs along a border;
13
+ * - it runs along the rank direction through each of dagre's points, and turns only in a gap
14
+ * between ranks, where no box and no arrow label is;
15
+ * - the turns in one gap are spread over tracks, so two runs across the same gap never lie on one
16
+ * line, and a gap too narrow for its tracks is widened, moving everything past it along.
17
+ *
18
+ * Every function here works in rank-down space (ranks stacked along y); a diagram ranked right is
19
+ * turned into it and back.
20
+ */
21
+ import type { FlowBox as Rect, FlowPoint as Point } from "./flowLayout.js";
22
+ /** One arrow to route: its ends, and dagre's points from the source to the target. */
23
+ type RouteEdge = {
24
+ from: string;
25
+ to: string;
26
+ points: readonly Point[];
27
+ };
28
+ /** The routed diagram: every arrow as a square path's corners, and how to move a y past widened gaps. */
29
+ type Routed = {
30
+ lines: Point[][];
31
+ shift: (y: number) => number;
32
+ grow: number;
33
+ };
34
+ /**
35
+ * Routes every arrow round the boxes and labels (rank-down space): see the file's comment. The
36
+ * lines come back in `edges`' order, in the space after the gaps are widened; `shift` moves a y
37
+ * from before into it, and `grow` is how much taller the diagram became.
38
+ */
39
+ export declare function routeEdges(boxes: ReadonlyMap<string, Rect>, labels: readonly Rect[], edges: readonly RouteEdge[]): Routed;
40
+ /** The SVG path through square corners: a move, then one straight run to each next corner. */
41
+ export declare function squarePath(points: readonly Point[]): string;
42
+ export {};
@@ -0,0 +1,238 @@
1
+ /**
2
+ * How `FlowDiagram`'s arrows are drawn round its boxes, after dagre has placed them. Internal.
3
+ *
4
+ * dagre ranks the boxes and gives each arrow a route: a point on the source, one point in every
5
+ * rank it passes (each clear of the boxes in that rank) and a point on the target. Drawn as square
6
+ * steps that turn halfway between two points, an arrow can turn inside a rank of tall boxes and run
7
+ * through one, and an arrow that leaves a box's side runs along its border. So this routes every
8
+ * arrow again, in the rank direction:
9
+ *
10
+ * - it leaves its source through the side facing its next point and enters its target through the
11
+ * side facing its last one, at ports spread along that side, so no two arrows share a port and
12
+ * none runs along a border;
13
+ * - it runs along the rank direction through each of dagre's points, and turns only in a gap
14
+ * between ranks, where no box and no arrow label is;
15
+ * - the turns in one gap are spread over tracks, so two runs across the same gap never lie on one
16
+ * line, and a gap too narrow for its tracks is widened, moving everything past it along.
17
+ *
18
+ * Every function here works in rank-down space (ranks stacked along y); a diagram ranked right is
19
+ * turned into it and back.
20
+ */
21
+ /** The space between two runs across one gap, and between a run and the gap's edges. */
22
+ const TRACK = 8;
23
+ /** How far a port keeps from a box's corner, and the least space between two ports. */
24
+ const PORT_INSET = 12;
25
+ /** How far a self loop reaches past its box. */
26
+ const LOOP_REACH = 16;
27
+ const round = (n) => Math.round(n * 10) / 10;
28
+ /** The y ranges no box or label covers, between the first and the last. */
29
+ function gapsBetween(obstacles) {
30
+ const spans = obstacles
31
+ .map((r) => ({ top: r.y, bottom: r.y + r.height }))
32
+ .toSorted((a, b) => a.top - b.top);
33
+ const gaps = [];
34
+ let reach = Number.NEGATIVE_INFINITY;
35
+ for (const s of spans) {
36
+ if (s.top > reach && reach > Number.NEGATIVE_INFINITY)
37
+ gaps.push({ top: reach, bottom: s.top });
38
+ reach = Math.max(reach, s.bottom);
39
+ }
40
+ return gaps;
41
+ }
42
+ /** Whether a point lies past a box's middle, in the rank direction. */
43
+ const below = (box, p) => p.y > box.y + box.height / 2;
44
+ /**
45
+ * Where each arrow leaves and enters its boxes: on the side facing the next point along it,
46
+ * spread evenly over that side in the order of where the arrows head, so they do not cross there.
47
+ */
48
+ function placePorts(boxes, edges) {
49
+ const ports = [];
50
+ edges.forEach((e, edge) => {
51
+ const first = e.points[1] ?? e.points[0];
52
+ const last = e.points.at(-2) ?? e.points.at(-1);
53
+ const from = boxes.get(e.from);
54
+ const to = boxes.get(e.to);
55
+ if (e.from === e.to || !first || !last || !from || !to)
56
+ return;
57
+ ports.push({
58
+ edge,
59
+ end: "from",
60
+ box: e.from,
61
+ side: below(from, first) ? "bottom" : "top",
62
+ toward: first.x,
63
+ }, { edge, end: "to", box: e.to, side: below(to, last) ? "bottom" : "top", toward: last.x });
64
+ });
65
+ const ends = edges.map(() => []);
66
+ const bySide = new Map();
67
+ for (const p of ports) {
68
+ const key = `${p.box}\u0000${p.side}`;
69
+ bySide.set(key, [...(bySide.get(key) ?? []), p]);
70
+ }
71
+ for (const group of bySide.values()) {
72
+ const [head] = group;
73
+ const box = head && boxes.get(head.box);
74
+ if (!head || !box)
75
+ continue;
76
+ const sorted = group.toSorted((a, b) => a.toward - b.toward || a.edge - b.edge);
77
+ const room = Math.max(0, box.width - 2 * PORT_INSET);
78
+ const step = sorted.length > 1 ? room / (sorted.length - 1) : 0;
79
+ sorted.forEach((p, i) => {
80
+ const x = sorted.length === 1
81
+ ? Math.min(Math.max(p.toward, box.x + PORT_INSET), box.x + box.width - PORT_INSET)
82
+ : box.x + PORT_INSET + i * step;
83
+ const y = p.side === "top" ? box.y : box.y + box.height;
84
+ const at = ends[p.edge];
85
+ if (at)
86
+ at[p.end === "from" ? 0 : 1] = { x: round(x), y };
87
+ });
88
+ }
89
+ return ends;
90
+ }
91
+ /** Gives each run in a gap the lowest track whose runs it does not overlap, and counts the tracks. */
92
+ function assignTracks(runs, gaps) {
93
+ const counts = Array.from({ length: gaps }, () => 0);
94
+ const ends = Array.from({ length: gaps }, () => []);
95
+ for (const run of runs.toSorted((a, b) => a.lo - b.lo)) {
96
+ const lanes = ends[run.gap] ?? [];
97
+ let track = lanes.findIndex((end) => end + TRACK <= run.lo);
98
+ if (track === -1)
99
+ track = lanes.length;
100
+ lanes[track] = run.hi;
101
+ ends[run.gap] = lanes;
102
+ run.track = track;
103
+ counts[run.gap] = Math.max(counts[run.gap] ?? 0, track + 1);
104
+ }
105
+ return counts;
106
+ }
107
+ /** The corners of a square loop out of a box's far side and back. */
108
+ function loop(box, points) {
109
+ const ys = points.map((p) => p.y);
110
+ const reach = Math.max(box.x + box.width + LOOP_REACH, ...points.map((p) => p.x));
111
+ const cy = box.y + box.height / 2;
112
+ const half = Math.min(box.height / 2 - 4, Math.max(8, (Math.max(...ys) - Math.min(...ys)) / 2));
113
+ const side = box.x + box.width;
114
+ return [
115
+ { x: side, y: cy - half },
116
+ { x: reach, y: cy - half },
117
+ { x: reach, y: cy + half },
118
+ { x: side, y: cy + half },
119
+ ];
120
+ }
121
+ /** Whether three corners lie on one straight line across or along. */
122
+ const inLine = (a, b, c) => (a.x === b.x && b.x === c.x) || (a.y === b.y && b.y === c.y);
123
+ /** Drops a corner that does not turn: a repeat, or one in line with its neighbours. */
124
+ function tidy(points) {
125
+ const out = [];
126
+ for (const p of points) {
127
+ const last = out.at(-1);
128
+ const before = out.at(-2);
129
+ if (last && last.x === p.x && last.y === p.y)
130
+ continue;
131
+ if (last && before && inLine(before, last, p))
132
+ out[out.length - 1] = p;
133
+ else
134
+ out.push(p);
135
+ }
136
+ return out;
137
+ }
138
+ /** The gap a step between two points turns in: the one it overlaps most, if any. */
139
+ function gapFor(gaps, a, b) {
140
+ const lo = Math.min(a.y, b.y);
141
+ const hi = Math.max(a.y, b.y);
142
+ return gaps
143
+ .map((g, index) => ({ index, size: Math.min(g.bottom, hi) - Math.max(g.top, lo) }))
144
+ .filter((g) => g.size > 0)
145
+ .toSorted((p, q) => q.size - p.size)[0]?.index;
146
+ }
147
+ /**
148
+ * An arrow's draft corners through `via`: a step that moves across turns on a run in the gap it
149
+ * overlaps most (added to `runs`), or halfway along when no gap lies between its points.
150
+ */
151
+ function draftSteps(via, gaps, runs) {
152
+ const [start] = via;
153
+ const out = start ? [start] : [];
154
+ for (let k = 1; k < via.length; k++) {
155
+ const a = via[k - 1];
156
+ const b = via[k];
157
+ if (!a || !b)
158
+ continue;
159
+ const gap = a.x === b.x ? undefined : gapFor(gaps, a, b);
160
+ if (a.x === b.x)
161
+ out.push(b);
162
+ else if (gap === undefined)
163
+ out.push({ x: a.x, y: (a.y + b.y) / 2 }, { x: b.x, y: (a.y + b.y) / 2 }, b);
164
+ else {
165
+ runs.push({ gap, lo: Math.min(a.x, b.x), hi: Math.max(a.x, b.x), track: 0 });
166
+ out.push({ run: runs.length - 1, a, b }, b);
167
+ }
168
+ }
169
+ return out;
170
+ }
171
+ /**
172
+ * Routes every arrow round the boxes and labels (rank-down space): see the file's comment. The
173
+ * lines come back in `edges`' order, in the space after the gaps are widened; `shift` moves a y
174
+ * from before into it, and `grow` is how much taller the diagram became.
175
+ */
176
+ export function routeEdges(boxes, labels, edges) {
177
+ const gaps = gapsBetween([...boxes.values(), ...labels]);
178
+ const ends = placePorts(boxes, edges);
179
+ const runs = [];
180
+ /**
181
+ * Whether one of dagre's points lies beside a box or a label rather than in a gap. A point in a
182
+ * gap (a group's border rank) has nothing to clear, and passing through it would make the arrow
183
+ * turn on a track elsewhere in that gap and double back.
184
+ */
185
+ const inRank = (p) => !gaps.some((g) => p.y > g.top && p.y < g.bottom);
186
+ /** Each arrow's corners, with a run's index in place of the y it turns at. */
187
+ const drafts = edges.map((e, i) => {
188
+ const box = boxes.get(e.from);
189
+ if (e.from === e.to)
190
+ return box ? loop(box, e.points) : [];
191
+ const [start, end] = ends[i] ?? [];
192
+ if (!start || !end)
193
+ return [...e.points];
194
+ return draftSteps([start, ...e.points.slice(1, -1).filter(inRank), end], gaps, runs);
195
+ });
196
+ const tracks = assignTracks(runs, gaps.length);
197
+ const widen = gaps.map((g, i) => Math.max(0, ((tracks[i] ?? 0) + 1) * TRACK - (g.bottom - g.top)));
198
+ const shift = (y) => y + gaps.reduce((sum, g, i) => sum + (y > g.top + 0.01 ? (widen[i] ?? 0) : 0), 0);
199
+ const trackY = (run) => {
200
+ const g = gaps[run.gap];
201
+ if (!g)
202
+ return 0;
203
+ const top = shift(g.top);
204
+ const height = g.bottom - g.top + (widen[run.gap] ?? 0);
205
+ return round(top + ((run.track + 1) * height) / ((tracks[run.gap] ?? 0) + 1));
206
+ };
207
+ /** A draft corner's points: a turn becomes its two corners on its run's track. */
208
+ const corners = (c) => {
209
+ if (!("run" in c))
210
+ return [{ x: c.x, y: round(shift(c.y)) }];
211
+ const run = runs[c.run];
212
+ if (!run)
213
+ return [];
214
+ const y = trackY(run);
215
+ return [
216
+ { x: c.a.x, y },
217
+ { x: c.b.x, y },
218
+ ];
219
+ };
220
+ const lines = drafts.map((draft) => tidy(draft.flatMap(corners)));
221
+ return { lines, shift, grow: widen.reduce((a, b) => a + b, 0) };
222
+ }
223
+ /** The SVG path through square corners: a move, then one straight run to each next corner. */
224
+ export function squarePath(points) {
225
+ const [first, ...rest] = points;
226
+ if (!first)
227
+ return "";
228
+ let d = `M${first.x},${first.y}`;
229
+ let at = first;
230
+ for (const p of rest) {
231
+ if (p.x !== at.x && p.y !== at.y)
232
+ d += `V${p.y}H${p.x}`;
233
+ else
234
+ d += p.x === at.x ? `V${p.y}` : `H${p.x}`;
235
+ at = p;
236
+ }
237
+ return d;
238
+ }
@@ -1,5 +1,5 @@
1
1
  import { type ReactElement } from "react";
2
- import type { FlowLayout, FlowNodeBox } from "./flowLayout.js";
2
+ import type { FlowLayout, FlowNodeBox, FlowSpacing } from "./flowLayout.js";
3
3
  import type { StateMachineItem } from "./StateMachine.js";
4
4
  /**
5
5
  * The box items whose `state` is no state of the machine go in. Printable, since it reaches the DOM
@@ -32,19 +32,24 @@ export declare function useMoves(items: readonly StateMachineItem[], known: Read
32
32
  /** How many slots a box with `count` items draws: all of them, or the first few and a `+N`; one more for "fewer" when open. */
33
33
  export declare function slotsFor(count: number, open: boolean): number;
34
34
  /**
35
- * The rows a box reserves for its dots, whatever its count: the nine it shows (the `+N` included),
35
+ * The rows a box reserves for its dots, whatever its count: the six it shows (the `+N` included),
36
36
  * or the rows of an open box's full list. A box with few or no items reserves the same rows, so
37
37
  * its size does not depend on how many items it holds.
38
38
  */
39
39
  export declare function rowsFor(slots: number): number;
40
40
  /**
41
41
  * The room a box reserves under its tags for `slots` dots: the full grid's width and `rowsFor`'s
42
- * height, so it is the same at 0, 1, 9 or 12 items (closed) and grows only when a box is opened.
42
+ * height, so it is the same at 0, 1, 6 or 12 items (closed) and grows only when a box is opened.
43
43
  */
44
44
  export declare function dotArea(slots: number): {
45
45
  width: number;
46
46
  height: number;
47
47
  };
48
+ /**
49
+ * A machine's gaps, closer than `FlowDiagram`'s: its boxes are all one size, and every gap between
50
+ * two ranks also holds a rank of arrow labels, so the loose gaps leave wide empty bands.
51
+ */
52
+ export declare const MACHINE_SPACING: FlowSpacing;
48
53
  /** A box's tag row: one small pill's height. */
49
54
  export declare const TAG_ROW = 20;
50
55
  /** The gap between the tag row and the dot area (`mt-1`). */
@@ -14,7 +14,7 @@ export const SLOT_W = 76;
14
14
  export const SLOT_H = 22;
15
15
  export const COLS = 3;
16
16
  /** Up to this many dots show in a box; past it, one fewer and a `+N` that shows the rest. */
17
- const LIMIT = 9;
17
+ const LIMIT = 6;
18
18
  /** From a box's bottom edge to its dots' bottom: its border and its bottom padding. */
19
19
  const BOX_INSET = 9;
20
20
  /** From a slot's left edge to its dot's centre: the chip's inset, its padding and half the dot. */
@@ -84,7 +84,7 @@ export function slotsFor(count, open) {
84
84
  return open ? count + 1 : LIMIT;
85
85
  }
86
86
  /**
87
- * The rows a box reserves for its dots, whatever its count: the nine it shows (the `+N` included),
87
+ * The rows a box reserves for its dots, whatever its count: the six it shows (the `+N` included),
88
88
  * or the rows of an open box's full list. A box with few or no items reserves the same rows, so
89
89
  * its size does not depend on how many items it holds.
90
90
  */
@@ -93,11 +93,16 @@ export function rowsFor(slots) {
93
93
  }
94
94
  /**
95
95
  * The room a box reserves under its tags for `slots` dots: the full grid's width and `rowsFor`'s
96
- * height, so it is the same at 0, 1, 9 or 12 items (closed) and grows only when a box is opened.
96
+ * height, so it is the same at 0, 1, 6 or 12 items (closed) and grows only when a box is opened.
97
97
  */
98
98
  export function dotArea(slots) {
99
99
  return { width: COLS * SLOT_W, height: rowsFor(slots) * SLOT_H };
100
100
  }
101
+ /**
102
+ * A machine's gaps, closer than `FlowDiagram`'s: its boxes are all one size, and every gap between
103
+ * two ranks also holds a rank of arrow labels, so the loose gaps leave wide empty bands.
104
+ */
105
+ export const MACHINE_SPACING = { node: 24, rank: 32, edge: 8 };
101
106
  /** A box's tag row: one small pill's height. */
102
107
  export const TAG_ROW = 20;
103
108
  /** The gap between the tag row and the dot area (`mt-1`). */
@@ -1,6 +1,6 @@
1
1
  import { type RefObject } from "react";
2
2
  import type { FlowEdge, FlowNode } from "./FlowDiagram.js";
3
- import { type FlowDirection, type FlowLayout } from "./flowLayout.js";
3
+ import { type FlowDirection, type FlowLayout, type FlowSpacing } from "./flowLayout.js";
4
4
  type Size = {
5
5
  width: number;
6
6
  height: number;
@@ -16,6 +16,17 @@ export type SizedNode = Pick<FlowNode, "id" | "label" | "group" | "content"> & {
16
16
  export declare function guessNode(node: SizedNode): Size;
17
17
  export declare const nodeKey: (id: string) => string;
18
18
  export declare const edgeKey: (index: number) => string;
19
+ export declare const labelKey: (id: string) => string;
20
+ export declare const contentKey: (id: string) => string;
21
+ /**
22
+ * Every box the same size (`uniform`): as wide as the widest content, its label wrapped to that
23
+ * width, and as tall as the tallest label and the tallest content make a box. A box's label
24
+ * (`labelKey`) and content (`contentKey`, its gap above included) are measured, not the box: their
25
+ * width is fixed, so their height does not depend on the layout, and a box drawn at its slot's size
26
+ * is never read back as its own size. A content measured taller than its `contentSize` (a row of
27
+ * tags that wraps) makes every box taller.
28
+ */
29
+ export declare function uniformSizes(nodes: readonly SizedNode[], measured: Readonly<Record<string, Size>>): Map<string, Size>;
19
30
  /**
20
31
  * How far to shrink a diagram `width` wide so it fits the box `frame` refers to: 1 when it fits
21
32
  * or the room is not known yet (the server render, a test's DOM), else the room over the width.
@@ -29,9 +40,13 @@ export declare function useFit(width: number): {
29
40
  * Lays the diagram out, first at guessed sizes, then at the sizes the browser draws each box and
30
41
  * arrow label at: every render measures them, and lays out again when one's size is not the one
31
42
  * the layout used. A box's size never depends on where it is placed, so this settles after one
32
- * pass; the observer catches a later change (a web font arriving).
43
+ * pass; the observer catches a later change (a web font arriving). `uniform` draws every box at one
44
+ * size (`uniformSizes`), and `spacing` sets dagre's gaps (`layoutFlow`'s default when not given).
33
45
  */
34
- export declare function useFlowLayout(nodes: readonly SizedNode[], edges: readonly FlowEdge[], direction: FlowDirection): {
46
+ export declare function useFlowLayout(nodes: readonly SizedNode[], edges: readonly FlowEdge[], direction: FlowDirection, options?: {
47
+ uniform?: boolean;
48
+ spacing?: FlowSpacing;
49
+ }): {
35
50
  canvas: RefObject<HTMLDivElement | null>;
36
51
  drawn: FlowLayout;
37
52
  };
@@ -17,9 +17,11 @@ const CONTENT_GAP = 8;
17
17
  const EDGE_CHAR = 6.6;
18
18
  const EDGE_PAD = 8;
19
19
  const EDGE_LINE = 16;
20
+ /** How many lines a box's label wraps to at `room` wide, guessed from its characters. */
21
+ const guessLines = (label, room) => Math.max(1, Math.ceil(Math.ceil(label.length * NODE_CHAR) / room));
20
22
  export function guessNode(node) {
21
23
  const text = Math.ceil(node.label.length * NODE_CHAR);
22
- const lines = Math.max(1, Math.ceil(text / (NODE_MAX - NODE_PAD_X)));
24
+ const lines = guessLines(node.label, NODE_MAX - NODE_PAD_X);
23
25
  const content = node.contentSize ?? { width: 0, height: CONTENT_GUESS - CONTENT_GAP };
24
26
  return {
25
27
  width: Math.min(NODE_MAX, Math.max(text, content.width) + NODE_PAD_X),
@@ -32,6 +34,30 @@ const guessLabel = (label) => ({
32
34
  });
33
35
  export const nodeKey = (id) => `n:${id}`;
34
36
  export const edgeKey = (index) => `e:${index}`;
37
+ export const labelKey = (id) => `l:${id}`;
38
+ export const contentKey = (id) => `c:${id}`;
39
+ /**
40
+ * Every box the same size (`uniform`): as wide as the widest content, its label wrapped to that
41
+ * width, and as tall as the tallest label and the tallest content make a box. A box's label
42
+ * (`labelKey`) and content (`contentKey`, its gap above included) are measured, not the box: their
43
+ * width is fixed, so their height does not depend on the layout, and a box drawn at its slot's size
44
+ * is never read back as its own size. A content measured taller than its `contentSize` (a row of
45
+ * tags that wraps) makes every box taller.
46
+ */
47
+ export function uniformSizes(nodes, measured) {
48
+ const room = Math.max(0, ...nodes.map((n) => n.contentSize?.width ?? 0));
49
+ const tallest = Math.max(NODE_LINE, ...nodes.map((n) => measured[labelKey(n.id)]?.height ?? guessLines(n.label, room) * NODE_LINE));
50
+ const content = Math.max(0, ...nodes.map((n) => n.content == null
51
+ ? 0
52
+ : Math.max(CONTENT_GAP + (n.contentSize?.height ?? 0), measured[contentKey(n.id)]?.height ?? 0)));
53
+ return new Map(nodes.map((n) => [
54
+ n.id,
55
+ {
56
+ width: room + NODE_PAD_X,
57
+ height: tallest + NODE_PAD_Y + (n.content == null ? 0 : content),
58
+ },
59
+ ]));
60
+ }
35
61
  /**
36
62
  * Reads the drawn size of every box and arrow label under `root`, keyed by `data-measure`, in the
37
63
  * diagram's own space: a canvas scaled to fit (`useFit`) is drawn smaller, so its sizes are read
@@ -83,25 +109,28 @@ const sameSizes = (a, b) => {
83
109
  * Lays the diagram out, first at guessed sizes, then at the sizes the browser draws each box and
84
110
  * arrow label at: every render measures them, and lays out again when one's size is not the one
85
111
  * the layout used. A box's size never depends on where it is placed, so this settles after one
86
- * pass; the observer catches a later change (a web font arriving).
112
+ * pass; the observer catches a later change (a web font arriving). `uniform` draws every box at one
113
+ * size (`uniformSizes`), and `spacing` sets dagre's gaps (`layoutFlow`'s default when not given).
87
114
  */
88
- export function useFlowLayout(nodes, edges, direction) {
115
+ export function useFlowLayout(nodes, edges, direction, options = {}) {
89
116
  const canvas = useRef(null);
90
117
  const [measured, setMeasured] = useState({});
118
+ const uniform = options.uniform ? uniformSizes(nodes, measured) : undefined;
91
119
  const layoutNodes = nodes.map((n) => ({
92
120
  id: n.id,
93
121
  group: n.group,
94
- ...(measured[nodeKey(n.id)] ?? guessNode(n)),
122
+ ...(uniform?.get(n.id) ?? measured[nodeKey(n.id)] ?? guessNode(n)),
95
123
  }));
96
124
  const layoutEdges = edges.map((e, index) => ({
97
125
  from: e.from,
98
126
  to: e.to,
99
127
  label: e.label ? (measured[edgeKey(index)] ?? guessLabel(e.label)) : undefined,
100
128
  }));
101
- const key = JSON.stringify([direction, layoutNodes, layoutEdges]);
129
+ const key = JSON.stringify([direction, options.spacing, layoutNodes, layoutEdges]);
102
130
  // The key holds every input the layout reads, so the layout reruns only when one changes.
131
+ const drawn = useMemo(() => layoutFlow(layoutNodes, layoutEdges, direction, options.spacing),
103
132
  // oxlint-disable-next-line react-hooks/exhaustive-deps -- keyed on the serialised input above
104
- const drawn = useMemo(() => layoutFlow(layoutNodes, layoutEdges, direction), [key]);
133
+ [key]);
105
134
  useLayoutEffect(() => {
106
135
  const root = canvas.current;
107
136
  if (!root)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slashsuite/ui-react",
3
- "version": "0.13.1",
3
+ "version": "0.13.3",
4
4
  "description": "UISlash React components: primitives, typography roles and a safe Markdown renderer, written against Tailwind v4 utilities. Pair with a theme from @slashsuite/themes.",
5
5
  "keywords": [
6
6
  "components",