@widgetic/workflows 0.2.15 → 0.2.16

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 (107) hide show
  1. package/README.md +117 -3
  2. package/dist/api/types.d.ts +17 -0
  3. package/dist/api/workflowsApi.d.ts +12 -1
  4. package/dist/api/workflowsApi.js +37 -0
  5. package/dist/assistant/assistantEvents.d.ts +44 -2
  6. package/dist/assistant/assistantEvents.js +58 -2
  7. package/dist/assistant/assistantReferences.d.ts +66 -0
  8. package/dist/assistant/assistantReferences.js +109 -0
  9. package/dist/assistant/assistantSaveMode.d.ts +15 -3
  10. package/dist/assistant/assistantSaveMode.js +16 -2
  11. package/dist/assistant/assistantSeed.d.ts +55 -0
  12. package/dist/assistant/assistantSeed.js +90 -0
  13. package/dist/assistant/assistantStream.js +81 -3
  14. package/dist/assistant/assistantSuggest.d.ts +18 -0
  15. package/dist/assistant/assistantSuggest.js +21 -0
  16. package/dist/assistant/assistantTurns.d.ts +75 -0
  17. package/dist/assistant/assistantTurns.js +56 -0
  18. package/dist/assistant/attachmentUploads.d.ts +42 -0
  19. package/dist/assistant/attachmentUploads.js +69 -0
  20. package/dist/assistant/canvasLink.d.ts +30 -0
  21. package/dist/assistant/canvasLink.js +51 -0
  22. package/dist/assistant/compositionMention.d.ts +18 -0
  23. package/dist/assistant/compositionMention.js +47 -0
  24. package/dist/assistant/liveData.d.ts +150 -0
  25. package/dist/assistant/liveData.js +286 -0
  26. package/dist/assistant/mcpMention.d.ts +20 -0
  27. package/dist/assistant/mcpMention.js +30 -0
  28. package/dist/assistant/mentionEntries.d.ts +39 -0
  29. package/dist/assistant/mentionEntries.js +69 -0
  30. package/dist/assistant/planFlow.d.ts +26 -0
  31. package/dist/assistant/planFlow.js +57 -0
  32. package/dist/assistant/templateDestinations.d.ts +37 -0
  33. package/dist/assistant/templateDestinations.js +64 -0
  34. package/dist/assistant/types.d.ts +99 -2
  35. package/dist/assistant/workflowPlanViewModel.d.ts +13 -2
  36. package/dist/assistant/workflowPlanViewModel.js +9 -1
  37. package/dist/components/Workflows.svelte +7 -1
  38. package/dist/components/WorkflowsWorkspace.svelte +29 -1
  39. package/dist/components/WorkflowsWorkspace.svelte.d.ts +3 -0
  40. package/dist/components/assistant/AssistantPlanStepRow.svelte +56 -0
  41. package/dist/components/assistant/AssistantPlanStepRow.svelte.d.ts +9 -0
  42. package/dist/components/assistant/CompositionMentionMenu.svelte +135 -0
  43. package/dist/components/assistant/CompositionMentionMenu.svelte.d.ts +9 -0
  44. package/dist/components/assistant/DataPreviewCard.svelte +108 -0
  45. package/dist/components/assistant/DataPreviewCard.svelte.d.ts +7 -0
  46. package/dist/components/assistant/PlanBindingsBlock.svelte +200 -0
  47. package/dist/components/assistant/PlanBindingsBlock.svelte.d.ts +14 -0
  48. package/dist/components/assistant/TemplateProjectCard.svelte +81 -0
  49. package/dist/components/assistant/TemplateProjectCard.svelte.d.ts +14 -0
  50. package/dist/components/assistant/WorkflowAssistantPanel.svelte +1045 -147
  51. package/dist/components/assistant/WorkflowAssistantPanel.svelte.d.ts +5 -0
  52. package/dist/components/canvas/CanvasContextMenu.svelte +199 -0
  53. package/dist/components/canvas/CanvasContextMenu.svelte.d.ts +16 -0
  54. package/dist/components/canvas/CompositionNodeView.svelte +7 -2
  55. package/dist/components/canvas/ConditionNodeView.svelte +5 -1
  56. package/dist/components/canvas/HandlePoint.svelte +25 -3
  57. package/dist/components/canvas/WorkflowCanvas.svelte +351 -12
  58. package/dist/components/canvas/WorkflowCanvas.svelte.d.ts +12 -1
  59. package/dist/components/canvas/altDragDuplicateController.d.ts +29 -0
  60. package/dist/components/canvas/altDragDuplicateController.js +92 -0
  61. package/dist/components/canvas/connectionSnapController.d.ts +29 -0
  62. package/dist/components/canvas/connectionSnapController.js +182 -0
  63. package/dist/components/canvas/spacePanController.d.ts +16 -0
  64. package/dist/components/canvas/spacePanController.js +103 -0
  65. package/dist/components/editor/EditorCanvasArea.svelte +98 -4
  66. package/dist/components/editor/EditorCanvasArea.svelte.d.ts +5 -0
  67. package/dist/components/editor/EditorTopBar.svelte +53 -42
  68. package/dist/components/editor/WorkflowEditor.svelte +74 -41
  69. package/dist/components/editor/WorkflowEditor.svelte.d.ts +5 -0
  70. package/dist/components/editor/WorkflowNameControl.svelte +9 -8
  71. package/dist/components/editor/WorkflowNameControl.svelte.d.ts +3 -1
  72. package/dist/components/list/WorkflowList.svelte +34 -20
  73. package/dist/components/list/WorkflowList.svelte.d.ts +5 -0
  74. package/dist/components/panel/CompositionForm.svelte +3 -2
  75. package/dist/components/panel/CompositionPicker.svelte +15 -20
  76. package/dist/components/panel/CompositionPicker.svelte.d.ts +2 -2
  77. package/dist/components/panel/CompositionSelect.svelte +4 -4
  78. package/dist/components/panel/CompositionSelect.svelte.d.ts +2 -2
  79. package/dist/components/ui/icons.d.ts +8 -0
  80. package/dist/components/ui/icons.js +24 -1
  81. package/dist/editor/autoLayout.d.ts +38 -0
  82. package/dist/editor/autoLayout.js +403 -0
  83. package/dist/editor/blockClipboard.svelte.d.ts +9 -0
  84. package/dist/editor/blockClipboard.svelte.js +24 -0
  85. package/dist/editor/blockCopy.d.ts +39 -0
  86. package/dist/editor/blockCopy.js +137 -0
  87. package/dist/editor/canvasMenu.d.ts +45 -0
  88. package/dist/editor/canvasMenu.js +68 -0
  89. package/dist/editor/connectionSnap.d.ts +90 -0
  90. package/dist/editor/connectionSnap.js +98 -0
  91. package/dist/editor/editorState.svelte.d.ts +122 -13
  92. package/dist/editor/editorState.svelte.js +262 -22
  93. package/dist/editor/graphIssues.d.ts +5 -0
  94. package/dist/editor/graphIssues.js +18 -0
  95. package/dist/editor/graphModel.d.ts +6 -1
  96. package/dist/editor/graphModel.js +8 -1
  97. package/dist/editor/keyHints.d.ts +21 -0
  98. package/dist/editor/keyHints.js +30 -0
  99. package/dist/editor/listState.svelte.d.ts +4 -4
  100. package/dist/editor/staleGuard.d.ts +111 -0
  101. package/dist/editor/staleGuard.js +279 -0
  102. package/dist/i18n/language.d.ts +3 -3
  103. package/dist/i18n/messages.d.ts +84 -1
  104. package/dist/i18n/messages.js +97 -4
  105. package/dist/index.d.ts +1 -0
  106. package/dist/types/index.d.ts +19 -2
  107. package/package.json +10 -10
@@ -0,0 +1,403 @@
1
+ /**
2
+ * Organise: where the blocks of a workflow go so that it is easy to follow. Plain data in and out (the engine's graph and
3
+ * the sizes of the blocks as the canvas measured them); nothing draws and nothing is stored.
4
+ *
5
+ * What the result looks like:
6
+ * - the workflow runs from left to right: a block is always in a column to the right of the blocks that lead to it, and the
7
+ * first composition (the start) is in the first column;
8
+ * - a condition's outputs come out of the block top to bottom (the order of its rules, then Default), and the blocks they
9
+ * lead to are in that same order, so lines from one condition do not cross each other;
10
+ * - a block sits level with the place its line leaves from, so a chain of blocks is a straight line when it can be;
11
+ * - no two blocks touch, and blocks that are not connected to the others are kept under the connected ones, side by side in
12
+ * rows as wide as the widest group of connected blocks (at least `SHELF_MIN_WIDTH`), so that a workflow whose lines were
13
+ * all taken away is a tidy grid and not one very long column;
14
+ * - the same workflow organised again stays where it is (the order inside a column starts from where the blocks are, and
15
+ * settles on an order that is then its own starting point).
16
+ *
17
+ * A graph the engine would refuse (a line back to an earlier block, a block with no line) is laid out too: the line that
18
+ * goes back is left out of the reckoning, so that the blocks it ties together are still in an order that makes sense.
19
+ */
20
+ import { DEFAULT_PORT } from '@widgetic/workflows-engine';
21
+ import { FIRST_BLOCK_POSITION } from './graphModel.js';
22
+ /** The room between two columns: enough for the line between them to be seen and for its arrow. */
23
+ export const COLUMN_GAP = 120;
24
+ export const ROW_GAP = 48;
25
+ export const GROUP_GAP = 96;
26
+ /**
27
+ * How wide a row of blocks that are not connected may be at least, in canvas units: four compositions side by side. A row is
28
+ * as wide as the widest group of connected blocks when that one is wider, so the grid lines up with the flow above it.
29
+ */
30
+ export const SHELF_MIN_WIDTH = 1500;
31
+ /** How tall a block is when the canvas has not measured it (the canvas always does; this is for a canvas that is not drawn). */
32
+ const ESTIMATED_SIZES = {
33
+ composition: { width: 240, height: 180 },
34
+ trigger: { width: 232, height: 100 }
35
+ };
36
+ const ESTIMATED_CONDITION = { width: 264, headerHeight: 48, rowHeight: 53 };
37
+ /** How many times the order of a column is looked at again, going left to right and back; it stops sooner when it is settled. */
38
+ const MAX_ORDERING_SWEEPS = 8;
39
+ /** How many times the places are made level with the lines that lead to them and from them. */
40
+ const ALIGNMENT_PASSES = 4;
41
+ /** The ports of a block in the order they are drawn, top to bottom. */
42
+ export function listPorts(node) {
43
+ return node.type === 'condition' ? [...node.cases.map((rule) => rule.id), DEFAULT_PORT] : ['out'];
44
+ }
45
+ function estimateMeasure(node) {
46
+ if (node.type !== 'condition') {
47
+ const size = ESTIMATED_SIZES[node.type];
48
+ return {
49
+ width: size.width,
50
+ height: size.height,
51
+ inputOffset: size.height / 2,
52
+ outputOffsets: { out: size.height / 2 }
53
+ };
54
+ }
55
+ const rows = node.cases.length + 1;
56
+ const height = ESTIMATED_CONDITION.headerHeight + rows * ESTIMATED_CONDITION.rowHeight;
57
+ const outputOffsets = {};
58
+ listPorts(node).forEach((port, index) => {
59
+ outputOffsets[port] =
60
+ ESTIMATED_CONDITION.headerHeight +
61
+ index * ESTIMATED_CONDITION.rowHeight +
62
+ ESTIMATED_CONDITION.rowHeight / 2;
63
+ });
64
+ return { width: ESTIMATED_CONDITION.width, height, inputOffset: height / 2, outputOffsets };
65
+ }
66
+ function completeMeasure(node, measured) {
67
+ const estimate = estimateMeasure(node);
68
+ if (!measured || !(measured.width > 0) || !(measured.height > 0))
69
+ return estimate;
70
+ const outputOffsets = {};
71
+ for (const port of listPorts(node)) {
72
+ const offset = measured.outputOffsets?.[port];
73
+ outputOffsets[port] = Number.isFinite(offset) ? offset : measured.height / 2;
74
+ }
75
+ return {
76
+ width: measured.width,
77
+ height: measured.height,
78
+ inputOffset: Number.isFinite(measured.inputOffset)
79
+ ? measured.inputOffset
80
+ : measured.height / 2,
81
+ outputOffsets
82
+ };
83
+ }
84
+ function compareText(left, right) {
85
+ return left < right ? -1 : left > right ? 1 : 0;
86
+ }
87
+ /**
88
+ * Where each block of the graph goes, as the new graph. A graph with no blocks, or in which no block needs to move, comes
89
+ * back as it is.
90
+ */
91
+ export function organiseGraph(graph, options = {}) {
92
+ if (graph.nodes.length === 0)
93
+ return graph;
94
+ const columnGap = options.columnGap ?? COLUMN_GAP;
95
+ const rowGap = options.rowGap ?? ROW_GAP;
96
+ const groupGap = options.groupGap ?? GROUP_GAP;
97
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
98
+ const measures = new Map(graph.nodes.map((node) => [node.id, completeMeasure(node, options.measureBlock?.(node))]));
99
+ const currentPosition = (nodeId) => nodesById.get(nodeId)?.position ?? { x: 0, y: 0 };
100
+ // Where the result goes: where the blocks are now, at their top left corner.
101
+ const positioned = graph.nodes.filter((node) => node.position !== undefined);
102
+ const origin = options.origin ??
103
+ (positioned.length > 0
104
+ ? {
105
+ x: Math.min(...positioned.map((node) => node.position.x)),
106
+ y: Math.min(...positioned.map((node) => node.position.y))
107
+ }
108
+ : { ...FIRST_BLOCK_POSITION });
109
+ // Every line that joins two blocks of this graph (a line to a block that is gone is not a line).
110
+ const edges = graph.edges.filter((edge) => nodesById.has(edge.source) && nodesById.has(edge.target) && edge.source !== edge.target);
111
+ // ---- groups of blocks that are joined (a line either way) ----------------------------------------------------------
112
+ const groupOf = new Map();
113
+ const findGroup = (nodeId) => {
114
+ let root = nodeId;
115
+ while (groupOf.get(root) !== root)
116
+ root = groupOf.get(root) ?? root;
117
+ return root;
118
+ };
119
+ for (const node of graph.nodes)
120
+ groupOf.set(node.id, node.id);
121
+ for (const edge of edges) {
122
+ const sourceGroup = findGroup(edge.source);
123
+ const targetGroup = findGroup(edge.target);
124
+ if (sourceGroup !== targetGroup)
125
+ groupOf.set(targetGroup, sourceGroup);
126
+ }
127
+ const groups = new Map();
128
+ for (const node of graph.nodes) {
129
+ const root = findGroup(node.id);
130
+ groups.set(root, [...(groups.get(root) ?? []), node]);
131
+ }
132
+ // The group with the start comes first, then the groups of joined blocks, then the blocks that are alone; each of those in
133
+ // the order they are on the canvas now.
134
+ const orderedGroups = [...groups.values()].sort((left, right) => {
135
+ const leftHasStart = left.some((node) => node.type === 'composition' && node.startsHere === true);
136
+ const rightHasStart = right.some((node) => node.type === 'composition' && node.startsHere === true);
137
+ if (leftHasStart !== rightHasStart)
138
+ return leftHasStart ? -1 : 1;
139
+ if ((left.length === 1) !== (right.length === 1))
140
+ return left.length === 1 ? 1 : -1;
141
+ const leftTop = Math.min(...left.map((node) => currentPosition(node.id).y));
142
+ const rightTop = Math.min(...right.map((node) => currentPosition(node.id).y));
143
+ if (leftTop !== rightTop)
144
+ return leftTop - rightTop;
145
+ const leftLeft = Math.min(...left.map((node) => currentPosition(node.id).x));
146
+ const rightLeft = Math.min(...right.map((node) => currentPosition(node.id).x));
147
+ if (leftLeft !== rightLeft)
148
+ return leftLeft - rightLeft;
149
+ return compareText(left.map((node) => node.id).sort(compareText)[0] ?? '', right.map((node) => node.id).sort(compareText)[0] ?? '');
150
+ });
151
+ const groupLayouts = orderedGroups.map((group) => {
152
+ const groupIds = new Set(group.map((node) => node.id));
153
+ return {
154
+ isAlone: group.length === 1,
155
+ layout: layOutGroup({
156
+ nodes: group,
157
+ edges: edges.filter((edge) => groupIds.has(edge.source)),
158
+ measures,
159
+ currentPosition,
160
+ columnGap,
161
+ rowGap
162
+ })
163
+ };
164
+ });
165
+ // Where the groups go: a group of connected blocks has a row of its own (one under the other, the start's first); a block
166
+ // with no line goes next to the one before it while the row is not full, then the next row starts.
167
+ const shelfWidth = Math.max(SHELF_MIN_WIDTH, ...groupLayouts.map(({ layout }) => layout.width));
168
+ const placed = new Map();
169
+ let rowTop = origin.y;
170
+ let rowLeft = 0;
171
+ let rowHeight = 0;
172
+ /** Ends the row that is being filled: the next group starts at the left of a new row. */
173
+ const startNewRow = () => {
174
+ if (rowHeight > 0)
175
+ rowTop += rowHeight + groupGap;
176
+ rowLeft = 0;
177
+ rowHeight = 0;
178
+ };
179
+ for (const { isAlone, layout } of groupLayouts) {
180
+ if (!isAlone || (rowLeft > 0 && rowLeft + layout.width > shelfWidth))
181
+ startNewRow();
182
+ for (const [nodeId, position] of layout.positions) {
183
+ placed.set(nodeId, { x: origin.x + rowLeft + position.x, y: rowTop + position.y });
184
+ }
185
+ rowHeight = Math.max(rowHeight, layout.height);
186
+ if (isAlone)
187
+ rowLeft += layout.width + groupGap;
188
+ else
189
+ startNewRow();
190
+ }
191
+ let changed = false;
192
+ const nodes = graph.nodes.map((node) => {
193
+ const position = placed.get(node.id);
194
+ if (!position)
195
+ return node;
196
+ const rounded = { x: Math.round(position.x), y: Math.round(position.y) };
197
+ if (node.position && node.position.x === rounded.x && node.position.y === rounded.y)
198
+ return node;
199
+ changed = true;
200
+ return { ...node, position: rounded };
201
+ });
202
+ return changed ? { ...graph, nodes } : graph;
203
+ }
204
+ /** Lays out one group of joined blocks: columns, order inside the columns, and the height of each block's place. */
205
+ function layOutGroup(input) {
206
+ const { nodes, measures, columnGap, rowGap } = input;
207
+ const nodeIds = new Set(nodes.map((node) => node.id));
208
+ const nodesById = new Map(nodes.map((node) => [node.id, node]));
209
+ const measureOf = (nodeId) => measures.get(nodeId);
210
+ // Where the blocks are now, top to bottom then left to right: the order that is kept when nothing says another.
211
+ const byCurrentPlace = (left, right) => {
212
+ const leftPlace = input.currentPosition(left);
213
+ const rightPlace = input.currentPosition(right);
214
+ return leftPlace.y - rightPlace.y || leftPlace.x - rightPlace.x || compareText(left, right);
215
+ };
216
+ // ---- the lines, with the place of their port ---------------------------------------------------------------------
217
+ const portIndexOf = (edge) => {
218
+ const node = nodesById.get(edge.source);
219
+ const index = node ? listPorts(node).indexOf(edge.sourcePort) : -1;
220
+ return index < 0 ? 0 : index;
221
+ };
222
+ const links = input.edges
223
+ .filter((edge) => nodeIds.has(edge.source) && nodeIds.has(edge.target))
224
+ .map((edge) => ({ edge, portIndex: portIndexOf(edge), isBack: false }));
225
+ const linksFrom = new Map();
226
+ const linksTo = new Map();
227
+ for (const link of links) {
228
+ linksFrom.set(link.edge.source, [...(linksFrom.get(link.edge.source) ?? []), link]);
229
+ linksTo.set(link.edge.target, [...(linksTo.get(link.edge.target) ?? []), link]);
230
+ }
231
+ const outgoing = (nodeId) => (linksFrom.get(nodeId) ?? []).filter((link) => !link.isBack);
232
+ const incoming = (nodeId) => (linksTo.get(nodeId) ?? []).filter((link) => !link.isBack);
233
+ // ---- lines that go back are left out ------------------------------------------------------------------------------
234
+ // Looked for from the start first (a line back to the start is the usual one), then from the blocks nothing leads to.
235
+ const hasStart = (nodeId) => {
236
+ const node = nodesById.get(nodeId);
237
+ return node?.type === 'composition' && node.startsHere === true;
238
+ };
239
+ const roots = [...nodeIds].sort((left, right) => {
240
+ const leftRank = hasStart(left) ? 0 : (linksTo.get(left)?.length ?? 0) === 0 ? 1 : 2;
241
+ const rightRank = hasStart(right) ? 0 : (linksTo.get(right)?.length ?? 0) === 0 ? 1 : 2;
242
+ return leftRank - rightRank || byCurrentPlace(left, right);
243
+ });
244
+ const visiting = new Set();
245
+ const visited = new Set();
246
+ const visit = (nodeId) => {
247
+ visiting.add(nodeId);
248
+ const next = [...(linksFrom.get(nodeId) ?? [])].sort((left, right) => left.portIndex - right.portIndex || byCurrentPlace(left.edge.target, right.edge.target));
249
+ for (const link of next) {
250
+ if (visiting.has(link.edge.target)) {
251
+ link.isBack = true;
252
+ }
253
+ else if (!visited.has(link.edge.target)) {
254
+ visit(link.edge.target);
255
+ }
256
+ }
257
+ visiting.delete(nodeId);
258
+ visited.add(nodeId);
259
+ };
260
+ for (const root of roots)
261
+ if (!visited.has(root))
262
+ visit(root);
263
+ // ---- columns: a block is one column to the right of the furthest block that leads to it --------------------------
264
+ const columnOf = new Map();
265
+ const remainingIncoming = new Map([...nodeIds].map((nodeId) => [nodeId, incoming(nodeId).length]));
266
+ const ready = [...nodeIds].filter((nodeId) => remainingIncoming.get(nodeId) === 0);
267
+ for (const nodeId of ready)
268
+ columnOf.set(nodeId, 0);
269
+ for (let cursor = 0; cursor < ready.length; cursor += 1) {
270
+ const nodeId = ready[cursor];
271
+ for (const link of outgoing(nodeId)) {
272
+ const target = link.edge.target;
273
+ columnOf.set(target, Math.max(columnOf.get(target) ?? 0, (columnOf.get(nodeId) ?? 0) + 1));
274
+ const remaining = (remainingIncoming.get(target) ?? 1) - 1;
275
+ remainingIncoming.set(target, remaining);
276
+ if (remaining === 0)
277
+ ready.push(target);
278
+ }
279
+ }
280
+ for (const nodeId of nodeIds)
281
+ if (!columnOf.has(nodeId))
282
+ columnOf.set(nodeId, 0);
283
+ const columnCount = Math.max(...[...columnOf.values()]) + 1;
284
+ const columns = Array.from({ length: columnCount }, () => []);
285
+ for (const nodeId of nodeIds)
286
+ columns[columnOf.get(nodeId) ?? 0].push(nodeId);
287
+ // The start is the first of its column; the others stay in the order they are on the canvas now.
288
+ for (const column of columns) {
289
+ column.sort((left, right) => {
290
+ const leftStart = hasStart(left) ? 0 : 1;
291
+ const rightStart = hasStart(right) ? 0 : 1;
292
+ return leftStart - rightStart || byCurrentPlace(left, right);
293
+ });
294
+ }
295
+ // ---- the order inside a column: blocks go where the blocks they are joined to are -------------------------------
296
+ const rankOf = new Map();
297
+ const writeRanks = () => {
298
+ for (const column of columns)
299
+ column.forEach((nodeId, index) => rankOf.set(nodeId, index));
300
+ };
301
+ writeRanks();
302
+ /** Where a line is in the column of its source block: its block's rank, and a little for how far down the block its port is. */
303
+ const portFraction = (link) => {
304
+ const portCount = listPorts(nodesById.get(link.edge.source)).length;
305
+ return link.portIndex / Math.max(portCount, 1);
306
+ };
307
+ const sortColumn = (column, keyOf) => {
308
+ const before = column.join('|');
309
+ const rankBefore = new Map(column.map((nodeId, index) => [nodeId, index]));
310
+ column.sort((left, right) => keyOf(left) - keyOf(right) || rankBefore.get(left) - rankBefore.get(right));
311
+ return column.join('|') !== before;
312
+ };
313
+ for (let sweep = 0; sweep < MAX_ORDERING_SWEEPS; sweep += 1) {
314
+ let moved = false;
315
+ // Left to right: by the blocks that lead to it
316
+ for (let index = 1; index < columns.length; index += 1) {
317
+ moved =
318
+ sortColumn(columns[index], (nodeId) => {
319
+ const leading = incoming(nodeId);
320
+ if (leading.length === 0)
321
+ return rankOf.get(nodeId) ?? 0;
322
+ return (leading.reduce((sum, link) => sum + (rankOf.get(link.edge.source) ?? 0) + portFraction(link), 0) / leading.length);
323
+ }) || moved;
324
+ writeRanks();
325
+ }
326
+ // Right to left: by the blocks it leads to
327
+ for (let index = columns.length - 2; index >= 0; index -= 1) {
328
+ moved =
329
+ sortColumn(columns[index], (nodeId) => {
330
+ const leaving = outgoing(nodeId);
331
+ if (leaving.length === 0)
332
+ return rankOf.get(nodeId) ?? 0;
333
+ return (leaving.reduce((sum, link) => sum + (rankOf.get(link.edge.target) ?? 0), 0) /
334
+ leaving.length);
335
+ }) || moved;
336
+ writeRanks();
337
+ }
338
+ if (!moved)
339
+ break;
340
+ }
341
+ // ---- height: level with the places the lines leave from and come in at -------------------------------------------
342
+ const top = new Map();
343
+ for (const column of columns) {
344
+ let cursor = 0;
345
+ for (const nodeId of column) {
346
+ top.set(nodeId, cursor);
347
+ cursor += measureOf(nodeId).height + rowGap;
348
+ }
349
+ }
350
+ /** Puts the blocks of a column at the heights they would like, without two of them touching. Keeps their order. */
351
+ const settleColumn = (column, wanted) => {
352
+ let floor = Number.NEGATIVE_INFINITY;
353
+ for (const nodeId of column) {
354
+ const placeTop = Math.max(wanted(nodeId), floor);
355
+ top.set(nodeId, placeTop);
356
+ floor = placeTop + measureOf(nodeId).height + rowGap;
357
+ }
358
+ };
359
+ const levelWithSources = (nodeId) => {
360
+ const leading = incoming(nodeId);
361
+ if (leading.length === 0)
362
+ return top.get(nodeId) ?? 0;
363
+ const total = leading.reduce((sum, link) => sum +
364
+ (top.get(link.edge.source) ?? 0) +
365
+ (measureOf(link.edge.source).outputOffsets[link.edge.sourcePort] ??
366
+ measureOf(link.edge.source).height / 2), 0);
367
+ return total / leading.length - measureOf(nodeId).inputOffset;
368
+ };
369
+ const levelWithTargets = (nodeId) => {
370
+ const leaving = outgoing(nodeId);
371
+ if (leaving.length === 0)
372
+ return top.get(nodeId) ?? 0;
373
+ const total = leaving.reduce((sum, link) => sum +
374
+ (top.get(link.edge.target) ?? 0) +
375
+ measureOf(link.edge.target).inputOffset -
376
+ (measureOf(nodeId).outputOffsets[link.edge.sourcePort] ?? measureOf(nodeId).height / 2), 0);
377
+ return total / leaving.length;
378
+ };
379
+ for (let pass = 0; pass < ALIGNMENT_PASSES; pass += 1) {
380
+ for (let index = 1; index < columns.length; index += 1)
381
+ settleColumn(columns[index], levelWithSources);
382
+ for (let index = columns.length - 2; index >= 0; index -= 1)
383
+ settleColumn(columns[index], levelWithTargets);
384
+ }
385
+ // Last, the blocks follow the blocks that lead to them: a line comes out of a block and goes straight to the next.
386
+ for (let index = 1; index < columns.length; index += 1)
387
+ settleColumn(columns[index], levelWithSources);
388
+ // ---- the group's own corner is its top left block ------------------------------------------------------------------
389
+ const groupTop = Math.min(...[...top.values()]);
390
+ const positions = new Map();
391
+ let columnLeft = 0;
392
+ let height = 0;
393
+ columns.forEach((column) => {
394
+ for (const nodeId of column) {
395
+ const placeTop = (top.get(nodeId) ?? 0) - groupTop;
396
+ positions.set(nodeId, { x: columnLeft, y: placeTop });
397
+ height = Math.max(height, placeTop + measureOf(nodeId).height);
398
+ }
399
+ columnLeft += Math.max(0, ...column.map((nodeId) => measureOf(nodeId).width)) + columnGap;
400
+ });
401
+ // `columnLeft` is one gap past the last column's right edge
402
+ return { positions, width: columnLeft - columnGap, height };
403
+ }
@@ -0,0 +1,9 @@
1
+ import type { BlockClip } from './blockCopy.js';
2
+ export declare const blockClipboard: {
3
+ /** Whether Paste has something to put down (the menu dims Paste without it). */
4
+ readonly hasContent: boolean;
5
+ /** Puts a copy aside, in place of what was there. */
6
+ write(next: BlockClip | null): void;
7
+ /** What was put aside, or `null`. The copy is read, never changed: pasting makes new blocks from it. */
8
+ read(): BlockClip | null;
9
+ };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * What Copy and Cut put aside for Paste: the blocks the person chose, and the connections between them, kept in memory for
3
+ * as long as the page is open. One shelf for every workflow of the page, so blocks copied in one workflow can be pasted into
4
+ * another.
5
+ *
6
+ * It is not the system clipboard, on purpose: the blocks of a workflow mean nothing outside of the editor, a copy must not
7
+ * replace what the person has copied from somewhere else, and a page that is not allowed to write to the clipboard still has a
8
+ * working Paste.
9
+ */
10
+ let clip = $state.raw(null);
11
+ export const blockClipboard = {
12
+ /** Whether Paste has something to put down (the menu dims Paste without it). */
13
+ get hasContent() {
14
+ return clip !== null;
15
+ },
16
+ /** Puts a copy aside, in place of what was there. */
17
+ write(next) {
18
+ clip = next;
19
+ },
20
+ /** What was put aside, or `null`. The copy is read, never changed: pasting makes new blocks from it. */
21
+ read() {
22
+ return clip;
23
+ }
24
+ };
@@ -0,0 +1,39 @@
1
+ import type { NodePosition, WorkflowEdge, WorkflowGraph, WorkflowNode } from '@widgetic/workflows-engine';
2
+ /** What a copy holds: the chosen blocks and the connections between them, as they were when they were copied. */
3
+ export interface BlockClip {
4
+ nodes: WorkflowNode[];
5
+ edges: WorkflowEdge[];
6
+ }
7
+ /** How far down and to the right a copy is put from the blocks it was made from, so that it does not hide them. */
8
+ export declare const COPY_OFFSET: Readonly<NodePosition>;
9
+ /** Why nothing was put down: the workflow holds as many blocks, or connections, as it may. */
10
+ export type PasteRefusal = 'too_many_blocks' | 'too_many_connections';
11
+ export interface PasteOptions {
12
+ /** Where the top left corner of the copy goes. Without it the copy goes `offset` from where it was copied from. */
13
+ topLeft?: NodePosition;
14
+ /** How far from where it was copied from (default `COPY_OFFSET`). Not used with `topLeft`. */
15
+ offset?: NodePosition;
16
+ /**
17
+ * Move the copy on, step by step, while it would sit on a block (default `true`): pasting twice, or duplicating a copy,
18
+ * does not pile the blocks up. An Alt-drag turns it off, because the copy is on its way to where the pointer takes it.
19
+ */
20
+ avoidCovering?: boolean;
21
+ /** For tests. */
22
+ random?: () => number;
23
+ }
24
+ export interface PasteResult {
25
+ graph: WorkflowGraph;
26
+ /** The ids of the new blocks, in the order they were copied in. Empty when nothing was put down. */
27
+ nodeIds: string[];
28
+ refused: PasteRefusal | null;
29
+ }
30
+ /** The chosen blocks, in the order the graph keeps them, with the connections between them. `null` when none is chosen. */
31
+ export declare function copyBlocks(graph: WorkflowGraph, nodeIds: readonly string[]): BlockClip | null;
32
+ /**
33
+ * Puts a copy down in the graph: new blocks and connections with ids that nothing else has, the connections between them
34
+ * kept, the rules of a condition renamed with their connections. Nothing is put down when the workflow would hold more
35
+ * than it may (`refused` says which limit).
36
+ */
37
+ export declare function pasteBlocks(graph: WorkflowGraph, clip: BlockClip, options?: PasteOptions): PasteResult;
38
+ /** Copies the chosen blocks and puts the copy down at once: what Duplicate and an Alt-drag do. */
39
+ export declare function duplicateBlocks(graph: WorkflowGraph, nodeIds: readonly string[], options?: PasteOptions): PasteResult;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Copying blocks of a workflow: Copy, Cut and Paste, Duplicate, and an Alt-drag. A copy keeps the blocks that were chosen
3
+ * and the connections that run between them (a connection to a block that was not chosen is left behind), and putting it
4
+ * down makes new blocks with new ids, so the same blocks may be put down again and again.
5
+ *
6
+ * Plain data in and out, like `graphModel.ts`: nothing draws, nothing is stored, and the graph given is never changed.
7
+ *
8
+ * What a copy is, and is not:
9
+ * - a copy of a composition block points at the same composition, and that is allowed: the same composition may sit on
10
+ * several blocks, each with its own id, triggers and connections (the copy is a new block that shows it again);
11
+ * - a copy is never the start of the workflow: exactly one composition starts it, and that one stays where it was;
12
+ * - a condition's rules get new ids too, and the connections that leave from them follow.
13
+ */
14
+ import { MAX_BLOCKS, MAX_EDGES } from '@widgetic/workflows-engine';
15
+ import { collectTakenIds, makeId } from './graphModel.js';
16
+ /** How far down and to the right a copy is put from the blocks it was made from, so that it does not hide them. */
17
+ export const COPY_OFFSET = { x: 48, y: 48 };
18
+ /** Two blocks whose corners are closer than this sit on top of each other. */
19
+ const SAME_PLACE_DISTANCE = 24;
20
+ /** How many times a copy moves on by `COPY_OFFSET` looking for a place where it does not cover a block. */
21
+ const MAX_MOVES_TO_FREE_PLACE = 24;
22
+ /** A deep copy of plain data (a block of a draft is JSON, whatever wraps it on the screen). */
23
+ function cloneData(value) {
24
+ return JSON.parse(JSON.stringify(value));
25
+ }
26
+ /** The chosen blocks, in the order the graph keeps them, with the connections between them. `null` when none is chosen. */
27
+ export function copyBlocks(graph, nodeIds) {
28
+ const chosen = new Set(nodeIds);
29
+ const nodes = graph.nodes.filter((node) => chosen.has(node.id)).map((node) => cloneData(node));
30
+ if (nodes.length === 0)
31
+ return null;
32
+ // A copy never starts the workflow
33
+ for (const node of nodes)
34
+ if (node.type === 'composition')
35
+ delete node.startsHere;
36
+ const kept = new Set(nodes.map((node) => node.id));
37
+ const edges = graph.edges
38
+ .filter((edge) => kept.has(edge.source) && kept.has(edge.target))
39
+ .map((edge) => cloneData(edge));
40
+ return { nodes, edges };
41
+ }
42
+ /** The top left corner of a group of blocks. */
43
+ function findTopLeft(nodes) {
44
+ const positions = nodes.map((node) => node.position ?? { x: 0, y: 0 });
45
+ return {
46
+ x: Math.min(...positions.map((position) => position.x)),
47
+ y: Math.min(...positions.map((position) => position.y))
48
+ };
49
+ }
50
+ /** Whether any block of the group sits on a block of the graph. */
51
+ function coversABlock(graph, positions, delta) {
52
+ return positions.some((position) => graph.nodes.some((node) => node.position !== undefined &&
53
+ Math.abs(node.position.x - (position.x + delta.x)) < SAME_PLACE_DISTANCE &&
54
+ Math.abs(node.position.y - (position.y + delta.y)) < SAME_PLACE_DISTANCE));
55
+ }
56
+ /**
57
+ * Puts a copy down in the graph: new blocks and connections with ids that nothing else has, the connections between them
58
+ * kept, the rules of a condition renamed with their connections. Nothing is put down when the workflow would hold more
59
+ * than it may (`refused` says which limit).
60
+ */
61
+ export function pasteBlocks(graph, clip, options = {}) {
62
+ const random = options.random ?? Math.random;
63
+ if (clip.nodes.length === 0)
64
+ return { graph, nodeIds: [], refused: null };
65
+ if (graph.nodes.length + clip.nodes.length > MAX_BLOCKS)
66
+ return { graph, nodeIds: [], refused: 'too_many_blocks' };
67
+ if (graph.edges.length + clip.edges.length > MAX_EDGES)
68
+ return { graph, nodeIds: [], refused: 'too_many_connections' };
69
+ const taken = collectTakenIds(graph);
70
+ const newNodeIds = new Map();
71
+ /** For each condition that was copied: the id of each of its rules, and the id that rule has in the copy. */
72
+ const newRuleIds = new Map();
73
+ const nodes = [];
74
+ for (const original of clip.nodes) {
75
+ const copy = cloneData(original);
76
+ const newId = makeId('n', taken, random);
77
+ taken.add(newId);
78
+ newNodeIds.set(original.id, newId);
79
+ copy.id = newId;
80
+ if (copy.type === 'composition')
81
+ delete copy.startsHere;
82
+ if (copy.type === 'condition') {
83
+ const ruleIds = new Map();
84
+ copy.cases = copy.cases.map((rule) => {
85
+ const newRuleId = makeId('r', taken, random);
86
+ taken.add(newRuleId);
87
+ ruleIds.set(rule.id, newRuleId);
88
+ return { ...rule, id: newRuleId };
89
+ });
90
+ newRuleIds.set(original.id, ruleIds);
91
+ }
92
+ nodes.push(copy);
93
+ }
94
+ // Where the copy goes
95
+ const oldPositions = clip.nodes.map((node) => node.position ?? { x: 0, y: 0 });
96
+ const topLeft = findTopLeft(clip.nodes);
97
+ let delta = options.topLeft
98
+ ? { x: options.topLeft.x - topLeft.x, y: options.topLeft.y - topLeft.y }
99
+ : { ...(options.offset ?? COPY_OFFSET) };
100
+ if (options.avoidCovering !== false) {
101
+ for (let move = 0; move < MAX_MOVES_TO_FREE_PLACE && coversABlock(graph, oldPositions, delta); move += 1) {
102
+ delta = { x: delta.x + COPY_OFFSET.x, y: delta.y + COPY_OFFSET.y };
103
+ }
104
+ }
105
+ nodes.forEach((node, index) => {
106
+ const from = oldPositions[index] ?? { x: 0, y: 0 };
107
+ node.position = { x: Math.round(from.x + delta.x), y: Math.round(from.y + delta.y) };
108
+ });
109
+ const edges = [];
110
+ for (const original of clip.edges) {
111
+ const source = newNodeIds.get(original.source);
112
+ const target = newNodeIds.get(original.target);
113
+ if (source === undefined || target === undefined)
114
+ continue;
115
+ const edgeId = makeId('e', taken, random);
116
+ taken.add(edgeId);
117
+ edges.push({
118
+ id: edgeId,
119
+ source,
120
+ // A rule's line leaves from the rule's new id; `out` and `default` are the same in a copy
121
+ sourcePort: newRuleIds.get(original.source)?.get(original.sourcePort) ?? original.sourcePort,
122
+ target
123
+ });
124
+ }
125
+ return {
126
+ graph: { ...graph, nodes: [...graph.nodes, ...nodes], edges: [...graph.edges, ...edges] },
127
+ nodeIds: nodes.map((node) => node.id),
128
+ refused: null
129
+ };
130
+ }
131
+ /** Copies the chosen blocks and puts the copy down at once: what Duplicate and an Alt-drag do. */
132
+ export function duplicateBlocks(graph, nodeIds, options = {}) {
133
+ const clip = copyBlocks(graph, nodeIds);
134
+ if (clip === null)
135
+ return { graph, nodeIds: [], refused: null };
136
+ return pasteBlocks(graph, clip, options);
137
+ }
@@ -0,0 +1,45 @@
1
+ import type { NodePosition } from '@widgetic/workflows-engine';
2
+ import type { WorkflowsMessageKey } from '../i18n/messages.js';
3
+ import type { Chord } from './keyHints.js';
4
+ /**
5
+ * The menu a right click opens on the canvas: which rows it has for a block and for the empty canvas, in which groups, and
6
+ * which of them can act now. Plain data, so the rows are tested as that and the component only draws them.
7
+ *
8
+ * It has the rows of the Widgetic canvas's menu that a workflow has something to do with (Cut, Copy, Paste, Duplicate, Select
9
+ * all, Delete), and two of its own for the lines (Organise, Disconnect). Group, Ungroup and Layer order are not here: the
10
+ * blocks of a workflow are not stacked or grouped, they are joined.
11
+ */
12
+ /** A shortcut of the clipboard, pressed on the canvas. */
13
+ export type ClipboardCommand = 'copy' | 'cut' | 'paste' | 'duplicate';
14
+ /** What the canvas tells the screen when a right click asks for the menu. */
15
+ export interface CanvasMenuRequest {
16
+ /** Where the pointer was, in pixels of the page (the menu opens there). */
17
+ clientX: number;
18
+ clientY: number;
19
+ /** A right click on a block selects it first (unless it is selected) and opens the menu of blocks. */
20
+ target: 'block' | 'pane';
21
+ nodeId: string | null;
22
+ /** Where the right click was on the canvas, in canvas units (a paste goes there). */
23
+ canvasPoint: NodePosition;
24
+ }
25
+ export type CanvasMenuAction = 'cut' | 'copy' | 'paste' | 'duplicate' | 'selectAll' | 'delete' | 'organise' | 'disconnect';
26
+ export interface CanvasMenuRow {
27
+ action: CanvasMenuAction;
28
+ messageKey: WorkflowsMessageKey;
29
+ chord?: Chord;
30
+ /** A row that can act on what is selected only; shown dimmed otherwise, and it does nothing. */
31
+ disabled: boolean;
32
+ /** In the colour of a destructive action. */
33
+ isDestructive: boolean;
34
+ }
35
+ /** What decides which rows can act. */
36
+ export interface CanvasMenuState {
37
+ /** At least one block is selected. */
38
+ hasSelection: boolean;
39
+ /** Copy or Cut put something aside, and the draft can be changed. */
40
+ canPaste: boolean;
41
+ blockCount: number;
42
+ connectionCount: number;
43
+ }
44
+ /** The groups of rows of the menu for this target, each row with whether it can act now. */
45
+ export declare function buildCanvasMenu(target: CanvasMenuRequest['target'], state: CanvasMenuState): CanvasMenuRow[][];