@widgetic/workflows 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +118 -46
  2. package/dist/api/apiContext.d.ts +4 -0
  3. package/dist/api/apiContext.js +17 -0
  4. package/dist/api/types.d.ts +201 -0
  5. package/dist/api/types.js +3 -0
  6. package/dist/api/workflowsApi.d.ts +133 -0
  7. package/dist/api/workflowsApi.js +763 -0
  8. package/dist/components/Workflows.svelte +43 -17
  9. package/dist/components/WorkflowsEmptyState.svelte +16 -5
  10. package/dist/components/WorkflowsEmptyState.svelte.d.ts +5 -16
  11. package/dist/components/WorkflowsHeader.svelte +2 -2
  12. package/dist/components/WorkflowsWorkspace.svelte +90 -0
  13. package/dist/components/WorkflowsWorkspace.svelte.d.ts +15 -0
  14. package/dist/components/canvas/AddBlockMenu.svelte +101 -0
  15. package/dist/components/canvas/AddBlockMenu.svelte.d.ts +5 -0
  16. package/dist/components/canvas/CanvasToolbar.svelte +95 -0
  17. package/dist/components/canvas/CanvasToolbar.svelte.d.ts +9 -0
  18. package/dist/components/canvas/CompositionNodeView.svelte +125 -0
  19. package/dist/components/canvas/CompositionNodeView.svelte.d.ts +5 -0
  20. package/dist/components/canvas/ConditionNodeView.svelte +95 -0
  21. package/dist/components/canvas/ConditionNodeView.svelte.d.ts +5 -0
  22. package/dist/components/canvas/HandlePoint.svelte +32 -0
  23. package/dist/components/canvas/HandlePoint.svelte.d.ts +14 -0
  24. package/dist/components/canvas/TriggerNodeView.svelte +75 -0
  25. package/dist/components/canvas/TriggerNodeView.svelte.d.ts +5 -0
  26. package/dist/components/canvas/WorkflowCanvas.svelte +380 -0
  27. package/dist/components/canvas/WorkflowCanvas.svelte.d.ts +25 -0
  28. package/dist/components/canvas/WorkflowEdgeView.svelte +58 -0
  29. package/dist/components/canvas/WorkflowEdgeView.svelte.d.ts +4 -0
  30. package/dist/components/editor/ConflictBanner.svelte +78 -0
  31. package/dist/components/editor/ConflictBanner.svelte.d.ts +3 -0
  32. package/dist/components/editor/EditorBanners.svelte +141 -0
  33. package/dist/components/editor/EditorBanners.svelte.d.ts +7 -0
  34. package/dist/components/editor/EditorCanvasArea.svelte +85 -0
  35. package/dist/components/editor/EditorCanvasArea.svelte.d.ts +3 -0
  36. package/dist/components/editor/EditorTabs.svelte +81 -0
  37. package/dist/components/editor/EditorTabs.svelte.d.ts +7 -0
  38. package/dist/components/editor/EditorTopBar.svelte +132 -0
  39. package/dist/components/editor/EditorTopBar.svelte.d.ts +9 -0
  40. package/dist/components/editor/PresenceBanner.svelte +126 -0
  41. package/dist/components/editor/PresenceBanner.svelte.d.ts +3 -0
  42. package/dist/components/editor/RunsTab.svelte +256 -0
  43. package/dist/components/editor/RunsTab.svelte.d.ts +3 -0
  44. package/dist/components/editor/SettingsTab.svelte +180 -0
  45. package/dist/components/editor/SettingsTab.svelte.d.ts +7 -0
  46. package/dist/components/editor/WorkflowEditor.svelte +198 -0
  47. package/dist/components/editor/WorkflowEditor.svelte.d.ts +17 -0
  48. package/dist/components/index.d.ts +0 -2
  49. package/dist/components/index.js +0 -2
  50. package/dist/components/list/CreateWorkflowDialog.svelte +89 -0
  51. package/dist/components/list/CreateWorkflowDialog.svelte.d.ts +9 -0
  52. package/dist/components/list/WorkflowList.svelte +204 -0
  53. package/dist/components/list/WorkflowList.svelte.d.ts +12 -0
  54. package/dist/components/list/WorkflowRow.svelte +191 -0
  55. package/dist/components/list/WorkflowRow.svelte.d.ts +10 -0
  56. package/dist/components/panel/BlockProblems.svelte +47 -0
  57. package/dist/components/panel/BlockProblems.svelte.d.ts +6 -0
  58. package/dist/components/panel/CompositionForm.svelte +127 -0
  59. package/dist/components/panel/CompositionForm.svelte.d.ts +7 -0
  60. package/dist/components/panel/CompositionPicker.svelte +179 -0
  61. package/dist/components/panel/CompositionPicker.svelte.d.ts +14 -0
  62. package/dist/components/panel/ConditionForm.svelte +105 -0
  63. package/dist/components/panel/ConditionForm.svelte.d.ts +7 -0
  64. package/dist/components/panel/EventValueRow.svelte +85 -0
  65. package/dist/components/panel/EventValueRow.svelte.d.ts +12 -0
  66. package/dist/components/panel/NextStepSelect.svelte +70 -0
  67. package/dist/components/panel/NextStepSelect.svelte.d.ts +12 -0
  68. package/dist/components/panel/ProblemsList.svelte +101 -0
  69. package/dist/components/panel/ProblemsList.svelte.d.ts +3 -0
  70. package/dist/components/panel/RuleCard.svelte +191 -0
  71. package/dist/components/panel/RuleCard.svelte.d.ts +13 -0
  72. package/dist/components/panel/SidePanel.svelte +82 -0
  73. package/dist/components/panel/SidePanel.svelte.d.ts +3 -0
  74. package/dist/components/panel/TestRow.svelte +150 -0
  75. package/dist/components/panel/TestRow.svelte.d.ts +15 -0
  76. package/dist/components/panel/TestRunPanel.svelte +85 -0
  77. package/dist/components/panel/TestRunPanel.svelte.d.ts +3 -0
  78. package/dist/components/panel/TestTriggerCard.svelte +121 -0
  79. package/dist/components/panel/TestTriggerCard.svelte.d.ts +7 -0
  80. package/dist/components/panel/TriggerForm.svelte +385 -0
  81. package/dist/components/panel/TriggerForm.svelte.d.ts +7 -0
  82. package/dist/components/panel/VersionHistory.svelte +123 -0
  83. package/dist/components/panel/VersionHistory.svelte.d.ts +3 -0
  84. package/dist/components/ui/ActionButton.svelte +85 -0
  85. package/dist/components/ui/ActionButton.svelte.d.ts +27 -0
  86. package/dist/components/ui/ConfirmDialog.svelte +52 -0
  87. package/dist/components/ui/ConfirmDialog.svelte.d.ts +16 -0
  88. package/dist/components/ui/Icon.svelte +32 -0
  89. package/dist/components/ui/Icon.svelte.d.ts +9 -0
  90. package/dist/components/ui/Menu.svelte +211 -0
  91. package/dist/components/ui/Menu.svelte.d.ts +21 -0
  92. package/dist/components/ui/Modal.svelte +129 -0
  93. package/dist/components/ui/Modal.svelte.d.ts +13 -0
  94. package/dist/components/ui/Notice.svelte +36 -0
  95. package/dist/components/ui/Notice.svelte.d.ts +11 -0
  96. package/dist/components/ui/SelectField.svelte +74 -0
  97. package/dist/components/ui/SelectField.svelte.d.ts +16 -0
  98. package/dist/components/ui/StatusBadge.svelte +41 -0
  99. package/dist/components/ui/StatusBadge.svelte.d.ts +9 -0
  100. package/dist/components/ui/TextField.svelte +97 -0
  101. package/dist/components/ui/TextField.svelte.d.ts +29 -0
  102. package/dist/components/ui/icons.d.ts +34 -0
  103. package/dist/components/ui/icons.js +54 -0
  104. package/dist/components/ui/types.d.ts +26 -0
  105. package/dist/components/ui/types.js +1 -0
  106. package/dist/editor/apiErrorText.d.ts +10 -0
  107. package/dist/editor/apiErrorText.js +53 -0
  108. package/dist/editor/autosave.d.ts +47 -0
  109. package/dist/editor/autosave.js +119 -0
  110. package/dist/editor/blockLabels.d.ts +91 -0
  111. package/dist/editor/blockLabels.js +196 -0
  112. package/dist/editor/canvasContext.d.ts +52 -0
  113. package/dist/editor/canvasContext.js +37 -0
  114. package/dist/editor/canvasWords.d.ts +24 -0
  115. package/dist/editor/canvasWords.js +40 -0
  116. package/dist/editor/capabilityModel.d.ts +46 -0
  117. package/dist/editor/capabilityModel.js +113 -0
  118. package/dist/editor/editLeaseController.d.ts +162 -0
  119. package/dist/editor/editLeaseController.js +459 -0
  120. package/dist/editor/editorState.svelte.d.ts +277 -0
  121. package/dist/editor/editorState.svelte.js +862 -0
  122. package/dist/editor/flowAdapter.d.ts +59 -0
  123. package/dist/editor/flowAdapter.js +166 -0
  124. package/dist/editor/formatCount.d.ts +5 -0
  125. package/dist/editor/formatCount.js +15 -0
  126. package/dist/editor/graphDiff.d.ts +27 -0
  127. package/dist/editor/graphDiff.js +64 -0
  128. package/dist/editor/graphModel.d.ts +154 -0
  129. package/dist/editor/graphModel.js +457 -0
  130. package/dist/editor/issueText.d.ts +64 -0
  131. package/dist/editor/issueText.js +101 -0
  132. package/dist/editor/keepCopy.d.ts +41 -0
  133. package/dist/editor/keepCopy.js +52 -0
  134. package/dist/editor/listState.svelte.d.ts +82 -0
  135. package/dist/editor/listState.svelte.js +250 -0
  136. package/dist/editor/statsRange.d.ts +26 -0
  137. package/dist/editor/statsRange.js +41 -0
  138. package/dist/editor/testRun.d.ts +36 -0
  139. package/dist/editor/testRun.js +74 -0
  140. package/dist/editor/zonedTime.d.ts +20 -0
  141. package/dist/editor/zonedTime.js +134 -0
  142. package/dist/i18n/language.d.ts +3 -3
  143. package/dist/i18n/messages.d.ts +429 -4
  144. package/dist/i18n/messages.js +456 -8
  145. package/dist/index.d.ts +2 -1
  146. package/dist/index.js +1 -1
  147. package/dist/types/index.d.ts +41 -3
  148. package/package.json +5 -1
@@ -0,0 +1,457 @@
1
+ /**
2
+ * Making and changing the pieces of a workflow, the way the editor does it. Everything here is plain data in and plain data
3
+ * out (the engine's `WorkflowGraph` and its blocks): nothing draws, nothing waits, nothing is stored. The canvas, the side
4
+ * panel and the tests all go through these functions, so "a new Trigger block", "remove a rule" or "where does the next
5
+ * block go" mean one thing.
6
+ *
7
+ * What is NOT decided here: whether a connection is allowed (the engine's `checkConnection`), whether a workflow can be
8
+ * published (the engine's `validate`), and what a composition can do (the API's composition options, `capabilityModel.ts`).
9
+ */
10
+ import { DEFAULT_PORT, MAX_BLOCKS, MAX_CASES_PER_CONDITION, MAX_TESTS_PER_CASE, OPERATORS_BY_TYPE, checkConnection, operatorNeedsValue } from '@widgetic/workflows-engine';
11
+ /** In the order the menu lists them. */
12
+ export const TRIGGER_KINDS = ['input', 'action', 'pageEvent', 'scheduled'];
13
+ /** How far apart blocks are placed, in canvas units. A composition card is about 240 wide. */
14
+ export const BLOCK_SPACING = { horizontal: 360, vertical: 220 };
15
+ /** Where the first block of an empty workflow goes. */
16
+ export const FIRST_BLOCK_POSITION = { x: 80, y: 120 };
17
+ const ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';
18
+ /** Random text of `length` characters of the id alphabet. `random` is for tests. */
19
+ function randomText(length, random) {
20
+ let text = '';
21
+ for (let position = 0; position < length; position += 1) {
22
+ text += ID_ALPHABET.charAt(Math.floor(random() * ID_ALPHABET.length) % ID_ALPHABET.length);
23
+ }
24
+ return text;
25
+ }
26
+ /**
27
+ * A new id for a block (`n_`), a connection (`e_`) or a rule (`r_`) that no other has in this graph. The engine accepts
28
+ * letters, digits, `_` and `-` up to 64 characters; these are short so a person who reads an exported graph can follow them.
29
+ */
30
+ export function makeId(prefix, takenIds, random = Math.random) {
31
+ for (let attempt = 0; attempt < 50; attempt += 1) {
32
+ const candidate = `${prefix}_${randomText(8, random)}`;
33
+ if (!takenIds.has(candidate))
34
+ return candidate;
35
+ }
36
+ // Fifty collisions in a row cannot happen with a working random source; a counter makes the answer certain anyway.
37
+ let counter = takenIds.size + 1;
38
+ while (takenIds.has(`${prefix}_${counter}`))
39
+ counter += 1;
40
+ return `${prefix}_${counter}`;
41
+ }
42
+ /** Every id of a block, a connection and a rule of the graph: what a new id must not be. */
43
+ export function collectTakenIds(graph) {
44
+ const taken = new Set();
45
+ for (const node of graph.nodes) {
46
+ taken.add(node.id);
47
+ if (node.type === 'condition')
48
+ for (const conditionCase of node.cases)
49
+ taken.add(conditionCase.id);
50
+ }
51
+ for (const edge of graph.edges)
52
+ taken.add(edge.id);
53
+ return taken;
54
+ }
55
+ export function makeEmptyGraph() {
56
+ return { schemaVersion: 1, nodes: [], edges: [] };
57
+ }
58
+ /** Whether another block fits (a workflow holds at most 25). */
59
+ export function canAddBlock(graph) {
60
+ return graph.nodes.length < MAX_BLOCKS;
61
+ }
62
+ // ---------------------------------------------------------------------------------------------------------------------
63
+ // New blocks
64
+ // ---------------------------------------------------------------------------------------------------------------------
65
+ export function makeCompositionBlock(options) {
66
+ const node = {
67
+ id: options.id,
68
+ type: 'composition',
69
+ compositionId: options.compositionId,
70
+ position: options.position
71
+ };
72
+ if (options.startsHere)
73
+ node.startsHere = true;
74
+ return node;
75
+ }
76
+ /** What a trigger starts as: the kind decides the shape, and the person fills in the rest (an unfinished draft is allowed). */
77
+ export function makeTriggerConfig(kind) {
78
+ switch (kind) {
79
+ case 'input':
80
+ return { kind: 'input', table: '' };
81
+ case 'action':
82
+ return { kind: 'action', actionId: '' };
83
+ case 'pageEvent':
84
+ return { kind: 'pageEvent', name: '', values: [] };
85
+ case 'scheduled':
86
+ return { kind: 'scheduled', schedule: { mode: 'after', amount: 1, unit: 'minutes' } };
87
+ }
88
+ }
89
+ export function makeTriggerBlock(options) {
90
+ return {
91
+ id: options.id,
92
+ type: 'trigger',
93
+ trigger: makeTriggerConfig(options.kind),
94
+ position: options.position
95
+ };
96
+ }
97
+ export function makeConditionBlock(options) {
98
+ return {
99
+ id: options.id,
100
+ type: 'condition',
101
+ cases: [{ id: options.firstRuleId, match: 'all', tests: [] }],
102
+ position: options.position
103
+ };
104
+ }
105
+ /**
106
+ * The same trigger asked to wait for something else. What belonged to the old kind goes with it; nothing is kept that the
107
+ * new kind has no place for.
108
+ */
109
+ export function changeTriggerKind(node, kind) {
110
+ if (node.trigger.kind === kind)
111
+ return node;
112
+ return { ...node, trigger: makeTriggerConfig(kind) };
113
+ }
114
+ // ---------------------------------------------------------------------------------------------------------------------
115
+ // Where blocks go
116
+ // ---------------------------------------------------------------------------------------------------------------------
117
+ function positionOf(node) {
118
+ return node?.position === undefined ? undefined : { x: node.position.x, y: node.position.y };
119
+ }
120
+ function overlaps(first, second) {
121
+ return (Math.abs(first.x - second.x) < BLOCK_SPACING.horizontal - 40 &&
122
+ Math.abs(first.y - second.y) < 120);
123
+ }
124
+ /**
125
+ * Where a new block is put. After a block, it goes one step to the right of it, and moves down until the place is free.
126
+ * With nothing to follow it goes under the lowest block of the leftmost column, or in the first place when the canvas is
127
+ * empty. A person moves it afterwards; this only makes sure it never lands on another block.
128
+ */
129
+ export function suggestPosition(graph, afterNodeId) {
130
+ const anchor = afterNodeId
131
+ ? positionOf(graph.nodes.find((node) => node.id === afterNodeId))
132
+ : undefined;
133
+ const taken = graph.nodes
134
+ .map(positionOf)
135
+ .filter((position) => position !== undefined);
136
+ let candidate;
137
+ if (anchor) {
138
+ candidate = { x: anchor.x + BLOCK_SPACING.horizontal, y: anchor.y };
139
+ }
140
+ else if (taken.length === 0) {
141
+ return { ...FIRST_BLOCK_POSITION };
142
+ }
143
+ else {
144
+ const leftmost = Math.min(...taken.map((position) => position.x));
145
+ const lowestInFirstColumn = Math.max(...taken.filter((position) => position.x === leftmost).map((position) => position.y));
146
+ candidate = { x: leftmost, y: lowestInFirstColumn + BLOCK_SPACING.vertical };
147
+ }
148
+ // Moves down (never in a loop: at most as many steps as there are blocks).
149
+ for (let attempt = 0; attempt <= taken.length; attempt += 1) {
150
+ if (!taken.some((position) => overlaps(position, candidate)))
151
+ break;
152
+ candidate = { x: candidate.x, y: candidate.y + BLOCK_SPACING.vertical / 2 };
153
+ }
154
+ return { x: Math.round(candidate.x), y: Math.round(candidate.y) };
155
+ }
156
+ /**
157
+ * The output a new block is joined from, after `anchor`: a composition and a trigger have one (a composition may lead to
158
+ * several triggers, so it is always free; a trigger leads to one next step, and is free only without one); a condition offers
159
+ * its first rule that leads nowhere yet, then Default.
160
+ */
161
+ export function findFreeOutput(graph, anchor) {
162
+ const taken = new Set(graph.edges.filter((edge) => edge.source === anchor.id).map((edge) => edge.sourcePort));
163
+ if (anchor.type === 'composition')
164
+ return 'out';
165
+ if (anchor.type === 'trigger')
166
+ return taken.has('out') ? null : 'out';
167
+ const free = [...anchor.cases.map((conditionCase) => conditionCase.id), DEFAULT_PORT].find((port) => !taken.has(port));
168
+ return free ?? null;
169
+ }
170
+ /**
171
+ * Plans a new block of this kind after the block the person has selected (or at a free place when nothing is selected).
172
+ * The block is joined to the anchor only when the engine would allow that line: a composition after a composition is not
173
+ * drawn for the person, and a trigger after a trigger neither. Nothing is changed here; the editor applies the plan.
174
+ *
175
+ * `random` is for tests.
176
+ */
177
+ export function planAddBlock(graph, request, anchorId, random = Math.random) {
178
+ if (!canAddBlock(graph))
179
+ return { refused: 'too_many_blocks', node: null, edge: null };
180
+ const taken = collectTakenIds(graph);
181
+ const nodeId = makeId('n', taken, random);
182
+ taken.add(nodeId);
183
+ const position = suggestPosition(graph, anchorId);
184
+ let node;
185
+ if (request.kind === 'composition') {
186
+ const isFirstComposition = !graph.nodes.some((candidate) => candidate.type === 'composition');
187
+ node = makeCompositionBlock({
188
+ id: nodeId,
189
+ compositionId: request.compositionId ?? '',
190
+ position,
191
+ startsHere: isFirstComposition
192
+ });
193
+ }
194
+ else if (request.kind === 'trigger') {
195
+ node = makeTriggerBlock({ id: nodeId, kind: request.triggerKind, position });
196
+ }
197
+ else {
198
+ const ruleId = makeId('r', taken, random);
199
+ node = makeConditionBlock({ id: nodeId, firstRuleId: ruleId, position });
200
+ }
201
+ const anchor = anchorId ? graph.nodes.find((candidate) => candidate.id === anchorId) : undefined;
202
+ const sourcePort = anchor ? findFreeOutput(graph, anchor) : null;
203
+ if (!anchor || sourcePort === null)
204
+ return { refused: null, node, edge: null };
205
+ const withNode = { ...graph, nodes: [...graph.nodes, node] };
206
+ if (!checkConnection(withNode, { source: anchor.id, sourcePort, target: node.id }).ok)
207
+ return { refused: null, node, edge: null };
208
+ const edgeId = makeId('e', taken, random);
209
+ return {
210
+ refused: null,
211
+ node,
212
+ edge: { id: edgeId, source: anchor.id, sourcePort, target: node.id }
213
+ };
214
+ }
215
+ // ---------------------------------------------------------------------------------------------------------------------
216
+ // Taking blocks away
217
+ // ---------------------------------------------------------------------------------------------------------------------
218
+ /** The graph without these blocks and without every connection that touched one of them. */
219
+ export function removeBlocks(graph, nodeIds) {
220
+ const removed = new Set(nodeIds);
221
+ return {
222
+ ...graph,
223
+ nodes: graph.nodes.filter((node) => !removed.has(node.id)),
224
+ edges: graph.edges.filter((edge) => !removed.has(edge.source) && !removed.has(edge.target))
225
+ };
226
+ }
227
+ /** The graph without these connections. */
228
+ export function removeConnections(graph, edgeIds) {
229
+ const removed = new Set(edgeIds);
230
+ return { ...graph, edges: graph.edges.filter((edge) => !removed.has(edge.id)) };
231
+ }
232
+ /**
233
+ * Exactly one composition starts a workflow. After blocks were taken away, the start may be gone while compositions are
234
+ * left; the first one (the one furthest left) starts it then. A graph that already has one start is returned as it is.
235
+ */
236
+ export function ensureOneStart(graph) {
237
+ const compositions = graph.nodes.filter((node) => node.type === 'composition');
238
+ if (compositions.length === 0)
239
+ return graph;
240
+ if (compositions.some((node) => node.startsHere === true))
241
+ return graph;
242
+ const first = [...compositions].sort((left, right) => (left.position?.x ?? 0) - (right.position?.x ?? 0))[0];
243
+ return setStartBlock(graph, first.id);
244
+ }
245
+ /** Makes this composition the start, and no other. Not a composition: the graph is returned as it is. */
246
+ export function setStartBlock(graph, nodeId) {
247
+ const target = graph.nodes.find((node) => node.id === nodeId);
248
+ if (target?.type !== 'composition')
249
+ return graph;
250
+ return {
251
+ ...graph,
252
+ nodes: graph.nodes.map((node) => {
253
+ if (node.type !== 'composition')
254
+ return node;
255
+ if (node.id === nodeId)
256
+ return { ...node, startsHere: true };
257
+ if (node.startsHere !== true)
258
+ return node;
259
+ const { startsHere: _startsHere, ...rest } = node;
260
+ return rest;
261
+ })
262
+ };
263
+ }
264
+ // ---------------------------------------------------------------------------------------------------------------------
265
+ // Rules and tests of a condition
266
+ // ---------------------------------------------------------------------------------------------------------------------
267
+ /** Whether another rule fits in this condition. */
268
+ export function canAddRule(node) {
269
+ return node.cases.length < MAX_CASES_PER_CONDITION;
270
+ }
271
+ /** Whether another test fits in this rule. */
272
+ export function canAddTest(conditionCase) {
273
+ return conditionCase.tests.length < MAX_TESTS_PER_CASE;
274
+ }
275
+ /** The operator a field starts with: the first one its type offers, "is". */
276
+ export function defaultOperatorFor(type) {
277
+ return OPERATORS_BY_TYPE[type][0] ?? 'is';
278
+ }
279
+ /** The value a test starts with for a type, or none for an operator that needs no value. */
280
+ export function defaultValueFor(type, operator) {
281
+ if (!operatorNeedsValue(operator))
282
+ return undefined;
283
+ if (type === 'boolean')
284
+ return true;
285
+ if (type === 'number')
286
+ return undefined;
287
+ return '';
288
+ }
289
+ /** A new test on a field, with its type's first operator. */
290
+ export function makeTest(field) {
291
+ const operator = defaultOperatorFor(field.type);
292
+ const value = defaultValueFor(field.type, operator);
293
+ return value === undefined ? { field, operator } : { field, operator, value };
294
+ }
295
+ /** A test whose field was replaced: the operator and the value stay when the new type still has them, and start over when not. */
296
+ export function changeTestField(test, field) {
297
+ if (test.field.type === field.type && OPERATORS_BY_TYPE[field.type].includes(test.operator)) {
298
+ return { ...test, field };
299
+ }
300
+ return makeTest(field);
301
+ }
302
+ /** A test with another operator: an operator that takes no value drops the value, one that takes a value gets a start for it. */
303
+ export function changeTestOperator(test, operator) {
304
+ if (!OPERATORS_BY_TYPE[test.field.type].includes(operator))
305
+ return test;
306
+ if (!operatorNeedsValue(operator)) {
307
+ const { value: _value, ...rest } = test;
308
+ return { ...rest, operator };
309
+ }
310
+ if (test.value !== undefined && test.value !== null)
311
+ return { ...test, operator };
312
+ const value = defaultValueFor(test.field.type, operator);
313
+ return value === undefined ? { ...test, operator } : { ...test, operator, value };
314
+ }
315
+ /**
316
+ * What a person typed into the value of a test, as the value the engine compares. A number field keeps what is not yet a
317
+ * number as nothing (the field is empty while the person types), a yes/no field reads `true` and `false`.
318
+ */
319
+ export function readTypedValue(type, text) {
320
+ if (type === 'boolean')
321
+ return text === 'true' ? true : text === 'false' ? false : undefined;
322
+ if (type === 'number') {
323
+ const trimmed = text.trim();
324
+ if (trimmed === '')
325
+ return undefined;
326
+ const number = Number(trimmed);
327
+ return Number.isFinite(number) ? number : undefined;
328
+ }
329
+ return text;
330
+ }
331
+ /** A new rule: a fresh id, matching all of its tests, with the first field a person can read when there is one. */
332
+ export function makeRule(takenIds, firstField, random) {
333
+ const id = makeId('r', takenIds, random);
334
+ return { id, match: 'all', tests: firstField ? [makeTest(firstField)] : [] };
335
+ }
336
+ /** The condition with a rule more. */
337
+ export function addRule(node, rule) {
338
+ return canAddRule(node) ? { ...node, cases: [...node.cases, rule] } : node;
339
+ }
340
+ /** The condition with one rule less. */
341
+ export function removeRule(node, ruleId) {
342
+ return { ...node, cases: node.cases.filter((conditionCase) => conditionCase.id !== ruleId) };
343
+ }
344
+ /** The condition with a rule moved to another place in the order (rules are tried in order, the first match wins). */
345
+ export function moveRule(node, ruleId, toIndex) {
346
+ const fromIndex = node.cases.findIndex((conditionCase) => conditionCase.id === ruleId);
347
+ if (fromIndex === -1)
348
+ return node;
349
+ const targetIndex = Math.max(0, Math.min(node.cases.length - 1, toIndex));
350
+ if (targetIndex === fromIndex)
351
+ return node;
352
+ const cases = [...node.cases];
353
+ const [moved] = cases.splice(fromIndex, 1);
354
+ cases.splice(targetIndex, 0, moved);
355
+ return { ...node, cases };
356
+ }
357
+ /** The condition with one of its rules replaced by what `change` makes of it. */
358
+ export function changeRule(node, ruleId, change) {
359
+ return {
360
+ ...node,
361
+ cases: node.cases.map((conditionCase) => conditionCase.id === ruleId ? change(conditionCase) : conditionCase)
362
+ };
363
+ }
364
+ /** The connections that leave a port that no longer exists: after a rule is removed its line goes with it. */
365
+ export function findStrandedConnections(graph) {
366
+ const portsByNode = new Map();
367
+ for (const node of graph.nodes) {
368
+ portsByNode.set(node.id, new Set(node.type === 'condition'
369
+ ? [...node.cases.map((conditionCase) => conditionCase.id), DEFAULT_PORT]
370
+ : ['out']));
371
+ }
372
+ return graph.edges.filter((edge) => !portsByNode.get(edge.source)?.has(edge.sourcePort));
373
+ }
374
+ /** The workflow without the lines that left from a place that is gone: removing a rule takes the line of that rule with it. */
375
+ export function dropStrandedConnections(graph) {
376
+ const strandedIds = new Set(findStrandedConnections(graph).map((edge) => edge.id));
377
+ if (strandedIds.size === 0)
378
+ return graph;
379
+ return { ...graph, edges: graph.edges.filter((edge) => !strandedIds.has(edge.id)) };
380
+ }
381
+ // ---------------------------------------------------------------------------------------------------------------------
382
+ // Schedules
383
+ // ---------------------------------------------------------------------------------------------------------------------
384
+ /** A wait of some time, the way a Scheduled trigger starts. */
385
+ export function makeWaitSchedule() {
386
+ return { mode: 'after', amount: 1, unit: 'minutes' };
387
+ }
388
+ const ONE_HOUR_MILLISECONDS = 60 * 60 * 1000;
389
+ /**
390
+ * A first moment for a schedule that is switched to "at a date and time": the next full hour, a day from `now`. It is a
391
+ * starting point the person changes, so the field never opens empty or in the past.
392
+ */
393
+ export function makeDateSchedule(now = new Date()) {
394
+ const nextFullHour = Math.ceil(now.getTime() / ONE_HOUR_MILLISECONDS) * ONE_HOUR_MILLISECONDS;
395
+ return { mode: 'at', at: new Date(nextFullHour + 24 * ONE_HOUR_MILLISECONDS).toISOString() };
396
+ }
397
+ /** Switches a schedule between "wait for" and "at a date and time"; the same mode keeps what was typed. */
398
+ export function changeScheduleMode(schedule, mode, now) {
399
+ if (schedule.mode === mode)
400
+ return schedule;
401
+ return mode === 'after' ? makeWaitSchedule() : makeDateSchedule(now);
402
+ }
403
+ // ---------------------------------------------------------------------------------------------------------------------
404
+ // Reading the graph for the screens
405
+ // ---------------------------------------------------------------------------------------------------------------------
406
+ /** The composition blocks of a graph, in the order they are stored. */
407
+ export function listCompositionBlocks(graph) {
408
+ return graph.nodes.filter((node) => node.type === 'composition');
409
+ }
410
+ /** The ids of the compositions a graph shows, once each. */
411
+ export function listCompositionIds(graph) {
412
+ return [
413
+ ...new Set(listCompositionBlocks(graph)
414
+ .map((node) => node.compositionId)
415
+ .filter((id) => id !== ''))
416
+ ];
417
+ }
418
+ /**
419
+ * The draft as the API stores it again: positions rounded to whole numbers, so that a block that was only touched by a
420
+ * pointer does not look changed. Two graphs that differ only below that are the same graph.
421
+ */
422
+ export function normalizePositions(graph) {
423
+ return {
424
+ ...graph,
425
+ nodes: graph.nodes.map((node) => node.position === undefined
426
+ ? node
427
+ : { ...node, position: { x: Math.round(node.position.x), y: Math.round(node.position.y) } })
428
+ };
429
+ }
430
+ /** JSON with the keys of every object in order, so that two documents with the same content read the same. */
431
+ export function writeStableJson(value) {
432
+ if (Array.isArray(value))
433
+ return `[${value.map(writeStableJson).join(',')}]`;
434
+ if (typeof value === 'object' && value !== null) {
435
+ const record = value;
436
+ const parts = Object.keys(record)
437
+ .filter((key) => record[key] !== undefined)
438
+ .sort()
439
+ .map((key) => `${JSON.stringify(key)}:${writeStableJson(record[key])}`);
440
+ return `{${parts.join(',')}}`;
441
+ }
442
+ return JSON.stringify(value) ?? 'null';
443
+ }
444
+ /** The graph with its blocks and connections in the order of their ids (the engine finds them by id, never by place in the list). */
445
+ function sortByIdentifier(graph) {
446
+ const byId = (left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
447
+ return { ...graph, nodes: [...graph.nodes].sort(byId), edges: [...graph.edges].sort(byId) };
448
+ }
449
+ /**
450
+ * Whether two graphs are the same document (every block, connection and setting), used to tell "saved" from "changed".
451
+ * The order of the rules of a condition counts (it is their meaning). The order of the blocks and of the connections in the
452
+ * list does not (the canvas may bring a block to the front), and neither does the order of an object's keys.
453
+ */
454
+ export function isSameGraph(left, right) {
455
+ return (writeStableJson(sortByIdentifier(normalizePositions(left))) ===
456
+ writeStableJson(sortByIdentifier(normalizePositions(right))));
457
+ }
@@ -0,0 +1,64 @@
1
+ import type { ValidationIssue } from '@widgetic/workflows-engine';
2
+ import type { WorkflowsMessageKey } from '../i18n/messages.js';
3
+ /**
4
+ * The words for what the engine found wrong with a workflow. The engine reports a code (never a sentence) and the block it
5
+ * belongs to; here each code is one message of the catalog, so the draft check, the publish check of the server and the
6
+ * highlight on the canvas all say the same thing in the person's language.
7
+ *
8
+ * `ISSUE_MESSAGE_KEYS` has to name every code the engine can report (the type says so, and a test reads the engine's list
9
+ * of codes): a code with no message would be an error the person cannot read.
10
+ */
11
+ export declare const ISSUE_MESSAGE_KEYS: {
12
+ readonly malformed: "workflows.issue.malformed";
13
+ readonly schema_version: "workflows.issue.schemaVersion";
14
+ readonly graph_too_large: "workflows.issue.graphTooLarge";
15
+ readonly unknown_node_type: "workflows.issue.unknownNodeType";
16
+ readonly unknown_trigger_kind: "workflows.issue.unknownTriggerKind";
17
+ readonly bad_id: "workflows.issue.badId";
18
+ readonly duplicate_id: "workflows.issue.duplicateId";
19
+ readonly too_many_blocks: "workflows.issue.tooManyBlocks";
20
+ readonly too_many_edges: "workflows.issue.tooManyEdges";
21
+ readonly no_composition: "workflows.issue.noComposition";
22
+ readonly no_start: "workflows.issue.noStart";
23
+ readonly many_starts: "workflows.issue.manyStarts";
24
+ readonly composition_missing_id: "workflows.issue.compositionMissingId";
25
+ readonly duplicate_composition: "workflows.issue.duplicateComposition";
26
+ readonly composition_not_available: "workflows.issue.compositionNotAvailable";
27
+ readonly composition_website_mismatch: "workflows.issue.compositionWebsiteMismatch";
28
+ readonly unreachable_block: "workflows.issue.unreachableBlock";
29
+ readonly edge_unknown_node: "workflows.issue.edgeUnknownNode";
30
+ readonly edge_bad_port: "workflows.issue.edgeBadPort";
31
+ readonly edge_invalid_connection: "workflows.issue.edgeInvalidConnection";
32
+ readonly port_many_targets: "workflows.issue.portManyTargets";
33
+ readonly cycle: "workflows.issue.cycle";
34
+ readonly trigger_no_source: "workflows.issue.triggerNoSource";
35
+ readonly trigger_many_sources: "workflows.issue.triggerManySources";
36
+ readonly trigger_no_target: "workflows.issue.triggerNoTarget";
37
+ readonly trigger_config_incomplete: "workflows.issue.triggerConfigIncomplete";
38
+ readonly schedule_invalid: "workflows.issue.scheduleInvalid";
39
+ readonly event_value_invalid: "workflows.issue.eventValueInvalid";
40
+ readonly trigger_capability_missing: "workflows.issue.triggerCapabilityMissing";
41
+ readonly condition_no_source: "workflows.issue.conditionNoSource";
42
+ readonly condition_many_sources: "workflows.issue.conditionManySources";
43
+ readonly condition_no_cases: "workflows.issue.conditionNoCases";
44
+ readonly condition_too_many_cases: "workflows.issue.conditionTooManyCases";
45
+ readonly case_bad_id: "workflows.issue.caseBadId";
46
+ readonly case_duplicate_id: "workflows.issue.caseDuplicateId";
47
+ readonly case_no_tests: "workflows.issue.caseNoTests";
48
+ readonly case_too_many_tests: "workflows.issue.caseTooManyTests";
49
+ readonly case_no_target: "workflows.issue.caseNoTarget";
50
+ readonly test_bad_field: "workflows.issue.testBadField";
51
+ readonly test_bad_operator: "workflows.issue.testBadOperator";
52
+ readonly test_missing_value: "workflows.issue.testMissingValue";
53
+ readonly field_unknown: "workflows.issue.fieldUnknown";
54
+ };
55
+ /** What the words of an issue are made from: the translator, and how a block is called in the person's workflow. */
56
+ export interface IssueTextContext {
57
+ t: (key: WorkflowsMessageKey, values?: Readonly<Record<string, string | number>>) => string;
58
+ /** What the block is called on the canvas (the composition's name, "Trigger", "Condition"): a name the person can find. */
59
+ describeBlock: (nodeId: string) => string;
60
+ }
61
+ /** The message that says an issue. */
62
+ export declare function pickIssueMessageKey(issue: ValidationIssue): WorkflowsMessageKey;
63
+ /** One sentence for an issue, in the person's language. */
64
+ export declare function describeIssue(issue: ValidationIssue, context: IssueTextContext): string;
@@ -0,0 +1,101 @@
1
+ import { MAX_BLOCKS, MAX_CASES_PER_CONDITION, MAX_TESTS_PER_CASE } from '@widgetic/workflows-engine';
2
+ /**
3
+ * The words for what the engine found wrong with a workflow. The engine reports a code (never a sentence) and the block it
4
+ * belongs to; here each code is one message of the catalog, so the draft check, the publish check of the server and the
5
+ * highlight on the canvas all say the same thing in the person's language.
6
+ *
7
+ * `ISSUE_MESSAGE_KEYS` has to name every code the engine can report (the type says so, and a test reads the engine's list
8
+ * of codes): a code with no message would be an error the person cannot read.
9
+ */
10
+ export const ISSUE_MESSAGE_KEYS = {
11
+ malformed: 'workflows.issue.malformed',
12
+ schema_version: 'workflows.issue.schemaVersion',
13
+ graph_too_large: 'workflows.issue.graphTooLarge',
14
+ unknown_node_type: 'workflows.issue.unknownNodeType',
15
+ unknown_trigger_kind: 'workflows.issue.unknownTriggerKind',
16
+ bad_id: 'workflows.issue.badId',
17
+ duplicate_id: 'workflows.issue.duplicateId',
18
+ too_many_blocks: 'workflows.issue.tooManyBlocks',
19
+ too_many_edges: 'workflows.issue.tooManyEdges',
20
+ no_composition: 'workflows.issue.noComposition',
21
+ no_start: 'workflows.issue.noStart',
22
+ many_starts: 'workflows.issue.manyStarts',
23
+ composition_missing_id: 'workflows.issue.compositionMissingId',
24
+ duplicate_composition: 'workflows.issue.duplicateComposition',
25
+ composition_not_available: 'workflows.issue.compositionNotAvailable',
26
+ composition_website_mismatch: 'workflows.issue.compositionWebsiteMismatch',
27
+ unreachable_block: 'workflows.issue.unreachableBlock',
28
+ edge_unknown_node: 'workflows.issue.edgeUnknownNode',
29
+ edge_bad_port: 'workflows.issue.edgeBadPort',
30
+ edge_invalid_connection: 'workflows.issue.edgeInvalidConnection',
31
+ port_many_targets: 'workflows.issue.portManyTargets',
32
+ cycle: 'workflows.issue.cycle',
33
+ trigger_no_source: 'workflows.issue.triggerNoSource',
34
+ trigger_many_sources: 'workflows.issue.triggerManySources',
35
+ trigger_no_target: 'workflows.issue.triggerNoTarget',
36
+ trigger_config_incomplete: 'workflows.issue.triggerConfigIncomplete',
37
+ schedule_invalid: 'workflows.issue.scheduleInvalid',
38
+ event_value_invalid: 'workflows.issue.eventValueInvalid',
39
+ trigger_capability_missing: 'workflows.issue.triggerCapabilityMissing',
40
+ condition_no_source: 'workflows.issue.conditionNoSource',
41
+ condition_many_sources: 'workflows.issue.conditionManySources',
42
+ condition_no_cases: 'workflows.issue.conditionNoCases',
43
+ condition_too_many_cases: 'workflows.issue.conditionTooManyCases',
44
+ case_bad_id: 'workflows.issue.caseBadId',
45
+ case_duplicate_id: 'workflows.issue.caseDuplicateId',
46
+ case_no_tests: 'workflows.issue.caseNoTests',
47
+ case_too_many_tests: 'workflows.issue.caseTooManyTests',
48
+ case_no_target: 'workflows.issue.caseNoTarget',
49
+ test_bad_field: 'workflows.issue.testBadField',
50
+ test_bad_operator: 'workflows.issue.testBadOperator',
51
+ test_missing_value: 'workflows.issue.testMissingValue',
52
+ field_unknown: 'workflows.issue.fieldUnknown'
53
+ };
54
+ /**
55
+ * Codes whose message depends on a detail the engine adds. The detail is a short machine-readable word (`table`, `count`,
56
+ * `input:Entries`), never a sentence, so the choice is made here and the words stay in the catalog.
57
+ */
58
+ const SPECIFIC_MESSAGE_KEYS = {
59
+ trigger_config_incomplete: {
60
+ table: 'workflows.issue.triggerNeedsTable',
61
+ actionId: 'workflows.issue.triggerNeedsAction',
62
+ name: 'workflows.issue.triggerNeedsName'
63
+ },
64
+ event_value_invalid: {
65
+ count: 'workflows.issue.eventTooManyValues'
66
+ },
67
+ trigger_capability_missing: {
68
+ input: 'workflows.issue.triggerInputMissing',
69
+ action: 'workflows.issue.triggerActionMissing'
70
+ }
71
+ };
72
+ /** The message that says an issue. */
73
+ export function pickIssueMessageKey(issue) {
74
+ const specific = SPECIFIC_MESSAGE_KEYS[issue.code];
75
+ if (specific && issue.detail) {
76
+ // `input:Entries` is the kind of the detail, then what it names.
77
+ const detailKind = issue.detail.split(':', 1)[0];
78
+ const specificKey = specific[detailKind];
79
+ if (specificKey)
80
+ return specificKey;
81
+ }
82
+ return ISSUE_MESSAGE_KEYS[issue.code] ?? 'workflows.issue.unknown';
83
+ }
84
+ /** What a specific detail names: `Entries` for `input:Entries`, the id for `action:id`, the value's name for an event value. */
85
+ function readNamedThing(issue) {
86
+ const detail = issue.detail ?? '';
87
+ const separatorIndex = detail.indexOf(':');
88
+ return separatorIndex === -1 ? detail : detail.slice(separatorIndex + 1);
89
+ }
90
+ /** One sentence for an issue, in the person's language. */
91
+ export function describeIssue(issue, context) {
92
+ const block = issue.nodeId === undefined ? '' : context.describeBlock(issue.nodeId);
93
+ return context.t(pickIssueMessageKey(issue), {
94
+ block,
95
+ name: readNamedThing(issue),
96
+ field: issue.detail ?? '',
97
+ maxBlocks: MAX_BLOCKS,
98
+ maxRules: MAX_CASES_PER_CONDITION,
99
+ maxTests: MAX_TESTS_PER_CASE
100
+ });
101
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Keeping what a person did when somebody else saved the draft first.
3
+ *
4
+ * Two people open the same workflow. One saves; the other's next save is refused (the draft is no longer the one that
5
+ * person started from). Nothing the other person typed is lost until they load the latest version, because that replaces
6
+ * the screen with the draft the server holds. So before that, the person may keep a copy: a new workflow that holds what
7
+ * is on their screen. No part of the API is new for it, a copy is a workflow made and then saved like any other:
8
+ *
9
+ * 1. the new workflow is made, with the name and the time zone the person has (`createWorkflow`);
10
+ * 2. the blocks and lines the person has are saved into it (`saveDraft`, with the revision the new workflow answered).
11
+ *
12
+ * If the second step fails the first is taken back (the workflow made is deleted: it was never published, so it can be), so
13
+ * that a failed attempt does not leave an empty workflow named after the person's work. Nothing is ever done to the workflow
14
+ * the person is editing: the other person's draft is not touched.
15
+ */
16
+ import type { WorkflowGraph } from '@widgetic/workflows-engine';
17
+ import type { WorkflowsApi } from '../api/workflowsApi.js';
18
+ /** The workflow that holds the person's changes. */
19
+ export interface KeptCopy {
20
+ id: string;
21
+ name: string;
22
+ }
23
+ /** What is on the person's screen and is to be kept. */
24
+ export interface KeepCopyInput {
25
+ /** The name of the copy, already worded in the person's language and cut to fit (see {@link nameForCopy}). */
26
+ name: string;
27
+ timezone: string;
28
+ graph: WorkflowGraph;
29
+ }
30
+ /**
31
+ * The name of a copy: the person's own words around the name of the workflow (`wording` puts them there, in the person's
32
+ * language: "{name} (my changes)"), cut so that the whole is at most what the API accepts. It is the workflow's name that
33
+ * gives way, with an ellipsis, never the words around it; a letter is never cut in two (an emoji is one letter here).
34
+ */
35
+ export declare function nameForCopy(name: string, wording: (name: string) => string, max?: number): string;
36
+ /**
37
+ * Makes a new workflow that holds the draft on the person's screen, and answers it. If the draft cannot be saved into it,
38
+ * the new workflow is deleted again and the failure is thrown. `signal` cancels the requests of the copy (the screen was
39
+ * left); the clean-up after a failure is made anyway.
40
+ */
41
+ export declare function keepCopyOfDraft(api: WorkflowsApi, input: KeepCopyInput, signal?: AbortSignal): Promise<KeptCopy>;