@widgetic/workflows 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +118 -46
  2. package/dist/api/apiContext.d.ts +4 -0
  3. package/dist/api/apiContext.js +17 -0
  4. package/dist/api/types.d.ts +201 -0
  5. package/dist/api/types.js +3 -0
  6. package/dist/api/workflowsApi.d.ts +133 -0
  7. package/dist/api/workflowsApi.js +763 -0
  8. package/dist/components/Workflows.svelte +43 -17
  9. package/dist/components/WorkflowsEmptyState.svelte +16 -5
  10. package/dist/components/WorkflowsEmptyState.svelte.d.ts +5 -16
  11. package/dist/components/WorkflowsHeader.svelte +2 -2
  12. package/dist/components/WorkflowsWorkspace.svelte +90 -0
  13. package/dist/components/WorkflowsWorkspace.svelte.d.ts +15 -0
  14. package/dist/components/canvas/AddBlockMenu.svelte +101 -0
  15. package/dist/components/canvas/AddBlockMenu.svelte.d.ts +5 -0
  16. package/dist/components/canvas/CanvasToolbar.svelte +95 -0
  17. package/dist/components/canvas/CanvasToolbar.svelte.d.ts +9 -0
  18. package/dist/components/canvas/CompositionNodeView.svelte +125 -0
  19. package/dist/components/canvas/CompositionNodeView.svelte.d.ts +5 -0
  20. package/dist/components/canvas/ConditionNodeView.svelte +95 -0
  21. package/dist/components/canvas/ConditionNodeView.svelte.d.ts +5 -0
  22. package/dist/components/canvas/HandlePoint.svelte +32 -0
  23. package/dist/components/canvas/HandlePoint.svelte.d.ts +14 -0
  24. package/dist/components/canvas/TriggerNodeView.svelte +75 -0
  25. package/dist/components/canvas/TriggerNodeView.svelte.d.ts +5 -0
  26. package/dist/components/canvas/WorkflowCanvas.svelte +380 -0
  27. package/dist/components/canvas/WorkflowCanvas.svelte.d.ts +25 -0
  28. package/dist/components/canvas/WorkflowEdgeView.svelte +58 -0
  29. package/dist/components/canvas/WorkflowEdgeView.svelte.d.ts +4 -0
  30. package/dist/components/editor/ConflictBanner.svelte +78 -0
  31. package/dist/components/editor/ConflictBanner.svelte.d.ts +3 -0
  32. package/dist/components/editor/EditorBanners.svelte +141 -0
  33. package/dist/components/editor/EditorBanners.svelte.d.ts +7 -0
  34. package/dist/components/editor/EditorCanvasArea.svelte +85 -0
  35. package/dist/components/editor/EditorCanvasArea.svelte.d.ts +3 -0
  36. package/dist/components/editor/EditorTabs.svelte +81 -0
  37. package/dist/components/editor/EditorTabs.svelte.d.ts +7 -0
  38. package/dist/components/editor/EditorTopBar.svelte +132 -0
  39. package/dist/components/editor/EditorTopBar.svelte.d.ts +9 -0
  40. package/dist/components/editor/PresenceBanner.svelte +126 -0
  41. package/dist/components/editor/PresenceBanner.svelte.d.ts +3 -0
  42. package/dist/components/editor/RunsTab.svelte +256 -0
  43. package/dist/components/editor/RunsTab.svelte.d.ts +3 -0
  44. package/dist/components/editor/SettingsTab.svelte +180 -0
  45. package/dist/components/editor/SettingsTab.svelte.d.ts +7 -0
  46. package/dist/components/editor/WorkflowEditor.svelte +198 -0
  47. package/dist/components/editor/WorkflowEditor.svelte.d.ts +17 -0
  48. package/dist/components/index.d.ts +0 -2
  49. package/dist/components/index.js +0 -2
  50. package/dist/components/list/CreateWorkflowDialog.svelte +89 -0
  51. package/dist/components/list/CreateWorkflowDialog.svelte.d.ts +9 -0
  52. package/dist/components/list/WorkflowList.svelte +204 -0
  53. package/dist/components/list/WorkflowList.svelte.d.ts +12 -0
  54. package/dist/components/list/WorkflowRow.svelte +191 -0
  55. package/dist/components/list/WorkflowRow.svelte.d.ts +10 -0
  56. package/dist/components/panel/BlockProblems.svelte +47 -0
  57. package/dist/components/panel/BlockProblems.svelte.d.ts +6 -0
  58. package/dist/components/panel/CompositionForm.svelte +127 -0
  59. package/dist/components/panel/CompositionForm.svelte.d.ts +7 -0
  60. package/dist/components/panel/CompositionPicker.svelte +179 -0
  61. package/dist/components/panel/CompositionPicker.svelte.d.ts +14 -0
  62. package/dist/components/panel/ConditionForm.svelte +105 -0
  63. package/dist/components/panel/ConditionForm.svelte.d.ts +7 -0
  64. package/dist/components/panel/EventValueRow.svelte +85 -0
  65. package/dist/components/panel/EventValueRow.svelte.d.ts +12 -0
  66. package/dist/components/panel/NextStepSelect.svelte +70 -0
  67. package/dist/components/panel/NextStepSelect.svelte.d.ts +12 -0
  68. package/dist/components/panel/ProblemsList.svelte +101 -0
  69. package/dist/components/panel/ProblemsList.svelte.d.ts +3 -0
  70. package/dist/components/panel/RuleCard.svelte +191 -0
  71. package/dist/components/panel/RuleCard.svelte.d.ts +13 -0
  72. package/dist/components/panel/SidePanel.svelte +82 -0
  73. package/dist/components/panel/SidePanel.svelte.d.ts +3 -0
  74. package/dist/components/panel/TestRow.svelte +150 -0
  75. package/dist/components/panel/TestRow.svelte.d.ts +15 -0
  76. package/dist/components/panel/TestRunPanel.svelte +85 -0
  77. package/dist/components/panel/TestRunPanel.svelte.d.ts +3 -0
  78. package/dist/components/panel/TestTriggerCard.svelte +121 -0
  79. package/dist/components/panel/TestTriggerCard.svelte.d.ts +7 -0
  80. package/dist/components/panel/TriggerForm.svelte +385 -0
  81. package/dist/components/panel/TriggerForm.svelte.d.ts +7 -0
  82. package/dist/components/panel/VersionHistory.svelte +123 -0
  83. package/dist/components/panel/VersionHistory.svelte.d.ts +3 -0
  84. package/dist/components/ui/ActionButton.svelte +85 -0
  85. package/dist/components/ui/ActionButton.svelte.d.ts +27 -0
  86. package/dist/components/ui/ConfirmDialog.svelte +52 -0
  87. package/dist/components/ui/ConfirmDialog.svelte.d.ts +16 -0
  88. package/dist/components/ui/Icon.svelte +32 -0
  89. package/dist/components/ui/Icon.svelte.d.ts +9 -0
  90. package/dist/components/ui/Menu.svelte +211 -0
  91. package/dist/components/ui/Menu.svelte.d.ts +21 -0
  92. package/dist/components/ui/Modal.svelte +129 -0
  93. package/dist/components/ui/Modal.svelte.d.ts +13 -0
  94. package/dist/components/ui/Notice.svelte +36 -0
  95. package/dist/components/ui/Notice.svelte.d.ts +11 -0
  96. package/dist/components/ui/SelectField.svelte +74 -0
  97. package/dist/components/ui/SelectField.svelte.d.ts +16 -0
  98. package/dist/components/ui/StatusBadge.svelte +41 -0
  99. package/dist/components/ui/StatusBadge.svelte.d.ts +9 -0
  100. package/dist/components/ui/TextField.svelte +97 -0
  101. package/dist/components/ui/TextField.svelte.d.ts +29 -0
  102. package/dist/components/ui/icons.d.ts +34 -0
  103. package/dist/components/ui/icons.js +54 -0
  104. package/dist/components/ui/types.d.ts +26 -0
  105. package/dist/components/ui/types.js +1 -0
  106. package/dist/editor/apiErrorText.d.ts +10 -0
  107. package/dist/editor/apiErrorText.js +53 -0
  108. package/dist/editor/autosave.d.ts +47 -0
  109. package/dist/editor/autosave.js +119 -0
  110. package/dist/editor/blockLabels.d.ts +91 -0
  111. package/dist/editor/blockLabels.js +196 -0
  112. package/dist/editor/canvasContext.d.ts +52 -0
  113. package/dist/editor/canvasContext.js +37 -0
  114. package/dist/editor/canvasWords.d.ts +24 -0
  115. package/dist/editor/canvasWords.js +40 -0
  116. package/dist/editor/capabilityModel.d.ts +46 -0
  117. package/dist/editor/capabilityModel.js +113 -0
  118. package/dist/editor/editLeaseController.d.ts +162 -0
  119. package/dist/editor/editLeaseController.js +459 -0
  120. package/dist/editor/editorState.svelte.d.ts +277 -0
  121. package/dist/editor/editorState.svelte.js +862 -0
  122. package/dist/editor/flowAdapter.d.ts +59 -0
  123. package/dist/editor/flowAdapter.js +166 -0
  124. package/dist/editor/formatCount.d.ts +5 -0
  125. package/dist/editor/formatCount.js +15 -0
  126. package/dist/editor/graphDiff.d.ts +27 -0
  127. package/dist/editor/graphDiff.js +64 -0
  128. package/dist/editor/graphModel.d.ts +154 -0
  129. package/dist/editor/graphModel.js +457 -0
  130. package/dist/editor/issueText.d.ts +64 -0
  131. package/dist/editor/issueText.js +101 -0
  132. package/dist/editor/keepCopy.d.ts +41 -0
  133. package/dist/editor/keepCopy.js +52 -0
  134. package/dist/editor/listState.svelte.d.ts +82 -0
  135. package/dist/editor/listState.svelte.js +250 -0
  136. package/dist/editor/statsRange.d.ts +26 -0
  137. package/dist/editor/statsRange.js +41 -0
  138. package/dist/editor/testRun.d.ts +36 -0
  139. package/dist/editor/testRun.js +74 -0
  140. package/dist/editor/zonedTime.d.ts +20 -0
  141. package/dist/editor/zonedTime.js +134 -0
  142. package/dist/i18n/language.d.ts +3 -3
  143. package/dist/i18n/messages.d.ts +429 -4
  144. package/dist/i18n/messages.js +456 -8
  145. package/dist/index.d.ts +2 -1
  146. package/dist/index.js +1 -1
  147. package/dist/types/index.d.ts +41 -3
  148. package/package.json +5 -1
@@ -0,0 +1,862 @@
1
+ import { getContext, setContext } from 'svelte';
2
+ import { hasErrors, validate } from '@widgetic/workflows-engine';
3
+ import { WorkflowsApiError, isCancelled } from '../api/workflowsApi.js';
4
+ import { workflowsError, workflowsWarn } from '../utils/logger.js';
5
+ import { pickApiErrorMessage } from './apiErrorText.js';
6
+ import { createDraftSaver } from './autosave.js';
7
+ import { toValidationContext } from './capabilityModel.js';
8
+ import { EditLeaseController, NO_PRESENCE } from './editLeaseController.js';
9
+ import { dropStrandedConnections, ensureOneStart, isSameGraph, listCompositionIds, makeEmptyGraph, planAddBlock, removeBlocks, removeConnections, setStartBlock } from './graphModel.js';
10
+ import { groupIssues } from './flowAdapter.js';
11
+ import { keepCopyOfDraft, nameForCopy } from './keepCopy.js';
12
+ import { fireTestTrigger, startTestRun } from './testRun.js';
13
+ const DEFAULT_NOTICE_MILLISECONDS = 5000;
14
+ /**
15
+ * Where the presence writes its own notes (a request refused as malformed, a listener that failed): the console of the
16
+ * package, which starts every line with `[Workflows]` and says a line once.
17
+ */
18
+ const PRESENCE_LOGGER = {
19
+ warn: (message, detail) => workflowsWarn(String(message), detail),
20
+ error: (message, detail) => workflowsError(String(message), detail)
21
+ };
22
+ /**
23
+ * Everything the open workflow is: what the server says about it, the draft the person is changing, the compositions that
24
+ * can be used, what the draft is missing, where saving stands, and the small things the person is in the middle of
25
+ * (what is selected, which panel is open, a test visitor).
26
+ *
27
+ * The draft lives in two places on purpose. The canvas holds the blocks while they are dragged and drawn; this holds the
28
+ * same workflow as the engine's plain graph, which is what is validated, saved and published. They are kept the same in one
29
+ * direction each way: a change on the canvas arrives here through `acceptCanvasGraph`, and a change made in the side panel
30
+ * or the Add block menu goes through `commit`, which tells the canvas, whose own change then arrives here. Nothing else
31
+ * writes `graph`.
32
+ *
33
+ * What it never does: decide a rule of the workflow (the engine does), word a sentence (the catalog does), or draw.
34
+ */
35
+ export class WorkflowEditorState {
36
+ workflowId;
37
+ // ---- what the server says -----------------------------------------------------------------------------------
38
+ workflow = $state.raw(null);
39
+ loadState = $state('loading');
40
+ loadFailure = $state.raw(null);
41
+ /** The compositions the workflow uses, as the API describes them. `null`: not there for this person. */
42
+ options = $state.raw({});
43
+ optionsReady = $state(false);
44
+ // ---- the draft ------------------------------------------------------------------------------------------------
45
+ graph = $state.raw(makeEmptyGraph());
46
+ name = $state('');
47
+ timezone = $state('UTC');
48
+ /** Bumped when the whole draft is replaced from outside (a reload, a restore), so the canvas starts again from it. */
49
+ draftEpoch = $state(0);
50
+ // ---- saving ---------------------------------------------------------------------------------------------------
51
+ saveState = $state('saved');
52
+ saveFailure = $state.raw(null);
53
+ // ---- what the person is doing ------------------------------------------------------------------------------
54
+ tab = $state('editor');
55
+ panel = $state('selection');
56
+ selectedNodeIds = $state.raw([]);
57
+ selectedEdgeIds = $state.raw([]);
58
+ busy = $state(null);
59
+ notice = $state.raw(null);
60
+ /** What a refused publish said was wrong (the server checks again with what it knows), until the next change. */
61
+ refusedIssues = $state.raw([]);
62
+ /** What the touch of a screen allows: with no pointer to draw lines with, the canvas only shows. */
63
+ canvasTouchOnly = $state(false);
64
+ /** Set when a publish was tried while the draft has problems: the blocks with problems are outlined until it is published. */
65
+ problemsRevealed = $state(false);
66
+ // ---- versions ------------------------------------------------------------------------------------------------
67
+ versions = $state.raw(null);
68
+ versionsState = $state('idle');
69
+ /** A published version being looked at, read-only. */
70
+ viewing = $state.raw(null);
71
+ // ---- the test visitor ------------------------------------------------------------------------------------------
72
+ testRun = $state.raw(null);
73
+ // ---- who else is editing ---------------------------------------------------------------------------------------
74
+ /** Where the claim on editing stands (see `EditLeaseController`). Nothing is blocked while it is `off` or `editing`. */
75
+ presence = $state.raw(NO_PRESENCE);
76
+ // ---- a copy of what the person did ------------------------------------------------------------------------------
77
+ /** The workflow that holds the changes the person made while somebody else saved the draft first, once it was made. */
78
+ keptCopy = $state.raw(null);
79
+ /** The canvas, while one is on the screen (a pointer that changes when the canvas comes and goes). */
80
+ canvas = $state.raw(null);
81
+ revision = 0;
82
+ lastSaved = { graph: makeEmptyGraph(), name: '', timezone: 'UTC' };
83
+ saver;
84
+ api;
85
+ reportError;
86
+ leave;
87
+ openWorkflow;
88
+ random;
89
+ noticeMilliseconds;
90
+ noticeTimer = null;
91
+ loadController = null;
92
+ disposed = false;
93
+ presenceWanted;
94
+ presenceOptions;
95
+ leaseController = null;
96
+ /** The latest look at the server's draft, after editing came back (see `catchUpAfterPause`): a newer look and leaving the screen cancel it. */
97
+ catchUpController = null;
98
+ constructor(options) {
99
+ this.workflowId = options.workflowId;
100
+ this.api = options.api;
101
+ this.reportError = options.reportError;
102
+ this.leave = options.leave;
103
+ this.openWorkflow = options.openWorkflow;
104
+ this.random = options.random ?? Math.random;
105
+ this.noticeMilliseconds = options.noticeMilliseconds ?? DEFAULT_NOTICE_MILLISECONDS;
106
+ this.presenceWanted = options.presence === true;
107
+ this.presenceOptions = options.presenceOptions;
108
+ this.saver = createDraftSaver({
109
+ readSnapshot: () => this.readSaveSnapshot(),
110
+ send: (snapshot) => this.api.saveDraft(this.workflowId, this.toSaveInput(snapshot)),
111
+ onSaved: (snapshot, answer) => this.applySaved(snapshot, answer),
112
+ onStateChange: (state, error) => this.followSaveState(state, error),
113
+ isConflict: (error) => error instanceof WorkflowsApiError && error.revisionChanged,
114
+ delayMilliseconds: options.saveDelayMilliseconds
115
+ });
116
+ }
117
+ // =================================================================================================================
118
+ // Derived
119
+ // =================================================================================================================
120
+ /** What the engine finds missing in the draft, with what it knows about the compositions once that has arrived. */
121
+ issues = $derived.by(() => validate(this.graph, this.optionsReady ? toValidationContext(this.options) : undefined).issues);
122
+ /** The problems drawn on the canvas: those of the draft, so none while a published version is being looked at. */
123
+ issuesOnCanvas = $derived(groupIssues(this.viewing !== null ? [] : this.issues));
124
+ /** Errors stop a publish; warnings are advice. */
125
+ hasPublishBlockers = $derived(hasErrors(this.issues));
126
+ status = $derived(this.workflow?.status ?? 'draft');
127
+ /**
128
+ * Archived workflows are only looked at; so is a version, and so is a workflow somebody else is editing (the person
129
+ * chose to look only, or has not yet chosen to take over). The canvas on a touch screen only shows, see `canEditCanvas`.
130
+ */
131
+ isReadOnly = $derived(this.status === 'archived' || this.viewing !== null || this.presence.editsBlocked);
132
+ /**
133
+ * The workflow as a whole can be changed now (paused, archived, put back to a version, deleted): nothing else is
134
+ * running, and nobody else is editing it. Those are the changes that take what somebody is working on from under them.
135
+ */
136
+ canChangeWorkflow = $derived(this.busy === null && !this.presence.editsBlocked);
137
+ canEditCanvas = $derived(!this.isReadOnly && !this.canvasTouchOnly && this.tab === 'editor');
138
+ hasChangesToPublish = $derived.by(() => {
139
+ const workflow = this.workflow;
140
+ if (!workflow)
141
+ return false;
142
+ if (workflow.status === 'draft')
143
+ return true;
144
+ return workflow.unpublishedChanges || this.saveState !== 'saved';
145
+ });
146
+ /** Publish can be tried: there is something to publish and nothing else in the way. The problems found are told on the try. */
147
+ canTryPublish = $derived(this.loadState === 'ready' &&
148
+ !this.isReadOnly &&
149
+ this.busy === null &&
150
+ this.saveState !== 'conflict' &&
151
+ this.hasChangesToPublish &&
152
+ this.graph.nodes.length > 0);
153
+ /** Publish will go through, as far as this screen can tell (the server checks again). */
154
+ canPublish = $derived(this.canTryPublish && !this.hasPublishBlockers);
155
+ selectedNode = $derived.by(() => {
156
+ if (this.selectedNodeIds.length !== 1)
157
+ return null;
158
+ const id = this.selectedNodeIds[0];
159
+ return this.graph.nodes.find((node) => node.id === id) ?? null;
160
+ });
161
+ startNodeId = $derived(this.graph.nodes.find((node) => node.type === 'composition' && node.startsHere === true)?.id ??
162
+ null);
163
+ compositionIds = $derived(listCompositionIds(this.graph));
164
+ /** The ids of the blocks a test visitor has passed, and where they are now, for the marks on the canvas. */
165
+ // Plain Sets, made anew whenever the test run changes and never changed afterwards: that is what a derived value is
166
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
167
+ testPassedIds = $derived(new Set(this.testRun?.passedNodeIds ?? []));
168
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
169
+ testTakenEdgeIds = $derived(new Set(this.testRun?.takenEdgeIds ?? []));
170
+ // =================================================================================================================
171
+ // Opening, reloading and closing
172
+ // =================================================================================================================
173
+ /** Reads the workflow and the compositions it uses. Safe to call again: it starts over from the server. */
174
+ async load() {
175
+ this.loadController?.abort();
176
+ const controller = new AbortController();
177
+ this.loadController = controller;
178
+ this.loadState = 'loading';
179
+ this.loadFailure = null;
180
+ try {
181
+ const detail = await this.api.getWorkflow(this.workflowId, { signal: controller.signal });
182
+ const optionsById = await this.readCompositionOptions(listCompositionIds(detail.graph), controller.signal);
183
+ if (this.disposed || controller.signal.aborted)
184
+ return;
185
+ this.options = optionsById;
186
+ this.optionsReady = true;
187
+ this.adoptServerDraft(detail);
188
+ this.loadState = 'ready';
189
+ }
190
+ catch (error) {
191
+ if (isCancelled(error) || this.disposed)
192
+ return;
193
+ this.loadState = 'failed';
194
+ this.loadFailure = pickApiErrorMessage(error) ?? 'workflows.error.generic';
195
+ this.noteFailure('Reading the workflow failed', error);
196
+ }
197
+ }
198
+ /** Stops everything that is waiting: timers, saves, requests. Called when the editor is taken off the screen. */
199
+ dispose() {
200
+ this.disposed = true;
201
+ this.loadController?.abort();
202
+ this.catchUpController?.abort();
203
+ this.saver.dispose();
204
+ // The claim on editing is given up with the screen, so a teammate does not have to wait for it to run out.
205
+ this.leaseController?.dispose();
206
+ this.leaseController = null;
207
+ if (this.noticeTimer !== null)
208
+ clearTimeout(this.noticeTimer);
209
+ this.noticeTimer = null;
210
+ this.canvas = null;
211
+ }
212
+ /** Sends what is waiting before the screen is left. Resolves to where saving stands. */
213
+ flushSaves() {
214
+ return this.saver.flush();
215
+ }
216
+ /** Leaves the workflow: what is waiting is sent first, then everything that was running is stopped. */
217
+ async finish() {
218
+ const state = await this.saver.flush();
219
+ this.dispose();
220
+ return state;
221
+ }
222
+ /**
223
+ * Takes what the server holds as the draft, replacing what is on the screen. A published version that was being looked
224
+ * at is let go of: the canvas shows the draft now, and a banner that says otherwise would be wrong.
225
+ */
226
+ adoptServerDraft(detail) {
227
+ this.viewing = null;
228
+ this.workflow = detail;
229
+ this.revision = detail.revision;
230
+ const graph = ensureOneStart(detail.graph);
231
+ this.graph = graph;
232
+ this.name = detail.name;
233
+ this.timezone = detail.timezone;
234
+ this.lastSaved = { graph: detail.graph, name: detail.name, timezone: detail.timezone };
235
+ this.saver.reset();
236
+ this.saveFailure = null;
237
+ this.selectedNodeIds = [];
238
+ this.selectedEdgeIds = [];
239
+ this.refusedIssues = [];
240
+ this.problemsRevealed = false;
241
+ this.testRun = null;
242
+ this.draftEpoch += 1;
243
+ this.canvas?.loadGraph(graph);
244
+ }
245
+ /** Throws away what is unsaved on this screen and reads the draft again (after somebody else changed it). */
246
+ async reloadDraft() {
247
+ await this.load();
248
+ if (this.loadState === 'ready')
249
+ this.showNotice('info', 'workflows.editor.reloaded');
250
+ }
251
+ // =================================================================================================================
252
+ // Who else is editing
253
+ // =================================================================================================================
254
+ /**
255
+ * Begins asking to edit, and keeps this tab's claim while the screen is open. When a teammate holds it, editing is paused
256
+ * here (`presence.editsBlocked`) until the person takes over or the teammate leaves. Nothing happens unless the page
257
+ * asked for presence: a personal workspace has no teammate, and there nothing is asked of the API and nothing is blocked.
258
+ */
259
+ startPresence() {
260
+ if (!this.presenceWanted || this.disposed || this.leaseController !== null)
261
+ return;
262
+ const workflowId = this.workflowId;
263
+ const controller = new EditLeaseController({
264
+ port: {
265
+ acquire: (sessionId, options) => this.api.acquireEditLease(workflowId, sessionId, options),
266
+ takeOver: (sessionId, options) => this.api.takeOverEditLease(workflowId, sessionId, options),
267
+ peek: (options) => this.api.peekEditLease(workflowId, options),
268
+ release: (sessionId, options) => this.api.releaseEditLease(workflowId, sessionId, options)
269
+ },
270
+ logger: PRESENCE_LOGGER,
271
+ ...this.presenceOptions
272
+ });
273
+ this.leaseController = controller;
274
+ controller.subscribe((state) => this.followPresence(state));
275
+ controller.start();
276
+ }
277
+ /** The person chose to take over from the teammate who is editing: their editing pauses, and what they saved stays. */
278
+ takeOverEditing() {
279
+ this.leaseController?.takeOver();
280
+ }
281
+ /** The person chose to only look, for now. */
282
+ lookOnly() {
283
+ this.leaseController?.openReadOnly();
284
+ }
285
+ /** The person chose to begin editing, after looking (the teammate is gone). */
286
+ startEditing() {
287
+ this.leaseController?.startEditing();
288
+ }
289
+ followPresence(next) {
290
+ const wasPaused = this.presence.editsBlocked;
291
+ this.presence = next;
292
+ // Editing is back (the person took over, or the teammate left): see what the teammate saved while it was paused.
293
+ if (wasPaused && !next.editsBlocked)
294
+ void this.catchUpAfterPause();
295
+ }
296
+ /**
297
+ * Editing came back after a pause, and what the screen shows may be older than what the other editor saved meanwhile.
298
+ * When everything on the screen is saved, the screen takes the server's draft if that is newer, so that the first thing
299
+ * the person does is not refused as a conflict. What is not saved is never replaced: the conflict banner decides that.
300
+ */
301
+ async catchUpAfterPause() {
302
+ // Not before the draft was read the first time: that read is the latest one. (Nothing gets here after the screen is
303
+ // gone: leaving it silences the claim's listeners.)
304
+ if (this.loadState !== 'ready')
305
+ return;
306
+ this.catchUpController?.abort();
307
+ const controller = new AbortController();
308
+ this.catchUpController = controller;
309
+ try {
310
+ const detail = await this.api.getWorkflow(this.workflowId, { signal: controller.signal });
311
+ // Leaving the screen, and a newer look, both abort this one: its answer is then of no use.
312
+ if (controller.signal.aborted)
313
+ return;
314
+ // A draft that is not newer is what the screen already has (or older than what it saved itself since).
315
+ if (detail.revision <= this.revision)
316
+ return;
317
+ await this.ensureOptionsFor(detail.graph);
318
+ if (controller.signal.aborted)
319
+ return;
320
+ // Something was typed while the look was on its way: it is not saved yet, and not for this to throw away.
321
+ if (this.saveState !== 'saved')
322
+ return;
323
+ this.adoptServerDraft(detail);
324
+ }
325
+ catch (error) {
326
+ // A look that was cancelled is no failure (`noteFailure` knows that), and nothing is said once the screen is gone.
327
+ if (this.disposed)
328
+ return;
329
+ this.noteFailure('Reading the latest draft failed', error);
330
+ }
331
+ }
332
+ // =================================================================================================================
333
+ // The compositions
334
+ // =================================================================================================================
335
+ /** Reads what the API says about these compositions; the ones it does not know come back as `null`. */
336
+ async readCompositionOptions(ids, signal) {
337
+ const byId = Object.create(null);
338
+ for (const id of ids)
339
+ byId[id] = null;
340
+ if (ids.length === 0)
341
+ return byId;
342
+ const answer = await this.api.listCompositionOptions({ ids, limit: Math.max(ids.length, 1) }, { signal });
343
+ for (const option of answer.items)
344
+ byId[option.id] = option;
345
+ return byId;
346
+ }
347
+ /** Remembers compositions the person picked from the list, so the blocks that show them have their names at once. */
348
+ rememberCompositions(items) {
349
+ if (items.length === 0)
350
+ return;
351
+ const next = Object.assign(Object.create(null), this.options);
352
+ for (const item of items)
353
+ next[item.id] = item;
354
+ this.options = next;
355
+ }
356
+ /** Asks the API for compositions that the draft uses and this screen has not read yet (after a restore, say). */
357
+ async refreshMissingCompositions() {
358
+ const missing = this.compositionIds.filter((id) => !(id in this.options));
359
+ if (missing.length === 0)
360
+ return;
361
+ try {
362
+ const readBack = await this.readCompositionOptions(missing);
363
+ this.options = Object.assign(Object.create(null), this.options, readBack);
364
+ }
365
+ catch (error) {
366
+ this.noteFailure('Reading the compositions failed', error);
367
+ }
368
+ }
369
+ // =================================================================================================================
370
+ // Changing the draft
371
+ // =================================================================================================================
372
+ /**
373
+ * A change that happened on the canvas (a block dragged, a line drawn, a block deleted): the draft follows it. Answers
374
+ * the draft as it is kept, which can differ from what the canvas held (the first composition left became the start), so
375
+ * that the canvas can take it over.
376
+ */
377
+ acceptCanvasGraph(fromCanvas) {
378
+ if (this.disposed || this.viewing !== null)
379
+ return fromCanvas;
380
+ const next = ensureOneStart(fromCanvas);
381
+ if (!isSameGraph(next, this.graph)) {
382
+ this.graph = next;
383
+ this.afterDraftChanged();
384
+ void this.refreshMissingCompositions();
385
+ }
386
+ return next;
387
+ }
388
+ /**
389
+ * A change made from the side panel or a menu. The canvas applies it (so it can be undone) and tells this state back,
390
+ * the same way a drag does. Without a canvas on the screen the draft changes directly.
391
+ */
392
+ commit(next) {
393
+ if (this.isReadOnly || this.disposed)
394
+ return;
395
+ // A rule that was removed takes its line with it, so no line is left that starts from nothing.
396
+ const normalized = ensureOneStart(dropStrandedConnections(next));
397
+ if (isSameGraph(normalized, this.graph))
398
+ return;
399
+ if (this.canvas)
400
+ this.canvas.applyGraph(normalized);
401
+ else
402
+ this.acceptCanvasGraph(normalized);
403
+ }
404
+ /** What follows any change of the draft: a published check is stale, a test visitor may be somewhere that is gone, saving is due. */
405
+ afterDraftChanged() {
406
+ this.refusedIssues = [];
407
+ if (this.testRun !== null)
408
+ this.testRun = null;
409
+ this.saver.markChanged();
410
+ }
411
+ /** Replaces one block (the side panel changed it). */
412
+ replaceBlock(node) {
413
+ this.commit({
414
+ ...this.graph,
415
+ nodes: this.graph.nodes.map((candidate) => (candidate.id === node.id ? node : candidate))
416
+ });
417
+ }
418
+ /** Draws a connection from a place of a block to another block, or takes it away (`targetNodeId` null). One line per place. */
419
+ connect(sourceNodeId, sourcePort, targetNodeId) {
420
+ const keptEdges = this.graph.edges.filter((edge) => !(edge.source === sourceNodeId && edge.sourcePort === sourcePort));
421
+ const withoutOld = { ...this.graph, edges: keptEdges };
422
+ if (targetNodeId === null) {
423
+ this.commit(withoutOld);
424
+ return;
425
+ }
426
+ // A local lookup for choosing an unused id, not state
427
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
428
+ const taken = new Set([
429
+ ...this.graph.nodes.map((node) => node.id),
430
+ ...this.graph.edges.map((edge) => edge.id)
431
+ ]);
432
+ let edgeId = `e_${Math.floor(this.random() * 36 ** 8)
433
+ .toString(36)
434
+ .padStart(8, '0')}`;
435
+ while (taken.has(edgeId))
436
+ edgeId = `${edgeId}x`;
437
+ const edge = {
438
+ id: edgeId,
439
+ source: sourceNodeId,
440
+ sourcePort,
441
+ target: targetNodeId
442
+ };
443
+ this.commit({ ...withoutOld, edges: [...keptEdges, edge] });
444
+ }
445
+ /** Adds a block after the selected one (or where there is room) and selects it. Resolves to why nothing was added, if so. */
446
+ addBlock(request) {
447
+ if (this.isReadOnly)
448
+ return null;
449
+ const anchorId = this.selectedNodeIds.length === 1 ? (this.selectedNodeIds[0] ?? null) : null;
450
+ const plan = planAddBlock(this.graph, request, anchorId, this.random);
451
+ if (plan.refused || !plan.node)
452
+ return plan.refused;
453
+ const nodes = [...this.graph.nodes, plan.node];
454
+ const edges = plan.edge ? [...this.graph.edges, plan.edge] : this.graph.edges;
455
+ this.commit({ ...this.graph, nodes, edges });
456
+ this.canvas?.selectNodes([plan.node.id]);
457
+ this.panel = 'selection';
458
+ return null;
459
+ }
460
+ /** Takes the selected blocks and lines off the draft. */
461
+ removeSelected() {
462
+ let next = this.graph;
463
+ if (this.selectedNodeIds.length > 0)
464
+ next = removeBlocks(next, this.selectedNodeIds);
465
+ if (this.selectedEdgeIds.length > 0)
466
+ next = removeConnections(next, this.selectedEdgeIds);
467
+ this.commit(next);
468
+ this.selectedNodeIds = [];
469
+ this.selectedEdgeIds = [];
470
+ }
471
+ removeBlock(nodeId) {
472
+ this.commit(removeBlocks(this.graph, [nodeId]));
473
+ this.selectedNodeIds = this.selectedNodeIds.filter((id) => id !== nodeId);
474
+ }
475
+ /** Makes a composition the first one visitors see. */
476
+ makeStart(nodeId) {
477
+ this.commit(setStartBlock(this.graph, nodeId));
478
+ }
479
+ /** The selection of the canvas, as the canvas reports it. */
480
+ followSelection(nodeIds, edgeIds) {
481
+ this.selectedNodeIds = nodeIds;
482
+ this.selectedEdgeIds = edgeIds;
483
+ if (nodeIds.length > 0 || edgeIds.length > 0) {
484
+ if (this.panel === 'history' && this.viewing === null)
485
+ this.panel = 'selection';
486
+ }
487
+ }
488
+ setName(name) {
489
+ if (this.isReadOnly)
490
+ return;
491
+ const trimmed = name.trim();
492
+ if (trimmed === '')
493
+ return;
494
+ if (trimmed === this.name)
495
+ return;
496
+ this.name = trimmed;
497
+ this.saver.markChanged();
498
+ }
499
+ setTimezone(timezone) {
500
+ if (this.isReadOnly || timezone === this.timezone)
501
+ return;
502
+ this.timezone = timezone;
503
+ this.refusedIssues = [];
504
+ this.saver.markChanged();
505
+ }
506
+ // =================================================================================================================
507
+ // Saving
508
+ // =================================================================================================================
509
+ /** What would go to the server now, or `null` when the server already has it. */
510
+ readSaveSnapshot() {
511
+ const snapshot = { revision: this.revision, next: { ...this.lastSaved } };
512
+ let changed = false;
513
+ if (!isSameGraph(this.graph, this.lastSaved.graph)) {
514
+ snapshot.graph = this.graph;
515
+ snapshot.next.graph = this.graph;
516
+ changed = true;
517
+ }
518
+ if (this.name !== this.lastSaved.name) {
519
+ snapshot.name = this.name;
520
+ snapshot.next.name = this.name;
521
+ changed = true;
522
+ }
523
+ if (this.timezone !== this.lastSaved.timezone) {
524
+ snapshot.timezone = this.timezone;
525
+ snapshot.next.timezone = this.timezone;
526
+ changed = true;
527
+ }
528
+ return changed ? snapshot : null;
529
+ }
530
+ toSaveInput(snapshot) {
531
+ const input = {
532
+ revision: snapshot.revision
533
+ };
534
+ if (snapshot.name !== undefined)
535
+ input.name = snapshot.name;
536
+ if (snapshot.timezone !== undefined)
537
+ input.timezone = snapshot.timezone;
538
+ if (snapshot.graph !== undefined)
539
+ input.graph = snapshot.graph;
540
+ return input;
541
+ }
542
+ applySaved(snapshot, answer) {
543
+ this.revision = answer.revision;
544
+ this.lastSaved = snapshot.next;
545
+ if (this.workflow)
546
+ this.workflow = { ...this.workflow, ...answer };
547
+ }
548
+ followSaveState(state, error) {
549
+ this.saveState = state;
550
+ if (state === 'failed' || state === 'conflict') {
551
+ this.saveFailure = pickApiErrorMessage(error) ?? 'workflows.error.generic';
552
+ this.noteFailure('Saving the draft failed', error);
553
+ }
554
+ else {
555
+ this.saveFailure = null;
556
+ }
557
+ // A copy was kept for one conflict: once it is over, a banner must not go on telling about it.
558
+ if (state !== 'conflict')
559
+ this.keptCopy = null;
560
+ }
561
+ /** Tries a failed save again (the person pressed "Try again"). */
562
+ retrySave() {
563
+ void this.saver.flush();
564
+ }
565
+ /**
566
+ * Somebody else saved the draft first, so what this person changed was not saved (`saveState` is `conflict`). Keeps what
567
+ * is on this screen as a new workflow, so that loading the latest version does not cost the person their work. The words
568
+ * of the copy's name are the screen's (`wording` puts them around the workflow's name, in the person's language).
569
+ * Nothing is done to the workflow being edited. Resolves to whether the copy was made; `keptCopy` says which.
570
+ */
571
+ async keepCopyOfChanges(wording) {
572
+ // While something else runs, `runBusy` below refuses (a second copy is not started).
573
+ if (this.disposed || this.saveState !== 'conflict')
574
+ return false;
575
+ const copy = await this.runBusy('keepingCopy', () => keepCopyOfDraft(this.api, {
576
+ name: nameForCopy(this.name, wording),
577
+ timezone: this.timezone,
578
+ graph: this.graph
579
+ }), 'Keeping a copy of the changes failed');
580
+ if (!copy)
581
+ return false;
582
+ this.keptCopy = copy;
583
+ return true;
584
+ }
585
+ /** The person chose to open the copy they kept: the page follows, as it does for a duplicate. Nothing without a copy. */
586
+ openKeptCopy() {
587
+ const copy = this.keptCopy;
588
+ if (copy)
589
+ this.openWorkflow(copy.id);
590
+ }
591
+ // =================================================================================================================
592
+ // Publishing, discarding, restoring
593
+ // =================================================================================================================
594
+ /** Runs one thing the person waits for. Nothing else that changes the workflow runs meanwhile. */
595
+ async runBusy(kind, action, whatFailed) {
596
+ if (this.busy !== null)
597
+ return undefined;
598
+ this.busy = kind;
599
+ try {
600
+ return await action();
601
+ }
602
+ catch (error) {
603
+ if (isCancelled(error))
604
+ return undefined;
605
+ this.noteFailure(whatFailed, error);
606
+ this.showFailureNotice(error);
607
+ return undefined;
608
+ }
609
+ finally {
610
+ this.busy = null;
611
+ }
612
+ }
613
+ /** Makes the draft the next version visitors get. */
614
+ async publish() {
615
+ if (!this.canTryPublish)
616
+ return false;
617
+ if (this.hasPublishBlockers) {
618
+ // The person pressed Publish on a draft that cannot be published: show them where it goes wrong, and publish nothing.
619
+ this.problemsRevealed = true;
620
+ this.panel = 'selection';
621
+ this.canvas?.selectNodes([]);
622
+ this.showNotice('problem', 'workflows.editor.fixProblems', {
623
+ count: this.issues.filter((issue) => issue.severity === 'error').length
624
+ });
625
+ return false;
626
+ }
627
+ const result = await this.runBusy('publishing', async () => {
628
+ const state = await this.saver.flush();
629
+ if (state !== 'saved') {
630
+ this.showNotice('problem', state === 'conflict' ? 'workflows.error.revisionChanged' : 'workflows.editor.saveFirst');
631
+ return null;
632
+ }
633
+ return this.api.publishWorkflow(this.workflowId, this.revision);
634
+ }, 'Publishing failed');
635
+ if (!result)
636
+ return false;
637
+ this.workflow = result.workflow;
638
+ this.revision = result.workflow.revision;
639
+ this.versions = null;
640
+ this.problemsRevealed = false;
641
+ this.refusedIssues = result.warnings;
642
+ this.showNotice('info', 'workflows.editor.published', { number: result.version.versionNumber });
643
+ return true;
644
+ }
645
+ /** Puts the draft back to what is live. */
646
+ async discardChanges() {
647
+ if (this.isReadOnly || this.busy !== null)
648
+ return false;
649
+ this.saver.reset();
650
+ const detail = await this.runBusy('discarding', () => this.api.discardChanges(this.workflowId, this.revision), 'Discarding changes failed');
651
+ if (!detail)
652
+ return false;
653
+ this.adoptServerDraft(detail);
654
+ this.showNotice('info', 'workflows.editor.discarded');
655
+ return true;
656
+ }
657
+ // ---- versions ---------------------------------------------------------------------------------------------------
658
+ async loadVersions() {
659
+ this.versionsState = 'loading';
660
+ try {
661
+ this.versions = await this.api.listVersions(this.workflowId);
662
+ this.versionsState = 'idle';
663
+ }
664
+ catch (error) {
665
+ if (isCancelled(error))
666
+ return;
667
+ this.versionsState = 'failed';
668
+ this.noteFailure('Reading the versions failed', error);
669
+ }
670
+ }
671
+ openHistory() {
672
+ this.panel = 'history';
673
+ if (this.versions === null)
674
+ void this.loadVersions();
675
+ }
676
+ closeHistory() {
677
+ if (this.viewing !== null)
678
+ this.leaveVersion();
679
+ this.panel = 'selection';
680
+ }
681
+ /** Shows a published version read-only on the canvas. */
682
+ async viewVersion(versionId) {
683
+ if (this.busy !== null)
684
+ return;
685
+ try {
686
+ const detail = await this.api.getVersion(this.workflowId, versionId);
687
+ await this.saver.flush();
688
+ this.viewing = detail;
689
+ this.selectedNodeIds = [];
690
+ this.selectedEdgeIds = [];
691
+ this.testRun = null;
692
+ await this.ensureOptionsFor(detail.graph);
693
+ this.draftEpoch += 1;
694
+ this.canvas?.loadGraph(detail.graph);
695
+ }
696
+ catch (error) {
697
+ if (isCancelled(error))
698
+ return;
699
+ this.noteFailure('Reading the version failed', error);
700
+ this.showFailureNotice(error);
701
+ }
702
+ }
703
+ /** Goes back from a version to the draft. */
704
+ leaveVersion() {
705
+ if (this.viewing === null)
706
+ return;
707
+ this.viewing = null;
708
+ this.draftEpoch += 1;
709
+ this.canvas?.loadGraph(this.graph);
710
+ }
711
+ /** Copies the version into the draft (the draft it replaces stays recoverable only through undo, so the screen asks first). */
712
+ async restoreViewedVersion() {
713
+ const viewing = this.viewing;
714
+ if (!viewing || !this.canChangeWorkflow)
715
+ return false;
716
+ const detail = await this.runBusy('restoring', () => this.api.restoreVersion(this.workflowId, viewing.id, this.revision), 'Restoring a version failed');
717
+ if (!detail)
718
+ return false;
719
+ this.viewing = null;
720
+ await this.ensureOptionsFor(detail.graph);
721
+ this.adoptServerDraft(detail);
722
+ this.panel = 'selection';
723
+ this.showNotice('info', 'workflows.editor.restored', { number: viewing.versionNumber });
724
+ return true;
725
+ }
726
+ /** Reads what the API says about the compositions of a graph (a version, say) that this screen has not read yet. */
727
+ async ensureOptionsFor(graph) {
728
+ const missing = listCompositionIds(graph).filter((id) => !(id in this.options));
729
+ if (missing.length === 0)
730
+ return;
731
+ try {
732
+ this.options = Object.assign(Object.create(null), this.options, await this.readCompositionOptions(missing));
733
+ }
734
+ catch (error) {
735
+ this.noteFailure('Reading the compositions failed', error);
736
+ }
737
+ }
738
+ // ---- states of the workflow -------------------------------------------------------------------------------
739
+ async changeState(action) {
740
+ if (!this.canChangeWorkflow)
741
+ return false;
742
+ await this.saver.flush();
743
+ const item = await this.runBusy('changingState', () => this.api.changeState(this.workflowId, action), 'Changing the state failed');
744
+ if (!item)
745
+ return false;
746
+ if (this.workflow)
747
+ this.workflow = { ...this.workflow, ...item };
748
+ this.revision = item.revision;
749
+ this.showNotice('info', STATE_NOTICE_KEYS[action]);
750
+ return true;
751
+ }
752
+ async duplicate() {
753
+ if (this.busy !== null)
754
+ return;
755
+ await this.saver.flush();
756
+ const copy = await this.runBusy('duplicating', () => this.api.duplicateWorkflow(this.workflowId), 'Duplicating failed');
757
+ if (copy)
758
+ this.openWorkflow(copy.id);
759
+ }
760
+ async deleteWorkflow() {
761
+ if (!this.canChangeWorkflow)
762
+ return;
763
+ this.saver.dispose();
764
+ const done = await this.runBusy('deleting', async () => {
765
+ await this.api.deleteWorkflow(this.workflowId);
766
+ return true;
767
+ }, 'Deleting failed');
768
+ if (done)
769
+ this.leave();
770
+ }
771
+ // =================================================================================================================
772
+ // The test visitor
773
+ // =================================================================================================================
774
+ openTestRun() {
775
+ this.panel = 'test';
776
+ this.testRun = startTestRun(this.graph);
777
+ }
778
+ closeTestRun() {
779
+ this.panel = 'selection';
780
+ this.testRun = null;
781
+ }
782
+ restartTestRun() {
783
+ this.testRun = startTestRun(this.graph);
784
+ }
785
+ /** The test visitor does one thing: a trigger of the composition they are on fires, carrying these values. */
786
+ fireTrigger(triggerId, values) {
787
+ const state = this.testRun;
788
+ if (!state)
789
+ return;
790
+ const trigger = this.graph.nodes.find((node) => node.type === 'trigger' && node.id === triggerId);
791
+ if (!trigger)
792
+ return;
793
+ this.testRun = fireTestTrigger(this.graph, state, trigger, values);
794
+ }
795
+ // =================================================================================================================
796
+ // Saying what happened
797
+ // =================================================================================================================
798
+ showNotice(tone, messageKey, values) {
799
+ if (this.noticeTimer !== null)
800
+ clearTimeout(this.noticeTimer);
801
+ this.noticeTimer = null;
802
+ this.notice = { tone, messageKey, values };
803
+ if (tone === 'info') {
804
+ this.noticeTimer = setTimeout(() => {
805
+ this.notice = null;
806
+ this.noticeTimer = null;
807
+ }, this.noticeMilliseconds);
808
+ }
809
+ }
810
+ dismissNotice() {
811
+ if (this.noticeTimer !== null)
812
+ clearTimeout(this.noticeTimer);
813
+ this.noticeTimer = null;
814
+ this.notice = null;
815
+ }
816
+ showFailureNotice(error) {
817
+ const key = pickApiErrorMessage(error);
818
+ if (key === null)
819
+ return;
820
+ if (error instanceof WorkflowsApiError && error.issues.length > 0)
821
+ this.refusedIssues = error.issues;
822
+ this.showNotice('problem', key);
823
+ }
824
+ /** Says a failure once in the console and tells the page. */
825
+ noteFailure(what, error) {
826
+ if (isCancelled(error))
827
+ return;
828
+ const detail = error instanceof Error ? error.message : String(error);
829
+ workflowsError(`${what}: ${detail}`, error);
830
+ const sessionEnded = error instanceof WorkflowsApiError && error.sessionEnded;
831
+ try {
832
+ this.reportError({
833
+ message: `${what}: ${detail}`,
834
+ code: sessionEnded ? 'SESSION_ENDED' : 'REQUEST_FAILED',
835
+ fatal: false
836
+ });
837
+ }
838
+ catch (handlerError) {
839
+ workflowsWarn('The onError handler of the page threw.', handlerError);
840
+ }
841
+ }
842
+ }
843
+ const STATE_NOTICE_KEYS = {
844
+ pause: 'workflows.editor.paused',
845
+ resume: 'workflows.editor.resumed',
846
+ archive: 'workflows.editor.archived',
847
+ unarchive: 'workflows.editor.unarchived'
848
+ };
849
+ // ---------------------------------------------------------------------------------------------------------------------
850
+ // Sharing the editor with the parts of the screen
851
+ // ---------------------------------------------------------------------------------------------------------------------
852
+ const EDITOR_STATE_KEY = Symbol('workflows-editor-state');
853
+ export function provideEditorState(state) {
854
+ return setContext(EDITOR_STATE_KEY, state);
855
+ }
856
+ /** Called by a part of the editor while it is created. The editor is always there for those parts: this throws if it is not. */
857
+ export function useEditorState() {
858
+ const state = getContext(EDITOR_STATE_KEY);
859
+ if (!state)
860
+ throw new Error('[Workflows] A part of the editor was drawn outside the editor.');
861
+ return state;
862
+ }