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