@whity/ui 0.5.0 → 1.0.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.
Files changed (205) hide show
  1. package/README.md +107 -107
  2. package/package.json +221 -192
  3. package/src/access-denied.stories.tsx +179 -179
  4. package/src/access-denied.tsx +305 -305
  5. package/src/action-proposal.tsx +338 -302
  6. package/src/actor-chip.tsx +71 -71
  7. package/src/agent-activity.tsx +163 -163
  8. package/src/agent-collaboration.stories.tsx +156 -156
  9. package/src/agent-run-status.tsx +196 -196
  10. package/src/alert-dialog.stories.tsx +45 -45
  11. package/src/alert-dialog.tsx +147 -147
  12. package/src/alert.stories.tsx +91 -91
  13. package/src/alert.tsx +89 -89
  14. package/src/app-sidebar.stories.tsx +195 -195
  15. package/src/app-sidebar.tsx +604 -500
  16. package/src/approval-queue.tsx +109 -108
  17. package/src/audience-group-picker.stories.tsx +198 -198
  18. package/src/audience-group-picker.tsx +362 -362
  19. package/src/audience-people-picker.stories.tsx +102 -102
  20. package/src/audience-people-picker.tsx +279 -279
  21. package/src/avatar-pattern.ts +138 -0
  22. package/src/avatar.tsx +125 -83
  23. package/src/badge.stories.tsx +105 -105
  24. package/src/badge.tsx +68 -68
  25. package/src/beta-warning.stories.tsx +79 -79
  26. package/src/beta-warning.tsx +189 -189
  27. package/src/bilingual-input.stories.tsx +82 -82
  28. package/src/bilingual-input.tsx +188 -183
  29. package/src/board.tsx +216 -0
  30. package/src/breadcrumb.stories.tsx +51 -51
  31. package/src/breadcrumb.tsx +90 -90
  32. package/src/built-on-whity.tsx +52 -0
  33. package/src/button.stories.tsx +87 -87
  34. package/src/button.tsx +123 -118
  35. package/src/card.stories.tsx +423 -423
  36. package/src/card.tsx +180 -180
  37. package/src/chart.stories.tsx +66 -66
  38. package/src/chart.tsx +228 -228
  39. package/src/checkbox.stories.tsx +62 -62
  40. package/src/checkbox.tsx +54 -54
  41. package/src/collapsible.stories.tsx +48 -48
  42. package/src/collapsible.tsx +34 -34
  43. package/src/color-card.stories.tsx +61 -61
  44. package/src/color-card.tsx +270 -270
  45. package/src/color-picker.stories.tsx +65 -65
  46. package/src/color-picker.tsx +425 -425
  47. package/src/column-matcher.tsx +84 -0
  48. package/src/command-palette.tsx +398 -306
  49. package/src/confirm-action.tsx +98 -0
  50. package/src/copy-block.stories.tsx +38 -38
  51. package/src/copy-block.tsx +85 -85
  52. package/src/data-table.stories.tsx +200 -200
  53. package/src/data-table.tsx +1686 -1106
  54. package/src/date-picker.stories.tsx +61 -61
  55. package/src/date-picker.tsx +456 -422
  56. package/src/design-cards.stories.tsx +551 -458
  57. package/src/dialog.stories.tsx +48 -48
  58. package/src/dialog.tsx +179 -166
  59. package/src/display-preferences.tsx +50 -0
  60. package/src/documents/barcode-svg.stories.tsx +72 -72
  61. package/src/documents/barcode-svg.tsx +79 -79
  62. package/src/dropdown-menu.stories.tsx +77 -77
  63. package/src/dropdown-menu.tsx +271 -271
  64. package/src/editor/agent-panel.tsx +222 -0
  65. package/src/editor/agents.stories.tsx +81 -0
  66. package/src/editor/agents.ts +55 -0
  67. package/src/editor/behaviour.ts +279 -279
  68. package/src/editor/block-ids.ts +44 -44
  69. package/src/editor/block-list.tsx +104 -101
  70. package/src/editor/block-toolbar.tsx +490 -477
  71. package/src/editor/bubble.tsx +119 -93
  72. package/src/editor/catalogue.ts +169 -103
  73. package/src/editor/collab-rail.tsx +746 -746
  74. package/src/editor/collab.stories.tsx +207 -207
  75. package/src/editor/collab.ts +87 -87
  76. package/src/editor/contract.ts +476 -408
  77. package/src/editor/convert.ts +414 -362
  78. package/src/editor/doc-editor.stories.tsx +98 -98
  79. package/src/editor/doc-editor.tsx +1492 -1287
  80. package/src/editor/editor.css +636 -536
  81. package/src/editor/extensions.ts +86 -86
  82. package/src/editor/field-bar.tsx +154 -0
  83. package/src/editor/field-picker.tsx +109 -107
  84. package/src/editor/fields.ts +100 -100
  85. package/src/editor/gutter.tsx +443 -367
  86. package/src/editor/index.ts +23 -22
  87. package/src/editor/label-sheet.tsx +289 -289
  88. package/src/editor/labels.ts +394 -310
  89. package/src/editor/link-tools.tsx +141 -141
  90. package/src/editor/node-views.tsx +461 -450
  91. package/src/editor/page-view.tsx +372 -353
  92. package/src/editor/phone.tsx +310 -0
  93. package/src/editor/plugin-block-view.tsx +230 -0
  94. package/src/editor/plugin-blocks.stories.tsx +96 -0
  95. package/src/editor/plugin-blocks.ts +52 -0
  96. package/src/editor/publish-check.tsx +201 -182
  97. package/src/editor/rich-blocks.stories.tsx +146 -146
  98. package/src/editor/sample.ts +40 -40
  99. package/src/editor/save-block-dialog.tsx +141 -0
  100. package/src/editor/saved-block-view.tsx +205 -0
  101. package/src/editor/saved-blocks.stories.tsx +105 -0
  102. package/src/editor/saved-parts.ts +192 -0
  103. package/src/editor/schema-rich.ts +156 -150
  104. package/src/editor/schema.ts +368 -315
  105. package/src/editor/services.tsx +205 -127
  106. package/src/editor/slash.ts +64 -64
  107. package/src/editor/suggesting.ts +372 -372
  108. package/src/editor/suggestions.ts +763 -763
  109. package/src/editor/table-keys.ts +66 -66
  110. package/src/editor/templates.stories.tsx +324 -324
  111. package/src/editor/toolbar.tsx +364 -358
  112. package/src/empty-state.stories.tsx +51 -51
  113. package/src/empty-state.tsx +126 -100
  114. package/src/empty-state.usage-notes.md +30 -30
  115. package/src/form.stories.tsx +112 -112
  116. package/src/form.tsx +176 -176
  117. package/src/globals.css +20 -20
  118. package/src/icon-button.tsx +85 -85
  119. package/src/icon-map.ts +335 -244
  120. package/src/icon.tsx +41 -41
  121. package/src/index.ts +90 -67
  122. package/src/input.stories.tsx +157 -157
  123. package/src/input.tsx +768 -759
  124. package/src/kpi-strip.tsx +47 -0
  125. package/src/localized-text.ts +76 -0
  126. package/src/locked-screen.stories.tsx +29 -29
  127. package/src/locked-screen.tsx +75 -61
  128. package/src/lockup.tsx +42 -0
  129. package/src/lottie.tsx +441 -0
  130. package/src/mark.tsx +62 -62
  131. package/src/math-text.stories.tsx +33 -33
  132. package/src/math-text.tsx +43 -43
  133. package/src/menu-bar.stories.tsx +198 -198
  134. package/src/menu-bar.tsx +373 -373
  135. package/src/message-thread.tsx +181 -0
  136. package/src/money/currency.ts +244 -230
  137. package/src/money/money-input.tsx +131 -0
  138. package/src/money/money.tsx +33 -0
  139. package/src/open-on-computer.tsx +150 -0
  140. package/src/otp-input.tsx +161 -0
  141. package/src/page-header.stories.tsx +95 -95
  142. package/src/page-header.tsx +122 -122
  143. package/src/page-shell.stories.tsx +42 -42
  144. package/src/page-shell.tsx +32 -32
  145. package/src/page-states.tsx +277 -0
  146. package/src/pagination.stories.tsx +45 -45
  147. package/src/pagination.tsx +98 -98
  148. package/src/paper-sheet.stories.tsx +88 -0
  149. package/src/paper-sheet.tsx +85 -0
  150. package/src/phone-tab-bar.tsx +152 -0
  151. package/src/plugin-card.stories.tsx +208 -180
  152. package/src/plugin-card.tsx +931 -848
  153. package/src/popover.stories.tsx +48 -48
  154. package/src/popover.tsx +55 -55
  155. package/src/radio-group.stories.tsx +26 -26
  156. package/src/radio-group.tsx +44 -44
  157. package/src/route-flow/editor.tsx +1087 -1014
  158. package/src/route-flow/model.ts +771 -716
  159. package/src/save-bar.tsx +94 -0
  160. package/src/scope-grant.tsx +139 -139
  161. package/src/screen-too-small.stories.tsx +61 -61
  162. package/src/screen-too-small.tsx +104 -104
  163. package/src/search-field.tsx +65 -0
  164. package/src/select.stories.tsx +44 -44
  165. package/src/select.tsx +197 -197
  166. package/src/separator.stories.tsx +34 -34
  167. package/src/separator.tsx +34 -34
  168. package/src/sheet.stories.tsx +49 -49
  169. package/src/sheet.tsx +168 -168
  170. package/src/skeleton.stories.tsx +28 -28
  171. package/src/skeleton.tsx +19 -19
  172. package/src/slider.stories.tsx +78 -78
  173. package/src/slider.tsx +300 -300
  174. package/src/spinner.stories.tsx +33 -33
  175. package/src/spinner.tsx +55 -55
  176. package/src/stepper.tsx +85 -0
  177. package/src/switch.stories.tsx +42 -42
  178. package/src/switch.tsx +41 -41
  179. package/src/switcher.stories.tsx +111 -111
  180. package/src/switcher.tsx +131 -131
  181. package/src/system-state.tsx +55 -0
  182. package/src/table.stories.tsx +48 -48
  183. package/src/table.tsx +121 -121
  184. package/src/tabs.stories.tsx +74 -74
  185. package/src/tabs.tsx +90 -90
  186. package/src/tag-input.stories.tsx +67 -67
  187. package/src/tag-input.tsx +117 -117
  188. package/src/tenant-logo.tsx +63 -63
  189. package/src/tenant-switcher.stories.tsx +38 -38
  190. package/src/tenant-switcher.tsx +164 -164
  191. package/src/textarea.stories.tsx +27 -27
  192. package/src/textarea.tsx +18 -18
  193. package/src/theme-mode.ts +52 -52
  194. package/src/time-grid.tsx +163 -0
  195. package/src/time-picker.stories.tsx +62 -62
  196. package/src/time-picker.tsx +615 -615
  197. package/src/toggle-group.tsx +138 -138
  198. package/src/tooltip.stories.tsx +43 -43
  199. package/src/tooltip.tsx +73 -73
  200. package/src/top-nav.stories.tsx +58 -58
  201. package/src/top-nav.tsx +324 -324
  202. package/src/undo-bar.tsx +107 -107
  203. package/src/utils.ts +45 -45
  204. package/src/view-toggle.stories.tsx +84 -84
  205. package/src/view-toggle.tsx +110 -110
@@ -1,1014 +1,1087 @@
1
- 'use client';
2
-
3
- import * as React from 'react';
4
- import {
5
- Background,
6
- BackgroundVariant,
7
- BaseEdge,
8
- Controls,
9
- Handle,
10
- MarkerType,
11
- Position,
12
- ReactFlow,
13
- getBezierPath,
14
- useNodesState,
15
- type Connection,
16
- type Edge,
17
- type EdgeProps,
18
- type EdgeTypes,
19
- type Node,
20
- type NodeProps,
21
- type NodeTypes,
22
- type ReactFlowInstance,
23
- } from '@xyflow/react';
24
- import '@xyflow/react/dist/style.css';
25
- import { cn } from '../utils';
26
- import {
27
- ROUTE_FLOW_MAX_NODES,
28
- ROUTE_FLOW_MAX_NOTES,
29
- ROUTE_FLOW_NODE_HEIGHT,
30
- ROUTE_FLOW_NODE_WIDTH,
31
- autoLayout,
32
- effectiveQuorum,
33
- handleFaces,
34
- needsAutoLayout,
35
- nextSlot,
36
- notesFor,
37
- renumber,
38
- resolveTransitions,
39
- stepsInOrder,
40
- type RouteFlowAudience,
41
- type RouteFlowDirection,
42
- type RouteFlowGraph,
43
- type RouteFlowOrientation,
44
- type RouteFlowStep,
45
- type RouteFlowVerdict,
46
- } from './model';
47
-
48
- /**
49
- * The node-based editor for document route flows (#1027).
50
- *
51
- * ─────────────────────────────────────────────────────────────────────────
52
- * WHY THIS IS NOT THE `flow` BLOCK
53
- * ─────────────────────────────────────────────────────────────────────────
54
- * #950 already ships a `flow` block, and it was the first thing checked. It is
55
- * not reusable here, for reasons that are properties of its contract rather than
56
- * gaps in its implementation:
57
- *
58
- * - IT IS READ-ONLY BY DESIGN. Its canvas sets `nodesConnectable={false}` and
59
- * `elementsSelectable={false}`, and its own comment says why: "`flow` is
60
- * read-only, so a drag must never be able to look like it created an edge."
61
- * Making it editable would not extend it; it would retire the guarantee.
62
- * - IT IS DATA-BOUND TO A URL. A block declares a `source` and renders whatever
63
- * comes back. An editor's graph is local, mutable state that is saved as one
64
- * document, which is a different lifecycle, not a different fetch.
65
- * - IT LIVES IN `web/components/plugin/blocks/`, so it ships to one of three
66
- * clients. A graph editor is precisely the component the second one wants.
67
- *
68
- * What it DID give, and what is taken from it rather than re-decided: the
69
- * composition that works (custom node cards, dotted background, `Controls`,
70
- * attribution hidden, `minZoom` low enough that `fitView` does not clip), and
71
- * the node ceiling — {@link ROUTE_FLOW_MAX_NODES} mirrors its
72
- * `BlockContract::FLOW_MAX_NODES` rather than inventing a second number for the
73
- * same question.
74
- *
75
- * ─────────────────────────────────────────────────────────────────────────
76
- * A NODE IS A TYPE, AND THIS COMPONENT CANNOT MAKE IT ANYTHING ELSE
77
- * ─────────────────────────────────────────────────────────────────────────
78
- * One node per RULE. "Everyone holding Instructor" is one card whether it
79
- * resolves to four people or four thousand, and there is no code path here that
80
- * expands a rule into people — {@link RouteFlowStep} has no field that could hold
81
- * them.
82
- *
83
- * How big a node is comes in through {@link RouteFlowEditorProps.audienceFor},
84
- * which a HOST answers from the server's existing preview. The card shows the
85
- * COUNT and never a roster, and where the host cannot resolve one it shows the
86
- * host's reason instead of a zero — a zero would read as "this reaches nobody",
87
- * which is a different and much more alarming statement than "you cannot see
88
- * this".
89
- *
90
- * ─────────────────────────────────────────────────────────────────────────
91
- * NO TRANSLATOR, NO FETCH, NO ROUTER
92
- * ─────────────────────────────────────────────────────────────────────────
93
- * Every string a person reads is a prop with an English default
94
- * ({@link RouteFlowEditorLabels}), because a kit component that imported a
95
- * translator would bind three clients to one app's i18n runtime. Rule kinds are
96
- * turned into human labels by {@link RouteFlowEditorProps.ruleLabelFor}, because
97
- * the catalogue of kinds is a server fact and includes whatever plugins the host
98
- * has installed.
99
- *
100
- * The INSPECTOR — choosing a rule kind, picking a group, setting a quorum — is
101
- * deliberately not here. Those need pickers bound to the host's own APIs, and one
102
- * of them (the group picker) is being built as its own kit component. This
103
- * component owns the CANVAS and reports selection; the host renders the panel.
104
- */
105
-
106
- export interface RouteFlowEditorLabels {
107
- /** Shown on the canvas when the flow has no steps at all. */
108
- empty: string;
109
- addStep: string;
110
- deleteStep: string;
111
- /** Badge on a step that demands a verdict. */
112
- decision: string;
113
- /**
114
- * Badge on a step that TELLS its people rather than asking them (#1054).
115
- *
116
- * Worded as what the stage does to the reader's document, not as the wire
117
- * value: "delivery" is the engine's word for the mechanism, and a canvas that
118
- * printed it would make an author guess whether it meant postage.
119
- */
120
- delivery: string;
121
- /** Prefix for the resolved audience, e.g. "reaches 1,043 people". */
122
- reaches: string;
123
- people: string;
124
- /**
125
- * The singular of {@link RouteFlowEditorLabels.people}.
126
- *
127
- * A separate label rather than a rule applied to `people`, because which
128
- * counts take which form is a property of the LANGUAGE and not of this
129
- * component: English splits at one, Arabic splits at one, two and eleven. A
130
- * host with a plural-aware translator passes the form its own rules chose;
131
- * this only ever asks for "the word for a count of 1".
132
- */
133
- person: string;
134
- /** Shown in place of a count the host could not resolve and gave no reason for. */
135
- audienceUnavailable: string;
136
- approved: string;
137
- rejected: string;
138
- /** The unconditional advance out of a non-decision step. */
139
- continues: string;
140
- /** Marker on a transition the engine takes that nobody drew. */
141
- implicit: string;
142
- /** Marker where a chain stops. */
143
- ends: string;
144
- /**
145
- * Marker on a stage that more than one path reaches.
146
- *
147
- * Says that arrivals MERGE, and states the RULE by which they do: the engine
148
- * de-duplicates PER PERSON, so a stage holds one item per person no matter
149
- * how many paths reached them. Without the marker, two arrows entering a box
150
- * read as two things carrying on through it, which is not what happens.
151
- *
152
- * IT USED TO SAY "settles once", WHICH WAS FALSE HALF THE TIME (#1058). That
153
- * holds only while both arrivals reach the SAME people — then the second
154
- * de-duplicates against an item they already hold and the stage settles once.
155
- * When the stage's rule is actor-relative the arrivals reach DIFFERENT people,
156
- * nothing de-duplicates, and the stage settles twice, each settlement opening
157
- * its own continuation.
158
- *
159
- * And that is the likely case, not the exotic one: an actor-relative rule
160
- * upstream is usually what put two chains there to begin with. So the canvas
161
- * was most confident exactly where it was least accurate — the same failure
162
- * as #1042, a picture becoming false by compression, in a shape a reviewer
163
- * will not question because it looks authoritative.
164
- *
165
- * Per-person is true in BOTH cases and is the mechanism rather than one of its
166
- * outcomes, so an author can work out which case they are in: if the two paths
167
- * reach the same people it settles once, and if they do not it settles once
168
- * each. `RouteFlowResolution.merges` says the same thing as "once per COHORT";
169
- * this is that sentence in words an author of a route already has.
170
- *
171
- * WHY THIS LABEL IS NOT CONDITIONAL, WHICH WAS #1058's PREFERRED FIX. The
172
- * canvas would have to know whether the stage's rule resolves against the
173
- * ACTOR, and no truthful version of that flag exists to pass it:
174
- *
175
- * - Per KIND is wrong for a kind core already ships. `group` dereferences a
176
- * stored user group, and a group whose own definition is `role_below_actor`
177
- * is actor-relative while one defined as `role` is not — so the answer for
178
- * `group` lives in another tenant record, behind `groups:read`, which an
179
- * author of a route does not necessarily hold. A per-kind boolean would
180
- * have to lie about `group` in one direction or the other.
181
- * - The other branch would be wrong too, and not rarely. De-duplication is
182
- * over OPEN items (migration 112's partial unique index), so even a rule
183
- * that never reads the actor settles TWICE when the second arrival lands
184
- * after the first cohort closed — a fan-out where one recipient approves
185
- * straight into the merge and another rejects the long way round does
186
- * exactly that. "Not actor-relative, therefore settles once" is the same
187
- * compression as "settles once", one level down.
188
- *
189
- * So a conditional card note would replace one confident falsehood with two
190
- * quieter ones. The mechanism is the only claim that survives both, and the
191
- * CASE DISTINCTION is stated where there is room to hedge it honestly: the
192
- * host's stage inspector (`routeTemplates.inspector.merges`), which is open on
193
- * the very stage in question at the moment its rule is being chosen.
194
- *
195
- * LENGTH IS LOAD-BEARING. Notes are joined into one span clamped to
196
- * {@link ROUTE_FLOW_MAX_NOTES} lines, so a longer string here pushes a later
197
- * note off the card — which is #1042 exactly. The replacement is the same
198
- * length as what it replaces.
199
- */
200
- arrivalsMerge: string;
201
- /**
202
- * Marker on a stage a document can come back round to.
203
- *
204
- * Says a LOOP exists in the design — not that any document has gone round it,
205
- * which the canvas cannot know. Worth stating because a rework loop is
206
- * authored deliberately and is invisible afterwards: nothing counts laps
207
- * (#1037), so a document on its ninth rejection looks like one on its first.
208
- */
209
- inCycle: string;
210
- /** Prefix for the effective quorum, e.g. "all must approve". */
211
- quorumAll: string;
212
- quorumAny: string;
213
- quorumMajority: string;
214
- /** Shown when the graph is larger than the ceiling and has been cut. */
215
- tooManyNodes: string;
216
- }
217
-
218
- const DEFAULT_LABELS: RouteFlowEditorLabels = {
219
- empty: 'No stages yet. Add the first one to start the flow.',
220
- addStep: 'Add stage',
221
- deleteStep: 'Delete stage',
222
- decision: 'Decision',
223
- delivery: 'Sent, not asked',
224
- reaches: 'Reaches',
225
- people: 'people',
226
- person: 'person',
227
- audienceUnavailable: 'Audience size unavailable',
228
- approved: 'Approved',
229
- rejected: 'Rejected',
230
- continues: 'Continues',
231
- implicit: 'implicit',
232
- ends: 'Ends here',
233
- arrivalsMerge: 'Paths merge — 1 item per person',
234
- inCycle: 'Can come back round — loops',
235
- quorumAll: 'all must approve',
236
- quorumAny: 'any one may approve',
237
- quorumMajority: 'a majority must approve',
238
- tooManyNodes: 'This flow is larger than the canvas will draw. Showing the first stages only.',
239
- };
240
-
241
- export interface RouteFlowEditorProps {
242
- graph: RouteFlowGraph;
243
- /**
244
- * Called with the whole next graph on every edit.
245
- *
246
- * The whole graph, not a patch: the editor's unit of work is the canvas, and a
247
- * patch would ask the host to re-apply changes it did not make.
248
- */
249
- onGraphChange?: (graph: RouteFlowGraph) => void;
250
- /** The step the host's inspector is editing, by `position`. */
251
- selectedPosition?: number | null;
252
- onSelectStep?: (position: number | null) => void;
253
- /**
254
- * Direction-NEUTRAL by default. See `positionStep` in the model for the full
255
- * argument: a top-to-bottom flow reads identically in Arabic and English.
256
- */
257
- orientation?: RouteFlowOrientation;
258
- /**
259
- * The reading direction. Mirrors every horizontal axis, including the handles,
260
- * so an arrow leaves the face a reader expects it to leave.
261
- *
262
- * "Including the handles" is load-bearing and was, for a while, untrue.
263
- * `@xyflow/react` sets `direction: ltr` on its own container — deliberately,
264
- * because its transforms are computed in one coordinate system — and that
265
- * neutralises `insetInlineStart` on anything inside it. The verdict handles
266
- * were positioned with exactly that property, so they stayed at 30% and 70%
267
- * from the LEFT in Arabic while {@link slotAt} put the reject lane on the
268
- * left, which is the "mirrored layout, unmirrored handles" failure
269
- * {@link handleFaces} warns about: the reject arrow left the far side of its
270
- * own card and crossed back underneath it.
271
- *
272
- * They are placed with a physical `left`, mirrored arithmetically from this
273
- * prop, so the mirroring does not depend on a container's inherited direction.
274
- * The card carries its own `dir` for the same reason — `text-start` inside the
275
- * canvas would otherwise resolve to "left" and left-align Arabic.
276
- */
277
- direction?: RouteFlowDirection;
278
- /**
279
- * The most nodes to draw. Defaults to {@link ROUTE_FLOW_MAX_NODES}; a host that
280
- * knows its tenant's `documents.routing_max_steps` should pass it, because THAT
281
- * is the authoritative limit on how many steps may be saved.
282
- */
283
- maxNodes?: number;
284
- readOnly?: boolean;
285
- /** How many people a step's rule currently reaches, resolved by the host. */
286
- audienceFor?: (step: RouteFlowStep) => RouteFlowAudience | undefined;
287
- /** A human label for a rule kind — the catalogue is a server fact. */
288
- ruleLabelFor?: (step: RouteFlowStep) => string;
289
- labels?: Partial<RouteFlowEditorLabels>;
290
- className?: string;
291
- }
292
-
293
- interface RouteFlowNodeData extends Record<string, unknown> {
294
- step: RouteFlowStep;
295
- quorumText: string;
296
- ruleLabel: string;
297
- audience: RouteFlowAudience | undefined;
298
- selected: boolean;
299
- readOnly: boolean;
300
- notes: string[];
301
- labels: RouteFlowEditorLabels;
302
- direction: RouteFlowDirection;
303
- sourceFace: Position;
304
- targetFace: Position;
305
- onSelect: (position: number) => void;
306
- onDelete: (position: number) => void;
307
- }
308
-
309
- /**
310
- * How big a handle is drawn.
311
- *
312
- * `@xyflow/react`'s default is 6×6 CSS px, which the canvas zoom then shrinks:
313
- * at the zoom a four-stage flow fits at, the measured target was 5.4px on
314
- * screen. Starting an edge meant hitting a 5px dot, and the alternative gesture
315
- * a person tries first — dropping on the target CARD — does nothing, because a
316
- * connection has to end on a handle. 12px is a target a hand can find, and it is
317
- * still small enough that two of them sit on one 224px face without touching.
318
- *
319
- * The other half of that fix is {@link CONNECTION_RADIUS}.
320
- */
321
- const HANDLE_CLASS = '!h-3 !w-3 !border-2 !border-card !bg-muted-foreground/60';
322
-
323
- /**
324
- * How far from a handle a drop still counts as landing on it.
325
- *
326
- * `@xyflow/react` defaults to 20px, so a connection had to be released within
327
- * 20px of a 5px dot; releasing over the target CARD — the gesture people try
328
- * first — did nothing at all, and did it silently.
329
- *
330
- * Widened to reach from the target handle (top-centre of a card) across most of
331
- * the card it belongs to, so dropping ON the node connects. Deliberately NOT
332
- * wide enough to span the gap to the next node: {@link ROUTE_FLOW_NODE_HEIGHT}
333
- * plus its layout gap is the distance between two stages, and this is well
334
- * inside half of that, so a drop is never claimed by the card an author was not
335
- * pointing at.
336
- */
337
- const CONNECTION_RADIUS = 80;
338
-
339
- /**
340
- * Where a verdict handle sits along the source face, as a physical inset.
341
- *
342
- * PHYSICAL, not logical. `insetInlineStart` would be the idiomatic choice and it
343
- * is the one that was here; it does not work, because `@xyflow/react` forces
344
- * `direction: ltr` on its container and a logical inset resolves against that
345
- * rather than against the document. So the mirroring is done here, from the
346
- * direction the host passed, where nothing can quietly undo it.
347
- */
348
- function verdictInset(
349
- direction: RouteFlowDirection,
350
- percentFromReadingStart: number
351
- ): React.CSSProperties {
352
- // Mirrored by arithmetic and still written as `left`, NOT by switching to
353
- // `right`. `@xyflow/react` centres a handle on its inset with a
354
- // `translateX(-50%)` of its own; anchoring from the other edge leaves that
355
- // translation pulling the wrong way and lands the handle half its own width
356
- // off — measured 0.65 where 0.70 was meant. One physical property, one
357
- // percentage, nothing left for a transform to disagree with.
358
- const fromLeft = direction === 'rtl' ? 100 - percentFromReadingStart : percentFromReadingStart;
359
-
360
- return { left: `${fromLeft}%` };
361
- }
362
-
363
- const FACE: Record<string, Position> = {
364
- top: Position.Top,
365
- bottom: Position.Bottom,
366
- left: Position.Left,
367
- right: Position.Right,
368
- };
369
-
370
- /**
371
- * One stage.
372
- *
373
- * A DECISION step carries TWO source handles — one per verdict — and an ordinary
374
- * step carries one. That is what makes "draw the approve edge and the reject
375
- * edge from one node" a gesture rather than a form: which handle a drag starts
376
- * from IS the verdict, so an author never picks it from a menu afterwards and
377
- * the two arrows are visibly different before they are drawn.
378
- *
379
- * A non-decision step gets no verdict handles at all, because an edge leaving one
380
- * could never fire — the server refuses it, and an affordance that produces a
381
- * refusal is worse than no affordance.
382
- */
383
- function RouteFlowNodeCard({ data }: NodeProps<Node<RouteFlowNodeData>>) {
384
- const {
385
- step,
386
- quorumText,
387
- ruleLabel,
388
- audience,
389
- selected,
390
- readOnly,
391
- notes,
392
- labels,
393
- direction,
394
- sourceFace,
395
- targetFace,
396
- onSelect,
397
- onDelete,
398
- } = data;
399
-
400
- const title = step.label !== null && step.label !== '' ? step.label : ruleLabel;
401
-
402
- return (
403
- <div
404
- // The card carries its OWN `dir`. `@xyflow/react` forces `direction: ltr`
405
- // on its container, so without this every `text-start` and every `end-*`
406
- // inside a node resolves to the left-to-right answer and Arabic labels sit
407
- // left-aligned in a right-to-left page.
408
- dir={direction}
409
- className={cn(
410
- 'flex flex-col gap-1 rounded-lg border bg-card px-3 py-2 text-start shadow-sm transition-colors',
411
- selected ? 'border-primary ring-2 ring-primary/30' : 'border-border'
412
- )}
413
- style={{ width: ROUTE_FLOW_NODE_WIDTH, height: ROUTE_FLOW_NODE_HEIGHT }}
414
- data-slot="route-flow-node"
415
- data-position={step.position}
416
- data-decision={step.decision ? 'true' : 'false'}
417
- data-satisfied-by={step.satisfiedBy}
418
- >
419
- <Handle type="target" position={targetFace} className={HANDLE_CLASS} />
420
-
421
- <button
422
- type="button"
423
- onClick={() => onSelect(step.position)}
424
- className="flex min-w-0 flex-col text-start outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
425
- >
426
- <span className="flex items-center gap-1.5">
427
- <span className="truncate text-sm font-medium text-foreground">{title}</span>
428
- {step.decision && (
429
- <span className="shrink-0 rounded bg-primary/10 px-1 text-[10px] font-medium uppercase text-primary">
430
- {labels.decision}
431
- </span>
432
- )}
433
- {/* A BADGE, NOT A NOTE, and that is a height decision rather than a
434
- style one. The card's height is DERIVED from its rows and the note
435
- clamp is derived from ROUTE_FLOW_MAX_NOTES, whose value is a
436
- PROVEN maximum over what notesFor() can emit — a fourth note would
437
- make the card silently drop one, which is exactly the #1042 defect
438
- those derivations were built to prevent.
439
-
440
- A delivery stage is never a decision stage (the server refuses the
441
- pair at three layers), so the two badges can never both appear and
442
- the title row cannot grow because of this. */}
443
- {step.satisfiedBy === 'delivery' && (
444
- <span
445
- className="shrink-0 rounded bg-muted px-1 text-[10px] font-medium uppercase text-muted-foreground"
446
- data-slot="route-flow-node-delivery-badge"
447
- >
448
- {labels.delivery}
449
- </span>
450
- )}
451
- </span>
452
- {/* The RULE, always visible. A card that showed only an author's label
453
- would let "Dean" sit on a node that actually reaches every registrar,
454
- and nothing on screen would say so. */}
455
- <span className="truncate text-xs text-muted-foreground">{ruleLabel}</span>
456
- </button>
457
-
458
- {/* THE COUNT, NEVER A ROSTER — the line that makes a type-node honest: one
459
- card, and the number of people behind it. */}
460
- <span className="truncate text-xs text-muted-foreground">
461
- {audience === undefined
462
- ? ' '
463
- : audience.count !== null
464
- ? `${labels.reaches} ${audience.count.toLocaleString()} ${
465
- audience.count === 1 ? labels.person : labels.people
466
- }`
467
- : (audience.unavailableReason ?? labels.audienceUnavailable)}
468
- </span>
469
-
470
- {/* THE QUORUM, on its own row.
471
-
472
- It is shown for every decision stage, INDEPENDENTLY of whether the
473
- count resolved. It used to be rendered inside the count branch, so a
474
- viewer who could not preview audiences (a 403 there is ordinary — the
475
- draft preview needs `groups:write`, which designing a flow does not
476
- imply) saw a gate with no indication of what would satisfy it. The two
477
- facts have different sources and only one of them can fail; binding
478
- them together made the reliable one vanish with the unreliable one.
479
-
480
- It was then joined onto the COUNT's line with a separator, and the pair
481
- overflowed one 224px row: "Reaches 1 people · all must appr…" — a
482
- quorum made unconditionally visible and then truncated mid-word, which
483
- is the same disappearance by a slower route (#1042). Its own row costs
484
- 16px of a height that is now derived from the rows it holds, and no
485
- audience string can crowd it out. */}
486
- <span className="truncate text-xs text-muted-foreground">
487
- {step.decision ? quorumText : ' '}
488
- </span>
489
-
490
- {notes.length > 0 && (
491
- <span
492
- data-slot="route-flow-notes"
493
- // Clamped from the SAME constant the card's height is budgeted against
494
- // (see ROUTE_FLOW_MAX_NOTES). Tailwind's `line-clamp-N` is a static
495
- // class and could only repeat the number as a literal, which is
496
- // precisely how the two drifted apart: the height was raised to hold
497
- // three lines while the clamp stayed at two, and a stage carrying
498
- // merge + loop + "Rejected: Ends here" dropped the last of them.
499
- style={{
500
- display: '-webkit-box',
501
- WebkitBoxOrient: 'vertical',
502
- WebkitLineClamp: ROUTE_FLOW_MAX_NOTES,
503
- overflow: 'hidden',
504
- }}
505
- className="text-[10px] uppercase leading-tight tracking-wide text-muted-foreground"
506
- >
507
- {notes.join(' · ')}
508
- </span>
509
- )}
510
-
511
- {!readOnly && (
512
- <button
513
- type="button"
514
- onClick={() => onDelete(step.position)}
515
- aria-label={labels.deleteStep}
516
- className="nodrag absolute end-1 top-1 rounded px-1 text-xs text-muted-foreground hover:text-destructive"
517
- >
518
- &times;
519
- </button>
520
- )}
521
-
522
- {/* A decision step's two verdict handles are stacked on the source face and
523
- coloured, so the gesture and the picture agree before an edge exists.
524
-
525
- On a horizontal face the two are offset along the VERTICAL axis, which
526
- no reading direction mirrors, so only the top/bottom case consults
527
- `direction`. */}
528
- {step.decision ? (
529
- <>
530
- <Handle
531
- id="approved"
532
- type="source"
533
- position={sourceFace}
534
- style={
535
- sourceFace === Position.Bottom || sourceFace === Position.Top
536
- ? verdictInset(direction, 30)
537
- : { top: '35%' }
538
- }
539
- className={cn(HANDLE_CLASS, '!bg-emerald-500')}
540
- data-testid={`approve-handle-${step.position}`}
541
- />
542
- <Handle
543
- id="rejected"
544
- type="source"
545
- position={sourceFace}
546
- style={
547
- sourceFace === Position.Bottom || sourceFace === Position.Top
548
- ? verdictInset(direction, 70)
549
- : { top: '70%' }
550
- }
551
- className={cn(HANDLE_CLASS, '!bg-rose-500')}
552
- data-testid={`reject-handle-${step.position}`}
553
- />
554
- </>
555
- ) : (
556
- <Handle type="source" position={sourceFace} className={HANDLE_CLASS} />
557
- )}
558
- </div>
559
- );
560
- }
561
-
562
- const nodeTypes: NodeTypes = { routeFlowStep: RouteFlowNodeCard };
563
-
564
- interface RouteFlowEdgeData extends Record<string, unknown> {
565
- kind: 'drawn' | 'derived';
566
- on: RouteFlowVerdict | 'continue';
567
- text: string;
568
- }
569
-
570
- /**
571
- * How far a transition's label is nudged off the middle of its own curve, by
572
- * verdict.
573
- *
574
- * ─────────────────────────────────────────────────────────────────────────
575
- * WHY A LABEL NEEDS AN OFFSET AT ALL
576
- * ─────────────────────────────────────────────────────────────────────────
577
- * Two transitions running BETWEEN THE SAME PAIR OF STAGES in opposite
578
- * directions have, to within a few pixels, the same midpoint — and a built-in
579
- * edge draws its label at exactly that midpoint. So a rework loop, which is the
580
- * commonest real design there is, printed both labels on top of each other:
581
- * "Approved (imp Rejected" (#1042).
582
- *
583
- * That is an anti-parallel PAIR, not "two edges leaving one node" — two edges
584
- * leaving one node diverge, and their labels separate on their own. The pair is
585
- * always a pair of DIFFERENT verdicts (one destination per verdict per stage is
586
- * enforced by the schema and by `onConnect`), so nudging by verdict is enough to
587
- * separate any pair that can exist, and it does it deterministically rather than
588
- * by a collision search whose answer would move as nodes are dragged.
589
- *
590
- * Bigger than a label's own line box, so the two clear rather than touch.
591
- */
592
- const LABEL_NUDGE: Record<RouteFlowVerdict | 'continue', number> = {
593
- approved: -18,
594
- continue: 0,
595
- rejected: 18,
596
- };
597
-
598
- /**
599
- * One transition.
600
- *
601
- * A custom edge only so the label can be moved; everything else is
602
- * `@xyflow/react`'s own, including the invisible interaction path that makes an
603
- * edge selectable and therefore deletable.
604
- *
605
- * The label is drawn on a background chip because it sits over a dotted
606
- * background and, in a loop, over the other arrow.
607
- */
608
- function RouteFlowTransitionEdge({
609
- sourceX,
610
- sourceY,
611
- sourcePosition,
612
- targetX,
613
- targetY,
614
- targetPosition,
615
- markerEnd,
616
- style,
617
- data,
618
- }: EdgeProps<Edge<RouteFlowEdgeData>>) {
619
- const [path, labelX, labelY] = getBezierPath({
620
- sourceX,
621
- sourceY,
622
- sourcePosition,
623
- targetX,
624
- targetY,
625
- targetPosition,
626
- });
627
-
628
- return (
629
- <BaseEdge
630
- path={path}
631
- markerEnd={markerEnd}
632
- style={style}
633
- label={data?.text}
634
- labelX={labelX}
635
- labelY={labelY + LABEL_NUDGE[data?.on ?? 'continue']}
636
- // SVG text defaults to black and `@xyflow/react` sets no fill of its own,
637
- // so an edge label was black on a near-black canvas in dark mode. Both
638
- // colours come from the theme, so the chip and its text move together.
639
- labelStyle={{ fontSize: 10, fill: 'var(--color-muted-foreground, #64748b)' }}
640
- labelShowBg
641
- labelBgPadding={[4, 2]}
642
- labelBgBorderRadius={3}
643
- labelBgStyle={{ fill: 'var(--color-card, #ffffff)', fillOpacity: 0.92 }}
644
- />
645
- );
646
- }
647
-
648
- const edgeTypes: EdgeTypes = { routeFlowTransition: RouteFlowTransitionEdge };
649
-
650
- /**
651
- * How the canvas frames itself.
652
- *
653
- * `maxZoom` is the important one and it was missing. `@xyflow/react` defaults a
654
- * fit to a maximum of 2×, and `fitView` runs on MOUNT — which, for a template
655
- * being authored from nothing, is the moment the FIRST node appears. One node
656
- * fits at 2×, the viewport froze there, and stages 2, 3 and 4 were then added
657
- * off-screen: the measured result was `scale(2)` with one of four nodes visible,
658
- * for every new flow anybody made (#1042).
659
- *
660
- * Capped at 1 rather than at some larger number because a node card is designed
661
- * at a fixed pixel size and a magnified one is not more legible, only bigger.
662
- * This bounds the automatic fit ONLY — the `maxZoom` prop is left at its default
663
- * so a person can still zoom in past this by hand.
664
- */
665
- const FIT_VIEW = { maxZoom: 1, padding: 0.15 };
666
-
667
- export function RouteFlowEditor({
668
- graph,
669
- onGraphChange,
670
- selectedPosition = null,
671
- onSelectStep,
672
- orientation = 'vertical',
673
- direction = 'ltr',
674
- maxNodes = ROUTE_FLOW_MAX_NODES,
675
- readOnly = false,
676
- audienceFor,
677
- ruleLabelFor,
678
- labels: labelOverrides,
679
- className,
680
- }: RouteFlowEditorProps) {
681
- const labels = React.useMemo<RouteFlowEditorLabels>(
682
- () => ({ ...DEFAULT_LABELS, ...labelOverrides }),
683
- [labelOverrides]
684
- );
685
-
686
- const faces = handleFaces(orientation, direction);
687
- const sourceFace = FACE[faces.source] ?? Position.Bottom;
688
- const targetFace = FACE[faces.target] ?? Position.Top;
689
-
690
- const ordered = React.useMemo(() => stepsInOrder(graph.steps), [graph.steps]);
691
- const cut = ordered.length > maxNodes;
692
- const drawn = cut ? ordered.slice(0, maxNodes) : ordered;
693
-
694
- const resolution = React.useMemo(() => resolveTransitions(graph), [graph]);
695
- const { transitions } = resolution;
696
-
697
- const quorumLabel = React.useCallback(
698
- (step: RouteFlowStep): string => {
699
- switch (effectiveQuorum(step, graph)) {
700
- case 'any':
701
- return labels.quorumAny;
702
- case 'majority':
703
- return labels.quorumMajority;
704
- default:
705
- return labels.quorumAll;
706
- }
707
- },
708
- [graph, labels]
709
- );
710
-
711
- const emit = React.useCallback(
712
- (next: RouteFlowGraph) => {
713
- onGraphChange?.(next);
714
- },
715
- [onGraphChange]
716
- );
717
-
718
- const handleDelete = React.useCallback(
719
- (position: number) => {
720
- // Renumber and rewrite edges in the same pass — see `renumber`. `position`
721
- // is also the FALLTHROUGH order, so a delete that left a gap would leave
722
- // an author reading arrows that no longer match the list.
723
- emit(
724
- renumber({
725
- ...graph,
726
- steps: graph.steps.filter((s) => s.position !== position),
727
- edges: graph.edges.filter((e) => e.from !== position && e.to !== position),
728
- })
729
- );
730
- if (selectedPosition === position) {
731
- onSelectStep?.(null);
732
- }
733
- },
734
- [emit, graph, onSelectStep, selectedPosition]
735
- );
736
-
737
- const [nodes, setNodes, onNodesChange] = useNodesState<Node<RouteFlowNodeData>>([]);
738
-
739
- React.useEffect(() => {
740
- // A graph nothing has ever arranged gets one tidy layout; anything an author
741
- // has touched keeps the arrangement they made. See `needsAutoLayout` for why
742
- // the test is deliberately narrow.
743
- const placed = needsAutoLayout(drawn)
744
- ? autoLayout({ ...graph, steps: drawn }, orientation, direction)
745
- : drawn;
746
-
747
- setNodes(
748
- placed.map((step) => {
749
- // WHICH notes a stage carries is decided in the model, by `notesFor`,
750
- // and only the wording is decided here. That split is what lets
751
- // ROUTE_FLOW_MAX_NOTES — the number the card's height is budgeted
752
- // against — be an assertion a test can make.
753
- const notes = notesFor(step.position, resolution).map((note) => {
754
- if (note.kind === 'merge') return labels.arrivalsMerge;
755
- if (note.kind === 'cycle') return labels.inCycle;
756
- const on =
757
- note.on === 'approved'
758
- ? labels.approved
759
- : note.on === 'rejected'
760
- ? labels.rejected
761
- : labels.continues;
762
- return `${on}: ${labels.ends}`;
763
- });
764
-
765
- return {
766
- id: String(step.position),
767
- type: 'routeFlowStep',
768
- position: { x: step.canvasX, y: step.canvasY },
769
- draggable: !readOnly,
770
- data: {
771
- step,
772
- quorumText: quorumLabel(step),
773
- ruleLabel: ruleLabelFor?.(step) ?? step.ruleKind,
774
- audience: audienceFor?.(step),
775
- selected: selectedPosition === step.position,
776
- readOnly,
777
- notes,
778
- labels,
779
- direction,
780
- sourceFace,
781
- targetFace,
782
- onSelect: (p: number) => onSelectStep?.(p),
783
- onDelete: handleDelete,
784
- },
785
- };
786
- })
787
- );
788
- }, [
789
- audienceFor,
790
- direction,
791
- drawn,
792
- graph,
793
- handleDelete,
794
- labels,
795
- onSelectStep,
796
- orientation,
797
- quorumLabel,
798
- readOnly,
799
- ruleLabelFor,
800
- resolution,
801
- selectedPosition,
802
- setNodes,
803
- sourceFace,
804
- targetFace,
805
- ]);
806
-
807
- const edges = React.useMemo<Edge[]>(() => {
808
- const visible = new Set(drawn.map((s) => s.position));
809
-
810
- return transitions
811
- .filter((t) => visible.has(t.from) && visible.has(t.to))
812
- .map((t) => {
813
- const isReject = t.on === 'rejected';
814
- const isApprove = t.on === 'approved';
815
- const label =
816
- t.on === 'approved'
817
- ? labels.approved
818
- : t.on === 'rejected'
819
- ? labels.rejected
820
- : labels.continues;
821
-
822
- return {
823
- id: `${t.from}-${t.on}-${t.to}`,
824
- source: String(t.from),
825
- target: String(t.to),
826
- sourceHandle: isApprove || isReject ? t.on : undefined,
827
- type: 'routeFlowTransition',
828
- // A DERIVED transition is dashed and says so. It is a real arrow — the
829
- // engine will take it — but it is not one the author drew, and it
830
- // cannot be deleted except by reordering the steps that imply it.
831
- animated: false,
832
- style: {
833
- strokeDasharray: t.kind === 'derived' ? '4 3' : undefined,
834
- stroke: isReject
835
- ? 'var(--color-rose-500, #f43f5e)'
836
- : isApprove
837
- ? 'var(--color-emerald-500, #10b981)'
838
- : undefined,
839
- },
840
- markerEnd: { type: MarkerType.ArrowClosed },
841
- // The label travels in `data` rather than in `label`, because the
842
- // custom edge draws it at a nudged position — see LABEL_NUDGE.
843
- data: {
844
- kind: t.kind,
845
- on: t.on,
846
- text: t.kind === 'derived' ? `${label} (${labels.implicit})` : label,
847
- },
848
- } satisfies Edge;
849
- });
850
- }, [drawn, labels, transitions]);
851
-
852
- /**
853
- * A drag between two handles becomes a stored edge.
854
- *
855
- * The verdict is the SOURCE HANDLE's id, never a guess: an author who dragged
856
- * from the green handle drew an approve edge, and there is no second place that
857
- * decision could be made differently. A drag from a plain (non-decision) handle
858
- * is dropped, because such an edge could never fire and the server would refuse
859
- * it — better to have the gesture do nothing visible than to save something
860
- * that comes back as an error.
861
- */
862
- const onConnect = React.useCallback(
863
- (connection: Connection) => {
864
- if (readOnly) return;
865
-
866
- const verdict = connection.sourceHandle;
867
- if (verdict !== 'approved' && verdict !== 'rejected') return;
868
-
869
- const from = Number(connection.source);
870
- const to = Number(connection.target);
871
- if (!Number.isFinite(from) || !Number.isFinite(to) || from === to) return;
872
-
873
- // One destination per verdict per node — the same uniqueness the schema
874
- // enforces. Re-drawing replaces rather than adding a second arrow, which
875
- // is what an author dragging again means.
876
- const kept = graph.edges.filter((e) => !(e.from === from && e.verdict === verdict));
877
- emit({ ...graph, edges: [...kept, { from, to, verdict: verdict as RouteFlowVerdict }] });
878
- },
879
- [emit, graph, readOnly]
880
- );
881
-
882
- const onEdgesDelete = React.useCallback(
883
- (removed: Edge[]) => {
884
- if (readOnly) return;
885
- // Only DRAWN edges can be removed. A derived one is a consequence of the
886
- // step order; deleting the arrow without deleting the cause would show a
887
- // canvas the engine disagrees with.
888
- const drawnIds = new Set(removed.filter((e) => (e.data as { kind?: string })?.kind === 'drawn').map((e) => e.id));
889
- if (drawnIds.size === 0) return;
890
-
891
- emit({
892
- ...graph,
893
- edges: graph.edges.filter((e) => !drawnIds.has(`${e.from}-${e.verdict}-${e.to}`)),
894
- });
895
- },
896
- [emit, graph, readOnly]
897
- );
898
-
899
- /**
900
- * Re-frame the canvas when the flow gains or loses a stage.
901
- *
902
- * `fitView` alone only ever fires once, on mount. Everything an author does
903
- * after that — and on a new template, everything they do at all — happens to a
904
- * viewport that was framed for a graph with one node in it.
905
- *
906
- * Keyed on the node COUNT and nothing else, deliberately. Re-fitting on every
907
- * graph change would yank the canvas out from under someone who had panned to
908
- * a corner and was renaming a stage; adding or deleting a stage is the one
909
- * edit that changes what there is to look at.
910
- *
911
- * `requestAnimationFrame` because the fit needs the new node MEASURED, and
912
- * this effect runs in the same commit that first renders it.
913
- */
914
- const instance = React.useRef<ReactFlowInstance<Node<RouteFlowNodeData>, Edge> | null>(null);
915
- const onInit = React.useCallback(
916
- (next: ReactFlowInstance<Node<RouteFlowNodeData>, Edge>) => {
917
- instance.current = next;
918
- },
919
- []
920
- );
921
-
922
- const nodeCount = drawn.length;
923
- React.useEffect(() => {
924
- if (nodeCount === 0) return undefined;
925
- const frame = requestAnimationFrame(() => {
926
- void instance.current?.fitView(FIT_VIEW);
927
- });
928
- return () => cancelAnimationFrame(frame);
929
- }, [nodeCount]);
930
-
931
- const onNodeDragStop = React.useCallback(
932
- (_event: MouseEvent | TouchEvent, node: Node) => {
933
- if (readOnly) return;
934
- const position = Number(node.id);
935
- emit({
936
- ...graph,
937
- steps: graph.steps.map((s) =>
938
- s.position === position
939
- ? { ...s, canvasX: Math.round(node.position.x), canvasY: Math.round(node.position.y) }
940
- : s
941
- ),
942
- });
943
- },
944
- [emit, graph, readOnly]
945
- );
946
-
947
- return (
948
- <div className={cn('relative h-[32rem] w-full rounded-lg border border-border bg-card', className)}>
949
- {cut && (
950
- <p
951
- className="absolute inset-x-0 top-0 z-10 bg-amber-500/10 px-3 py-1 text-xs text-foreground"
952
- role="status"
953
- >
954
- {labels.tooManyNodes}
955
- </p>
956
- )}
957
- {drawn.length === 0 ? (
958
- <p className="flex h-full items-center justify-center px-6 text-center text-sm text-muted-foreground">
959
- {labels.empty}
960
- </p>
961
- ) : (
962
- <ReactFlow
963
- nodes={nodes}
964
- edges={edges}
965
- nodeTypes={nodeTypes}
966
- edgeTypes={edgeTypes}
967
- onInit={onInit}
968
- onNodesChange={onNodesChange}
969
- onNodeDragStop={onNodeDragStop}
970
- onConnect={onConnect}
971
- onEdgesDelete={onEdgesDelete}
972
- nodesDraggable={!readOnly}
973
- nodesConnectable={!readOnly}
974
- elementsSelectable
975
- connectionRadius={CONNECTION_RADIUS}
976
- fitView
977
- fitViewOptions={FIT_VIEW}
978
- // react-flow's default minZoom (0.5) defeats fitView on anything wider
979
- // than about twice the canvas: the fit clamps at 0.5 and centres,
980
- // silently clipping the outermost nodes. The OU hub hit this first and
981
- // the `flow` block records it; a route flow with a reject lane is wide
982
- // enough to hit it sooner.
983
- minZoom={0.1}
984
- proOptions={{ hideAttribution: true }}
985
- >
986
- <Background variant={BackgroundVariant.Dots} gap={16} size={1} />
987
- <Controls showInteractive={false} />
988
- </ReactFlow>
989
- )}
990
- </div>
991
- );
992
- }
993
-
994
- /**
995
- * Append a stage to a flow, placed in the next free slot.
996
- *
997
- * Exported beside the editor rather than living inside it because ADDING a stage
998
- * needs a rule, and choosing one is the host's inspector's job. The host builds
999
- * the step and calls this to get the placement and the numbering right.
1000
- */
1001
- export function appendStep(
1002
- graph: RouteFlowGraph,
1003
- step: Omit<RouteFlowStep, 'position' | 'canvasX' | 'canvasY'>,
1004
- orientation: RouteFlowOrientation = 'vertical',
1005
- direction: RouteFlowDirection = 'ltr'
1006
- ): RouteFlowGraph {
1007
- const positions = graph.steps.map((s) => s.position);
1008
- const position = positions.length === 0 ? 1 : Math.max(...positions) + 1;
1009
-
1010
- return {
1011
- ...graph,
1012
- steps: [...graph.steps, { ...step, position, ...nextSlot(graph, orientation, direction) }],
1013
- };
1014
- }
1
+ 'use client';
2
+
3
+ import * as React from 'react';
4
+ import {
5
+ Background,
6
+ BackgroundVariant,
7
+ BaseEdge,
8
+ Controls,
9
+ Handle,
10
+ MarkerType,
11
+ Panel,
12
+ Position,
13
+ ReactFlow,
14
+ getBezierPath,
15
+ useNodesState,
16
+ type Connection,
17
+ type Edge,
18
+ type EdgeProps,
19
+ type EdgeTypes,
20
+ type Node,
21
+ type NodeProps,
22
+ type NodeTypes,
23
+ type ReactFlowInstance,
24
+ } from '@xyflow/react';
25
+ import '@xyflow/react/dist/style.css';
26
+ import { cn } from '../utils';
27
+ import {
28
+ ROUTE_FLOW_MAX_NODES,
29
+ ROUTE_FLOW_MAX_NOTES,
30
+ ROUTE_FLOW_NODE_HEIGHT,
31
+ ROUTE_FLOW_NODE_WIDTH,
32
+ autoLayout,
33
+ effectiveQuorum,
34
+ handleFaces,
35
+ needsAutoLayout,
36
+ nextSlot,
37
+ notesFor,
38
+ renumber,
39
+ resolveTransitions,
40
+ stepsInOrder,
41
+ type RouteFlowAudience,
42
+ type RouteFlowDirection,
43
+ type RouteFlowGraph,
44
+ type RouteFlowOrientation,
45
+ type RouteFlowStep,
46
+ type RouteFlowVerdict,
47
+ } from './model';
48
+
49
+ /**
50
+ * The node-based editor for document route flows (#1027).
51
+ *
52
+ * ─────────────────────────────────────────────────────────────────────────
53
+ * WHY THIS IS NOT THE `flow` BLOCK
54
+ * ─────────────────────────────────────────────────────────────────────────
55
+ * #950 already ships a `flow` block, and it was the first thing checked. It is
56
+ * not reusable here, for reasons that are properties of its contract rather than
57
+ * gaps in its implementation:
58
+ *
59
+ * - IT IS READ-ONLY BY DESIGN. Its canvas sets `nodesConnectable={false}` and
60
+ * `elementsSelectable={false}`, and its own comment says why: "`flow` is
61
+ * read-only, so a drag must never be able to look like it created an edge."
62
+ * Making it editable would not extend it; it would retire the guarantee.
63
+ * - IT IS DATA-BOUND TO A URL. A block declares a `source` and renders whatever
64
+ * comes back. An editor's graph is local, mutable state that is saved as one
65
+ * document, which is a different lifecycle, not a different fetch.
66
+ * - IT LIVES IN `web/components/plugin/blocks/`, so it ships to one of three
67
+ * clients. A graph editor is precisely the component the second one wants.
68
+ *
69
+ * What it DID give, and what is taken from it rather than re-decided: the
70
+ * composition that works (custom node cards, dotted background, `Controls`,
71
+ * attribution hidden, `minZoom` low enough that `fitView` does not clip), and
72
+ * the node ceiling — {@link ROUTE_FLOW_MAX_NODES} mirrors its
73
+ * `BlockContract::FLOW_MAX_NODES` rather than inventing a second number for the
74
+ * same question.
75
+ *
76
+ * ─────────────────────────────────────────────────────────────────────────
77
+ * A NODE IS A TYPE, AND THIS COMPONENT CANNOT MAKE IT ANYTHING ELSE
78
+ * ─────────────────────────────────────────────────────────────────────────
79
+ * One node per RULE. "Everyone holding Instructor" is one card whether it
80
+ * resolves to four people or four thousand, and there is no code path here that
81
+ * expands a rule into people — {@link RouteFlowStep} has no field that could hold
82
+ * them.
83
+ *
84
+ * How big a node is comes in through {@link RouteFlowEditorProps.audienceFor},
85
+ * which a HOST answers from the server's existing preview. The card shows the
86
+ * COUNT and never a roster, and where the host cannot resolve one it shows the
87
+ * host's reason instead of a zero — a zero would read as "this reaches nobody",
88
+ * which is a different and much more alarming statement than "you cannot see
89
+ * this".
90
+ *
91
+ * ─────────────────────────────────────────────────────────────────────────
92
+ * NO TRANSLATOR, NO FETCH, NO ROUTER
93
+ * ─────────────────────────────────────────────────────────────────────────
94
+ * Every string a person reads is a prop with an English default
95
+ * ({@link RouteFlowEditorLabels}), because a kit component that imported a
96
+ * translator would bind three clients to one app's i18n runtime. Rule kinds are
97
+ * turned into human labels by {@link RouteFlowEditorProps.ruleLabelFor}, because
98
+ * the catalogue of kinds is a server fact and includes whatever plugins the host
99
+ * has installed.
100
+ *
101
+ * The INSPECTOR — choosing a rule kind, picking a group, setting a quorum — is
102
+ * deliberately not here. Those need pickers bound to the host's own APIs, and one
103
+ * of them (the group picker) is being built as its own kit component. This
104
+ * component owns the CANVAS and reports selection; the host renders the panel.
105
+ */
106
+
107
+ export interface RouteFlowEditorLabels {
108
+ /** Shown on the canvas when the flow has no steps at all. */
109
+ empty: string;
110
+ addStep: string;
111
+ deleteStep: string;
112
+ /** Badge on a step that demands a verdict. */
113
+ decision: string;
114
+ /**
115
+ * Badge on a step that TELLS its people rather than asking them (#1054).
116
+ *
117
+ * Worded as what the stage does to the reader's document, not as the wire
118
+ * value: "delivery" is the engine's word for the mechanism, and a canvas that
119
+ * printed it would make an author guess whether it meant postage.
120
+ */
121
+ delivery: string;
122
+ /**
123
+ * Badge on the stage that makes the final document (WHIT-921). Optional so a
124
+ * host that offers no such stage need not translate it.
125
+ */
126
+ finalise?: string;
127
+ /** Prefix for the resolved audience, e.g. "reaches 1,043 people". */
128
+ reaches: string;
129
+ people: string;
130
+ /**
131
+ * The singular of {@link RouteFlowEditorLabels.people}.
132
+ *
133
+ * A separate label rather than a rule applied to `people`, because which
134
+ * counts take which form is a property of the LANGUAGE and not of this
135
+ * component: English splits at one, Arabic splits at one, two and eleven. A
136
+ * host with a plural-aware translator passes the form its own rules chose;
137
+ * this only ever asks for "the word for a count of 1".
138
+ */
139
+ person: string;
140
+ /** Shown in place of a count the host could not resolve and gave no reason for. */
141
+ audienceUnavailable: string;
142
+ approved: string;
143
+ rejected: string;
144
+ /** The unconditional advance out of a non-decision step. */
145
+ continues: string;
146
+ /** Marker on a transition the engine takes that nobody drew. */
147
+ implicit: string;
148
+ /** Marker where a chain stops. */
149
+ ends: string;
150
+ /** The pill at the top: where a document enters the route. */
151
+ start?: string;
152
+ /**
153
+ * Marker on a stage that more than one path reaches.
154
+ *
155
+ * Says that arrivals MERGE, and states the RULE by which they do: the engine
156
+ * de-duplicates PER PERSON, so a stage holds one item per person no matter
157
+ * how many paths reached them. Without the marker, two arrows entering a box
158
+ * read as two things carrying on through it, which is not what happens.
159
+ *
160
+ * IT USED TO SAY "settles once", WHICH WAS FALSE HALF THE TIME (#1058). That
161
+ * holds only while both arrivals reach the SAME people — then the second
162
+ * de-duplicates against an item they already hold and the stage settles once.
163
+ * When the stage's rule is actor-relative the arrivals reach DIFFERENT people,
164
+ * nothing de-duplicates, and the stage settles twice, each settlement opening
165
+ * its own continuation.
166
+ *
167
+ * And that is the likely case, not the exotic one: an actor-relative rule
168
+ * upstream is usually what put two chains there to begin with. So the canvas
169
+ * was most confident exactly where it was least accurate — the same failure
170
+ * as #1042, a picture becoming false by compression, in a shape a reviewer
171
+ * will not question because it looks authoritative.
172
+ *
173
+ * Per-person is true in BOTH cases and is the mechanism rather than one of its
174
+ * outcomes, so an author can work out which case they are in: if the two paths
175
+ * reach the same people it settles once, and if they do not it settles once
176
+ * each. `RouteFlowResolution.merges` says the same thing as "once per COHORT";
177
+ * this is that sentence in words an author of a route already has.
178
+ *
179
+ * WHY THIS LABEL IS NOT CONDITIONAL, WHICH WAS #1058's PREFERRED FIX. The
180
+ * canvas would have to know whether the stage's rule resolves against the
181
+ * ACTOR, and no truthful version of that flag exists to pass it:
182
+ *
183
+ * - Per KIND is wrong for a kind core already ships. `group` dereferences a
184
+ * stored user group, and a group whose own definition is `role_below_actor`
185
+ * is actor-relative while one defined as `role` is not — so the answer for
186
+ * `group` lives in another tenant record, behind `groups:read`, which an
187
+ * author of a route does not necessarily hold. A per-kind boolean would
188
+ * have to lie about `group` in one direction or the other.
189
+ * - The other branch would be wrong too, and not rarely. De-duplication is
190
+ * over OPEN items (migration 112's partial unique index), so even a rule
191
+ * that never reads the actor settles TWICE when the second arrival lands
192
+ * after the first cohort closed — a fan-out where one recipient approves
193
+ * straight into the merge and another rejects the long way round does
194
+ * exactly that. "Not actor-relative, therefore settles once" is the same
195
+ * compression as "settles once", one level down.
196
+ *
197
+ * So a conditional card note would replace one confident falsehood with two
198
+ * quieter ones. The mechanism is the only claim that survives both, and the
199
+ * CASE DISTINCTION is stated where there is room to hedge it honestly: the
200
+ * host's stage inspector (`routeTemplates.inspector.merges`), which is open on
201
+ * the very stage in question at the moment its rule is being chosen.
202
+ *
203
+ * LENGTH IS LOAD-BEARING. Notes are joined into one span clamped to
204
+ * {@link ROUTE_FLOW_MAX_NOTES} lines, so a longer string here pushes a later
205
+ * note off the card — which is #1042 exactly. The replacement is the same
206
+ * length as what it replaces.
207
+ */
208
+ arrivalsMerge: string;
209
+ /**
210
+ * Marker on a stage a document can come back round to.
211
+ *
212
+ * Says a LOOP exists in the design — not that any document has gone round it,
213
+ * which the canvas cannot know. Worth stating because a rework loop is
214
+ * authored deliberately and is invisible afterwards: nothing counts laps
215
+ * (#1037), so a document on its ninth rejection looks like one on its first.
216
+ */
217
+ inCycle: string;
218
+ /** Prefix for the effective quorum, e.g. "all must approve". */
219
+ quorumAll: string;
220
+ quorumAny: string;
221
+ quorumMajority: string;
222
+ /** Optional so older callers keep working; falls back to the English. */
223
+ quorumFirst?: string;
224
+ /** Shown when the graph is larger than the ceiling and has been cut. */
225
+ tooManyNodes: string;
226
+ }
227
+
228
+ const DEFAULT_LABELS: RouteFlowEditorLabels = {
229
+ empty: 'No stages yet. Add the first one to start the flow.',
230
+ addStep: 'Add stage',
231
+ deleteStep: 'Delete stage',
232
+ decision: 'Decision',
233
+ delivery: 'Sent, not asked',
234
+ reaches: 'Reaches',
235
+ people: 'people',
236
+ person: 'person',
237
+ audienceUnavailable: 'Audience size unavailable',
238
+ approved: 'Approved',
239
+ rejected: 'Rejected',
240
+ continues: 'Continues',
241
+ implicit: 'implicit',
242
+ ends: 'Ends here',
243
+ start: 'A document is sent',
244
+ arrivalsMerge: 'Paths merge — 1 item per person',
245
+ inCycle: 'Can come back round — loops',
246
+ quorumAll: 'all must approve',
247
+ quorumAny: 'any one may approve',
248
+ quorumMajority: 'a majority must approve',
249
+ tooManyNodes: 'This flow is larger than the canvas will draw. Showing the first stages only.',
250
+ };
251
+
252
+ export interface RouteFlowEditorProps {
253
+ graph: RouteFlowGraph;
254
+ /**
255
+ * Called with the whole next graph on every edit.
256
+ *
257
+ * The whole graph, not a patch: the editor's unit of work is the canvas, and a
258
+ * patch would ask the host to re-apply changes it did not make.
259
+ */
260
+ onGraphChange?: (graph: RouteFlowGraph) => void;
261
+ /** The step the host's inspector is editing, by `position`. */
262
+ selectedPosition?: number | null;
263
+ onSelectStep?: (position: number | null) => void;
264
+ /**
265
+ * Direction-NEUTRAL by default. See `positionStep` in the model for the full
266
+ * argument: a top-to-bottom flow reads identically in Arabic and English.
267
+ */
268
+ orientation?: RouteFlowOrientation;
269
+ /**
270
+ * The reading direction. Mirrors every horizontal axis, including the handles,
271
+ * so an arrow leaves the face a reader expects it to leave.
272
+ *
273
+ * "Including the handles" is load-bearing and was, for a while, untrue.
274
+ * `@xyflow/react` sets `direction: ltr` on its own container — deliberately,
275
+ * because its transforms are computed in one coordinate system — and that
276
+ * neutralises `insetInlineStart` on anything inside it. The verdict handles
277
+ * were positioned with exactly that property, so they stayed at 30% and 70%
278
+ * from the LEFT in Arabic while {@link slotAt} put the reject lane on the
279
+ * left, which is the "mirrored layout, unmirrored handles" failure
280
+ * {@link handleFaces} warns about: the reject arrow left the far side of its
281
+ * own card and crossed back underneath it.
282
+ *
283
+ * They are placed with a physical `left`, mirrored arithmetically from this
284
+ * prop, so the mirroring does not depend on a container's inherited direction.
285
+ * The card carries its own `dir` for the same reason — `text-start` inside the
286
+ * canvas would otherwise resolve to "left" and left-align Arabic.
287
+ */
288
+ direction?: RouteFlowDirection;
289
+ /**
290
+ * The most nodes to draw. Defaults to {@link ROUTE_FLOW_MAX_NODES}; a host that
291
+ * knows its tenant's `documents.routing_max_steps` should pass it, because THAT
292
+ * is the authoritative limit on how many steps may be saved.
293
+ */
294
+ maxNodes?: number;
295
+ readOnly?: boolean;
296
+ /** How many people a step's rule currently reaches, resolved by the host. */
297
+ audienceFor?: (step: RouteFlowStep) => RouteFlowAudience | undefined;
298
+ /** A human label for a rule kind — the catalogue is a server fact. */
299
+ ruleLabelFor?: (step: RouteFlowStep) => string;
300
+ labels?: Partial<RouteFlowEditorLabels>;
301
+ className?: string;
302
+ }
303
+
304
+ interface RouteFlowNodeData extends Record<string, unknown> {
305
+ step: RouteFlowStep;
306
+ quorumText: string;
307
+ ruleLabel: string;
308
+ audience: RouteFlowAudience | undefined;
309
+ selected: boolean;
310
+ readOnly: boolean;
311
+ notes: string[];
312
+ labels: RouteFlowEditorLabels;
313
+ direction: RouteFlowDirection;
314
+ sourceFace: Position;
315
+ targetFace: Position;
316
+ onSelect: (position: number) => void;
317
+ onDelete: (position: number) => void;
318
+ }
319
+
320
+ /**
321
+ * How big a handle is drawn.
322
+ *
323
+ * `@xyflow/react`'s default is 6×6 CSS px, which the canvas zoom then shrinks:
324
+ * at the zoom a four-stage flow fits at, the measured target was 5.4px on
325
+ * screen. Starting an edge meant hitting a 5px dot, and the alternative gesture
326
+ * a person tries first — dropping on the target CARD — does nothing, because a
327
+ * connection has to end on a handle. 12px is a target a hand can find, and it is
328
+ * still small enough that two of them sit on one 224px face without touching.
329
+ *
330
+ * The other half of that fix is {@link CONNECTION_RADIUS}.
331
+ */
332
+ const HANDLE_CLASS = '!h-3 !w-3 !border-2 !border-card !bg-muted-foreground/60';
333
+
334
+ /**
335
+ * How far from a handle a drop still counts as landing on it.
336
+ *
337
+ * `@xyflow/react` defaults to 20px, so a connection had to be released within
338
+ * 20px of a 5px dot; releasing over the target CARD — the gesture people try
339
+ * first — did nothing at all, and did it silently.
340
+ *
341
+ * Widened to reach from the target handle (top-centre of a card) across most of
342
+ * the card it belongs to, so dropping ON the node connects. Deliberately NOT
343
+ * wide enough to span the gap to the next node: {@link ROUTE_FLOW_NODE_HEIGHT}
344
+ * plus its layout gap is the distance between two stages, and this is well
345
+ * inside half of that, so a drop is never claimed by the card an author was not
346
+ * pointing at.
347
+ */
348
+ const CONNECTION_RADIUS = 80;
349
+
350
+ /**
351
+ * Where a verdict handle sits along the source face, as a physical inset.
352
+ *
353
+ * PHYSICAL, not logical. `insetInlineStart` would be the idiomatic choice and it
354
+ * is the one that was here; it does not work, because `@xyflow/react` forces
355
+ * `direction: ltr` on its container and a logical inset resolves against that
356
+ * rather than against the document. So the mirroring is done here, from the
357
+ * direction the host passed, where nothing can quietly undo it.
358
+ */
359
+ function verdictInset(
360
+ direction: RouteFlowDirection,
361
+ percentFromReadingStart: number
362
+ ): React.CSSProperties {
363
+ // Mirrored by arithmetic and still written as `left`, NOT by switching to
364
+ // `right`. `@xyflow/react` centres a handle on its inset with a
365
+ // `translateX(-50%)` of its own; anchoring from the other edge leaves that
366
+ // translation pulling the wrong way and lands the handle half its own width
367
+ // off — measured 0.65 where 0.70 was meant. One physical property, one
368
+ // percentage, nothing left for a transform to disagree with.
369
+ const fromLeft = direction === 'rtl' ? 100 - percentFromReadingStart : percentFromReadingStart;
370
+
371
+ return { left: `${fromLeft}%` };
372
+ }
373
+
374
+ const FACE: Record<string, Position> = {
375
+ top: Position.Top,
376
+ bottom: Position.Bottom,
377
+ left: Position.Left,
378
+ right: Position.Right,
379
+ };
380
+
381
+ /**
382
+ * One stage.
383
+ *
384
+ * A DECISION step carries TWO source handles — one per verdict — and an ordinary
385
+ * step carries one. That is what makes "draw the approve edge and the reject
386
+ * edge from one node" a gesture rather than a form: which handle a drag starts
387
+ * from IS the verdict, so an author never picks it from a menu afterwards and
388
+ * the two arrows are visibly different before they are drawn.
389
+ *
390
+ * A non-decision step gets no verdict handles at all, because an edge leaving one
391
+ * could never fire — the server refuses it, and an affordance that produces a
392
+ * refusal is worse than no affordance.
393
+ */
394
+ function RouteFlowNodeCard({ data }: NodeProps<Node<RouteFlowNodeData>>) {
395
+ const {
396
+ step,
397
+ quorumText,
398
+ ruleLabel,
399
+ audience,
400
+ selected,
401
+ readOnly,
402
+ notes,
403
+ labels,
404
+ direction,
405
+ sourceFace,
406
+ targetFace,
407
+ onSelect,
408
+ onDelete,
409
+ } = data;
410
+
411
+ const title = step.label !== null && step.label !== '' ? step.label : ruleLabel;
412
+
413
+ return (
414
+ <div
415
+ // The card carries its OWN `dir`. `@xyflow/react` forces `direction: ltr`
416
+ // on its container, so without this every `text-start` and every `end-*`
417
+ // inside a node resolves to the left-to-right answer and Arabic labels sit
418
+ // left-aligned in a right-to-left page.
419
+ dir={direction}
420
+ className={cn(
421
+ 'flex flex-col gap-1 rounded-lg border bg-card px-3 py-2 text-start shadow-sm transition-colors',
422
+ selected ? 'border-primary ring-2 ring-primary/30' : 'border-border'
423
+ )}
424
+ style={{ width: ROUTE_FLOW_NODE_WIDTH, height: ROUTE_FLOW_NODE_HEIGHT }}
425
+ data-slot="route-flow-node"
426
+ data-position={step.position}
427
+ data-decision={step.decision ? 'true' : 'false'}
428
+ data-satisfied-by={step.satisfiedBy}
429
+ data-kind={step.kind ?? undefined}
430
+ >
431
+ <Handle type="target" position={targetFace} className={HANDLE_CLASS} />
432
+
433
+ <button
434
+ type="button"
435
+ onClick={() => onSelect(step.position)}
436
+ className="flex min-w-0 flex-col text-start outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
437
+ >
438
+ <span className="flex items-center gap-1.5">
439
+ <span className="truncate text-sm font-medium text-foreground">{title}</span>
440
+ {step.decision && (
441
+ <span className="shrink-0 rounded bg-primary/10 px-1 text-xs font-medium uppercase text-primary">
442
+ {labels.decision}
443
+ </span>
444
+ )}
445
+ {/* A BADGE, NOT A NOTE, and that is a height decision rather than a
446
+ style one. The card's height is DERIVED from its rows and the note
447
+ clamp is derived from ROUTE_FLOW_MAX_NOTES, whose value is a
448
+ PROVEN maximum over what notesFor() can emit — a fourth note would
449
+ make the card silently drop one, which is exactly the #1042 defect
450
+ those derivations were built to prevent.
451
+
452
+ A delivery stage is never a decision stage (the server refuses the
453
+ pair at three layers), so the two badges can never both appear and
454
+ the title row cannot grow because of this. */}
455
+ {step.satisfiedBy === 'delivery' && (
456
+ <span
457
+ className="shrink-0 rounded bg-muted px-1 text-xs font-medium uppercase text-muted-foreground"
458
+ data-slot="route-flow-node-delivery-badge"
459
+ >
460
+ {labels.delivery}
461
+ </span>
462
+ )}
463
+ {/* WHIT-921: never a decision and never a delivery, so this badge
464
+ cannot share the row with either. */}
465
+ {step.kind === 'finalise' && labels.finalise !== undefined && (
466
+ <span
467
+ className="shrink-0 rounded bg-muted px-1 text-xs font-medium uppercase text-muted-foreground"
468
+ data-slot="route-flow-node-finalise-badge"
469
+ >
470
+ {labels.finalise}
471
+ </span>
472
+ )}
473
+ </span>
474
+ {/* The RULE, always visible. A card that showed only an author's label
475
+ would let "Dean" sit on a node that actually reaches every registrar,
476
+ and nothing on screen would say so. */}
477
+ <span className="truncate text-xs text-muted-foreground">{ruleLabel}</span>
478
+ </button>
479
+
480
+ {/* THE COUNT, NEVER A ROSTER — the line that makes a type-node honest: one
481
+ card, and the number of people behind it. */}
482
+ <span className="truncate text-xs text-muted-foreground">
483
+ {audience === undefined
484
+ ? ' '
485
+ : audience.count !== null
486
+ ? `${labels.reaches} ${audience.count.toLocaleString()} ${
487
+ audience.count === 1 ? labels.person : labels.people
488
+ }`
489
+ : (audience.unavailableReason ?? labels.audienceUnavailable)}
490
+ </span>
491
+
492
+ {/* THE QUORUM, on its own row.
493
+
494
+ It is shown for every decision stage, INDEPENDENTLY of whether the
495
+ count resolved. It used to be rendered inside the count branch, so a
496
+ viewer who could not preview audiences (a 403 there is ordinary — the
497
+ draft preview needs `groups:write`, which designing a flow does not
498
+ imply) saw a gate with no indication of what would satisfy it. The two
499
+ facts have different sources and only one of them can fail; binding
500
+ them together made the reliable one vanish with the unreliable one.
501
+
502
+ It was then joined onto the COUNT's line with a separator, and the pair
503
+ overflowed one 224px row: "Reaches 1 people · all must appr…" — a
504
+ quorum made unconditionally visible and then truncated mid-word, which
505
+ is the same disappearance by a slower route (#1042). Its own row costs
506
+ 16px of a height that is now derived from the rows it holds, and no
507
+ audience string can crowd it out. */}
508
+ <span className="truncate text-xs text-muted-foreground">
509
+ {step.decision ? quorumText : ' '}
510
+ </span>
511
+
512
+ {notes.length > 0 && (
513
+ <span
514
+ data-slot="route-flow-notes"
515
+ // Clamped from the SAME constant the card's height is budgeted against
516
+ // (see ROUTE_FLOW_MAX_NOTES). Tailwind's `line-clamp-N` is a static
517
+ // class and could only repeat the number as a literal, which is
518
+ // precisely how the two drifted apart: the height was raised to hold
519
+ // three lines while the clamp stayed at two, and a stage carrying
520
+ // merge + loop + "Rejected: Ends here" dropped the last of them.
521
+ style={{
522
+ display: '-webkit-box',
523
+ WebkitBoxOrient: 'vertical',
524
+ WebkitLineClamp: ROUTE_FLOW_MAX_NOTES,
525
+ overflow: 'hidden',
526
+ }}
527
+ className="text-xs uppercase leading-tight tracking-wide text-muted-foreground"
528
+ >
529
+ {notes.join(' · ')}
530
+ </span>
531
+ )}
532
+
533
+ {!readOnly && (
534
+ <button
535
+ type="button"
536
+ onClick={() => onDelete(step.position)}
537
+ aria-label={labels.deleteStep}
538
+ className="nodrag absolute end-1 top-1 rounded px-1 text-xs text-muted-foreground hover:text-destructive"
539
+ >
540
+ &times;
541
+ </button>
542
+ )}
543
+
544
+ {/* A decision step's two verdict handles are stacked on the source face and
545
+ coloured, so the gesture and the picture agree before an edge exists.
546
+
547
+ On a horizontal face the two are offset along the VERTICAL axis, which
548
+ no reading direction mirrors, so only the top/bottom case consults
549
+ `direction`. */}
550
+ {step.decision ? (
551
+ <>
552
+ <Handle
553
+ id="approved"
554
+ type="source"
555
+ position={sourceFace}
556
+ style={
557
+ sourceFace === Position.Bottom || sourceFace === Position.Top
558
+ ? verdictInset(direction, 30)
559
+ : { top: '35%' }
560
+ }
561
+ className={cn(HANDLE_CLASS, '!bg-emerald-500')}
562
+ data-testid={`approve-handle-${step.position}`}
563
+ />
564
+ <Handle
565
+ id="rejected"
566
+ type="source"
567
+ position={sourceFace}
568
+ style={
569
+ sourceFace === Position.Bottom || sourceFace === Position.Top
570
+ ? verdictInset(direction, 70)
571
+ : { top: '70%' }
572
+ }
573
+ className={cn(HANDLE_CLASS, '!bg-rose-500')}
574
+ data-testid={`reject-handle-${step.position}`}
575
+ />
576
+ </>
577
+ ) : (
578
+ <Handle type="source" position={sourceFace} className={HANDLE_CLASS} />
579
+ )}
580
+ </div>
581
+ );
582
+ }
583
+
584
+ const nodeTypes: NodeTypes = { routeFlowStep: RouteFlowNodeCard };
585
+
586
+ /** The app's own theme (the `dark` class on the page), followed live. */
587
+ function useAppColorMode(): 'light' | 'dark' {
588
+ const [mode, setMode] = React.useState<'light' | 'dark'>('light');
589
+ React.useEffect(() => {
590
+ const root = document.documentElement;
591
+ const read = () => setMode(root.classList.contains('dark') ? 'dark' : 'light');
592
+ read();
593
+ const observer = new MutationObserver(read);
594
+ observer.observe(root, { attributes: true, attributeFilter: ['class'] });
595
+ return () => observer.disconnect();
596
+ }, []);
597
+ return mode;
598
+ }
599
+
600
+ interface RouteFlowEdgeData extends Record<string, unknown> {
601
+ kind: 'drawn' | 'derived';
602
+ on: RouteFlowVerdict | 'continue';
603
+ text: string;
604
+ }
605
+
606
+ /**
607
+ * How far a transition's label is nudged off the middle of its own curve, by
608
+ * verdict.
609
+ *
610
+ * ─────────────────────────────────────────────────────────────────────────
611
+ * WHY A LABEL NEEDS AN OFFSET AT ALL
612
+ * ─────────────────────────────────────────────────────────────────────────
613
+ * Two transitions running BETWEEN THE SAME PAIR OF STAGES in opposite
614
+ * directions have, to within a few pixels, the same midpoint — and a built-in
615
+ * edge draws its label at exactly that midpoint. So a rework loop, which is the
616
+ * commonest real design there is, printed both labels on top of each other:
617
+ * "Approved (imp Rejected" (#1042).
618
+ *
619
+ * That is an anti-parallel PAIR, not "two edges leaving one node" — two edges
620
+ * leaving one node diverge, and their labels separate on their own. The pair is
621
+ * always a pair of DIFFERENT verdicts (one destination per verdict per stage is
622
+ * enforced by the schema and by `onConnect`), so nudging by verdict is enough to
623
+ * separate any pair that can exist, and it does it deterministically rather than
624
+ * by a collision search whose answer would move as nodes are dragged.
625
+ *
626
+ * Bigger than a label's own line box, so the two clear rather than touch.
627
+ */
628
+ const LABEL_NUDGE: Record<RouteFlowVerdict | 'continue', number> = {
629
+ approved: -22,
630
+ continue: 0,
631
+ rejected: 22,
632
+ };
633
+
634
+ /**
635
+ * One transition.
636
+ *
637
+ * A custom edge only so the label can be moved; everything else is
638
+ * `@xyflow/react`'s own, including the invisible interaction path that makes an
639
+ * edge selectable and therefore deletable.
640
+ *
641
+ * The label is drawn on a background chip because it sits over a dotted
642
+ * background and, in a loop, over the other arrow.
643
+ */
644
+ function RouteFlowTransitionEdge({
645
+ sourceX,
646
+ sourceY,
647
+ sourcePosition,
648
+ targetX,
649
+ targetY,
650
+ targetPosition,
651
+ markerEnd,
652
+ style,
653
+ data,
654
+ }: EdgeProps<Edge<RouteFlowEdgeData>>) {
655
+ const [path, labelX, labelY] = getBezierPath({
656
+ sourceX,
657
+ sourceY,
658
+ sourcePosition,
659
+ targetX,
660
+ targetY,
661
+ targetPosition,
662
+ });
663
+
664
+ return (
665
+ <BaseEdge
666
+ path={path}
667
+ markerEnd={markerEnd}
668
+ style={style}
669
+ label={data?.text}
670
+ labelX={labelX}
671
+ labelY={labelY + LABEL_NUDGE[data?.on ?? 'continue']}
672
+ // SVG text defaults to black and `@xyflow/react` sets no fill of its own,
673
+ // so an edge label was black on a near-black canvas in dark mode. Both
674
+ // colours come from the theme, so the chip and its text move together.
675
+ // `--text-xs` (13px, the floor, A.1), and it grows with Larger text.
676
+ labelStyle={{ fontSize: 'var(--text-xs)', fill: 'var(--color-muted-foreground, #64748b)' }}
677
+ labelShowBg
678
+ labelBgPadding={[4, 2]}
679
+ labelBgBorderRadius={3}
680
+ labelBgStyle={{ fill: 'var(--color-card, #ffffff)', fillOpacity: 0.92 }}
681
+ />
682
+ );
683
+ }
684
+
685
+ const edgeTypes: EdgeTypes = { routeFlowTransition: RouteFlowTransitionEdge };
686
+
687
+ /**
688
+ * How the canvas frames itself.
689
+ *
690
+ * `maxZoom` is the important one and it was missing. `@xyflow/react` defaults a
691
+ * fit to a maximum of 2×, and `fitView` runs on MOUNT — which, for a template
692
+ * being authored from nothing, is the moment the FIRST node appears. One node
693
+ * fits at 2×, the viewport froze there, and stages 2, 3 and 4 were then added
694
+ * off-screen: the measured result was `scale(2)` with one of four nodes visible,
695
+ * for every new flow anybody made (#1042).
696
+ *
697
+ * Capped at 1 rather than at some larger number because a node card is designed
698
+ * at a fixed pixel size and a magnified one is not more legible, only bigger.
699
+ * This bounds the automatic fit ONLY — the `maxZoom` prop is left at its default
700
+ * so a person can still zoom in past this by hand.
701
+ */
702
+ // More room above than around: the start pill sits over the first stage.
703
+ const FIT_VIEW = { maxZoom: 1, padding: { top: '56px', right: '24px', bottom: '24px', left: '24px' } as const };
704
+
705
+ export function RouteFlowEditor({
706
+ graph,
707
+ onGraphChange,
708
+ selectedPosition = null,
709
+ onSelectStep,
710
+ orientation = 'vertical',
711
+ direction = 'ltr',
712
+ maxNodes = ROUTE_FLOW_MAX_NODES,
713
+ readOnly = false,
714
+ audienceFor,
715
+ ruleLabelFor,
716
+ labels: labelOverrides,
717
+ className,
718
+ }: RouteFlowEditorProps) {
719
+ const labels = React.useMemo<RouteFlowEditorLabels>(
720
+ () => ({ ...DEFAULT_LABELS, ...labelOverrides }),
721
+ [labelOverrides]
722
+ );
723
+
724
+ const faces = handleFaces(orientation, direction);
725
+ const sourceFace = FACE[faces.source] ?? Position.Bottom;
726
+ const targetFace = FACE[faces.target] ?? Position.Top;
727
+
728
+ const ordered = React.useMemo(() => stepsInOrder(graph.steps), [graph.steps]);
729
+ const cut = ordered.length > maxNodes;
730
+ const drawn = cut ? ordered.slice(0, maxNodes) : ordered;
731
+
732
+ const resolution = React.useMemo(() => resolveTransitions(graph), [graph]);
733
+ const { transitions } = resolution;
734
+
735
+ const quorumLabel = React.useCallback(
736
+ (step: RouteFlowStep): string => {
737
+ switch (effectiveQuorum(step, graph)) {
738
+ case 'any':
739
+ return labels.quorumAny;
740
+ case 'majority':
741
+ return labels.quorumMajority;
742
+ case 'first':
743
+ return labels.quorumFirst ?? 'the first answer decides';
744
+ default:
745
+ return labels.quorumAll;
746
+ }
747
+ },
748
+ [graph, labels]
749
+ );
750
+
751
+ const emit = React.useCallback(
752
+ (next: RouteFlowGraph) => {
753
+ onGraphChange?.(next);
754
+ },
755
+ [onGraphChange]
756
+ );
757
+
758
+ const handleDelete = React.useCallback(
759
+ (position: number) => {
760
+ // Renumber and rewrite edges in the same pass — see `renumber`. `position`
761
+ // is also the FALLTHROUGH order, so a delete that left a gap would leave
762
+ // an author reading arrows that no longer match the list.
763
+ emit(
764
+ renumber({
765
+ ...graph,
766
+ steps: graph.steps.filter((s) => s.position !== position),
767
+ edges: graph.edges.filter((e) => e.from !== position && e.to !== position),
768
+ })
769
+ );
770
+ if (selectedPosition === position) {
771
+ onSelectStep?.(null);
772
+ }
773
+ },
774
+ [emit, graph, onSelectStep, selectedPosition]
775
+ );
776
+
777
+ const [nodes, setNodes, onNodesChange] = useNodesState<Node<RouteFlowNodeData>>([]);
778
+
779
+ React.useEffect(() => {
780
+ // A graph nothing has ever arranged gets one tidy layout; anything an author
781
+ // has touched keeps the arrangement they made. See `needsAutoLayout` for why
782
+ // the test is deliberately narrow.
783
+ const placed = needsAutoLayout(drawn)
784
+ ? autoLayout({ ...graph, steps: drawn }, orientation, direction)
785
+ : drawn;
786
+
787
+ setNodes(
788
+ placed.map((step) => {
789
+ // WHICH notes a stage carries is decided in the model, by `notesFor`,
790
+ // and only the wording is decided here. That split is what lets
791
+ // ROUTE_FLOW_MAX_NOTES — the number the card's height is budgeted
792
+ // against — be an assertion a test can make.
793
+ const notes = notesFor(step.position, resolution).map((note) => {
794
+ if (note.kind === 'merge') return labels.arrivalsMerge;
795
+ if (note.kind === 'cycle') return labels.inCycle;
796
+ const on =
797
+ note.on === 'approved'
798
+ ? labels.approved
799
+ : note.on === 'rejected'
800
+ ? labels.rejected
801
+ : labels.continues;
802
+ return `${on}: ${labels.ends}`;
803
+ });
804
+
805
+ return {
806
+ id: String(step.position),
807
+ type: 'routeFlowStep',
808
+ position: { x: step.canvasX, y: step.canvasY },
809
+ draggable: !readOnly,
810
+ data: {
811
+ step,
812
+ quorumText: quorumLabel(step),
813
+ ruleLabel: ruleLabelFor?.(step) ?? step.ruleKind,
814
+ audience: audienceFor?.(step),
815
+ selected: selectedPosition === step.position,
816
+ readOnly,
817
+ notes,
818
+ labels,
819
+ direction,
820
+ sourceFace,
821
+ targetFace,
822
+ onSelect: (p: number) => onSelectStep?.(p),
823
+ onDelete: handleDelete,
824
+ },
825
+ };
826
+ })
827
+ );
828
+ }, [
829
+ audienceFor,
830
+ direction,
831
+ drawn,
832
+ graph,
833
+ handleDelete,
834
+ labels,
835
+ onSelectStep,
836
+ orientation,
837
+ quorumLabel,
838
+ readOnly,
839
+ ruleLabelFor,
840
+ resolution,
841
+ selectedPosition,
842
+ setNodes,
843
+ sourceFace,
844
+ targetFace,
845
+ ]);
846
+
847
+ const edges = React.useMemo<Edge[]>(() => {
848
+ const visible = new Set(drawn.map((s) => s.position));
849
+
850
+ return transitions
851
+ .filter((t) => visible.has(t.from) && visible.has(t.to))
852
+ .map((t) => {
853
+ const isReject = t.on === 'rejected';
854
+ const isApprove = t.on === 'approved';
855
+ const label =
856
+ t.on === 'approved'
857
+ ? labels.approved
858
+ : t.on === 'rejected'
859
+ ? labels.rejected
860
+ : labels.continues;
861
+
862
+ return {
863
+ id: `${t.from}-${t.on}-${t.to}`,
864
+ source: String(t.from),
865
+ target: String(t.to),
866
+ sourceHandle: isApprove || isReject ? t.on : undefined,
867
+ type: 'routeFlowTransition',
868
+ // A DERIVED transition is dashed and says so. It is a real arrow — the
869
+ // engine will take it — but it is not one the author drew, and it
870
+ // cannot be deleted except by reordering the steps that imply it.
871
+ animated: false,
872
+ style: {
873
+ strokeDasharray: t.kind === 'derived' ? '4 3' : undefined,
874
+ stroke: isReject
875
+ ? 'var(--color-rose-500, #f43f5e)'
876
+ : isApprove
877
+ ? 'var(--color-emerald-500, #10b981)'
878
+ : undefined,
879
+ },
880
+ markerEnd: { type: MarkerType.ArrowClosed },
881
+ // The label travels in `data` rather than in `label`, because the
882
+ // custom edge draws it at a nudged position — see LABEL_NUDGE.
883
+ data: {
884
+ kind: t.kind,
885
+ on: t.on,
886
+ text: t.kind === 'derived' ? `${label} (${labels.implicit})` : label,
887
+ },
888
+ } satisfies Edge;
889
+ });
890
+ }, [drawn, labels, transitions]);
891
+
892
+ /**
893
+ * A drag between two handles becomes a stored edge.
894
+ *
895
+ * The verdict is the SOURCE HANDLE's id, never a guess: an author who dragged
896
+ * from the green handle drew an approve edge, and there is no second place that
897
+ * decision could be made differently. A drag from a plain (non-decision) handle
898
+ * is dropped, because such an edge could never fire and the server would refuse
899
+ * it — better to have the gesture do nothing visible than to save something
900
+ * that comes back as an error.
901
+ */
902
+ const onConnect = React.useCallback(
903
+ (connection: Connection) => {
904
+ if (readOnly) return;
905
+
906
+ const verdict = connection.sourceHandle;
907
+ if (verdict !== 'approved' && verdict !== 'rejected') return;
908
+
909
+ const from = Number(connection.source);
910
+ const to = Number(connection.target);
911
+ if (!Number.isFinite(from) || !Number.isFinite(to) || from === to) return;
912
+
913
+ // One destination per verdict per node — the same uniqueness the schema
914
+ // enforces. Re-drawing replaces rather than adding a second arrow, which
915
+ // is what an author dragging again means.
916
+ const kept = graph.edges.filter((e) => !(e.from === from && e.verdict === verdict));
917
+ emit({ ...graph, edges: [...kept, { from, to, verdict: verdict as RouteFlowVerdict }] });
918
+ },
919
+ [emit, graph, readOnly]
920
+ );
921
+
922
+ const onEdgesDelete = React.useCallback(
923
+ (removed: Edge[]) => {
924
+ if (readOnly) return;
925
+ // Only DRAWN edges can be removed. A derived one is a consequence of the
926
+ // step order; deleting the arrow without deleting the cause would show a
927
+ // canvas the engine disagrees with.
928
+ const drawnIds = new Set(removed.filter((e) => (e.data as { kind?: string })?.kind === 'drawn').map((e) => e.id));
929
+ if (drawnIds.size === 0) return;
930
+
931
+ emit({
932
+ ...graph,
933
+ edges: graph.edges.filter((e) => !drawnIds.has(`${e.from}-${e.verdict}-${e.to}`)),
934
+ });
935
+ },
936
+ [emit, graph, readOnly]
937
+ );
938
+
939
+ /**
940
+ * Re-frame the canvas when the flow gains or loses a stage.
941
+ *
942
+ * `fitView` alone only ever fires once, on mount. Everything an author does
943
+ * after that — and on a new template, everything they do at all — happens to a
944
+ * viewport that was framed for a graph with one node in it.
945
+ *
946
+ * Keyed on the node COUNT and nothing else, deliberately. Re-fitting on every
947
+ * graph change would yank the canvas out from under someone who had panned to
948
+ * a corner and was renaming a stage; adding or deleting a stage is the one
949
+ * edit that changes what there is to look at.
950
+ *
951
+ * `requestAnimationFrame` because the fit needs the new node MEASURED, and
952
+ * this effect runs in the same commit that first renders it.
953
+ */
954
+ const instance = React.useRef<ReactFlowInstance<Node<RouteFlowNodeData>, Edge> | null>(null);
955
+ const onInit = React.useCallback(
956
+ (next: ReactFlowInstance<Node<RouteFlowNodeData>, Edge>) => {
957
+ instance.current = next;
958
+ },
959
+ []
960
+ );
961
+
962
+ const colorMode = useAppColorMode();
963
+
964
+ const nodeCount = drawn.length;
965
+ React.useEffect(() => {
966
+ if (nodeCount === 0) return undefined;
967
+ const frame = requestAnimationFrame(() => {
968
+ void instance.current?.fitView(FIT_VIEW);
969
+ });
970
+ return () => cancelAnimationFrame(frame);
971
+ }, [nodeCount]);
972
+
973
+ const onNodeDragStop = React.useCallback(
974
+ (_event: MouseEvent | TouchEvent, node: Node) => {
975
+ if (readOnly) return;
976
+ const position = Number(node.id);
977
+ emit({
978
+ ...graph,
979
+ steps: graph.steps.map((s) =>
980
+ s.position === position
981
+ ? { ...s, canvasX: Math.round(node.position.x), canvasY: Math.round(node.position.y) }
982
+ : s
983
+ ),
984
+ });
985
+ },
986
+ [emit, graph, readOnly]
987
+ );
988
+
989
+ return (
990
+ <div className={cn('relative h-[32rem] w-full rounded-lg border border-border bg-card', className)}>
991
+ {cut && (
992
+ <p
993
+ className="absolute inset-x-0 top-0 z-10 bg-amber-500/10 px-3 py-1 text-xs text-foreground"
994
+ role="status"
995
+ >
996
+ {labels.tooManyNodes}
997
+ </p>
998
+ )}
999
+ {drawn.length === 0 ? (
1000
+ <p className="flex h-full items-center justify-center px-6 text-center text-sm text-muted-foreground">
1001
+ {labels.empty}
1002
+ </p>
1003
+ ) : (
1004
+ <ReactFlow
1005
+ nodes={nodes}
1006
+ edges={edges}
1007
+ nodeTypes={nodeTypes}
1008
+ edgeTypes={edgeTypes}
1009
+ onInit={onInit}
1010
+ onNodesChange={onNodesChange}
1011
+ onNodeDragStop={onNodeDragStop}
1012
+ onConnect={onConnect}
1013
+ onEdgesDelete={onEdgesDelete}
1014
+ nodesDraggable={!readOnly}
1015
+ nodesConnectable={!readOnly}
1016
+ elementsSelectable
1017
+ connectionRadius={CONNECTION_RADIUS}
1018
+ fitView
1019
+ fitViewOptions={FIT_VIEW}
1020
+ // react-flow's default minZoom (0.5) defeats fitView on anything wider
1021
+ // than about twice the canvas: the fit clamps at 0.5 and centres,
1022
+ // silently clipping the outermost nodes. The OU hub hit this first and
1023
+ // the `flow` block records it; a route flow with a reject lane is wide
1024
+ // enough to hit it sooner.
1025
+ minZoom={0.1}
1026
+ // `@xyflow/react` defaults to its own `light` class, and the design
1027
+ // tokens also define a `.light` theme, so in dark mode every card
1028
+ // came out white. The canvas follows the app's theme instead.
1029
+ colorMode={colorMode}
1030
+ proOptions={{ hideAttribution: true }}
1031
+ >
1032
+ <Panel position="top-center">
1033
+ <span
1034
+ className="whitespace-nowrap rounded-full border border-border bg-card px-3 py-1 text-sm text-foreground"
1035
+ data-slot="route-flow-start"
1036
+ >
1037
+ {labels.start}
1038
+ </span>
1039
+ </Panel>
1040
+ <Background variant={BackgroundVariant.Dots} gap={16} size={1} />
1041
+ <Controls showInteractive={false} />
1042
+ </ReactFlow>
1043
+ )}
1044
+ </div>
1045
+ );
1046
+ }
1047
+
1048
+ /**
1049
+ * Append a stage to a flow, placed in the next free slot.
1050
+ *
1051
+ * Exported beside the editor rather than living inside it because ADDING a stage
1052
+ * needs a rule, and choosing one is the host's inspector's job. The host builds
1053
+ * the step and calls this to get the placement and the numbering right.
1054
+ */
1055
+ export function appendStep(
1056
+ graph: RouteFlowGraph,
1057
+ step: Omit<RouteFlowStep, 'position' | 'canvasX' | 'canvasY'>,
1058
+ orientation: RouteFlowOrientation = 'vertical',
1059
+ direction: RouteFlowDirection = 'ltr'
1060
+ ): RouteFlowGraph {
1061
+ const positions = graph.steps.map((s) => s.position);
1062
+ const position = positions.length === 0 ? 1 : Math.max(...positions) + 1;
1063
+ const slot = nextSlot(graph, orientation, direction);
1064
+
1065
+ // WHIT-921: the final document stage is always last, so a stage added after
1066
+ // it takes its place and it moves down one. Edges name positions, so the
1067
+ // ones arriving at it follow it.
1068
+ const last = graph.steps.find((s) => s.position === position - 1);
1069
+ if (step.kind !== 'finalise' && last !== undefined && last.kind === 'finalise') {
1070
+ const moved = last.position;
1071
+ return {
1072
+ ...graph,
1073
+ steps: [
1074
+ ...graph.steps.map((s) =>
1075
+ s.position === moved ? { ...s, position, canvasX: slot.canvasX, canvasY: slot.canvasY } : s
1076
+ ),
1077
+ { ...step, position: moved, canvasX: last.canvasX, canvasY: last.canvasY },
1078
+ ],
1079
+ edges: graph.edges.map((e) => (e.to === moved ? { ...e, to: position } : e)),
1080
+ };
1081
+ }
1082
+
1083
+ return {
1084
+ ...graph,
1085
+ steps: [...graph.steps, { ...step, position, ...slot }],
1086
+ };
1087
+ }