@widgetic/workflows 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +107 -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 +168 -0
  5. package/dist/api/types.js +3 -0
  6. package/dist/api/workflowsApi.d.ts +109 -0
  7. package/dist/api/workflowsApi.js +657 -0
  8. package/dist/components/Workflows.svelte +41 -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 +87 -0
  13. package/dist/components/WorkflowsWorkspace.svelte.d.ts +14 -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/EditorBanners.svelte +143 -0
  31. package/dist/components/editor/EditorBanners.svelte.d.ts +7 -0
  32. package/dist/components/editor/EditorCanvasArea.svelte +85 -0
  33. package/dist/components/editor/EditorCanvasArea.svelte.d.ts +3 -0
  34. package/dist/components/editor/EditorTabs.svelte +81 -0
  35. package/dist/components/editor/EditorTabs.svelte.d.ts +7 -0
  36. package/dist/components/editor/EditorTopBar.svelte +132 -0
  37. package/dist/components/editor/EditorTopBar.svelte.d.ts +9 -0
  38. package/dist/components/editor/RunsTab.svelte +256 -0
  39. package/dist/components/editor/RunsTab.svelte.d.ts +3 -0
  40. package/dist/components/editor/SettingsTab.svelte +180 -0
  41. package/dist/components/editor/SettingsTab.svelte.d.ts +7 -0
  42. package/dist/components/editor/WorkflowEditor.svelte +185 -0
  43. package/dist/components/editor/WorkflowEditor.svelte.d.ts +15 -0
  44. package/dist/components/index.d.ts +0 -2
  45. package/dist/components/index.js +0 -2
  46. package/dist/components/list/CreateWorkflowDialog.svelte +89 -0
  47. package/dist/components/list/CreateWorkflowDialog.svelte.d.ts +9 -0
  48. package/dist/components/list/WorkflowList.svelte +204 -0
  49. package/dist/components/list/WorkflowList.svelte.d.ts +12 -0
  50. package/dist/components/list/WorkflowRow.svelte +191 -0
  51. package/dist/components/list/WorkflowRow.svelte.d.ts +10 -0
  52. package/dist/components/panel/BlockProblems.svelte +47 -0
  53. package/dist/components/panel/BlockProblems.svelte.d.ts +6 -0
  54. package/dist/components/panel/CompositionForm.svelte +127 -0
  55. package/dist/components/panel/CompositionForm.svelte.d.ts +7 -0
  56. package/dist/components/panel/CompositionPicker.svelte +179 -0
  57. package/dist/components/panel/CompositionPicker.svelte.d.ts +14 -0
  58. package/dist/components/panel/ConditionForm.svelte +105 -0
  59. package/dist/components/panel/ConditionForm.svelte.d.ts +7 -0
  60. package/dist/components/panel/EventValueRow.svelte +85 -0
  61. package/dist/components/panel/EventValueRow.svelte.d.ts +12 -0
  62. package/dist/components/panel/NextStepSelect.svelte +70 -0
  63. package/dist/components/panel/NextStepSelect.svelte.d.ts +12 -0
  64. package/dist/components/panel/ProblemsList.svelte +101 -0
  65. package/dist/components/panel/ProblemsList.svelte.d.ts +3 -0
  66. package/dist/components/panel/RuleCard.svelte +191 -0
  67. package/dist/components/panel/RuleCard.svelte.d.ts +13 -0
  68. package/dist/components/panel/SidePanel.svelte +82 -0
  69. package/dist/components/panel/SidePanel.svelte.d.ts +3 -0
  70. package/dist/components/panel/TestRow.svelte +150 -0
  71. package/dist/components/panel/TestRow.svelte.d.ts +15 -0
  72. package/dist/components/panel/TestRunPanel.svelte +85 -0
  73. package/dist/components/panel/TestRunPanel.svelte.d.ts +3 -0
  74. package/dist/components/panel/TestTriggerCard.svelte +121 -0
  75. package/dist/components/panel/TestTriggerCard.svelte.d.ts +7 -0
  76. package/dist/components/panel/TriggerForm.svelte +385 -0
  77. package/dist/components/panel/TriggerForm.svelte.d.ts +7 -0
  78. package/dist/components/panel/VersionHistory.svelte +123 -0
  79. package/dist/components/panel/VersionHistory.svelte.d.ts +3 -0
  80. package/dist/components/ui/ActionButton.svelte +85 -0
  81. package/dist/components/ui/ActionButton.svelte.d.ts +27 -0
  82. package/dist/components/ui/ConfirmDialog.svelte +52 -0
  83. package/dist/components/ui/ConfirmDialog.svelte.d.ts +16 -0
  84. package/dist/components/ui/Icon.svelte +32 -0
  85. package/dist/components/ui/Icon.svelte.d.ts +9 -0
  86. package/dist/components/ui/Menu.svelte +211 -0
  87. package/dist/components/ui/Menu.svelte.d.ts +21 -0
  88. package/dist/components/ui/Modal.svelte +129 -0
  89. package/dist/components/ui/Modal.svelte.d.ts +13 -0
  90. package/dist/components/ui/Notice.svelte +36 -0
  91. package/dist/components/ui/Notice.svelte.d.ts +11 -0
  92. package/dist/components/ui/SelectField.svelte +74 -0
  93. package/dist/components/ui/SelectField.svelte.d.ts +16 -0
  94. package/dist/components/ui/StatusBadge.svelte +41 -0
  95. package/dist/components/ui/StatusBadge.svelte.d.ts +9 -0
  96. package/dist/components/ui/TextField.svelte +97 -0
  97. package/dist/components/ui/TextField.svelte.d.ts +29 -0
  98. package/dist/components/ui/icons.d.ts +34 -0
  99. package/dist/components/ui/icons.js +54 -0
  100. package/dist/components/ui/types.d.ts +26 -0
  101. package/dist/components/ui/types.js +1 -0
  102. package/dist/editor/apiErrorText.d.ts +10 -0
  103. package/dist/editor/apiErrorText.js +53 -0
  104. package/dist/editor/autosave.d.ts +47 -0
  105. package/dist/editor/autosave.js +119 -0
  106. package/dist/editor/blockLabels.d.ts +91 -0
  107. package/dist/editor/blockLabels.js +196 -0
  108. package/dist/editor/canvasContext.d.ts +52 -0
  109. package/dist/editor/canvasContext.js +37 -0
  110. package/dist/editor/canvasWords.d.ts +24 -0
  111. package/dist/editor/canvasWords.js +40 -0
  112. package/dist/editor/capabilityModel.d.ts +46 -0
  113. package/dist/editor/capabilityModel.js +113 -0
  114. package/dist/editor/editorState.svelte.d.ts +220 -0
  115. package/dist/editor/editorState.svelte.js +713 -0
  116. package/dist/editor/flowAdapter.d.ts +59 -0
  117. package/dist/editor/flowAdapter.js +166 -0
  118. package/dist/editor/formatCount.d.ts +5 -0
  119. package/dist/editor/formatCount.js +15 -0
  120. package/dist/editor/graphDiff.d.ts +27 -0
  121. package/dist/editor/graphDiff.js +64 -0
  122. package/dist/editor/graphModel.d.ts +154 -0
  123. package/dist/editor/graphModel.js +457 -0
  124. package/dist/editor/issueText.d.ts +64 -0
  125. package/dist/editor/issueText.js +101 -0
  126. package/dist/editor/listState.svelte.d.ts +82 -0
  127. package/dist/editor/listState.svelte.js +250 -0
  128. package/dist/editor/statsRange.d.ts +26 -0
  129. package/dist/editor/statsRange.js +41 -0
  130. package/dist/editor/testRun.d.ts +36 -0
  131. package/dist/editor/testRun.js +74 -0
  132. package/dist/editor/zonedTime.d.ts +20 -0
  133. package/dist/editor/zonedTime.js +134 -0
  134. package/dist/i18n/language.d.ts +3 -3
  135. package/dist/i18n/messages.d.ts +396 -4
  136. package/dist/i18n/messages.js +421 -8
  137. package/dist/index.d.ts +2 -1
  138. package/dist/index.js +1 -1
  139. package/dist/types/index.d.ts +31 -3
  140. package/package.json +5 -1
@@ -0,0 +1,95 @@
1
+ <!--
2
+ A condition block on the canvas: the rules that decide where a visitor goes after a trigger, in the order they are
3
+ tried (the first rule that matches wins), and the Default for a visitor no rule matched. Every rule has its own place on
4
+ the right edge for the line to the next composition, in the row of that rule; the Default's place is in its row too. A
5
+ Default with no line means the visitor stays on the composition they are on.
6
+ -->
7
+ <script lang="ts">
8
+ import type { NodeProps } from 'kaykay';
9
+ import { DEFAULT_PORT } from '@widgetic/workflows-engine';
10
+ import type { ConditionNode, FieldReference } from '@widgetic/workflows-engine';
11
+ import { useTextDirection } from '@widgetic/design-system/components/textDirection';
12
+ import {
13
+ INPUT_ACCEPTS,
14
+ INPUT_HANDLE_ID,
15
+ OUTPUT_PORT_TYPE,
16
+ type WorkflowBlockData
17
+ } from '../../editor/flowAdapter.js';
18
+ import { nameRule, summarizeRule } from '../../editor/blockLabels.js';
19
+ import { findEdgeFrom, useCanvasContext } from '../../editor/canvasContext.js';
20
+ import { useWorkflowsLanguage } from '../../i18n/language.js';
21
+ import Icon from '../ui/Icon.svelte';
22
+ import HandlePoint from './HandlePoint.svelte';
23
+
24
+ let { id, data }: NodeProps<WorkflowBlockData> = $props();
25
+
26
+ const { t } = useWorkflowsLanguage();
27
+ const textDirection = useTextDirection();
28
+ const readContext = useCanvasContext();
29
+
30
+ const node = $derived(data.node as ConditionNode);
31
+ const marks = $derived(readContext().marks);
32
+ const problemCount = $derived(marks.problemCountOf(id));
33
+ /** Without a line from the Default, a visitor no rule matched stays where they are: the block says so. */
34
+ const defaultStays = $derived(
35
+ findEdgeFrom(readContext().words.graph, id, DEFAULT_PORT) === undefined
36
+ );
37
+
38
+ /** What a field of a test is called: the widget's label for a column, the name of a value of the page's event. */
39
+ function labelField(field: FieldReference): string {
40
+ return readContext().words.labelField(id, field);
41
+ }
42
+ </script>
43
+
44
+ <div
45
+ class="relative flex w-72 flex-col gap-1 rounded-large border border-grey2 bg-white py-3 text-start text-ink-primary shadow-sm"
46
+ dir={$textDirection}
47
+ data-workflow-block="condition"
48
+ >
49
+ <div class="flex items-center gap-2 px-3 pb-1">
50
+ <Icon name="condition" class="size-4 text-ink-muted" />
51
+ <p class="min-w-0 flex-1 truncate text-xs font-medium text-ink-muted">
52
+ {$t('workflows.block.condition')}
53
+ </p>
54
+ </div>
55
+ {#if problemCount > 0}
56
+ <p class="flex items-center gap-1 px-3 text-xs text-error">
57
+ <Icon name="warning" class="size-3.5" />
58
+ {$t('workflows.block.problems', { count: problemCount })}
59
+ </p>
60
+ {/if}
61
+
62
+ <!-- Each row is the positioned parent of its own connection point, which sits on the right edge in the middle of the row. -->
63
+ {#each node.cases as rule, index (rule.id)}
64
+ <div class="relative border-t border-grey2 px-3 py-2">
65
+ <p class="truncate pe-3 text-sm font-medium" dir="auto">{nameRule(rule, index, $t)}</p>
66
+ <p class="line-clamp-2 pe-3 text-xs text-ink-muted" dir="auto">
67
+ {summarizeRule(rule, labelField, $t)}
68
+ </p>
69
+ <HandlePoint id={rule.id} type="output" port={OUTPUT_PORT_TYPE.condition} position="right" />
70
+ </div>
71
+ {/each}
72
+
73
+ <div class="relative border-t border-grey2 px-3 py-2">
74
+ <p class="truncate pe-3 text-sm font-medium">{$t('workflows.condition.defaultName')}</p>
75
+ <p class="text-xs text-ink-muted">
76
+ {defaultStays
77
+ ? $t('workflows.condition.defaultStays')
78
+ : $t('workflows.condition.defaultHint')}
79
+ </p>
80
+ <HandlePoint
81
+ id={DEFAULT_PORT}
82
+ type="output"
83
+ port={OUTPUT_PORT_TYPE.condition}
84
+ position="right"
85
+ />
86
+ </div>
87
+
88
+ <HandlePoint
89
+ id={INPUT_HANDLE_ID}
90
+ type="input"
91
+ port={INPUT_HANDLE_ID}
92
+ accept={INPUT_ACCEPTS.condition}
93
+ position="left"
94
+ />
95
+ </div>
@@ -0,0 +1,5 @@
1
+ import type { NodeProps } from 'kaykay';
2
+ import { type WorkflowBlockData } from '../../editor/flowAdapter.js';
3
+ declare const ConditionNodeView: import("svelte").Component<NodeProps<WorkflowBlockData>, {}, "">;
4
+ type ConditionNodeView = ReturnType<typeof ConditionNodeView>;
5
+ export default ConditionNodeView;
@@ -0,0 +1,32 @@
1
+ <!--
2
+ A connection point of a block: the small circle a line starts from or ends at. kaykay places it, measures it and runs the
3
+ dragging; this only draws it, in the screen's palette. While a line is being dragged, kaykay marks every point with what
4
+ it would do (`can-connect`, `connecting`, `incompatible`) and this picture follows: a point that accepts the line turns
5
+ green, one that cannot is dimmed by kaykay itself.
6
+
7
+ The circle is the handle's one child, so kaykay drops its own square look (`has-custom-shape`) and leaves the drawing to
8
+ the classes below. `group` lets the circle react to the class kaykay puts on the handle around it.
9
+ -->
10
+ <script lang="ts">
11
+ import { Handle } from 'kaykay';
12
+ import type { HandlePosition } from 'kaykay';
13
+
14
+ interface Props {
15
+ id: string;
16
+ type: 'input' | 'output';
17
+ /** What this place carries (`shown`, `fired`, `path`); a line may only end where the place accepts it. */
18
+ port: string;
19
+ /** For an input: the ports it accepts. */
20
+ accept?: readonly string[];
21
+ /** The side of the block the point sits on. The canvas is always drawn left to right, so this is a physical side. */
22
+ position: HandlePosition;
23
+ }
24
+
25
+ let { id, type, port, accept, position }: Props = $props();
26
+ </script>
27
+
28
+ <Handle {id} {type} {port} accept={accept ? [...accept] : undefined} {position} class="group">
29
+ <span
30
+ class="block size-3.5 rounded-pill border-2 border-ink-subtle bg-white transition-colors group-hover:border-primary-green group-[.can-connect]:border-primary-green group-[.can-connect]:bg-primary-green group-[.connecting]:border-primary-green group-[.connecting]:bg-primary-green"
31
+ ></span>
32
+ </Handle>
@@ -0,0 +1,14 @@
1
+ import type { HandlePosition } from 'kaykay';
2
+ interface Props {
3
+ id: string;
4
+ type: 'input' | 'output';
5
+ /** What this place carries (`shown`, `fired`, `path`); a line may only end where the place accepts it. */
6
+ port: string;
7
+ /** For an input: the ports it accepts. */
8
+ accept?: readonly string[];
9
+ /** The side of the block the point sits on. The canvas is always drawn left to right, so this is a physical side. */
10
+ position: HandlePosition;
11
+ }
12
+ declare const HandlePoint: import("svelte").Component<Props, {}, "">;
13
+ type HandlePoint = ReturnType<typeof HandlePoint>;
14
+ export default HandlePoint;
@@ -0,0 +1,75 @@
1
+ <!--
2
+ A trigger block on the canvas: what makes a visitor leave the composition before it (a visitor adds an entry, does
3
+ something in the widget, the page sends an event, or time passes), told in one line. A line comes in from the composition
4
+ on the left and leaves to the next step on the right. In the Runs tab it also says how many times it fired.
5
+ -->
6
+ <script lang="ts">
7
+ import type { NodeProps } from 'kaykay';
8
+ import type { TriggerNode } from '@widgetic/workflows-engine';
9
+ import { useTextDirection } from '@widgetic/design-system/components/textDirection';
10
+ import {
11
+ INPUT_ACCEPTS,
12
+ INPUT_HANDLE_ID,
13
+ OUTPUT_HANDLE_ID,
14
+ OUTPUT_PORT_TYPE,
15
+ type WorkflowBlockData
16
+ } from '../../editor/flowAdapter.js';
17
+ import { TRIGGER_KIND_MESSAGE_KEYS } from '../../editor/blockLabels.js';
18
+ import { useCanvasContext } from '../../editor/canvasContext.js';
19
+ import { formatCount } from '../../editor/formatCount.js';
20
+ import { useWorkflowsLanguage } from '../../i18n/language.js';
21
+ import Icon from '../ui/Icon.svelte';
22
+ import HandlePoint from './HandlePoint.svelte';
23
+
24
+ let { id, data }: NodeProps<WorkflowBlockData> = $props();
25
+
26
+ const { t, locale } = useWorkflowsLanguage();
27
+ const textDirection = useTextDirection();
28
+ const readContext = useCanvasContext();
29
+
30
+ const node = $derived(data.node as TriggerNode);
31
+ const marks = $derived(readContext().marks);
32
+ /** What the trigger waits for, as one line. `summarizeTrigger` is read from the shared context so that it speaks the page's language. */
33
+ const summary = $derived(readContext().words.summarizeTrigger(node.trigger));
34
+ const problemCount = $derived(marks.problemCountOf(id));
35
+ const firedCount = $derived(marks.entryCountOf(id));
36
+ </script>
37
+
38
+ <div
39
+ class="relative flex w-60 flex-col gap-1.5 rounded-large border border-grey2 bg-white p-3 text-start text-ink-primary shadow-sm"
40
+ dir={$textDirection}
41
+ data-workflow-block="trigger"
42
+ >
43
+ <div class="flex items-center gap-2">
44
+ <Icon name="trigger" class="size-4 text-ink-muted" />
45
+ <p class="min-w-0 flex-1 truncate text-xs font-medium text-ink-muted">
46
+ {$t(TRIGGER_KIND_MESSAGE_KEYS[node.trigger.kind])}
47
+ </p>
48
+ </div>
49
+ <p class="text-sm break-words" dir="auto">{summary}</p>
50
+ {#if problemCount > 0}
51
+ <p class="flex items-center gap-1 text-xs text-error">
52
+ <Icon name="warning" class="size-3.5" />
53
+ {$t('workflows.block.problems', { count: problemCount })}
54
+ </p>
55
+ {/if}
56
+ {#if firedCount !== null}
57
+ <p class="text-xs text-ink-muted">
58
+ {$t('workflows.runs.fired', { count: formatCount(firedCount, $locale) })}
59
+ </p>
60
+ {/if}
61
+
62
+ <HandlePoint
63
+ id={INPUT_HANDLE_ID}
64
+ type="input"
65
+ port={INPUT_HANDLE_ID}
66
+ accept={INPUT_ACCEPTS.trigger}
67
+ position="left"
68
+ />
69
+ <HandlePoint
70
+ id={OUTPUT_HANDLE_ID}
71
+ type="output"
72
+ port={OUTPUT_PORT_TYPE.trigger}
73
+ position="right"
74
+ />
75
+ </div>
@@ -0,0 +1,5 @@
1
+ import type { NodeProps } from 'kaykay';
2
+ import { type WorkflowBlockData } from '../../editor/flowAdapter.js';
3
+ declare const TriggerNodeView: import("svelte").Component<NodeProps<WorkflowBlockData>, {}, "">;
4
+ type TriggerNodeView = ReturnType<typeof TriggerNodeView>;
5
+ export default TriggerNodeView;
@@ -0,0 +1,380 @@
1
+ <!--
2
+ The canvas: where the blocks of a workflow are laid out and joined with lines. It is kaykay's canvas, wrapped so that it
3
+ speaks the engine's graph instead of its own, and so that nothing of it escapes the screen it is part of.
4
+
5
+ What it does and does not do:
6
+ - It holds the blocks while they are dragged and drawn. Every change a person makes arrives at the owner as the engine's
7
+ graph (`onGraphChange`), once per change. The owner answers with the graph it keeps, which can differ (the first
8
+ composition left becomes the start) and the canvas takes that over without making an undo step.
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.
11
+ - 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 the
14
+ clipboard is the person's own); everything else of kaykay's keyboard stays (arrows move, Delete deletes, undo, redo).
15
+ - kaykay names its connection points in English; here they are named in the page's language.
16
+
17
+ It is always drawn left to right, whatever the page's direction: lines run from the composition on the left to the next
18
+ step on the right in every language, and only the words inside the blocks follow the page.
19
+ -->
20
+ <script lang="ts">
21
+ import { onDestroy, onMount, untrack } from 'svelte';
22
+ import { Canvas } from 'kaykay';
23
+ import type {
24
+ EdgeTypes,
25
+ FlowCallbacks,
26
+ FlowConfig,
27
+ FlowState,
28
+ NodeStatus,
29
+ NodeTypes
30
+ } from 'kaykay';
31
+ import type { WorkflowGraph } from '@widgetic/workflows-engine';
32
+ import { provideCanvasContext, type CanvasContext } from '../../editor/canvasContext.js';
33
+ import type { CanvasHandle } from '../../editor/editorState.svelte.js';
34
+ import {
35
+ WORKFLOW_EDGE_TYPE,
36
+ createConnectionValidator,
37
+ flowToGraph,
38
+ graphToFlow,
39
+ toFlowEdge,
40
+ toFlowNode
41
+ } from '../../editor/flowAdapter.js';
42
+ import { diffGraphs } from '../../editor/graphDiff.js';
43
+ import { isSameGraph } from '../../editor/graphModel.js';
44
+ import { useWorkflowsLanguage } from '../../i18n/language.js';
45
+ import { workflowsError } from '../../utils/logger.js';
46
+ import CompositionNodeView from './CompositionNodeView.svelte';
47
+ import ConditionNodeView from './ConditionNodeView.svelte';
48
+ import TriggerNodeView from './TriggerNodeView.svelte';
49
+ import WorkflowEdgeView from './WorkflowEdgeView.svelte';
50
+
51
+ interface Props {
52
+ /** The workflow the canvas starts with. Everything after that goes through the handle. */
53
+ initialGraph: WorkflowGraph;
54
+ /** What the blocks and lines ask about the workflow around them (see `CanvasContext`). */
55
+ readContext: () => CanvasContext;
56
+ /** The canvas only shows: blocks cannot be moved, joined or taken away. */
57
+ readOnly: boolean;
58
+ /** Outlines by block: `error` (red), `running` (where a test visitor is), `completed` (passed). */
59
+ statuses?: Record<string, NodeStatus>;
60
+ /** The graph after a change on the canvas. Answers the graph the owner keeps, if it is not the one it was given. */
61
+ onGraphChange?: (graph: WorkflowGraph) => WorkflowGraph | undefined;
62
+ onSelectionChange?: (nodeIds: readonly string[], edgeIds: readonly string[]) => void;
63
+ /** The `B` key was pressed on the canvas: the owner opens its Add block menu. */
64
+ onAddBlockShortcut?: () => void;
65
+ /** Gives the owner the handle once the canvas is on the screen, and `null` when it leaves. */
66
+ onReady?: (handle: CanvasHandle | null) => void;
67
+ class?: string;
68
+ }
69
+
70
+ let {
71
+ initialGraph,
72
+ readContext,
73
+ readOnly,
74
+ statuses = {},
75
+ onGraphChange,
76
+ onSelectionChange,
77
+ onAddBlockShortcut,
78
+ onReady,
79
+ class: className = ''
80
+ }: Props = $props();
81
+
82
+ const { t } = useWorkflowsLanguage();
83
+
84
+ // The blocks and the lines below this ask for what they need through the context.
85
+ provideCanvasContext(() => readContext());
86
+
87
+ const nodeTypes: NodeTypes = {
88
+ composition: CompositionNodeView,
89
+ trigger: TriggerNodeView,
90
+ condition: ConditionNodeView
91
+ };
92
+ const edgeTypes: EdgeTypes = { [WORKFLOW_EDGE_TYPE]: WorkflowEdgeView };
93
+
94
+ // kaykay reads `flow`, `config` and `callbacks` once, when it is made: the canvas holds its own state from then on.
95
+ const firstFlow = untrack(() => graphToFlow(initialGraph));
96
+
97
+ /** The canvas component, once it is on the screen: it hands out kaykay's state of the flow. */
98
+ let canvas = $state<{ getFlow: () => FlowState } | undefined>();
99
+
100
+ let wrapperElement = $state<HTMLDivElement>();
101
+
102
+ /** How many of our own changes are in the middle of being made: kaykay reports each of them and we do not want to hear. */
103
+ let ownChanges = 0;
104
+ let isReadScheduled = false;
105
+ let fitFrame: number | null = null;
106
+
107
+ function getFlow(): FlowState | undefined {
108
+ return canvas?.getFlow();
109
+ }
110
+
111
+ const flowConfig: FlowConfig = {
112
+ min_zoom: 0.25,
113
+ max_zoom: 1.5,
114
+ allow_delete: true,
115
+ pan_on_scroll: true,
116
+ zoom_on_scroll: false,
117
+ max_history: 100,
118
+ // A line drawn by hand is made by kaykay: without this it is drawn as kaykay's own line, not as ours (counts, highlights)
119
+ default_edge_type: WORKFLOW_EDGE_TYPE,
120
+ locked: untrack(() => readOnly),
121
+ is_valid_connection: createConnectionValidator(
122
+ () => {
123
+ const flow = getFlow();
124
+ return flow ? flowToGraph(flow) : initialGraph;
125
+ },
126
+ () => getFlow()?.draft_connection?.reconnect_edge_id
127
+ )
128
+ };
129
+
130
+ const flowCallbacks: FlowCallbacks = {
131
+ on_change: () => scheduleRead(),
132
+ on_selection_change: (nodeIds, edgeIds) => onSelectionChange?.(nodeIds, edgeIds)
133
+ };
134
+
135
+ // ---- what the canvas holds, as the engine's graph -----------------------------------------------------------------
136
+
137
+ /** Reads the canvas after the operation that is going on is over: kaykay reports once per step, a drag or a paste is many. */
138
+ function scheduleRead(): void {
139
+ if (ownChanges > 0 || isReadScheduled) return;
140
+ isReadScheduled = true;
141
+ queueMicrotask(() => {
142
+ isReadScheduled = false;
143
+ readCanvasNow();
144
+ });
145
+ }
146
+
147
+ function readCanvasNow(): void {
148
+ const flow = getFlow();
149
+ if (!flow) return;
150
+ try {
151
+ const fromCanvas = flowToGraph(flow);
152
+ const kept = onGraphChange?.(fromCanvas);
153
+ // The owner keeps a graph that differs from the canvas's (a new start): take it over, as no step to undo.
154
+ if (kept && !isSameGraph(kept, fromCanvas)) applyGraph(kept, false);
155
+ } catch (error) {
156
+ workflowsError('The canvas could not tell the editor about a change.', error);
157
+ }
158
+ }
159
+
160
+ function reportSelection(): void {
161
+ const flow = getFlow();
162
+ if (!flow) return;
163
+ onSelectionChange?.([...flow.selected_node_ids], [...flow.selected_edge_ids]);
164
+ }
165
+
166
+ // ---- changes that come from outside the canvas -------------------------------------------------------------------
167
+
168
+ /**
169
+ * Turns what the canvas holds into this workflow, with only the steps it takes: blocks and lines taken away, blocks whose
170
+ * content changed, blocks added, blocks moved, lines drawn. Lines go in directly (kaykay checks a line against the points
171
+ * of the blocks, which a block added a moment ago does not have yet; the engine has checked these already).
172
+ */
173
+ function applyGraph(next: WorkflowGraph, recordHistory: boolean): void {
174
+ const flow = getFlow();
175
+ if (!flow) return;
176
+ const difference = diffGraphs(flowToGraph(flow), next);
177
+ if (difference.isEmpty) return;
178
+
179
+ // A canvas that cannot be changed by hand (a touch screen) is still changed from the side panel.
180
+ const wasLocked = flow.locked;
181
+ ownChanges += 1;
182
+ if (wasLocked) flow.setLocked(false);
183
+ flow.beginTransaction();
184
+ try {
185
+ // Counts as a change even when only lines were moved about, so that the step is kept for undo.
186
+ flow.pushSnapshot();
187
+ if (difference.removedEdgeIds.length > 0) {
188
+ const removed = new Set(difference.removedEdgeIds);
189
+ flow.edges = flow.edges.filter((edge) => !removed.has(edge.id));
190
+ }
191
+ for (const nodeId of difference.removedNodeIds) flow.removeNode(nodeId);
192
+ for (const node of difference.changedNodes)
193
+ flow.updateNodeData(node.id, toFlowNode(node).data);
194
+ for (const node of difference.addedNodes) flow.addNode(toFlowNode(node));
195
+ for (const move of difference.movedNodes)
196
+ flow.updateNodePosition(move.id, { x: move.position.x, y: move.position.y });
197
+ if (difference.addedEdges.length > 0)
198
+ flow.edges.push(...difference.addedEdges.map(toFlowEdge));
199
+ } catch (error) {
200
+ // Half a change must not stay on the canvas: start again from the workflow that was asked for.
201
+ workflowsError('The canvas could not take over a change; it is drawn again.', error);
202
+ flow.cancelTransaction();
203
+ flow.fromJSON(graphToFlow(next));
204
+ } finally {
205
+ flow.endTransaction(recordHistory, 'batch');
206
+ if (wasLocked) flow.setLocked(true);
207
+ ownChanges -= 1;
208
+ }
209
+ reportSelection();
210
+ if (recordHistory) readCanvasNow();
211
+ }
212
+
213
+ /** Draws a whole other workflow, as a reload or a version does: nothing to undo afterwards. */
214
+ function loadGraph(graph: WorkflowGraph): void {
215
+ const flow = getFlow();
216
+ if (!flow) return;
217
+ ownChanges += 1;
218
+ try {
219
+ flow.fromJSON(graphToFlow(graph));
220
+ flow.clearHistory();
221
+ } catch (error) {
222
+ workflowsError('The canvas could not load the workflow.', error);
223
+ } finally {
224
+ ownChanges -= 1;
225
+ }
226
+ reportSelection();
227
+ fitSoon();
228
+ }
229
+
230
+ /** Fits all the blocks in view once they have been measured (the frame after they are drawn). */
231
+ function fitSoon(): void {
232
+ if (fitFrame !== null) cancelAnimationFrame(fitFrame);
233
+ fitFrame = requestAnimationFrame(() => {
234
+ fitFrame = requestAnimationFrame(() => {
235
+ fitFrame = null;
236
+ getFlow()?.fitView(80);
237
+ });
238
+ });
239
+ }
240
+
241
+ const handle: CanvasHandle = {
242
+ applyGraph: (next) => applyGraph(next, true),
243
+ loadGraph,
244
+ selectNodes(nodeIds) {
245
+ const flow = getFlow();
246
+ if (!flow) return;
247
+ flow.clearSelection();
248
+ for (const nodeId of nodeIds) flow.selectNode(nodeId, true);
249
+ },
250
+ fitView: () => getFlow()?.fitView(80),
251
+ zoomIn: () => getFlow()?.zoomIn(0.15),
252
+ zoomOut: () => getFlow()?.zoomOut(0.15),
253
+ undo: () => void getFlow()?.undo(),
254
+ redo: () => void getFlow()?.redo(),
255
+ get canUndo() {
256
+ return getFlow()?.canUndo ?? false;
257
+ },
258
+ get canRedo() {
259
+ return getFlow()?.canRedo ?? false;
260
+ }
261
+ };
262
+
263
+ // A canvas that is switched to read-only (a version, a touch screen, an archived workflow) is locked in kaykay too.
264
+ $effect(() => {
265
+ const flow = canvas?.getFlow();
266
+ if (flow && flow.locked !== readOnly) flow.setLocked(readOnly);
267
+ });
268
+
269
+ // ---- the keyboard ------------------------------------------------------------------------------------------------
270
+
271
+ /** Whether the key was pressed in a field where letters are text. */
272
+ function isTypingTarget(target: EventTarget | null): boolean {
273
+ if (!(target instanceof HTMLElement)) return false;
274
+ return (
275
+ target.tagName === 'INPUT' ||
276
+ target.tagName === 'TEXTAREA' ||
277
+ target.tagName === 'SELECT' ||
278
+ target.isContentEditable
279
+ );
280
+ }
281
+
282
+ /**
283
+ * Runs before kaykay hears the key. Copy, paste, cut and "log selection" are taken away from it. `B` is "Add block".
284
+ */
285
+ function handleKeydownCapture(event: KeyboardEvent): void {
286
+ if (isTypingTarget(event.target)) return;
287
+ const key = event.key.toLowerCase();
288
+ const hasCommand = event.ctrlKey || event.metaKey;
289
+ if (hasCommand && (key === 'c' || key === 'v' || key === 'x' || key === 'l')) {
290
+ event.preventDefault();
291
+ event.stopPropagation();
292
+ return;
293
+ }
294
+ if (!hasCommand && !event.altKey && !event.shiftKey && key === 'b' && !readOnly) {
295
+ event.preventDefault();
296
+ event.stopPropagation();
297
+ onAddBlockShortcut?.();
298
+ }
299
+ }
300
+
301
+ // ---- kaykay's English names for its connection points ---------------------------------------------------------
302
+
303
+ /** Names every connection point in the page's language, and drops the tip kaykay puts on it (English and about its ids). */
304
+ function nameConnectionPoints(): void {
305
+ if (!wrapperElement) return;
306
+ for (const point of wrapperElement.querySelectorAll<HTMLElement>('[data-handle-id]')) {
307
+ const name =
308
+ point.dataset.handleType === 'input'
309
+ ? $t('workflows.canvas.pointIn')
310
+ : $t('workflows.canvas.pointOut');
311
+ if (point.getAttribute('aria-label') !== name) point.setAttribute('aria-label', name);
312
+ if (point.hasAttribute('title')) point.removeAttribute('title');
313
+ }
314
+ }
315
+
316
+ let namingObserver: MutationObserver | null = null;
317
+ let isNamingScheduled = false;
318
+
319
+ onMount(() => {
320
+ if (wrapperElement) {
321
+ namingObserver = new MutationObserver(() => {
322
+ if (isNamingScheduled) return;
323
+ isNamingScheduled = true;
324
+ queueMicrotask(() => {
325
+ isNamingScheduled = false;
326
+ nameConnectionPoints();
327
+ });
328
+ });
329
+ namingObserver.observe(wrapperElement, {
330
+ subtree: true,
331
+ childList: true,
332
+ attributes: true,
333
+ attributeFilter: ['aria-label', 'title']
334
+ });
335
+ nameConnectionPoints();
336
+ }
337
+ fitSoon();
338
+ onReady?.(handle);
339
+ });
340
+
341
+ // The names follow the page's language when it changes.
342
+ $effect(() => {
343
+ void $t('workflows.canvas.pointIn');
344
+ nameConnectionPoints();
345
+ });
346
+
347
+ onDestroy(() => {
348
+ namingObserver?.disconnect();
349
+ namingObserver = null;
350
+ if (fitFrame !== null) cancelAnimationFrame(fitFrame);
351
+ fitFrame = null;
352
+ onReady?.(null);
353
+ });
354
+ </script>
355
+
356
+ <!--
357
+ `dir="ltr"` (see the note at the top): the canvas is drawn left to right in every language.
358
+ `isolate`: kaykay gives its layers z-indexes up to 10000; this keeps them inside the canvas, below the rest of the screen.
359
+ The two `--kaykay-*` lines below the canvas colour are what kaykay reads from the element around it; its own background
360
+ variable is set on the canvas element itself, so it needs the `!`.
361
+ -->
362
+ <div
363
+ bind:this={wrapperElement}
364
+ class="isolate h-full min-h-0 w-full overflow-hidden rounded-large border border-grey2 [--kaykay-node-completed-outline:var(--color-primary-green)] [--kaykay-node-error-outline:var(--color-error)] [--kaykay-node-running-outline:var(--color-forest-green)] [--kaykay-node-selected-outline:var(--color-primary-green)] [&_.kaykay-node]:rounded-large {className}"
365
+ dir="ltr"
366
+ role="region"
367
+ aria-label={$t('workflows.canvas.label')}
368
+ onkeydowncapture={handleKeydownCapture}
369
+ >
370
+ <Canvas
371
+ flow={firstFlow}
372
+ {nodeTypes}
373
+ {edgeTypes}
374
+ config={flowConfig}
375
+ callbacks={flowCallbacks}
376
+ node_statuses={statuses}
377
+ class="[--kaykay-canvas-bg:var(--color-surface-canvas)]!"
378
+ bind:this={canvas}
379
+ />
380
+ </div>
@@ -0,0 +1,25 @@
1
+ import type { NodeStatus } from 'kaykay';
2
+ import type { WorkflowGraph } from '@widgetic/workflows-engine';
3
+ import { type CanvasContext } from '../../editor/canvasContext.js';
4
+ import type { CanvasHandle } from '../../editor/editorState.svelte.js';
5
+ interface Props {
6
+ /** The workflow the canvas starts with. Everything after that goes through the handle. */
7
+ initialGraph: WorkflowGraph;
8
+ /** What the blocks and lines ask about the workflow around them (see `CanvasContext`). */
9
+ readContext: () => CanvasContext;
10
+ /** The canvas only shows: blocks cannot be moved, joined or taken away. */
11
+ readOnly: boolean;
12
+ /** Outlines by block: `error` (red), `running` (where a test visitor is), `completed` (passed). */
13
+ statuses?: Record<string, NodeStatus>;
14
+ /** The graph after a change on the canvas. Answers the graph the owner keeps, if it is not the one it was given. */
15
+ onGraphChange?: (graph: WorkflowGraph) => WorkflowGraph | undefined;
16
+ onSelectionChange?: (nodeIds: readonly string[], edgeIds: readonly string[]) => void;
17
+ /** The `B` key was pressed on the canvas: the owner opens its Add block menu. */
18
+ onAddBlockShortcut?: () => void;
19
+ /** Gives the owner the handle once the canvas is on the screen, and `null` when it leaves. */
20
+ onReady?: (handle: CanvasHandle | null) => void;
21
+ class?: string;
22
+ }
23
+ declare const WorkflowCanvas: import("svelte").Component<Props, {}, "">;
24
+ type WorkflowCanvas = ReturnType<typeof WorkflowCanvas>;
25
+ export default WorkflowCanvas;