@whity/ui 0.0.0-stage → 0.5.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 (169) hide show
  1. package/README.md +107 -3
  2. package/package.json +192 -6
  3. package/src/access-denied.stories.tsx +179 -0
  4. package/src/access-denied.tsx +305 -0
  5. package/src/action-proposal.tsx +302 -0
  6. package/src/actor-chip.tsx +71 -0
  7. package/src/agent-activity.tsx +163 -0
  8. package/src/agent-collaboration.stories.tsx +156 -0
  9. package/src/agent-run-status.tsx +196 -0
  10. package/src/alert-dialog.stories.tsx +45 -0
  11. package/src/alert-dialog.tsx +147 -0
  12. package/src/alert.stories.tsx +91 -0
  13. package/src/alert.tsx +89 -0
  14. package/src/app-sidebar.stories.tsx +195 -0
  15. package/src/app-sidebar.tsx +500 -0
  16. package/src/approval-queue.tsx +108 -0
  17. package/src/audience-group-picker.stories.tsx +198 -0
  18. package/src/audience-group-picker.tsx +362 -0
  19. package/src/audience-people-picker.stories.tsx +102 -0
  20. package/src/audience-people-picker.tsx +279 -0
  21. package/src/avatar.tsx +83 -0
  22. package/src/badge.stories.tsx +105 -0
  23. package/src/badge.tsx +68 -0
  24. package/src/beta-warning.stories.tsx +79 -0
  25. package/src/beta-warning.tsx +189 -0
  26. package/src/bilingual-input.stories.tsx +82 -0
  27. package/src/bilingual-input.tsx +183 -0
  28. package/src/breadcrumb.stories.tsx +51 -0
  29. package/src/breadcrumb.tsx +90 -0
  30. package/src/button.stories.tsx +87 -0
  31. package/src/button.tsx +118 -0
  32. package/src/card.stories.tsx +423 -0
  33. package/src/card.tsx +180 -0
  34. package/src/chart.stories.tsx +66 -0
  35. package/src/chart.tsx +228 -0
  36. package/src/checkbox.stories.tsx +62 -0
  37. package/src/checkbox.tsx +54 -0
  38. package/src/collapsible.stories.tsx +48 -0
  39. package/src/collapsible.tsx +34 -0
  40. package/src/color-card.stories.tsx +61 -0
  41. package/src/color-card.tsx +270 -0
  42. package/src/color-picker.stories.tsx +65 -0
  43. package/src/color-picker.tsx +425 -0
  44. package/src/command-palette.tsx +306 -0
  45. package/src/copy-block.stories.tsx +38 -0
  46. package/src/copy-block.tsx +85 -0
  47. package/src/data-table.stories.tsx +200 -0
  48. package/src/data-table.tsx +1106 -0
  49. package/src/date-picker.stories.tsx +61 -0
  50. package/src/date-picker.tsx +422 -0
  51. package/src/design-cards.stories.tsx +458 -0
  52. package/src/dialog.stories.tsx +48 -0
  53. package/src/dialog.tsx +166 -0
  54. package/src/documents/barcode-svg.stories.tsx +72 -0
  55. package/src/documents/barcode-svg.tsx +79 -0
  56. package/src/dropdown-menu.stories.tsx +77 -0
  57. package/src/dropdown-menu.tsx +271 -0
  58. package/src/editor/behaviour.ts +279 -0
  59. package/src/editor/block-ids.ts +44 -0
  60. package/src/editor/block-list.tsx +101 -0
  61. package/src/editor/block-toolbar.tsx +477 -0
  62. package/src/editor/bubble.tsx +93 -0
  63. package/src/editor/catalogue.ts +103 -0
  64. package/src/editor/collab-rail.tsx +746 -0
  65. package/src/editor/collab.stories.tsx +207 -0
  66. package/src/editor/collab.ts +87 -0
  67. package/src/editor/contract.ts +408 -0
  68. package/src/editor/convert.ts +362 -0
  69. package/src/editor/doc-editor.stories.tsx +98 -0
  70. package/src/editor/doc-editor.tsx +1287 -0
  71. package/src/editor/editor.css +536 -0
  72. package/src/editor/extensions.ts +86 -0
  73. package/src/editor/field-picker.tsx +107 -0
  74. package/src/editor/fields.ts +100 -0
  75. package/src/editor/gutter.tsx +367 -0
  76. package/src/editor/index.ts +22 -0
  77. package/src/editor/label-sheet.tsx +289 -0
  78. package/src/editor/labels.ts +310 -0
  79. package/src/editor/link-tools.tsx +141 -0
  80. package/src/editor/node-views.tsx +450 -0
  81. package/src/editor/page-view.tsx +353 -0
  82. package/src/editor/publish-check.tsx +182 -0
  83. package/src/editor/rich-blocks.stories.tsx +146 -0
  84. package/src/editor/sample.ts +40 -0
  85. package/src/editor/schema-rich.ts +150 -0
  86. package/src/editor/schema.ts +315 -0
  87. package/src/editor/services.tsx +127 -0
  88. package/src/editor/slash.ts +64 -0
  89. package/src/editor/suggesting.ts +372 -0
  90. package/src/editor/suggestions.ts +763 -0
  91. package/src/editor/table-keys.ts +66 -0
  92. package/src/editor/templates.stories.tsx +324 -0
  93. package/src/editor/toolbar.tsx +358 -0
  94. package/src/empty-state.stories.tsx +51 -0
  95. package/src/empty-state.tsx +100 -0
  96. package/src/empty-state.usage-notes.md +30 -0
  97. package/src/form.stories.tsx +112 -0
  98. package/src/form.tsx +176 -0
  99. package/src/globals.css +20 -0
  100. package/src/icon-button.tsx +85 -0
  101. package/src/icon-map.ts +244 -0
  102. package/src/icon.tsx +41 -0
  103. package/src/index.ts +67 -0
  104. package/src/input.stories.tsx +157 -0
  105. package/src/input.tsx +759 -0
  106. package/src/locked-screen.stories.tsx +29 -0
  107. package/src/locked-screen.tsx +61 -0
  108. package/src/mark.tsx +62 -0
  109. package/src/math-text.stories.tsx +33 -0
  110. package/src/math-text.tsx +43 -0
  111. package/src/menu-bar.stories.tsx +198 -0
  112. package/src/menu-bar.tsx +373 -0
  113. package/src/money/currency.ts +230 -0
  114. package/src/page-header.stories.tsx +95 -0
  115. package/src/page-header.tsx +122 -0
  116. package/src/page-shell.stories.tsx +42 -0
  117. package/src/page-shell.tsx +32 -0
  118. package/src/pagination.stories.tsx +45 -0
  119. package/src/pagination.tsx +98 -0
  120. package/src/plugin-card.stories.tsx +180 -0
  121. package/src/plugin-card.tsx +848 -0
  122. package/src/popover.stories.tsx +48 -0
  123. package/src/popover.tsx +55 -0
  124. package/src/radio-group.stories.tsx +26 -0
  125. package/src/radio-group.tsx +44 -0
  126. package/src/route-flow/editor.tsx +1014 -0
  127. package/src/route-flow/model.ts +716 -0
  128. package/src/scope-grant.tsx +139 -0
  129. package/src/screen-too-small.stories.tsx +61 -0
  130. package/src/screen-too-small.tsx +104 -0
  131. package/src/select.stories.tsx +44 -0
  132. package/src/select.tsx +197 -0
  133. package/src/separator.stories.tsx +34 -0
  134. package/src/separator.tsx +34 -0
  135. package/src/sheet.stories.tsx +49 -0
  136. package/src/sheet.tsx +168 -0
  137. package/src/skeleton.stories.tsx +28 -0
  138. package/src/skeleton.tsx +19 -0
  139. package/src/slider.stories.tsx +78 -0
  140. package/src/slider.tsx +300 -0
  141. package/src/spinner.stories.tsx +33 -0
  142. package/src/spinner.tsx +55 -0
  143. package/src/switch.stories.tsx +42 -0
  144. package/src/switch.tsx +41 -0
  145. package/src/switcher.stories.tsx +111 -0
  146. package/src/switcher.tsx +131 -0
  147. package/src/table.stories.tsx +48 -0
  148. package/src/table.tsx +121 -0
  149. package/src/tabs.stories.tsx +74 -0
  150. package/src/tabs.tsx +90 -0
  151. package/src/tag-input.stories.tsx +67 -0
  152. package/src/tag-input.tsx +117 -0
  153. package/src/tenant-logo.tsx +63 -0
  154. package/src/tenant-switcher.stories.tsx +38 -0
  155. package/src/tenant-switcher.tsx +164 -0
  156. package/src/textarea.stories.tsx +27 -0
  157. package/src/textarea.tsx +18 -0
  158. package/src/theme-mode.ts +52 -0
  159. package/src/time-picker.stories.tsx +62 -0
  160. package/src/time-picker.tsx +615 -0
  161. package/src/toggle-group.tsx +138 -0
  162. package/src/tooltip.stories.tsx +43 -0
  163. package/src/tooltip.tsx +73 -0
  164. package/src/top-nav.stories.tsx +58 -0
  165. package/src/top-nav.tsx +324 -0
  166. package/src/undo-bar.tsx +107 -0
  167. package/src/utils.ts +45 -0
  168. package/src/view-toggle.stories.tsx +84 -0
  169. package/src/view-toggle.tsx +110 -0
@@ -0,0 +1,716 @@
1
+ /**
2
+ * The model behind the route-flow editor (#1027) — everything about a flow that
3
+ * is a FACT rather than a pixel.
4
+ *
5
+ * Deliberately a separate module from the canvas, and free of React and of
6
+ * `@xyflow/react`. What a graph MEANS — which transitions exist, which of them
7
+ * the author drew and which the engine will take anyway, where a chain ends — is
8
+ * contract behaviour, and contract behaviour that lives inside a component can
9
+ * only be tested by rendering one. The same split `flow-model.ts` /
10
+ * `flow-canvas.tsx` already makes for the read-only `flow` block.
11
+ *
12
+ * ─────────────────────────────────────────────────────────────────────────
13
+ * THE ONE IDEA: A NODE IS A TYPE, NEVER AN ENUMERATION
14
+ * ─────────────────────────────────────────────────────────────────────────
15
+ * A step carries a `ruleKind` and a `ruleConfig` and NOTHING ELSE about who it
16
+ * reaches. "Everyone holding Instructor" is ONE node and stays one node whether
17
+ * it resolves to four people or four thousand — there is no field on
18
+ * {@link RouteFlowStep} that could hold a roster, and nothing in this module
19
+ * expands one.
20
+ *
21
+ * How big a node is, is a live fact about the organisation and therefore not
22
+ * part of the model at all. The editor renders it from {@link RouteFlowAudience}
23
+ * that a HOST supplies, because resolving a rule needs the server and a kit
24
+ * component must not fetch. A count that went stale in a model would be worse
25
+ * than no count.
26
+ *
27
+ * ─────────────────────────────────────────────────────────────────────────
28
+ * DERIVED EDGES: WHY THE PICTURE CANNOT DISAGREE WITH THE ENGINE
29
+ * ─────────────────────────────────────────────────────────────────────────
30
+ * Only two kinds of edge are ever STORED — `approved` and `rejected` — and the
31
+ * engine's rule for everything else is positional (#1014):
32
+ *
33
+ * - a step that is not a decision continues to the NEXT AUTHORING ORDINAL;
34
+ * - a decision step's approval takes its `approved` edge if one was drawn, and
35
+ * otherwise falls through to the next authoring ordinal;
36
+ * - a decision step's rejection takes its `rejected` edge if one was drawn,
37
+ * and otherwise ENDS THE CHAIN. It never falls through to where an approval
38
+ * would have gone.
39
+ *
40
+ * {@link resolveTransitions} applies exactly those three rules and returns every
41
+ * transition the engine will actually take, each tagged with whether it was
42
+ * DRAWN or DERIVED. The canvas renders that list and nothing else.
43
+ *
44
+ * That is the whole reason this function exists. An editor that drew only the
45
+ * stored edges would show a linear approval route as a set of disconnected boxes
46
+ * — every arrow in it is implicit — and an author would "fix" it by drawing
47
+ * edges that changed nothing. An editor that drew arrows by its own separate
48
+ * guess would eventually guess differently from the engine, and the picture
49
+ * would be a confident lie. One derivation, rendered.
50
+ */
51
+
52
+ /** The verdicts a stored edge may be keyed by. Mirrors core's `RouteVerdict`. */
53
+ export type RouteFlowVerdict = 'approved' | 'rejected';
54
+
55
+ /** What "this node approved" means. Mirrors core's `RouteQuorum`. */
56
+ export type RouteFlowQuorum = 'all' | 'any' | 'majority';
57
+
58
+ /**
59
+ * Whether a stage ASKS or TELLS. Mirrors core's `RouteSatisfaction`.
60
+ *
61
+ * `'act'` waits for somebody to forward, acknowledge or return. `'delivery'`
62
+ * closes every row it opens, so the stage is satisfied by the sending itself —
63
+ * "put the PDF in every instructor's mailbox", where nobody downstream logs in
64
+ * and nobody acknowledges anything.
65
+ */
66
+ export type RouteFlowSatisfaction = 'act' | 'delivery';
67
+
68
+ /**
69
+ * One stage of a flow.
70
+ *
71
+ * `position` is the identity on the wire and within this module. Database ids
72
+ * are deliberately absent: a graph save REPLACES rather than diffs, so ids churn
73
+ * and a client holding one across a save would be holding a stale number.
74
+ */
75
+ export interface RouteFlowStep {
76
+ /** 1-based authoring ordinal. Unique within a flow, and its handle. */
77
+ position: number;
78
+ /** The RULE this stage reaches — never a person. */
79
+ ruleKind: string;
80
+ /** The rule's own configuration. Opaque here; only the server validates it. */
81
+ ruleConfig: Record<string, unknown>;
82
+ /** An author's name for the stage, or null to fall back to the rule. */
83
+ label: string | null;
84
+ /** Whether this stage is a GATE that demands a verdict. */
85
+ decision: boolean;
86
+ /**
87
+ * What "this node approved" means here.
88
+ *
89
+ * `null` is NOT "no quorum" — it means "follow the tenant setting", which is
90
+ * why {@link RouteFlowGraph.defaultQuorum} exists and why the editor draws the
91
+ * effective value rather than a blank.
92
+ */
93
+ decisionQuorum: RouteFlowQuorum | null;
94
+ /**
95
+ * Whether the people this stage reaches are ASKED TO ACT or simply TOLD
96
+ * (#1054).
97
+ *
98
+ * `'delivery'` closes every recipient row the instant it creates them —
99
+ * nobody is asked for anything and nobody can answer. It is therefore
100
+ * mutually exclusive with {@link decision}, which needs somebody holding the
101
+ * item; the server refuses the pair at three layers.
102
+ *
103
+ * CARRIED HERE EVEN THOUGH NOTHING DRAWS IT YET, because a field the model
104
+ * does not hold is a field a round trip destroys. `RouteTemplatePresenter`
105
+ * publishes it precisely so "a canvas that could not show it would let an
106
+ * author 'correct' it away by saving a graph that never carried it" — and
107
+ * that is exactly what happened: the save path omitted it, the server
108
+ * defaulted the missing value to `'act'`, and a delivery stage quietly became
109
+ * an ordinary one the first time anybody moved a node.
110
+ */
111
+ satisfiedBy: RouteFlowSatisfaction;
112
+ canvasX: number;
113
+ canvasY: number;
114
+ }
115
+
116
+ /** One STORED transition, keyed by the verdict that takes it. */
117
+ export interface RouteFlowEdge {
118
+ /** The `position` this edge leaves. Always a decision step. */
119
+ from: number;
120
+ /** The `position` this edge arrives at. */
121
+ to: number;
122
+ verdict: RouteFlowVerdict;
123
+ }
124
+
125
+ /** A whole flow, as the editor holds it. */
126
+ export interface RouteFlowGraph {
127
+ steps: RouteFlowStep[];
128
+ edges: RouteFlowEdge[];
129
+ /** What a step with a null `decisionQuorum` will actually do. */
130
+ defaultQuorum: RouteFlowQuorum;
131
+ }
132
+
133
+ /**
134
+ * How many people a step's rule currently reaches, as a HOST resolved it.
135
+ *
136
+ * Supplied to the editor rather than fetched by it: resolving a rule is a server
137
+ * question, and a kit component that fetched would need a base URL, an auth
138
+ * scheme and a permission model that belong to whichever app is embedding it.
139
+ *
140
+ * `count` is null when the host could not resolve it — most often because the
141
+ * viewer does not hold the permission the preview needs. The editor then renders
142
+ * the node WITHOUT a number and says why, rather than showing a zero that would
143
+ * read as "this reaches nobody".
144
+ */
145
+ export interface RouteFlowAudience {
146
+ count: number | null;
147
+ /** Why the count is missing, shown verbatim when `count` is null. */
148
+ unavailableReason?: string;
149
+ }
150
+
151
+ /**
152
+ * A transition the engine will actually take, ready to draw.
153
+ *
154
+ * `kind` is what separates an arrow an author DREW from one the engine will take
155
+ * regardless. The editor styles them differently and lets only the first be
156
+ * deleted, because "delete" on a derived arrow could only mean deleting the step
157
+ * ordering that produced it.
158
+ */
159
+ export interface RouteFlowTransition {
160
+ from: number;
161
+ to: number;
162
+ /**
163
+ * The verdict that takes it, or `continue` for the unconditional advance out
164
+ * of a step that asks for no verdict.
165
+ */
166
+ on: RouteFlowVerdict | 'continue';
167
+ kind: 'drawn' | 'derived';
168
+ }
169
+
170
+ /**
171
+ * A place a chain STOPS, which is a fact worth drawing.
172
+ *
173
+ * A rejection with no `rejected` edge ends the flow, and so does the last step's
174
+ * approval. Both are legitimate designs and both are invisible on a canvas that
175
+ * draws only arrows — an author cannot tell "I have not drawn that yet" from
176
+ * "this is where it ends", and those are very different documents.
177
+ */
178
+ export interface RouteFlowTerminal {
179
+ from: number;
180
+ on: RouteFlowVerdict | 'continue';
181
+ }
182
+
183
+ export interface RouteFlowResolution {
184
+ transitions: RouteFlowTransition[];
185
+ terminals: RouteFlowTerminal[];
186
+ /**
187
+ * Positions that MORE THAN ONE transition arrives at.
188
+ *
189
+ * WHY THIS IS A FACT THE EDITOR HAS TO STATE OUT LOUD
190
+ * ---------------------------------------------------
191
+ * When two chains reach the same person at the same step, the engine
192
+ * DE-DUPLICATES them into one inbox item — migration 112's partial unique
193
+ * index over the open recipient rows. The second arrival opens no cohort and
194
+ * gets no continuation of its own: the stage settles ONCE per cohort, not once
195
+ * per chain that reached it.
196
+ *
197
+ * "ONCE PER COHORT" IS NOT "ONCE", AND THE DIFFERENCE IS WHY THE CARD NOTE
198
+ * STATES THE MECHANISM RATHER THAN AN OUTCOME (#1058). A second arrival is
199
+ * absorbed only where it reaches people who still hold an OPEN item here, so
200
+ * it opens a cohort of its own — and settles the stage again, and continues
201
+ * again — in two ordinary situations the canvas can see neither of:
202
+ *
203
+ * - the arrivals reach DIFFERENT people, which is what an actor-relative rule
204
+ * such as `role_below_actor` produces, since each chain resolves it from a
205
+ * different actor; and
206
+ * - the arrivals reach the SAME people but do not overlap in TIME, because
207
+ * the index is partial over `closed_by_event_id IS NULL`. A fan-out where
208
+ * one recipient approves straight into the merge and another rejects the
209
+ * long way round can close the first cohort before the second gets there.
210
+ *
211
+ * Both are facts about a document in flight, not about a design, which is the
212
+ * whole reason the note names the de-duplication rule and leaves the outcome
213
+ * to be worked out from it. The host's inspector states the two cases in
214
+ * prose, where there is room to hedge them accurately.
215
+ *
216
+ * That is pre-existing fan-out behaviour, not something verdicts introduced.
217
+ * It never mattered before because a LINEAR composer cannot draw two paths
218
+ * meeting. A canvas can, and will, the first time anybody uses one — and the
219
+ * natural reading of two arrows entering a box is that both carry on through
220
+ * it. They do not. One continuation happens, and which chain "owns" it is not
221
+ * something the author chose or can choose.
222
+ *
223
+ * REFUSING CONVERGENCE WAS NOT AVAILABLE, WHICH IS WHY THIS IS A LABEL RATHER
224
+ * THAN A VALIDATION. Convergence is not something this editor PERMITS — the
225
+ * engine does it regardless. The positional fallthrough alone produces
226
+ * arrivals nobody drew: step N-1 continuing into step N IS an arrival, so any
227
+ * explicit edge that also targets N converges with it. Refusing convergence
228
+ * would mean refusing the ordinal fallthrough, which is the engine's own
229
+ * documented behaviour and the thing that lets a plain linear route work with
230
+ * no graph authored at all. The drawing cannot prevent the merge; it can only
231
+ * avoid lying about it.
232
+ *
233
+ * Converging designs are also perfectly ordinary and worth keeping: "approve →
234
+ * archive" and "reject → fix → archive" both ending at one archive stage is a
235
+ * flow somebody obviously means to author.
236
+ */
237
+ merges: number[];
238
+ /**
239
+ * Positions that can be reached again from themselves.
240
+ *
241
+ * A rejection that sends a document BACK — "to the author, to fix" — is the
242
+ * most common real approval design, is fully supported by the engine
243
+ * (`nextForVerdict()` resolves by id with no position comparison anywhere, so
244
+ * backwards and forwards are literally the same code path), and produces a
245
+ * cycle. It is authored deliberately and must not be refused.
246
+ *
247
+ * What the engine does NOT do is count laps (#1037). One traversal per act, so
248
+ * no request can spin — the loop is human-driven, exactly as `returned` has
249
+ * been since #989. The cost is INVISIBILITY rather than runaway: a document on
250
+ * its ninth rejection looks identical to one on its first, because there is one
251
+ * inbox item and a trail nobody reads to the end.
252
+ *
253
+ * This editor is the first surface where somebody DRAWS that loop, so it is the
254
+ * first place that can say a loop exists at the moment it is created. That is
255
+ * all this does — it marks the design, not any document's laps, which the
256
+ * canvas cannot see and should not pretend to.
257
+ */
258
+ cycles: number[];
259
+ }
260
+
261
+ /**
262
+ * Steps in authoring order.
263
+ *
264
+ * Sorted defensively rather than trusting the caller: the server returns them
265
+ * ordered, but the editor mutates this array locally on every drag and add, and
266
+ * a fallthrough computed over a locally-reordered list would be wrong in exactly
267
+ * the situation the author is watching.
268
+ */
269
+ export function stepsInOrder(steps: readonly RouteFlowStep[]): RouteFlowStep[] {
270
+ return [...steps].sort((a, b) => a.position - b.position);
271
+ }
272
+
273
+ /**
274
+ * Every transition the engine will take, and every place a chain ends.
275
+ *
276
+ * See the module docblock for the three rules this applies. They are #1014's,
277
+ * not this module's, and they are written here once so the canvas has nothing to
278
+ * decide.
279
+ */
280
+ export function resolveTransitions(graph: RouteFlowGraph): RouteFlowResolution {
281
+ const ordered = stepsInOrder(graph.steps);
282
+ const transitions: RouteFlowTransition[] = [];
283
+ const terminals: RouteFlowTerminal[] = [];
284
+
285
+ // Only edges whose BOTH ends are still on the canvas. A step deleted locally
286
+ // takes its edges with it server-side (they cascade), and drawing an arrow to
287
+ // a node that is no longer there would be the editor showing state that cannot
288
+ // be saved.
289
+ const present = new Set(ordered.map((s) => s.position));
290
+ const drawn = graph.edges.filter((e) => present.has(e.from) && present.has(e.to));
291
+
292
+ const edgeFor = (from: number, verdict: RouteFlowVerdict): RouteFlowEdge | undefined =>
293
+ drawn.find((e) => e.from === from && e.verdict === verdict);
294
+
295
+ ordered.forEach((step, index) => {
296
+ const next = ordered[index + 1];
297
+
298
+ if (!step.decision) {
299
+ // A step that asks for no verdict advances unconditionally. It has no
300
+ // stored edge and cannot have one — the server refuses an edge leaving a
301
+ // non-decision step, because such an edge could never fire.
302
+ if (next !== undefined) {
303
+ transitions.push({ from: step.position, to: next.position, on: 'continue', kind: 'derived' });
304
+ } else {
305
+ terminals.push({ from: step.position, on: 'continue' });
306
+ }
307
+ return;
308
+ }
309
+
310
+ const approved = edgeFor(step.position, 'approved');
311
+ if (approved !== undefined) {
312
+ transitions.push({ from: approved.from, to: approved.to, on: 'approved', kind: 'drawn' });
313
+ } else if (next !== undefined) {
314
+ transitions.push({ from: step.position, to: next.position, on: 'approved', kind: 'derived' });
315
+ } else {
316
+ terminals.push({ from: step.position, on: 'approved' });
317
+ }
318
+
319
+ const rejected = edgeFor(step.position, 'rejected');
320
+ if (rejected !== undefined) {
321
+ transitions.push({ from: rejected.from, to: rejected.to, on: 'rejected', kind: 'drawn' });
322
+ } else {
323
+ // NO FALLTHROUGH. A rejection with nowhere to go ends the chain; it never
324
+ // continues to where an approval would have gone. #1014 records that
325
+ // fallback as the precise failure it is written against — a rejection that
326
+ // records dissent and lets the document proceed is not approval, and it
327
+ // fails silently because every screen still shows a document moving
328
+ // normally.
329
+ terminals.push({ from: step.position, on: 'rejected' });
330
+ }
331
+ });
332
+
333
+ // Computed from the SAME transition list the canvas draws, so a node marked as
334
+ // merging is one the picture actually shows two arrows entering. Deriving it
335
+ // from the STORED edges instead would miss every convergence that involves the
336
+ // positional fallthrough — which is most of them.
337
+ const arrivals = new Map<number, number>();
338
+ for (const transition of transitions) {
339
+ arrivals.set(transition.to, (arrivals.get(transition.to) ?? 0) + 1);
340
+ }
341
+ const merges = [...arrivals.entries()]
342
+ .filter(([, count]) => count > 1)
343
+ .map(([position]) => position)
344
+ .sort((a, b) => a - b);
345
+
346
+ // A position is on a cycle when it can reach ITSELF by following transitions.
347
+ // Walked over the derived list for the same reason `merges` is: a loop closed
348
+ // through the positional fallthrough (reject back to 1, then 1..N forward
349
+ // again) involves edges nobody drew, and a scan of stored edges would not see
350
+ // it — which is the ordinary shape of a rework loop, not an exotic one.
351
+ const outgoing = new Map<number, number[]>();
352
+ for (const transition of transitions) {
353
+ outgoing.set(transition.from, [...(outgoing.get(transition.from) ?? []), transition.to]);
354
+ }
355
+
356
+ const reachesItself = (origin: number): boolean => {
357
+ const seen = new Set<number>();
358
+ const stack = [...(outgoing.get(origin) ?? [])];
359
+ while (stack.length > 0) {
360
+ const at = stack.pop() as number;
361
+ if (at === origin) {
362
+ return true;
363
+ }
364
+ if (seen.has(at)) {
365
+ continue;
366
+ }
367
+ seen.add(at);
368
+ stack.push(...(outgoing.get(at) ?? []));
369
+ }
370
+
371
+ return false;
372
+ };
373
+
374
+ const cycles = ordered
375
+ .map((s) => s.position)
376
+ .filter(reachesItself);
377
+
378
+ return { transitions, terminals, merges, cycles };
379
+ }
380
+
381
+ /**
382
+ * One semantic note on a stage: a fact about the DESIGN that the arrows alone
383
+ * do not say.
384
+ *
385
+ * Kinds, not sentences, because every string a person reads is a label the host
386
+ * supplies; the canvas maps these onto them.
387
+ */
388
+ export type RouteFlowNote =
389
+ | { kind: 'merge' }
390
+ | { kind: 'cycle' }
391
+ | { kind: 'terminal'; on: RouteFlowVerdict | 'continue' };
392
+
393
+ /**
394
+ * Every note one stage carries, in the order they are read.
395
+ *
396
+ * Lives here rather than inside the canvas's render pass for two reasons. The
397
+ * first is that it can then be TESTED — the clipping bug in #1042 was a claim
398
+ * about how many notes exist meeting a clamp that assumed fewer, and neither
399
+ * side of that was reachable from a test while the note list was assembled
400
+ * inline in an effect. The second is {@link ROUTE_FLOW_MAX_NOTES}: a bound on
401
+ * this function's output is what the card's height is budgeted against, so the
402
+ * two have to be able to see each other.
403
+ *
404
+ * The merge note comes FIRST: it is the more surprising of the two markers, and
405
+ * the one a reader is most likely to have assumed the opposite of.
406
+ */
407
+ export function notesFor(position: number, resolution: RouteFlowResolution): RouteFlowNote[] {
408
+ const notes: RouteFlowNote[] = [];
409
+
410
+ if (resolution.merges.includes(position)) {
411
+ notes.push({ kind: 'merge' });
412
+ }
413
+ if (resolution.cycles.includes(position)) {
414
+ notes.push({ kind: 'cycle' });
415
+ }
416
+ for (const terminal of resolution.terminals) {
417
+ if (terminal.from === position) {
418
+ notes.push({ kind: 'terminal', on: terminal.on });
419
+ }
420
+ }
421
+
422
+ return notes;
423
+ }
424
+
425
+ /**
426
+ * The effective quorum for a step: its own, or the tenant's.
427
+ *
428
+ * One function so the node card, the inspector and any future summary cannot
429
+ * each decide differently what a null means.
430
+ */
431
+ export function effectiveQuorum(step: RouteFlowStep, graph: RouteFlowGraph): RouteFlowQuorum {
432
+ return step.decisionQuorum ?? graph.defaultQuorum;
433
+ }
434
+
435
+ // ─────────────────────────────────────────────────────────────────────────────
436
+ // LAYOUT, AND THE DIRECTION DECISION
437
+ // ─────────────────────────────────────────────────────────────────────────────
438
+
439
+ export type RouteFlowOrientation = 'vertical' | 'horizontal';
440
+ export type RouteFlowDirection = 'ltr' | 'rtl';
441
+
442
+ /**
443
+ * Node geometry. Exported so the canvas and the layout agree on one set of
444
+ * numbers instead of each carrying its own copy.
445
+ */
446
+ export const ROUTE_FLOW_NODE_WIDTH = 224;
447
+
448
+ /**
449
+ * Every text row a card draws, and the line box each one occupies.
450
+ *
451
+ * ─────────────────────────────────────────────────────────────────────────
452
+ * WHY THE HEIGHT IS A SUM AND NOT A NUMBER
453
+ * ─────────────────────────────────────────────────────────────────────────
454
+ * It used to be a literal (`124`), and the note clamp on the card was a
455
+ * separate literal (`line-clamp-2`). Nothing tied them together, so they
456
+ * drifted: the height was raised to hold three note lines and the clamp stayed
457
+ * at two, and a stage carrying merge + loop + "Rejected: Ends here" silently
458
+ * dropped the third — the canvas going quiet about the fact that rejection ends
459
+ * the chain, in a card with visible empty space underneath (#1042).
460
+ *
461
+ * So the height is now DERIVED from the rows, and the clamp is derived from
462
+ * {@link ROUTE_FLOW_MAX_NOTES}, which is the same number the height budget uses.
463
+ * Adding a row, or making a fourth note reachable, moves both at once or moves
464
+ * neither; it can no longer move one.
465
+ *
466
+ * The values are the rendered line boxes of the classes the card uses, measured
467
+ * in a browser rather than guessed: `text-sm` (20), `text-xs` (16) and
468
+ * `text-[10px] leading-tight` (12.6, rounded up to 13).
469
+ */
470
+ const NODE_ROW = {
471
+ /** The stage's title, `text-sm`. */
472
+ title: 20,
473
+ /** The rule the stage names, `text-xs` — always visible, never only the label. */
474
+ rule: 16,
475
+ /** How many people the rule reaches, `text-xs`. */
476
+ audience: 16,
477
+ /** What counts as approved, `text-xs`. Its own row, so a long audience line cannot truncate it. */
478
+ quorum: 16,
479
+ /** One semantic note, `text-[10px] leading-tight`. */
480
+ note: 13,
481
+ } as const;
482
+
483
+ /** `px-3 py-2` top + bottom. */
484
+ const NODE_PADDING_Y = 8 * 2;
485
+ /** The 1px border, top + bottom. */
486
+ const NODE_BORDER_Y = 1 * 2;
487
+ /** `gap-1` between the four flex children (title+rule block, audience, quorum, notes). */
488
+ const NODE_GAPS_Y = 4 * 3;
489
+
490
+ /**
491
+ * The most semantic notes one stage can ever carry — and it is a PROVEN
492
+ * maximum, not a chosen one.
493
+ *
494
+ * {@link notesFor} can emit at most four things: the merge note, the loop note,
495
+ * and one terminal per verdict that ends the chain there. Three is the ceiling
496
+ * because the fourth is unreachable:
497
+ *
498
+ * - A step showing BOTH an "approved: ends here" and a "rejected: ends here"
499
+ * has no outgoing transition at all, so nothing can lead back to it and
500
+ * {@link RouteFlowResolution.cycles} cannot contain it. Two terminals
501
+ * therefore exclude the loop note.
502
+ * - A step with only ONE terminal leaves room for merge and loop, which is
503
+ * three.
504
+ * - A non-decision step has at most one terminal ('continue'), so it is
505
+ * bounded by the same three.
506
+ *
507
+ * `route-flow-model.test.ts` asserts this over the constructed shapes rather
508
+ * than trusting the argument, because the argument is only as good as
509
+ * {@link resolveTransitions} staying the way it is.
510
+ */
511
+ export const ROUTE_FLOW_MAX_NOTES = 3;
512
+
513
+ /**
514
+ * Tall enough for everything a stage can say at once.
515
+ *
516
+ * Derived, so the card cannot be given a row it has no room to draw. The layout
517
+ * strides are derived from this in turn, so spacing follows the card rather than
518
+ * being kept in step with it by hand.
519
+ */
520
+ export const ROUTE_FLOW_NODE_HEIGHT =
521
+ NODE_PADDING_Y +
522
+ NODE_BORDER_Y +
523
+ NODE_ROW.title +
524
+ NODE_ROW.rule +
525
+ NODE_ROW.audience +
526
+ NODE_ROW.quorum +
527
+ NODE_GAPS_Y +
528
+ ROUTE_FLOW_MAX_NOTES * NODE_ROW.note;
529
+
530
+ const GAP_ALONG = 72;
531
+ const GAP_ACROSS = 40;
532
+
533
+ /**
534
+ * The readability ceiling on how many nodes a canvas will draw.
535
+ *
536
+ * Mirrors `BlockContract::FLOW_MAX_NODES`, the ceiling #950 already declared for
537
+ * the read-only `flow` block, rather than inventing a second number for the same
538
+ * question. It is a DEFAULT and not a rule: the host passes its own, because the
539
+ * authoritative limit on how many steps a route may declare is the tenant's
540
+ * `documents.routing_max_steps` and only the server knows it.
541
+ */
542
+ export const ROUTE_FLOW_MAX_NODES = 150;
543
+
544
+ /**
545
+ * Whether a graph has never been arranged by a person.
546
+ *
547
+ * Every step sitting at exactly (0, 0) means the rows were written by something
548
+ * that had no canvas — the API, a seed, an import — and drawing them would stack
549
+ * every node on one square. One step at the origin is NOT that: it is a single
550
+ * node somebody left where it started.
551
+ *
552
+ * The test is deliberately narrow. An author's arrangement is a shared design and
553
+ * re-laying it out because a heuristic preferred a different shape would discard
554
+ * meaning they encoded in the positions.
555
+ */
556
+ export function needsAutoLayout(steps: readonly RouteFlowStep[]): boolean {
557
+ return steps.length > 1 && steps.every((s) => s.canvasX === 0 && s.canvasY === 0);
558
+ }
559
+
560
+ /**
561
+ * Place every step on a tidy default grid.
562
+ *
563
+ * Used when {@link needsAutoLayout} is true, and for one node at a time as an
564
+ * author adds them. Not a general graph layout: the spine is authoring order,
565
+ * and the only thing that leaves it is a step reachable ONLY as a rejection
566
+ * target, which is pushed into the next lane so the divergent path reads as
567
+ * divergent. That is the shape this feature is for — approval with a reject
568
+ * path — and a force-directed layout would scramble the one thing worth seeing.
569
+ */
570
+ export function autoLayout(
571
+ graph: RouteFlowGraph,
572
+ orientation: RouteFlowOrientation,
573
+ direction: RouteFlowDirection
574
+ ): RouteFlowStep[] {
575
+ const ordered = stepsInOrder(graph.steps);
576
+
577
+ // Reachability is read off {@link resolveTransitions} rather than off the
578
+ // stored edges, and that distinction is the whole correctness of this lane
579
+ // assignment. A step is on the SPINE when something continues or approves into
580
+ // it — including the DERIVED fallthrough from the step above, which is how a
581
+ // linear route is connected at all and which a scan of stored edges would not
582
+ // see. A step only a rejection can reach is the divergent path, and gets its
583
+ // own lane so that it reads as divergent.
584
+ const { transitions } = resolveTransitions(graph);
585
+
586
+ const rejectOnly = new Set<number>();
587
+ for (const step of ordered) {
588
+ const arrivals = transitions.filter((t) => t.to === step.position);
589
+ if (arrivals.length > 0 && arrivals.every((t) => t.on === 'rejected')) {
590
+ rejectOnly.add(step.position);
591
+ }
592
+ }
593
+
594
+ return ordered.map((step, index) => ({
595
+ ...step,
596
+ ...slotAt(index, rejectOnly.has(step.position) ? 1 : 0, orientation, direction),
597
+ }));
598
+ }
599
+
600
+ /**
601
+ * Where the NEXT node an author adds should go: one slot past the last one.
602
+ */
603
+ export function nextSlot(
604
+ graph: RouteFlowGraph,
605
+ orientation: RouteFlowOrientation,
606
+ direction: RouteFlowDirection
607
+ ): { canvasX: number; canvasY: number } {
608
+ return slotAt(graph.steps.length, 0, orientation, direction);
609
+ }
610
+
611
+ /**
612
+ * Put one step at (depth, lane), mirroring every HORIZONTAL axis under RTL.
613
+ *
614
+ * ─────────────────────────────────────────────────────────────────────────
615
+ * THE RTL DECISION, AND WHY IT IS NOT "SET dir AND HOPE"
616
+ * ─────────────────────────────────────────────────────────────────────────
617
+ * A graph is not text. `dir="rtl"` mirrors text and flexbox; it does nothing to
618
+ * absolute coordinates on a canvas, so a left-to-right flow stays left-to-right
619
+ * in Arabic while every label beside it flips — which reads as a diagram running
620
+ * BACKWARDS, and an arrowhead pointing the wrong way is worse than no arrowhead.
621
+ *
622
+ * Two deliberate choices follow.
623
+ *
624
+ * FIRST, THE DEFAULT ORIENTATION IS VERTICAL. A top-to-bottom flow is
625
+ * direction-NEUTRAL: it reads identically in Arabic and in English, needs no
626
+ * mirroring, and cannot be got wrong by a host that forgets to pass a direction.
627
+ * It is also the better metaphor for the thing being drawn — a document travels
628
+ * DOWN a chain of custody — and it is the same choice the OU tree already makes
629
+ * for the same reason. Making the safe reading the default is worth more than
630
+ * making the familiar one the default.
631
+ *
632
+ * SECOND, WHEN AN AUTHOR CHOOSES HORIZONTAL, EVERY HORIZONTAL AXIS MIRRORS. Not
633
+ * just the flow axis: under RTL, depth advances right-to-left AND lanes spread
634
+ * right-to-left, because in a right-to-left reading the first of several
635
+ * branches is the rightmost. One rule — "a horizontal axis runs in the reading
636
+ * direction" — applied to whichever axis happens to be horizontal, rather than
637
+ * two rules that could be applied inconsistently. The canvas swaps its handles
638
+ * to match, so an arrow still leaves the face a reader expects it to leave.
639
+ *
640
+ * Under the vertical default the across-axis is horizontal, so lanes mirror
641
+ * there too and the depth axis does not — which is the same one rule, and why it
642
+ * is expressed as a rule instead of as two cases.
643
+ */
644
+ export function slotAt(
645
+ depth: number,
646
+ lane: number,
647
+ orientation: RouteFlowOrientation,
648
+ direction: RouteFlowDirection
649
+ ): { canvasX: number; canvasY: number } {
650
+ const horizontal = orientation === 'horizontal';
651
+ const alongStride = (horizontal ? ROUTE_FLOW_NODE_WIDTH : ROUTE_FLOW_NODE_HEIGHT) + GAP_ALONG;
652
+ const acrossStride = (horizontal ? ROUTE_FLOW_NODE_HEIGHT : ROUTE_FLOW_NODE_WIDTH) + GAP_ACROSS;
653
+
654
+ const along = depth * alongStride;
655
+ const across = lane * acrossStride;
656
+
657
+ // The single rule: a horizontal axis runs in the reading direction.
658
+ const mirror = direction === 'rtl' ? -1 : 1;
659
+
660
+ return horizontal
661
+ ? { canvasX: along * mirror, canvasY: across }
662
+ : { canvasX: across * mirror, canvasY: along };
663
+ }
664
+
665
+ /**
666
+ * Which faces edges leave and arrive on, for the current orientation and
667
+ * direction.
668
+ *
669
+ * Returned as plain strings so this module stays free of `@xyflow/react`; the
670
+ * canvas maps them onto its own `Position` enum. Kept HERE rather than in the
671
+ * canvas so the handles cannot drift from the coordinates — a mirrored layout
672
+ * with unmirrored handles draws every arrow through the middle of its own node.
673
+ */
674
+ export function handleFaces(
675
+ orientation: RouteFlowOrientation,
676
+ direction: RouteFlowDirection
677
+ ): { source: 'top' | 'bottom' | 'left' | 'right'; target: 'top' | 'bottom' | 'left' | 'right' } {
678
+ if (orientation === 'vertical') {
679
+ return { target: 'top', source: 'bottom' };
680
+ }
681
+
682
+ return direction === 'rtl' ? { target: 'right', source: 'left' } : { target: 'left', source: 'right' };
683
+ }
684
+
685
+ /**
686
+ * Renumber steps to a contiguous 1..N in their current order.
687
+ *
688
+ * Called after a delete, and it rewrites the edges to match in the same pass.
689
+ * Doing the two together is the point: positions are what edges NAME, so a
690
+ * renumber that did not carry the edges would silently re-point every branch at
691
+ * whichever step inherited the number — an approval route whose reject path
692
+ * quietly moved to a different stage, with nothing on screen to show it.
693
+ *
694
+ * Contiguity is not required by the schema (the unique constraint is on
695
+ * `(template_id, position)`, not on the sequence), and it is done anyway because
696
+ * `position` is also the FALLTHROUGH ORDER: after deleting step 3, "the next
697
+ * ordinal" from step 2 must be the step a reader now sees below it.
698
+ */
699
+ export function renumber(graph: RouteFlowGraph): RouteFlowGraph {
700
+ const ordered = stepsInOrder(graph.steps);
701
+
702
+ const remap = new Map<number, number>();
703
+ ordered.forEach((step, index) => remap.set(step.position, index + 1));
704
+
705
+ return {
706
+ ...graph,
707
+ steps: ordered.map((step) => ({ ...step, position: remap.get(step.position) ?? step.position })),
708
+ edges: graph.edges
709
+ .filter((e) => remap.has(e.from) && remap.has(e.to))
710
+ .map((e) => ({
711
+ ...e,
712
+ from: remap.get(e.from) as number,
713
+ to: remap.get(e.to) as number,
714
+ })),
715
+ };
716
+ }