@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
@@ -1,16 +1,21 @@
1
1
  import { getContext, setContext } from 'svelte';
2
- import { hasErrors, validate } from '@widgetic/workflows-engine';
2
+ import { MAX_BLOCKS, MAX_EDGES, hasErrors } from '@widgetic/workflows-engine';
3
3
  import { WorkflowsApiError, isCancelled } from '../api/workflowsApi.js';
4
4
  import { workflowsError, workflowsWarn } from '../utils/logger.js';
5
5
  import { pickApiErrorMessage } from './apiErrorText.js';
6
+ import { organiseGraph } from './autoLayout.js';
6
7
  import { createDraftSaver } from './autosave.js';
8
+ import { blockClipboard } from './blockClipboard.svelte.js';
9
+ import { copyBlocks, duplicateBlocks, pasteBlocks } from './blockCopy.js';
7
10
  import { createDraftJournal } from '../drafts/draftJournal.js';
8
11
  import { WORKFLOW_DRAFT_NAMESPACE, applyDraftRestoreRule, draftPayloadFromServerCopy, payloadsEqual, serverBaseRevision, KEEPALIVE_SAVE_MAX_BYTES, validateWorkflowEditorViewState, viewStateStorageKey, parseViewStateEntry, serializeViewState } from '../drafts/workflowDraft.js';
9
12
  import { toValidationContext } from './capabilityModel.js';
10
13
  import { EditLeaseController, NO_PRESENCE } from './editLeaseController.js';
11
- import { dropStrandedConnections, ensureOneStart, isSameGraph, listCompositionIds, makeEmptyGraph, planAddBlock, removeBlocks, removeConnections, setStartBlock } from './graphModel.js';
14
+ import { dropStrandedConnections, ensureOneStart, isSameGraph, listCompositionIds, makeEmptyGraph, planAddBlock, removeAllConnections, removeBlocks, removeConnections, setStartBlock } from './graphModel.js';
12
15
  import { groupIssues } from './flowAdapter.js';
16
+ import { findGraphIssues } from './graphIssues.js';
13
17
  import { keepCopyOfDraft, nameForCopy } from './keepCopy.js';
18
+ import { createStaleGuard } from './staleGuard.js';
14
19
  import { fireTestTrigger, startTestRun } from './testRun.js';
15
20
  const DEFAULT_NOTICE_MILLISECONDS = 5000;
16
21
  /**
@@ -21,6 +26,10 @@ const PRESENCE_LOGGER = {
21
26
  warn: (message, detail) => workflowsWarn(String(message), detail),
22
27
  error: (message, detail) => workflowsError(String(message), detail)
23
28
  };
29
+ /** Where the guard that brings a tab up to date writes its notes: the console of the package, a line once (`workflowsWarn`). */
30
+ function logStaleGuard(event, detail) {
31
+ workflowsWarn(event, detail);
32
+ }
24
33
  /**
25
34
  * Everything the open workflow is: what the server says about it, the draft the person is changing, the compositions that
26
35
  * can be used, what the draft is missing, where saving stands, and the small things the person is in the middle of
@@ -86,6 +95,12 @@ export class WorkflowEditorState {
86
95
  // ---- who else is editing ---------------------------------------------------------------------------------------
87
96
  /** Where the claim on editing stands (see `EditLeaseController`). Nothing is blocked while it is `off` or `editing`. */
88
97
  presence = $state.raw(NO_PRESENCE);
98
+ // ---- a tab that comes back after the draft changed somewhere else -----------------------------------------------------
99
+ /**
100
+ * What the guard of `startStaleGuard` is doing. `updating` is the overlay: the screen is taking a newer draft and nothing
101
+ * on it can be changed until that is done. `conflict` waits for the person (the conflict line is on the screen).
102
+ */
103
+ staleGuardPhase = $state('idle');
89
104
  // ---- a copy of what the person did ------------------------------------------------------------------------------
90
105
  /** The workflow that holds the changes the person made while somebody else saved the draft first, once it was made. */
91
106
  keptCopy = $state.raw(null);
@@ -106,8 +121,16 @@ export class WorkflowEditorState {
106
121
  presenceWanted;
107
122
  presenceOptions;
108
123
  leaseController = null;
109
- /** The latest look at the server's draft, after editing came back (see `catchUpAfterPause`): a newer look and leaving the screen cancel it. */
124
+ /**
125
+ * The latest look at the server's draft, after editing came back or the assistant saved a change (see
126
+ * `takeNewerServerDraft`): a newer look and leaving the screen cancel it.
127
+ */
110
128
  catchUpController = null;
129
+ staleGuardOptions;
130
+ /** Asks the server whether the draft on the screen is still the latest, whenever the tab comes back (see `startStaleGuard`). */
131
+ staleGuard = null;
132
+ /** True while the canvas is being given a draft the server holds, so what it reads back is not taken as the person's change. */
133
+ applyingSavedDraft = false;
111
134
  draftJournal;
112
135
  onDraftRestored;
113
136
  draftBaseRevision = null;
@@ -126,6 +149,7 @@ export class WorkflowEditorState {
126
149
  this.noticeMilliseconds = options.noticeMilliseconds ?? DEFAULT_NOTICE_MILLISECONDS;
127
150
  this.presenceWanted = options.presence === true;
128
151
  this.presenceOptions = options.presenceOptions;
152
+ this.staleGuardOptions = options.staleGuardOptions;
129
153
  this.onDraftRestored = options.onDraftRestored;
130
154
  this.now = options.now ?? (() => Date.now());
131
155
  this.viewStateStorage =
@@ -159,7 +183,7 @@ export class WorkflowEditorState {
159
183
  // Derived
160
184
  // =================================================================================================================
161
185
  /** What the engine finds missing in the draft, with what it knows about the compositions once that has arrived. */
162
- issues = $derived.by(() => validate(this.graph, this.optionsReady ? toValidationContext(this.options) : undefined).issues);
186
+ issues = $derived.by(() => findGraphIssues(this.graph, this.optionsReady ? toValidationContext(this.options) : undefined));
163
187
  /** The problems drawn on the canvas: those of the draft, so none while a published version is being looked at. */
164
188
  issuesOnCanvas = $derived(groupIssues(this.viewing !== null ? [] : this.issues));
165
189
  /** Errors stop a publish; warnings are advice. */
@@ -194,14 +218,20 @@ export class WorkflowEditorState {
194
218
  status = $derived(this.workflow?.status ?? 'draft');
195
219
  /**
196
220
  * Archived workflows are only looked at; so is a version, and so is a workflow somebody else is editing (the person
197
- * chose to look only, or has not yet chosen to take over). The canvas on a touch screen only shows, see `canEditCanvas`.
221
+ * chose to look only, or has not yet chosen to take over). So is the draft while the screen takes a newer one (the
222
+ * overlay of `staleGuardPhase`): a copy that is out of date is never changed. The canvas on a touch screen only shows,
223
+ * see `canEditCanvas`.
198
224
  */
199
- isReadOnly = $derived(this.status === 'archived' || this.viewing !== null || this.presence.editsBlocked);
225
+ isReadOnly = $derived(this.status === 'archived' ||
226
+ this.viewing !== null ||
227
+ this.presence.editsBlocked ||
228
+ this.staleGuardPhase === 'updating');
200
229
  /**
201
230
  * The workflow as a whole can be changed now (paused, archived, put back to a version, deleted): nothing else is
202
- * running, and nobody else is editing it. Those are the changes that take what somebody is working on from under them.
231
+ * running, nobody else is editing it, and the screen is not taking a newer draft. Those are the changes that take what
232
+ * somebody is working on from under them.
203
233
  */
204
- canChangeWorkflow = $derived(this.busy === null && !this.presence.editsBlocked);
234
+ canChangeWorkflow = $derived(this.busy === null && !this.presence.editsBlocked && this.staleGuardPhase !== 'updating');
205
235
  canEditCanvas = $derived(!this.isReadOnly && !this.canvasTouchOnly && this.tab === 'editor');
206
236
  hasChangesToPublish = $derived.by(() => {
207
237
  const workflow = this.workflow;
@@ -270,6 +300,9 @@ export class WorkflowEditorState {
270
300
  this.disposed = true;
271
301
  this.loadController?.abort();
272
302
  this.catchUpController?.abort();
303
+ // The tab that is closed asks nothing more, and a question that is out is let go of
304
+ this.staleGuard?.dispose();
305
+ this.staleGuard = null;
273
306
  this.saver.dispose();
274
307
  this.leaveFlushDisposer?.();
275
308
  this.leaveFlushDisposer = null;
@@ -296,9 +329,11 @@ export class WorkflowEditorState {
296
329
  }
297
330
  /**
298
331
  * Takes what the server holds as the draft, replacing what is on the screen. A published version that was being looked
299
- * at is let go of: the canvas shows the draft now, and a banner that says otherwise would be wrong.
332
+ * at is let go of: the canvas shows the draft now, and a banner that says otherwise would be wrong. A conflict the
333
+ * stale-tab guard raised is over with it (the screen is the latest again). `keepViewport`: the canvas stays where it was
334
+ * (a tab that was brought up to date), instead of fitting the blocks in view as a reload does.
300
335
  */
301
- adoptServerDraft(detail) {
336
+ adoptServerDraft(detail, options = {}) {
302
337
  this.viewing = null;
303
338
  this.workflow = detail;
304
339
  this.revision = detail.revision;
@@ -318,7 +353,8 @@ export class WorkflowEditorState {
318
353
  this.testRun = null;
319
354
  this.expandedRuleId = null;
320
355
  this.draftEpoch += 1;
321
- this.canvas?.loadGraph(graph);
356
+ this.canvas?.loadGraph(graph, options.keepViewport === true ? { keepViewport: true } : undefined);
357
+ this.staleGuard?.settleConflict();
322
358
  }
323
359
  /** Throws away what is unsaved on this screen and reads the draft again (after somebody else changed it). */
324
360
  async reloadDraft() {
@@ -331,23 +367,41 @@ export class WorkflowEditorState {
331
367
  if (workflowId !== this.workflowId)
332
368
  this.openWorkflow(workflowId);
333
369
  }
334
- /** After the workflows assistant saved remotely: reload when clean, otherwise use the existing conflict banner. */
335
- async respondToAssistantWorkflowUpdate() {
370
+ /**
371
+ * The workflows assistant saved a change to this workflow (a `workflow_updated` event while its chat works, or the end of a
372
+ * plan the person approved): shows it on the spot. When everything on the screen is saved, the draft the server holds is read
373
+ * and drawn without a loading screen: only what differs changes on the canvas, so the blocks that stay keep their place, the
374
+ * selection and the view, and the change is one step that Undo takes back. When something the person changed is not saved
375
+ * yet nothing is replaced: the conflict banner decides. `savedRevision` is the revision the assistant's save made, when it is
376
+ * known: a screen already at it has nothing to read.
377
+ */
378
+ async respondToAssistantWorkflowUpdate(savedRevision) {
336
379
  if (this.disposed || this.loadState !== 'ready')
337
380
  return;
338
381
  const { decideAssistantRemoteChangeAction } = await import('../assistant/assistantRemoteChange.js');
382
+ if (this.disposed)
383
+ return;
339
384
  const action = decideAssistantRemoteChangeAction(this.saveState);
340
385
  if (action === 'noop')
341
386
  return;
342
387
  if (action === 'showConflict') {
343
- this.followSaveState('conflict', new WorkflowsApiError('This workflow was changed somewhere else.', {
344
- status: 409,
345
- code: 'BUSINESS_STATE_CONFLICT',
346
- details: { reason: 'revision_changed' },
347
- }));
388
+ this.raiseRevisionConflict();
348
389
  return;
349
390
  }
350
- await this.reloadDraft();
391
+ if (typeof savedRevision === 'number' && savedRevision <= this.revision)
392
+ return;
393
+ await this.takeNewerServerDraft('inPlace', 'Showing the change the assistant saved failed');
394
+ }
395
+ /**
396
+ * The draft on the server moved on while this screen holds changes of its own that were not saved: puts the existing
397
+ * conflict line on the screen (`saveState` is `conflict`), which offers to keep the changes as a copy or to load the latest.
398
+ */
399
+ raiseRevisionConflict() {
400
+ this.followSaveState('conflict', new WorkflowsApiError('This workflow was changed somewhere else.', {
401
+ status: 409,
402
+ code: 'BUSINESS_STATE_CONFLICT',
403
+ details: { reason: 'revision_changed' }
404
+ }));
351
405
  }
352
406
  // =================================================================================================================
353
407
  // Who else is editing
@@ -400,6 +454,14 @@ export class WorkflowEditorState {
400
454
  * the person does is not refused as a conflict. What is not saved is never replaced: the conflict banner decides that.
401
455
  */
402
456
  async catchUpAfterPause() {
457
+ await this.takeNewerServerDraft('replace', 'Reading the latest draft failed');
458
+ }
459
+ /**
460
+ * Looks at the draft the server holds and, when it is newer than what the screen has and everything on the screen is saved,
461
+ * takes it. `replace` draws it from scratch (the selection and the view start over, nothing is left to undo); `inPlace` changes
462
+ * only what differs (see `adoptServerDraftInPlace`). A newer look, and leaving the screen, cancel one that is still on its way.
463
+ */
464
+ async takeNewerServerDraft(how, failureMessage) {
403
465
  // Not before the draft was read the first time: that read is the latest one. (Nothing gets here after the screen is
404
466
  // gone: leaving it silences the claim's listeners.)
405
467
  if (this.loadState !== 'ready')
@@ -421,14 +483,109 @@ export class WorkflowEditorState {
421
483
  // Something was typed while the look was on its way: it is not saved yet, and not for this to throw away.
422
484
  if (this.saveState !== 'saved')
423
485
  return;
424
- this.adoptServerDraft(detail);
486
+ // A published version being looked at is replaced by the draft, which the canvas then shows from scratch.
487
+ if (how === 'inPlace' && this.viewing === null)
488
+ this.adoptServerDraftInPlace(detail);
489
+ else
490
+ this.adoptServerDraft(detail);
425
491
  }
426
492
  catch (error) {
427
493
  // A look that was cancelled is no failure (`noteFailure` knows that), and nothing is said once the screen is gone.
428
494
  if (this.disposed)
429
495
  return;
430
- this.noteFailure('Reading the latest draft failed', error);
496
+ this.noteFailure(failureMessage, error);
497
+ }
498
+ }
499
+ /**
500
+ * Takes the draft the server holds without drawing the canvas again from scratch: the canvas changes only where it differs from
501
+ * what it shows (`showSavedDraft`), so the blocks that stay keep their place, the selection and the view, and the whole
502
+ * change is a step the person can undo (undoing it is the person's own change, saved like any other). Used for what the
503
+ * assistant saves while the person watches; `adoptServerDraft` starts over from the server.
504
+ */
505
+ adoptServerDraftInPlace(detail) {
506
+ const graph = ensureOneStart(detail.graph);
507
+ this.workflow = detail;
508
+ this.revision = detail.revision;
509
+ this.graph = graph;
510
+ this.name = detail.name;
511
+ this.timezone = detail.timezone;
512
+ this.lastSaved = { graph: detail.graph, name: detail.name, timezone: detail.timezone };
513
+ this.draftBaseRevision = serverBaseRevision(detail.revision);
514
+ this.pendingWorkflowName = null;
515
+ this.saver.reset();
516
+ this.saveFailure = null;
517
+ // What was found wrong with the old draft, and a test visitor somewhere in it, are no longer true of this one.
518
+ this.refusedIssues = [];
519
+ this.testRun = null;
520
+ this.applyingSavedDraft = true;
521
+ try {
522
+ this.canvas?.showSavedDraft(graph);
523
+ }
524
+ finally {
525
+ this.applyingSavedDraft = false;
431
526
  }
527
+ this.showNotice('info', 'workflows.editor.assistantChanged');
528
+ }
529
+ // =================================================================================================================
530
+ // A tab that comes back after the draft changed somewhere else
531
+ // =================================================================================================================
532
+ /**
533
+ * Begins watching for the tab coming back (`staleGuard.ts`). Whenever it does, the server is asked for the draft, and when
534
+ * that is newer than the one on the screen (the assistant, an MCP client, another tab or a teammate saved it meanwhile)
535
+ * the screen takes it behind the overlay (`staleGuardPhase` is `updating`), so a draft that is out of date is never edited.
536
+ * What is not saved is never replaced: the conflict line decides that, as for any draft somebody else saved first.
537
+ * Safe to call again; the editor going away stops it.
538
+ */
539
+ startStaleGuard() {
540
+ if (this.disposed || this.staleGuard !== null)
541
+ return;
542
+ const guard = createStaleGuard({
543
+ probe: async ({ signal }) => {
544
+ const detail = await this.api.getWorkflow(this.workflowId, { signal });
545
+ // The same revision is what the screen has; an older one is what it saved past itself since the question went out
546
+ if (detail.revision <= this.revision)
547
+ return { outcome: 'unchanged' };
548
+ return { outcome: 'changed', token: detail.revision, snapshot: detail };
549
+ },
550
+ readCurrentToken: () => (this.loadState === 'ready' ? this.revision : null),
551
+ readBlocker: () => this.readStaleGuardBlocker(),
552
+ apply: async (detail) => {
553
+ await this.ensureOptionsFor(detail.graph);
554
+ if (this.disposed)
555
+ return;
556
+ this.adoptServerDraft(detail, { keepViewport: true });
557
+ this.showNotice('info', 'workflows.editor.reloaded');
558
+ },
559
+ onConflict: () => this.raiseRevisionConflict(),
560
+ onPhaseChange: (phase) => {
561
+ this.staleGuardPhase = phase;
562
+ },
563
+ log: logStaleGuard,
564
+ ...this.staleGuardOptions
565
+ });
566
+ this.staleGuard = guard;
567
+ guard.start();
568
+ }
569
+ /**
570
+ * Whether the screen may take a newer draft now. Nothing to guard while the draft is not read yet, a published version
571
+ * is looked at (leaving it asks again) or the conflict line is already there. A save that is on its way, or something the
572
+ * person waits for, is waited out: what it sends moves the revision this screen is at. Changes that could not be sent
573
+ * are only here, so they are never replaced.
574
+ */
575
+ readStaleGuardBlocker() {
576
+ if (this.loadState !== 'ready' || this.viewing !== null)
577
+ return 'skip';
578
+ if (this.saveState === 'conflict')
579
+ return 'skip';
580
+ if (this.busy !== null ||
581
+ this.saveState === 'pending' ||
582
+ this.saveState === 'saving' ||
583
+ this.pendingWorkflowName !== null) {
584
+ return 'busy';
585
+ }
586
+ if (this.saveState === 'failed')
587
+ return 'dirty';
588
+ return null;
432
589
  }
433
590
  // =================================================================================================================
434
591
  // The compositions
@@ -476,7 +633,8 @@ export class WorkflowEditorState {
476
633
  * that the canvas can take it over.
477
634
  */
478
635
  acceptCanvasGraph(fromCanvas) {
479
- if (this.disposed || this.viewing !== null)
636
+ // A draft the server holds was just drawn: it is saved already, and reading it back must not schedule a save of it.
637
+ if (this.disposed || this.viewing !== null || this.applyingSavedDraft)
480
638
  return fromCanvas;
481
639
  const next = ensureOneStart(fromCanvas);
482
640
  if (!isSameGraph(next, this.graph)) {
@@ -579,6 +737,86 @@ export class WorkflowEditorState {
579
737
  makeStart(nodeId) {
580
738
  this.commit(setStartBlock(this.graph, nodeId));
581
739
  }
740
+ // ---- copying blocks, laying them out, taking the lines away (the canvas menu and its shortcuts) ------------------
741
+ /** Whether Paste has something to put down. */
742
+ get canPaste() {
743
+ return !this.isReadOnly && blockClipboard.hasContent;
744
+ }
745
+ /** Says why a copy was not put down: the workflow holds as many blocks, or connections, as it may. */
746
+ reportCopyRefusal(refusal) {
747
+ if (refusal === 'too_many_blocks')
748
+ this.showNotice('problem', 'workflows.editor.blockLimit', { max: MAX_BLOCKS });
749
+ else
750
+ this.showNotice('problem', 'workflows.editor.connectionLimit', { max: MAX_EDGES });
751
+ }
752
+ /** Puts the selected blocks, and the connections between them, aside for Paste. Answers whether there was anything to copy. */
753
+ copySelected() {
754
+ const clip = copyBlocks(this.graph, this.selectedNodeIds);
755
+ if (clip === null)
756
+ return false;
757
+ blockClipboard.write(clip);
758
+ return true;
759
+ }
760
+ /** Copy, then takes the selected blocks off the draft. Answers whether there was anything to cut. */
761
+ cutSelected() {
762
+ if (this.isReadOnly || !this.copySelected())
763
+ return false;
764
+ this.removeSelected();
765
+ return true;
766
+ }
767
+ /**
768
+ * Puts what Copy put aside on the draft and selects the new blocks. `topLeft` is where the top left corner of the copy goes
769
+ * (the point a menu was opened at, or where the pointer is); without it the copy goes a little below and to the right of
770
+ * the blocks it was made from.
771
+ */
772
+ pasteClipboard(topLeft) {
773
+ if (this.isReadOnly)
774
+ return;
775
+ const clip = blockClipboard.read();
776
+ if (clip === null)
777
+ return;
778
+ this.putDown(pasteBlocks(this.graph, clip, { topLeft, random: this.random }));
779
+ }
780
+ /** Copies the selected blocks and puts the copies next to them, selected. What Copy put aside is left as it is. */
781
+ duplicateSelected() {
782
+ if (this.isReadOnly || this.selectedNodeIds.length === 0)
783
+ return;
784
+ this.putDown(duplicateBlocks(this.graph, this.selectedNodeIds, { random: this.random }));
785
+ }
786
+ /** Makes what a paste or a duplicate made the draft, as one step, and selects it (or says why it was not made). */
787
+ putDown(result) {
788
+ if (result.refused !== null) {
789
+ this.reportCopyRefusal(result.refused);
790
+ return;
791
+ }
792
+ if (result.nodeIds.length === 0)
793
+ return;
794
+ this.commit(result.graph);
795
+ this.canvas?.selectNodes(result.nodeIds);
796
+ this.panel = 'selection';
797
+ }
798
+ /** Selects every block. */
799
+ selectAllBlocks() {
800
+ this.canvas?.selectAll();
801
+ }
802
+ /**
803
+ * Moves the blocks to where the workflow is easy to follow (see `organiseGraph`), as one step that one undo takes back,
804
+ * and brings them all into view. The sizes the canvas measured are used, so blocks of any height are kept apart.
805
+ */
806
+ organise() {
807
+ if (this.isReadOnly || this.graph.nodes.length === 0)
808
+ return;
809
+ const measured = this.canvas?.measureBlocks();
810
+ this.commit(organiseGraph(this.graph, { measureBlock: (node) => measured?.get(node.id) }));
811
+ this.canvas?.fitView();
812
+ }
813
+ /** Takes every connection away and leaves the blocks as they are, as one step that one undo takes back. */
814
+ disconnectAll() {
815
+ if (this.isReadOnly)
816
+ return;
817
+ this.commit(removeAllConnections(this.graph));
818
+ this.selectedEdgeIds = [];
819
+ }
582
820
  /** The selection of the canvas, as the canvas reports it. */
583
821
  followSelection(nodeIds, edgeIds) {
584
822
  this.selectedNodeIds = nodeIds;
@@ -831,6 +1069,8 @@ export class WorkflowEditorState {
831
1069
  this.viewing = null;
832
1070
  this.draftEpoch += 1;
833
1071
  this.canvas?.loadGraph(this.graph);
1072
+ // The draft was not watched while the version was looked at (the tab may have come back meanwhile): look now
1073
+ void this.staleGuard?.check('request', { force: true });
834
1074
  }
835
1075
  /** Copies the version into the draft (the draft it replaces stays recoverable only through undo, so the screen asks first). */
836
1076
  async restoreViewedVersion() {
@@ -0,0 +1,5 @@
1
+ import type { ValidationContext, ValidationIssue, WorkflowGraph } from '@widgetic/workflows-engine';
2
+ /** Issue codes an engine may still send that are not problems any more. */
3
+ export declare const RETIRED_ISSUE_CODES: ReadonlySet<string>;
4
+ /** The issues of a graph, errors and warnings, without the retired codes. `context` is what is known about the compositions. */
5
+ export declare function findGraphIssues(graph: WorkflowGraph, context?: ValidationContext): ValidationIssue[];
@@ -0,0 +1,18 @@
1
+ /**
2
+ * What is wrong with a draft, as the engine's `validate` finds it, minus the rules the product has retired.
3
+ *
4
+ * One rule is retired: a composition has one block. The same composition may sit on several blocks now (an Alt-drag, a
5
+ * Duplicate and a Paste make exactly that), each block with its own triggers and connections. `@widgetic/workflows-engine`
6
+ * up to 0.1.1 still reports it as `duplicate_composition`; from 0.1.2 it never does, and this filter then changes nothing.
7
+ * Keeping it here means the editor stops showing a problem that is no longer one without waiting for the pin of the engine
8
+ * to move, and the engine can move at its own pace.
9
+ *
10
+ * Plain data in and out, like `graphModel.ts`: nothing is drawn, nothing is stored.
11
+ */
12
+ import { validate } from '@widgetic/workflows-engine';
13
+ /** Issue codes an engine may still send that are not problems any more. */
14
+ export const RETIRED_ISSUE_CODES = new Set(['duplicate_composition']);
15
+ /** The issues of a graph, errors and warnings, without the retired codes. `context` is what is known about the compositions. */
16
+ export function findGraphIssues(graph, context) {
17
+ return validate(graph, context).issues.filter((issue) => !RETIRED_ISSUE_CODES.has(issue.code));
18
+ }
@@ -86,6 +86,11 @@ export declare function planAddBlock(graph: WorkflowGraph, request: BlockRequest
86
86
  export declare function removeBlocks(graph: WorkflowGraph, nodeIds: readonly string[]): WorkflowGraph;
87
87
  /** The graph without these connections. */
88
88
  export declare function removeConnections(graph: WorkflowGraph, edgeIds: readonly string[]): WorkflowGraph;
89
+ /**
90
+ * The graph with every connection taken away (the canvas menu's Disconnect). The blocks stay where they are and keep what
91
+ * was set on them, so a person can draw the lines again, differently. A graph without connections is returned as it is.
92
+ */
93
+ export declare function removeAllConnections(graph: WorkflowGraph): WorkflowGraph;
89
94
  /**
90
95
  * Exactly one composition starts a workflow. After blocks were taken away, the start may be gone while compositions are
91
96
  * left; the first one (the one furthest left) starts it then. A graph that already has one start is returned as it is.
@@ -137,7 +142,7 @@ export declare function makeDateSchedule(now?: Date): ScheduleConfig;
137
142
  export declare function changeScheduleMode(schedule: ScheduleConfig, mode: ScheduleConfig['mode'], now?: Date): ScheduleConfig;
138
143
  /** The composition blocks of a graph, in the order they are stored. */
139
144
  export declare function listCompositionBlocks(graph: WorkflowGraph): CompositionNode[];
140
- /** The ids of the compositions a graph shows, once each. */
145
+ /** The ids of the compositions a graph shows, once each (a composition on several blocks is listed once). */
141
146
  export declare function listCompositionIds(graph: WorkflowGraph): string[];
142
147
  /**
143
148
  * The draft as the API stores it again: positions rounded to whole numbers, so that a block that was only touched by a
@@ -229,6 +229,13 @@ export function removeConnections(graph, edgeIds) {
229
229
  const removed = new Set(edgeIds);
230
230
  return { ...graph, edges: graph.edges.filter((edge) => !removed.has(edge.id)) };
231
231
  }
232
+ /**
233
+ * The graph with every connection taken away (the canvas menu's Disconnect). The blocks stay where they are and keep what
234
+ * was set on them, so a person can draw the lines again, differently. A graph without connections is returned as it is.
235
+ */
236
+ export function removeAllConnections(graph) {
237
+ return graph.edges.length === 0 ? graph : { ...graph, edges: [] };
238
+ }
232
239
  /**
233
240
  * Exactly one composition starts a workflow. After blocks were taken away, the start may be gone while compositions are
234
241
  * left; the first one (the one furthest left) starts it then. A graph that already has one start is returned as it is.
@@ -407,7 +414,7 @@ export function changeScheduleMode(schedule, mode, now) {
407
414
  export function listCompositionBlocks(graph) {
408
415
  return graph.nodes.filter((node) => node.type === 'composition');
409
416
  }
410
- /** The ids of the compositions a graph shows, once each. */
417
+ /** The ids of the compositions a graph shows, once each (a composition on several blocks is listed once). */
411
418
  export function listCompositionIds(graph) {
412
419
  return [
413
420
  ...new Set(listCompositionBlocks(graph)
@@ -0,0 +1,21 @@
1
+ import type { TranslateWorkflowsMessage } from './blockLabels.js';
2
+ /**
3
+ * How a shortcut is written beside a row of the canvas menu, the way the Widgetic canvas writes it: "Cmd X" on a Mac and
4
+ * "Ctrl X" on Windows and Linux. The key cap names ("X", "C", "V") read the same in every language; the word Ctrl comes from the
5
+ * page's language.
6
+ */
7
+ /** A shortcut: the shortcut key (Ctrl, or Command on a Mac) and one more key. */
8
+ export interface Chord {
9
+ mod?: boolean;
10
+ /** A key cap that reads the same everywhere ("X", "]"). */
11
+ key: string;
12
+ }
13
+ /** True on a Mac, an iPhone or an iPad, where the shortcut key is Command. */
14
+ export declare function isApplePlatform(navigatorOfPage?: Navigator | undefined): boolean;
15
+ /** The text beside a menu row: "Cmd X" on a Mac, "Ctrl X" elsewhere. */
16
+ export declare function menuChordText(chord: Chord, apple: boolean, t: TranslateWorkflowsMessage): string;
17
+ /**
18
+ * The same shortcut as `aria-keyshortcuts` writes it, which names the keys in English whatever the page's language:
19
+ * "Meta+X" on a Mac, "Control+X" elsewhere.
20
+ */
21
+ export declare function ariaKeyShortcut(chord: Chord, apple: boolean): string;
@@ -0,0 +1,30 @@
1
+ /** The platform name of a browser, from the newer API when there is one. */
2
+ function platformName(navigatorOfPage) {
3
+ const withData = navigatorOfPage;
4
+ return withData.userAgentData?.platform ?? navigatorOfPage.platform ?? '';
5
+ }
6
+ /** True on a Mac, an iPhone or an iPad, where the shortcut key is Command. */
7
+ export function isApplePlatform(navigatorOfPage = typeof navigator === 'undefined' ? undefined : navigator) {
8
+ if (!navigatorOfPage)
9
+ return false;
10
+ return /mac|iphone|ipad|ipod/i.test(platformName(navigatorOfPage));
11
+ }
12
+ /** The text beside a menu row: "Cmd X" on a Mac, "Ctrl X" elsewhere. */
13
+ export function menuChordText(chord, apple, t) {
14
+ const parts = [];
15
+ if (chord.mod)
16
+ parts.push(apple ? 'Cmd' : t('workflows.key.ctrl'));
17
+ parts.push(chord.key);
18
+ return parts.join(' ');
19
+ }
20
+ /**
21
+ * The same shortcut as `aria-keyshortcuts` writes it, which names the keys in English whatever the page's language:
22
+ * "Meta+X" on a Mac, "Control+X" elsewhere.
23
+ */
24
+ export function ariaKeyShortcut(chord, apple) {
25
+ const parts = [];
26
+ if (chord.mod)
27
+ parts.push(apple ? 'Meta' : 'Control');
28
+ parts.push(chord.key);
29
+ return parts.join('+');
30
+ }