@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
@@ -7,11 +7,19 @@
7
7
  graph (`onGraphChange`), once per change. The owner answers with the graph it keeps, which can differ (the first
8
8
  composition left becomes the start) and the canvas takes that over without making an undo step.
9
9
  - A change made elsewhere (the side panel, the Add block menu) comes in through the handle's `applyGraph`, as one step
10
- that one undo takes back; a whole new workflow (a reload, a version) comes in through `loadGraph` with no history.
10
+ that one undo takes back; a draft the assistant saved while the person watches comes in through `showSavedDraft`, the
11
+ same way (and the view is fitted when blocks were added); a whole new workflow (a reload, a version) comes in through
12
+ `loadGraph` with no history.
11
13
  - Lines can only be drawn where the engine allows them (`createConnectionValidator`): kaykay greys out the other places
12
- while a line is dragged.
13
- - Copy, paste and "log selection" are off (a pasted block would have the id of the one it was copied from, and
14
- the clipboard is the person's own); everything else of kaykay's keyboard stays (arrows move, Delete deletes, undo, redo).
14
+ while a line is dragged. A line dragged near a block snaps to its connection point like a magnet (see
15
+ `connectionSnapController.ts`, and `CONNECTION_SNAP_ENABLED` to switch it off).
16
+ - A drag on the empty canvas draws a selection box, as on the Widgetic canvas; every block it touches is selected and
17
+ they are dragged together. The view moves with a scroll, the middle button, or Space held and a drag.
18
+ - Alt and drag carries copies of the selected blocks away (`altDragDuplicateController.ts`); a right click asks the owner
19
+ for the canvas menu (`onContextMenuRequest`); Cmd or Ctrl with C, X, V and D ask it to copy, cut, paste and duplicate.
20
+ The copies are the owner's work (a copy needs new ids, which the engine's graph model makes): kaykay's own copy and
21
+ paste are taken away from it, as is "log selection". The rest of kaykay's keyboard stays (arrows move, Delete deletes,
22
+ undo, redo, select all).
15
23
  - kaykay names its connection points in English; here they are named in the page's language.
16
24
 
17
25
  It is always drawn left to right, whatever the page's direction: lines run from the composition on the left to the next
@@ -29,7 +37,10 @@
29
37
  NodeTypes,
30
38
  Viewport
31
39
  } from 'kaykay';
32
- import type { WorkflowGraph } from '@widgetic/workflows-engine';
40
+ import type { NodePosition, WorkflowGraph } from '@widgetic/workflows-engine';
41
+ import type { BlockMeasure } from '../../editor/autoLayout.js';
42
+ import { duplicateBlocks, type PasteRefusal } from '../../editor/blockCopy.js';
43
+ import type { CanvasMenuRequest, ClipboardCommand } from '../../editor/canvasMenu.js';
33
44
  import { provideCanvasContext, type CanvasContext } from '../../editor/canvasContext.js';
34
45
  import type { CanvasHandle } from '../../editor/editorState.svelte.js';
35
46
  import {
@@ -44,6 +55,9 @@
44
55
  import { isSameGraph } from '../../editor/graphModel.js';
45
56
  import { useWorkflowsLanguage } from '../../i18n/language.js';
46
57
  import { workflowsError } from '../../utils/logger.js';
58
+ import { installAltDragDuplicate } from './altDragDuplicateController.js';
59
+ import { installConnectionSnap, type ConnectionSnap } from './connectionSnapController.js';
60
+ import { installSpacePan } from './spacePanController.js';
47
61
  import CompositionNodeView from './CompositionNodeView.svelte';
48
62
  import ConditionNodeView from './ConditionNodeView.svelte';
49
63
  import TriggerNodeView from './TriggerNodeView.svelte';
@@ -63,6 +77,15 @@
63
77
  onSelectionChange?: (nodeIds: readonly string[], edgeIds: readonly string[]) => void;
64
78
  /** The `B` key was pressed on the canvas: the owner opens its Add block menu. */
65
79
  onAddBlockShortcut?: () => void;
80
+ /**
81
+ * Cmd or Ctrl with C, X, V or D was pressed on the canvas. `at` is where the pointer is on the canvas, in canvas units,
82
+ * for a paste (`null` when it is not over the canvas). The owner does the work: a copy needs new ids.
83
+ */
84
+ onClipboardShortcut?: (command: ClipboardCommand, at: NodePosition | null) => void;
85
+ /** A right click asked for the canvas menu. A block that was pressed is selected first. Not asked on a canvas that only shows. */
86
+ onContextMenuRequest?: (request: CanvasMenuRequest) => void;
87
+ /** Copies made by Alt and drag were refused: the workflow holds as many blocks or connections as it may. */
88
+ onCopyRefused?: (refusal: PasteRefusal) => void;
66
89
  /** Pan/zoom updates (toolbar zoom label); not every `on_change` includes the viewport. */
67
90
  onViewportChange?: (viewport: Viewport) => void;
68
91
  /** Gives the owner the handle once the canvas is on the screen, and `null` when it leaves. */
@@ -78,6 +101,9 @@
78
101
  onGraphChange,
79
102
  onSelectionChange,
80
103
  onAddBlockShortcut,
104
+ onClipboardShortcut,
105
+ onContextMenuRequest,
106
+ onCopyRefused,
81
107
  onViewportChange,
82
108
  onReady,
83
109
  class: className = ''
@@ -122,6 +148,10 @@
122
148
  allow_delete: true,
123
149
  pan_on_scroll: true,
124
150
  zoom_on_scroll: false,
151
+ // A drag on the empty canvas draws a selection box (Shift adds to the selection, Ctrl or Cmd toggles, Alt takes away).
152
+ // The view moves with a scroll, the middle button or Space (`spacePanController.ts`), so the left button is free for the box.
153
+ selection_on_drag: true,
154
+ pan_on_drag: true,
125
155
  max_history: 100,
126
156
  // A line drawn by hand is made by kaykay: without this it is drawn as kaykay's own line, not as ours (counts, highlights)
127
157
  default_edge_type: WORKFLOW_EDGE_TYPE,
@@ -179,7 +209,7 @@
179
209
  * content changed, blocks added, blocks moved, lines drawn. Lines go in directly (kaykay checks a line against the points
180
210
  * of the blocks, which a block added a moment ago does not have yet; the engine has checked these already).
181
211
  */
182
- function applyGraph(next: WorkflowGraph, recordHistory: boolean): void {
212
+ function applyGraph(next: WorkflowGraph, recordHistory: boolean, fitToNewBlocks = false): void {
183
213
  const flow = getFlow();
184
214
  if (!flow) return;
185
215
  const difference = diffGraphs(flowToGraph(flow), next);
@@ -217,10 +247,15 @@
217
247
  }
218
248
  reportSelection();
219
249
  if (recordHistory) readCanvasNow();
250
+ // Blocks that were just added may be where the person is not looking: bring them all into view.
251
+ if (fitToNewBlocks && difference.addedNodes.length > 0) fitSoon();
220
252
  }
221
253
 
222
- /** Draws a whole other workflow, as a reload or a version does: nothing to undo afterwards. */
223
- function loadGraph(graph: WorkflowGraph): void {
254
+ /**
255
+ * Draws a whole other workflow, as a reload or a version does: nothing to undo afterwards, and the blocks are fitted in
256
+ * view. A tab that was brought up to date (`keepViewport`) stays where the person had it.
257
+ */
258
+ function loadGraph(graph: WorkflowGraph, options?: { keepViewport?: boolean }): void {
224
259
  const flow = getFlow();
225
260
  if (!flow) return;
226
261
  ownChanges += 1;
@@ -233,7 +268,7 @@
233
268
  ownChanges -= 1;
234
269
  }
235
270
  reportSelection();
236
- fitSoon();
271
+ if (options?.keepViewport !== true) fitSoon();
237
272
  }
238
273
 
239
274
  /** Fits all the blocks in view once they have been measured (the frame after they are drawn). */
@@ -247,8 +282,68 @@
247
282
  });
248
283
  }
249
284
 
285
+ /**
286
+ * What the canvas measured of each block that is drawn: its size, and how far down it each connection point is (the centre
287
+ * of the point, from the top of the block), for laying the blocks out. A point is named as its block's lines are: `out`, a
288
+ * rule's id, or `default` for the places a line leaves from, and the one place a line comes in at.
289
+ */
290
+ function readBlockMeasures(): Map<string, BlockMeasure> {
291
+ const flow = getFlow();
292
+ if (!flow) return new Map();
293
+ const measured: [string, BlockMeasure][] = [];
294
+ for (const node of flow.nodes) {
295
+ if (!(node.computed_width > 0) || !(node.computed_height > 0)) continue;
296
+ const origin = flow.getAbsolutePosition(node.id);
297
+ const outputOffsets: Record<string, number> = {};
298
+ let inputOffset: number | undefined;
299
+ for (const point of node.handles.values()) {
300
+ const centre = flow.getHandlePosition(node.id, point.id) ?? point.absolute_position;
301
+ if (!centre) continue;
302
+ if (point.type === 'input') inputOffset ??= centre.y - origin.y;
303
+ else outputOffsets[point.id] = centre.y - origin.y;
304
+ }
305
+ measured.push([
306
+ node.id,
307
+ { width: node.computed_width, height: node.computed_height, inputOffset, outputOffsets }
308
+ ]);
309
+ }
310
+ return new Map(measured);
311
+ }
312
+
313
+ // ---- Alt and drag: copies of the selected blocks, carried by the pointer ------------------------------------------
314
+
315
+ /**
316
+ * The first part of the step an Alt-drag is: opens it, and adds copies of the selected blocks in the same places, selected.
317
+ * The step stays open while the copies are carried (`finishCopies` closes it), so one Undo takes the copies away.
318
+ * Answers the ids of the copies, or `null` when there are none (nothing selected, or the workflow is full: the owner is told).
319
+ */
320
+ function beginCopies(): string[] | null {
321
+ const flow = getFlow();
322
+ if (!flow) return null;
323
+ const result = duplicateBlocks(flowToGraph(flow), [...flow.selected_node_ids], {
324
+ offset: { x: 0, y: 0 },
325
+ avoidCovering: false
326
+ });
327
+ if (result.refused !== null) {
328
+ onCopyRefused?.(result.refused);
329
+ return null;
330
+ }
331
+ if (result.nodeIds.length === 0) return null;
332
+ flow.beginTransaction();
333
+ applyGraph(result.graph, false);
334
+ flow.clearSelection();
335
+ for (const nodeId of result.nodeIds) flow.selectNode(nodeId, true);
336
+ return result.nodeIds;
337
+ }
338
+
339
+ /** Closes the step of an Alt-drag: the copies are where the pointer left them, and the owner hears of it once. */
340
+ function finishCopies(): void {
341
+ getFlow()?.endTransaction(true, 'batch');
342
+ }
343
+
250
344
  const handle: CanvasHandle = {
251
345
  applyGraph: (next) => applyGraph(next, true),
346
+ showSavedDraft: (next) => applyGraph(next, true, true),
252
347
  loadGraph,
253
348
  selectNodes(nodeIds) {
254
349
  const flow = getFlow();
@@ -256,6 +351,8 @@
256
351
  flow.clearSelection();
257
352
  for (const nodeId of nodeIds) flow.selectNode(nodeId, true);
258
353
  },
354
+ selectAll: () => getFlow()?.selectAll(),
355
+ measureBlocks: readBlockMeasures,
259
356
  fitView: () => getFlow()?.fitView(80),
260
357
  zoomIn: () => getFlow()?.zoomIn(0.15),
261
358
  zoomOut: () => getFlow()?.zoomOut(0.15),
@@ -302,15 +399,41 @@
302
399
  }
303
400
 
304
401
  /**
305
- * Runs before kaykay hears the key. Copy, paste, cut and "log selection" are taken away from it. `B` is "Add block".
402
+ * The letter of a shortcut: the key that was pressed, or, on a keyboard layout without Latin letters (the shortcuts of an
403
+ * app are still the letters of a Latin keyboard there), the letter of the key's place.
404
+ */
405
+ function readShortcutLetter(event: KeyboardEvent): string {
406
+ const key = event.key.toLowerCase();
407
+ if (/^[a-z]$/.test(key)) return key;
408
+ return /^Key[A-Z]$/.test(event.code) ? event.code.slice(3).toLowerCase() : key;
409
+ }
410
+
411
+ const CLIPBOARD_COMMANDS: Readonly<Record<string, ClipboardCommand>> = {
412
+ c: 'copy',
413
+ x: 'cut',
414
+ v: 'paste',
415
+ d: 'duplicate'
416
+ };
417
+
418
+ /**
419
+ * Runs before kaykay hears the key. Copy, cut, paste and duplicate are the owner's work, so kaykay (whose paste would
420
+ * make a block with a number for an id, from the system clipboard) never hears them; "log selection" is taken away from it.
421
+ * `B` is "Add block".
306
422
  */
307
423
  function handleKeydownCapture(event: KeyboardEvent): void {
308
424
  if (isTypingTarget(event.target)) return;
309
425
  const key = event.key.toLowerCase();
310
426
  const hasCommand = event.ctrlKey || event.metaKey;
311
- if (hasCommand && (key === 'c' || key === 'v' || key === 'x' || key === 'l')) {
427
+ const letter = readShortcutLetter(event);
428
+ const command = hasCommand ? (CLIPBOARD_COMMANDS[letter] ?? null) : null;
429
+ if (command !== null || (hasCommand && letter === 'l')) {
312
430
  event.preventDefault();
313
431
  event.stopPropagation();
432
+ // Shift or Alt makes it another shortcut (one of the page's or the browser's): swallowed, not run
433
+ if (command === null || event.shiftKey || event.altKey) return;
434
+ // Copying changes nothing, so it also works on a canvas that only shows
435
+ if (command !== 'copy' && readOnly) return;
436
+ onClipboardShortcut?.(command, command === 'paste' ? readPointerOnCanvas() : null);
314
437
  return;
315
438
  }
316
439
  if (!hasCommand && !event.altKey && !event.shiftKey && key === 'b' && !readOnly) {
@@ -320,6 +443,148 @@
320
443
  }
321
444
  }
322
445
 
446
+ // ---- the pointer: the empty canvas, the right click, and where Paste goes -----------------------------------------------
447
+
448
+ /** Where the pointer last was over the canvas, in pixels of the page; `null` while it is not over it. */
449
+ let lastPointer: { clientX: number; clientY: number } | null = null;
450
+
451
+ function rememberPointer(event: MouseEvent): void {
452
+ lastPointer = { clientX: event.clientX, clientY: event.clientY };
453
+ }
454
+
455
+ function forgetPointer(): void {
456
+ lastPointer = null;
457
+ }
458
+
459
+ /** A place of the page, as a place on the canvas (canvas units, whole numbers). */
460
+ function toCanvasPoint(clientX: number, clientY: number): NodePosition | null {
461
+ const flow = getFlow();
462
+ const surface = wrapperElement?.querySelector<HTMLElement>('.kaykay-canvas');
463
+ if (!flow || !surface) return null;
464
+ const bounds = surface.getBoundingClientRect();
465
+ const point = flow.screenToCanvas({ x: clientX - bounds.left, y: clientY - bounds.top });
466
+ return { x: Math.round(point.x), y: Math.round(point.y) };
467
+ }
468
+
469
+ /** Where the pointer is on the canvas, or `null` when it is not over it. */
470
+ function readPointerOnCanvas(): NodePosition | null {
471
+ return lastPointer ? toCanvasPoint(lastPointer.clientX, lastPointer.clientY) : null;
472
+ }
473
+
474
+ /**
475
+ * A press on the empty canvas, with no key held, clears the selection first (as it did when a press there moved the view);
476
+ * the selection box that follows then selects what it covers. A press on a block, a connection point or a line is theirs,
477
+ * and with Space held a press moves the view.
478
+ */
479
+ function handlePressCapture(event: MouseEvent): void {
480
+ if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
481
+ return;
482
+ if (wrapperElement?.hasAttribute('data-space-held')) return;
483
+ const target = event.target instanceof Element ? event.target : null;
484
+ if (!target || target.closest('[data-node-id], [data-handle-id], .kaykay-edge')) return;
485
+ getFlow()?.clearSelection();
486
+ }
487
+
488
+ /**
489
+ * A right click: the owner is asked for the canvas menu, on the block that was pressed (selected first, unless it is already
490
+ * part of the selection) or on the empty canvas. A canvas that only shows keeps the browser's own menu.
491
+ */
492
+ function handleContextMenu(event: MouseEvent): void {
493
+ const flow = getFlow();
494
+ if (!flow || readOnly || !onContextMenuRequest) return;
495
+ const canvasPoint = toCanvasPoint(event.clientX, event.clientY);
496
+ if (!canvasPoint) return;
497
+ event.preventDefault();
498
+ const target = event.target instanceof Element ? event.target : null;
499
+ const nodeId = target?.closest<HTMLElement>('[data-node-id]')?.dataset.nodeId ?? null;
500
+ if (nodeId !== null && !flow.selected_node_ids.has(nodeId)) flow.selectNode(nodeId, false);
501
+ try {
502
+ onContextMenuRequest({
503
+ clientX: event.clientX,
504
+ clientY: event.clientY,
505
+ target: nodeId === null ? 'pane' : 'block',
506
+ nodeId,
507
+ canvasPoint
508
+ });
509
+ } catch (error) {
510
+ workflowsError('The canvas could not open its menu.', error);
511
+ }
512
+ }
513
+
514
+ // ---- the selection box, drawn over the blocks as the Widgetic canvas draws it ----------------------------------------
515
+
516
+ /** A box on the canvas as the styles that place it, in pixels of the canvas (measured from the start of its line: it is drawn left to right). */
517
+ interface MarqueeBoxStyle {
518
+ start: string;
519
+ top: string;
520
+ width: string;
521
+ height: string;
522
+ radius: string;
523
+ }
524
+
525
+ /** The box being drawn, and the blocks it touches (outlined, so a person sees what the box will select). */
526
+ interface MarqueeView {
527
+ box: MarqueeBoxStyle;
528
+ touched: (MarqueeBoxStyle & { id: string })[];
529
+ }
530
+
531
+ /** The corner radius of a block (`rounded-xl`), in canvas units. */
532
+ const BLOCK_RADIUS = 12;
533
+
534
+ /** A length in pixels, as a style says it. */
535
+ function toPixels(value: number): string {
536
+ return `${Math.round(value * 10) / 10}px`;
537
+ }
538
+
539
+ const marquee = $derived.by<MarqueeView | null>(() => {
540
+ const flow = canvas?.getFlow();
541
+ const rectangle = flow?.selection_rect;
542
+ if (!flow || !rectangle) return null;
543
+ const from = flow.canvasToScreen(rectangle.start);
544
+ const to = flow.canvasToScreen(rectangle.end);
545
+ const boxWidth = Math.abs(from.x - to.x);
546
+ const boxHeight = Math.abs(from.y - to.y);
547
+ // A click is not a box: nothing is drawn until the pointer has moved a little
548
+ if (boxWidth < 3 && boxHeight < 3) return null;
549
+ const box: MarqueeBoxStyle = {
550
+ start: toPixels(Math.min(from.x, to.x)),
551
+ top: toPixels(Math.min(from.y, to.y)),
552
+ width: toPixels(boxWidth),
553
+ height: toPixels(boxHeight),
554
+ radius: toPixels(0)
555
+ };
556
+ const zoom = flow.viewport.zoom;
557
+ const reach = {
558
+ left: Math.min(rectangle.start.x, rectangle.end.x),
559
+ right: Math.max(rectangle.start.x, rectangle.end.x),
560
+ top: Math.min(rectangle.start.y, rectangle.end.y),
561
+ bottom: Math.max(rectangle.start.y, rectangle.end.y)
562
+ };
563
+ const touched: MarqueeView['touched'] = [];
564
+ for (const node of flow.nodes) {
565
+ const origin = flow.getAbsolutePosition(node.id);
566
+ // The same test kaykay selects by: a block that touches the box, however little, is in it
567
+ const isTouched = !(
568
+ origin.x + node.computed_width < reach.left ||
569
+ origin.x > reach.right ||
570
+ origin.y + node.computed_height < reach.top ||
571
+ origin.y > reach.bottom
572
+ );
573
+ if (!isTouched) continue;
574
+ const corner = flow.canvasToScreen(origin);
575
+ // The box of the block itself: its outline (see the template) is drawn just outside the edge, as the canvas does
576
+ touched.push({
577
+ id: node.id,
578
+ start: toPixels(corner.x),
579
+ top: toPixels(corner.y),
580
+ width: toPixels(node.computed_width * zoom),
581
+ height: toPixels(node.computed_height * zoom),
582
+ radius: toPixels(BLOCK_RADIUS * zoom)
583
+ });
584
+ }
585
+ return { box, touched };
586
+ });
587
+
323
588
  // ---- kaykay's English names for its connection points ---------------------------------------------------------
324
589
 
325
590
  /** Names every connection point in the page's language, and drops the tip kaykay puts on it (English and about its ids). */
@@ -338,7 +603,47 @@
338
603
  let namingObserver: MutationObserver | null = null;
339
604
  let isNamingScheduled = false;
340
605
 
606
+ /** The gestures that are put on kaykay's canvas, to take off again when this one goes. */
607
+ let connectionSnap: ConnectionSnap | null = null;
608
+ let removeSpacePan: (() => void) | null = null;
609
+ let removeAltDragDuplicate: (() => void) | null = null;
610
+
611
+ /** Puts the magnet of a line, Space to move the view, and Alt and drag to copy, on the canvas. */
612
+ function installGestures(flow: FlowState, wrapper: HTMLElement): void {
613
+ try {
614
+ connectionSnap = installConnectionSnap(flow, wrapper);
615
+ removeSpacePan = installSpacePan({ flow, wrapper });
616
+ removeAltDragDuplicate = installAltDragDuplicate({
617
+ flow,
618
+ wrapper,
619
+ canChange: () => !readOnly,
620
+ beginCopies,
621
+ finishCopies
622
+ });
623
+ } catch (error) {
624
+ // The canvas still works without them: kaykay's own gestures are all that is left
625
+ workflowsError('The canvas could not set up its gestures.', error);
626
+ }
627
+ }
628
+
629
+ function removeGestures(): void {
630
+ connectionSnap?.dispose();
631
+ connectionSnap = null;
632
+ removeSpacePan?.();
633
+ removeSpacePan = null;
634
+ removeAltDragDuplicate?.();
635
+ removeAltDragDuplicate = null;
636
+ }
637
+
638
+ // The point that held a line lets go when the line is over (it was connected, or cancelled)
639
+ $effect(() => {
640
+ const flow = canvas?.getFlow();
641
+ if (flow && flow.draft_connection === null) connectionSnap?.release();
642
+ });
643
+
341
644
  onMount(() => {
645
+ const mountedFlow = getFlow();
646
+ if (mountedFlow && wrapperElement) installGestures(mountedFlow, wrapperElement);
342
647
  if (wrapperElement) {
343
648
  namingObserver = new MutationObserver(() => {
344
649
  if (isNamingScheduled) return;
@@ -369,6 +674,7 @@
369
674
  });
370
675
 
371
676
  onDestroy(() => {
677
+ removeGestures();
372
678
  namingObserver?.disconnect();
373
679
  namingObserver = null;
374
680
  if (fitFrame !== null) cancelAnimationFrame(fitFrame);
@@ -383,14 +689,22 @@
383
689
  kaykay reads CSS variables from the canvas element (`.kaykay-canvas`) and from the node wrapper (`.kaykay-node`).
384
690
  The grid of dots keeps kaykay's own faint colour: the design draws a flat surface, and the dots only help the eye while the
385
691
  canvas is panned and zoomed.
692
+ The cursor is the arrow on the empty canvas (a drag draws a selection box there), the open hand while Space is held and the
693
+ closed hand while the view is dragged: kaykay's own style says "grab" and is not layered, so these say `!`.
694
+ kaykay draws its selection box under the blocks: it is hidden, and the box is drawn here above them (below, in the template),
695
+ with the outline of each block it would select. The block that a line is about to snap to gets a soft ring.
386
696
  -->
387
697
  <div
388
698
  bind:this={wrapperElement}
389
- class="isolate h-full min-h-0 w-full overflow-hidden [&_.kaykay-canvas]:[--kaykay-canvas-bg:var(--color-muted)] [&_.kaykay-node]:rounded-xl [&_.kaykay-node.selected:not(.status-error):not(.status-running):not(.status-completed)]:[--kaykay-node-selected-outline:transparent] [&_.kaykay-node.status-error]:[--kaykay-node-error-outline:transparent] [&_.kaykay-node]:[--kaykay-node-running-outline:var(--color-primary)] [&_.kaykay-node]:[--kaykay-node-completed-outline:var(--color-brand)] [&_.kaykay-handle]:[--kaykay-handle-input-bg:var(--color-background)] [&_.kaykay-handle]:[--kaykay-handle-input-border:var(--color-muted-foreground)] [&_.kaykay-handle]:[--kaykay-handle-output-bg:var(--color-background)] [&_.kaykay-handle]:[--kaykay-handle-output-border:var(--color-muted-foreground)] [&_.kaykay-handle]:[--kaykay-handle-can-connect-bg:var(--color-primary)] [&_.kaykay-handle]:[--kaykay-handle-can-connect-border:var(--color-primary)] {className}"
699
+ class="relative isolate h-full min-h-0 w-full overflow-hidden [&_.kaykay-canvas]:cursor-default! [&_.kaykay-canvas:active]:cursor-default! data-[space-held=true]:[&_.kaykay-canvas]:cursor-grab! data-[panning=true]:[&_.kaykay-canvas]:cursor-grabbing! [&_.kaykay-selection-rect]:hidden [&_.kaykay-node[data-snap-target]]:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_25%,transparent)] [&_.kaykay-canvas]:[--kaykay-canvas-bg:var(--color-muted)] [&_.kaykay-node]:rounded-xl [&_.kaykay-node.selected:not(.status-error):not(.status-running):not(.status-completed)]:[--kaykay-node-selected-outline:transparent] [&_.kaykay-node.status-error]:[--kaykay-node-error-outline:transparent] [&_.kaykay-node]:[--kaykay-node-running-outline:var(--color-primary)] [&_.kaykay-node]:[--kaykay-node-completed-outline:var(--color-brand)] [&_.kaykay-handle]:[--kaykay-handle-input-bg:var(--color-background)] [&_.kaykay-handle]:[--kaykay-handle-input-border:var(--color-muted-foreground)] [&_.kaykay-handle]:[--kaykay-handle-output-bg:var(--color-background)] [&_.kaykay-handle]:[--kaykay-handle-output-border:var(--color-muted-foreground)] [&_.kaykay-handle]:[--kaykay-handle-can-connect-bg:var(--color-primary)] [&_.kaykay-handle]:[--kaykay-handle-can-connect-border:var(--color-primary)] {className}"
390
700
  dir="ltr"
391
701
  role="region"
392
702
  aria-label={$t('workflows.canvas.label')}
393
703
  onkeydowncapture={handleKeydownCapture}
704
+ onmousedowncapture={handlePressCapture}
705
+ onmousemove={rememberPointer}
706
+ onmouseleave={forgetPointer}
707
+ oncontextmenu={handleContextMenu}
394
708
  >
395
709
  <Canvas
396
710
  flow={firstFlow}
@@ -402,4 +716,29 @@
402
716
  class="h-full w-full min-h-0"
403
717
  bind:this={canvas}
404
718
  />
719
+ {#if marquee}
720
+ <div
721
+ class="pointer-events-none absolute inset-0 z-[10001] overflow-hidden"
722
+ aria-hidden="true"
723
+ data-workflow-marquee
724
+ >
725
+ <div
726
+ class="absolute border border-ring bg-ring/10"
727
+ style:inset-inline-start={marquee.box.start}
728
+ style:top={marquee.box.top}
729
+ style:width={marquee.box.width}
730
+ style:height={marquee.box.height}
731
+ ></div>
732
+ {#each marquee.touched as block (block.id)}
733
+ <div
734
+ class="absolute outline outline-1 outline-ring"
735
+ style:inset-inline-start={block.start}
736
+ style:top={block.top}
737
+ style:width={block.width}
738
+ style:height={block.height}
739
+ style:border-radius={block.radius}
740
+ ></div>
741
+ {/each}
742
+ </div>
743
+ {/if}
405
744
  </div>
@@ -1,5 +1,7 @@
1
1
  import type { NodeStatus, Viewport } from 'kaykay';
2
- import type { WorkflowGraph } from '@widgetic/workflows-engine';
2
+ import type { NodePosition, WorkflowGraph } from '@widgetic/workflows-engine';
3
+ import { type PasteRefusal } from '../../editor/blockCopy.js';
4
+ import type { CanvasMenuRequest, ClipboardCommand } from '../../editor/canvasMenu.js';
3
5
  import { type CanvasContext } from '../../editor/canvasContext.js';
4
6
  import type { CanvasHandle } from '../../editor/editorState.svelte.js';
5
7
  interface Props {
@@ -16,6 +18,15 @@ interface Props {
16
18
  onSelectionChange?: (nodeIds: readonly string[], edgeIds: readonly string[]) => void;
17
19
  /** The `B` key was pressed on the canvas: the owner opens its Add block menu. */
18
20
  onAddBlockShortcut?: () => void;
21
+ /**
22
+ * Cmd or Ctrl with C, X, V or D was pressed on the canvas. `at` is where the pointer is on the canvas, in canvas units,
23
+ * for a paste (`null` when it is not over the canvas). The owner does the work: a copy needs new ids.
24
+ */
25
+ onClipboardShortcut?: (command: ClipboardCommand, at: NodePosition | null) => void;
26
+ /** A right click asked for the canvas menu. A block that was pressed is selected first. Not asked on a canvas that only shows. */
27
+ onContextMenuRequest?: (request: CanvasMenuRequest) => void;
28
+ /** Copies made by Alt and drag were refused: the workflow holds as many blocks or connections as it may. */
29
+ onCopyRefused?: (refusal: PasteRefusal) => void;
19
30
  /** Pan/zoom updates (toolbar zoom label); not every `on_change` includes the viewport. */
20
31
  onViewportChange?: (viewport: Viewport) => void;
21
32
  /** Gives the owner the handle once the canvas is on the screen, and `null` when it leaves. */
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Alt and drag a block: the blocks that are selected stay where they are, and copies of them are carried away by the pointer.
3
+ *
4
+ * kaykay moves a block when it is pressed on, and knows nothing of copies, so the press is heard first (capture phase) when
5
+ * Alt is held: kaykay never sees it, and this controller carries the drag itself. Nothing is copied by a press that does not
6
+ * become a drag (a click with Alt held is only a click). Once the pointer has moved a few pixels:
7
+ * - the owner makes the copies and gives their ids (`beginCopies`): the first thing of the gesture's one undo step;
8
+ * - the copies follow the pointer, all together, until it is released;
9
+ * - the owner closes the step (`finishCopies`), so one Undo takes the copies away, and one Redo brings them back.
10
+ *
11
+ * The same distance as kaykay's own drag (5px) separates a click from a drag, so Alt and click selects like a click does.
12
+ */
13
+ import type { FlowState } from 'kaykay';
14
+ export interface AltDragDuplicateOptions {
15
+ flow: FlowState;
16
+ /** The element that holds kaykay's canvas. */
17
+ wrapper: HTMLElement;
18
+ /** Whether the canvas may be changed now (not read-only). */
19
+ canChange: () => boolean;
20
+ /**
21
+ * Makes copies of the selected blocks, in the same places, as the first part of the step the drag is. Answers their ids,
22
+ * or `null` when there are none (nothing is selected, or the workflow cannot hold more blocks: the owner says why).
23
+ */
24
+ beginCopies: () => string[] | null;
25
+ /** Closes the step: the copies are where the pointer left them. */
26
+ finishCopies: () => void;
27
+ }
28
+ /** Puts the gesture on the canvas. Answers what takes it off again. */
29
+ export declare function installAltDragDuplicate(options: AltDragDuplicateOptions): () => void;
@@ -0,0 +1,92 @@
1
+ import { workflowsError } from '../../utils/logger.js';
2
+ /** How far the pointer goes, in pixels of the screen, before a press with Alt held is a drag. */
3
+ const DRAG_THRESHOLD = 5;
4
+ /** Puts the gesture on the canvas. Answers what takes it off again. */
5
+ export function installAltDragDuplicate(options) {
6
+ const { flow, wrapper } = options;
7
+ /** The press that may become a drag, until it is released. */
8
+ let press = null;
9
+ /** The copies that are being carried, with where each was when the drag began (canvas units). */
10
+ let carried = null;
11
+ function stop() {
12
+ press = null;
13
+ carried = null;
14
+ window.removeEventListener('mousemove', handleMouseMove);
15
+ window.removeEventListener('mouseup', handleMouseUp);
16
+ }
17
+ function handleMouseMove(event) {
18
+ if (!press)
19
+ return;
20
+ const distance = Math.hypot(event.clientX - press.clientX, event.clientY - press.clientY);
21
+ if (carried === null) {
22
+ if (distance <= DRAG_THRESHOLD)
23
+ return;
24
+ try {
25
+ const ids = options.beginCopies();
26
+ if (ids === null || ids.length === 0) {
27
+ stop();
28
+ return;
29
+ }
30
+ carried = ids.flatMap((id) => {
31
+ const node = flow.getNode(id);
32
+ return node ? [{ id, x: node.position.x, y: node.position.y }] : [];
33
+ });
34
+ }
35
+ catch (error) {
36
+ workflowsError('The canvas could not copy the blocks being dragged.', error);
37
+ stop();
38
+ return;
39
+ }
40
+ }
41
+ // The copies move with the pointer, by the same amount, whatever the zoom
42
+ const zoom = flow.viewport.zoom > 0 ? flow.viewport.zoom : 1;
43
+ const deltaX = (event.clientX - press.clientX) / zoom;
44
+ const deltaY = (event.clientY - press.clientY) / zoom;
45
+ for (const copy of carried) {
46
+ flow.updateNodePosition(copy.id, { x: copy.x + deltaX, y: copy.y + deltaY });
47
+ }
48
+ }
49
+ function handleMouseUp() {
50
+ const wasCarrying = carried !== null;
51
+ stop();
52
+ if (!wasCarrying)
53
+ return;
54
+ try {
55
+ options.finishCopies();
56
+ }
57
+ catch (error) {
58
+ workflowsError('The canvas could not finish copying the blocks.', error);
59
+ }
60
+ }
61
+ function handleMouseDownCapture(event) {
62
+ if (event.button !== 0 || !event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
63
+ return;
64
+ if (!options.canChange() || press !== null)
65
+ return;
66
+ const target = event.target instanceof Element ? event.target : null;
67
+ const nodeElement = target?.closest('[data-node-id]');
68
+ if (!nodeElement || target?.closest('[data-handle-id]'))
69
+ return;
70
+ const nodeId = nodeElement.dataset.nodeId;
71
+ if (!nodeId)
72
+ return;
73
+ // kaykay does not hear this press: it would start moving the original
74
+ event.stopPropagation();
75
+ event.preventDefault();
76
+ wrapper.querySelector('.kaykay-canvas')?.focus({ preventScroll: true });
77
+ // Pressing on a block that is not selected selects it, as a plain press does; a selected block keeps the selection
78
+ if (!flow.selected_node_ids.has(nodeId))
79
+ flow.selectNode(nodeId, false);
80
+ press = { clientX: event.clientX, clientY: event.clientY };
81
+ window.addEventListener('mousemove', handleMouseMove);
82
+ window.addEventListener('mouseup', handleMouseUp);
83
+ }
84
+ wrapper.addEventListener('mousedown', handleMouseDownCapture, true);
85
+ return () => {
86
+ wrapper.removeEventListener('mousedown', handleMouseDownCapture, true);
87
+ const wasCarrying = carried !== null;
88
+ stop();
89
+ if (wasCarrying)
90
+ options.finishCopies();
91
+ };
92
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The magnet of a line, put on kaykay's canvas. The maths of what a line snaps to is `editor/connectionSnap.ts`; this reads
3
+ * the blocks of the canvas for it, puts its answer where kaykay draws the end of the line, marks the point that holds the
4
+ * line, and connects the line there when the person lets go.
5
+ *
6
+ * Three things are done on kaykay's own objects, because kaykay has no place to ask for them:
7
+ * - kaykay works out the end of the line from the pointer (`flow.updateConnection`, once per frame). It is called through
8
+ * this canvas's state, so the call is wrapped: the end it is given is the point the line snaps to, when there is one;
9
+ * - kaykay connects a line where the pointer is released only when the pointer is on a connection point, and cancels it when
10
+ * the person clicks the empty canvas to finish a line. Both are heard first, in the capture phase, and when a point holds
11
+ * the line the line is finished there;
12
+ * - the point that holds the line is marked on its element (`data-snapped`, and `data-snap-target` on its block), which
13
+ * `HandlePoint` and the canvas styles answer.
14
+ *
15
+ * With `CONNECTION_SNAP_ENABLED` off nothing of this is installed: kaykay runs as it did.
16
+ */
17
+ import type { FlowState } from 'kaykay';
18
+ /** What the canvas does with the magnet. */
19
+ export interface ConnectionSnap {
20
+ /** Lets go of the point that holds the line (the line ended or was cancelled): its marks go. */
21
+ release(): void;
22
+ /** Takes the magnet off the canvas. */
23
+ dispose(): void;
24
+ }
25
+ /**
26
+ * Puts the magnet on a canvas. `wrapper` is the element that holds kaykay's canvas (the events and the marks are on it).
27
+ * Answers what the canvas calls to let go of a point and to take the magnet off again.
28
+ */
29
+ export declare function installConnectionSnap(flow: FlowState, wrapper: HTMLElement): ConnectionSnap;