@widgetic/workflows 0.2.0 → 0.2.2

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 (36) hide show
  1. package/README.md +28 -5
  2. package/dist/api/types.d.ts +55 -1
  3. package/dist/api/workflowsApi.d.ts +47 -1
  4. package/dist/api/workflowsApi.js +179 -1
  5. package/dist/components/Workflows.svelte +2 -0
  6. package/dist/components/WorkflowsWorkspace.svelte +3 -0
  7. package/dist/components/WorkflowsWorkspace.svelte.d.ts +1 -0
  8. package/dist/components/editor/ConflictBanner.svelte +78 -0
  9. package/dist/components/editor/ConflictBanner.svelte.d.ts +3 -0
  10. package/dist/components/editor/EditorBanners.svelte +9 -11
  11. package/dist/components/editor/PresenceBanner.svelte +126 -0
  12. package/dist/components/editor/PresenceBanner.svelte.d.ts +3 -0
  13. package/dist/components/editor/SettingsTab.svelte +19 -11
  14. package/dist/components/editor/WorkflowEditor.svelte +14 -1
  15. package/dist/components/editor/WorkflowEditor.svelte.d.ts +2 -0
  16. package/dist/components/list/CreateWorkflowDialog.svelte +140 -14
  17. package/dist/components/list/WorkflowRow.svelte +8 -6
  18. package/dist/components/panel/VersionHistory.svelte +1 -1
  19. package/dist/editor/apiErrorText.js +10 -0
  20. package/dist/editor/deleteWords.d.ts +39 -0
  21. package/dist/editor/deleteWords.js +28 -0
  22. package/dist/editor/editLeaseController.d.ts +162 -0
  23. package/dist/editor/editLeaseController.js +459 -0
  24. package/dist/editor/editorState.svelte.d.ts +62 -5
  25. package/dist/editor/editorState.svelte.js +155 -6
  26. package/dist/editor/keepCopy.d.ts +41 -0
  27. package/dist/editor/keepCopy.js +52 -0
  28. package/dist/editor/listState.svelte.d.ts +39 -3
  29. package/dist/editor/listState.svelte.js +80 -1
  30. package/dist/editor/presetChoice.d.ts +26 -0
  31. package/dist/editor/presetChoice.js +32 -0
  32. package/dist/i18n/language.d.ts +3 -3
  33. package/dist/i18n/messages.d.ts +55 -2
  34. package/dist/i18n/messages.js +60 -3
  35. package/dist/types/index.d.ts +10 -0
  36. package/package.json +1 -1
package/README.md CHANGED
@@ -17,6 +17,15 @@ Workflows are for **Teams and partner accounts** only. On Widgetic the page is
17
17
  went through, and when it was last published. Search by name, show or hide the archived ones, order by name, date
18
18
  created, last published or visitors, and make a workflow (`New workflow`), duplicate it or delete it. The page is told
19
19
  when one is opened (`onOpenWorkflow`) so the address can follow.
20
+ - **Start from a preset.** `New workflow` starts blank (a name, and optionally the composition visitors see first) or, when
21
+ the workspace is offered presets, from one of them. A preset is a published workflow that Widgetic (or, for a partner's
22
+ customer, the partner) offers as a place to start; its card shows the widgets it chains, how many blocks it has and a
23
+ line from the offerer. Choosing one gives the person their own copy of every widget it chains and a draft workflow wired
24
+ like the preset's live version, named as they like (after the preset when they leave it empty); nothing they change
25
+ reaches the preset. The dialog asks for the presets when it opens, so a workspace that is offered none sees the dialog as
26
+ it always was, and when they cannot be read it says so and the blank start keeps working. A start copies every widget,
27
+ so it is given longer than another request, and it is sent with an `Idempotency-Key`: asking again after a timeout does
28
+ not copy twice.
20
29
  - **The editor.** A canvas of blocks joined by lines. A **Composition** block shows a composition; a **Trigger** block
21
30
  waits for something a visitor does (a value they add to a widget, an action in the widget, an event on the page, or a
22
31
  time); a **Condition** block sends the visitor on by the first rule that matches. Blocks go forward only, a workflow
@@ -33,8 +42,10 @@ Workflows are for **Teams and partner accounts** only. On Widgetic the page is
33
42
  - **Runs.** The _Runs_ tab shows how many visitors went through each block and each line over a range of days (counts
34
43
  only: what a visitor typed is never stored).
35
44
  - **Settings.** The time zone that scheduled triggers are told in, the embed code, and the state of the workflow: pause
36
- or resume it, archive or restore it, duplicate it, or delete it (only a draft that was never published: a published
37
- workflow can only be archived, because pages may still use it). The name is edited in the bar above the canvas.
45
+ or resume it, archive or restore it, duplicate it, or delete it. A workflow can be deleted in any state, after one
46
+ confirmation that says what goes with it (its draft, and once it was published its versions and its counts; the
47
+ compositions it uses stay). Archiving is the way to take a workflow out of the list and keep it. The name is edited in
48
+ the bar above the canvas.
38
49
  - Speaks the page's language (`locale`, `messages`) and turns around for right to left (`dir`).
39
50
  - Takes its colours, font and corners from CSS custom properties, so a host or a ui-sdk theme restyles it.
40
51
  - Reports what goes wrong to the page (`onError`) and shows the visitor a "Try again" in place of a part that failed.
@@ -108,6 +119,7 @@ the screen needs, the screen scrolls inside it; it never spills over what the pa
108
119
  | `workflowId` | `string \| null` | the list | The workflow that is open. The page owns it (it is part of the page's address); left out, the screen keeps track by itself. |
109
120
  | `onOpenWorkflow` | `(workflowId: string \| null) => void` | none | The person opened a workflow, or went back to the list (`null`). |
110
121
  | `onShowEmbedCode` | `(workflowId: string) => void` | none | Shows the embed code of a workflow. The dialog is the page's (it knows how the tag is built for its Embed SDK); without it there is no button. |
122
+ | `presence` | `boolean` | `false` | Tells who else is editing the workflow that is open, and keeps this screen from writing over them (below). Read when a workflow is opened. |
111
123
  | `locale` | `string \| null` | English | A BCP 47 tag (`de`, `pt-BR`): plural rules, how numbers and dates are written. Translates nothing. |
112
124
  | `messages` | `Readonly<Record<string, unknown>> \| null` | none | Your own words, by key. A key you leave out stays English. |
113
125
  | `dir` | `'ltr' \| 'rtl'` | the screen around it | Which way the screen is read. You decide it; it is not worked out from `locale`. |
@@ -119,10 +131,21 @@ the screen needs, the screen scrolls inside it; it never spills over what the pa
119
131
  The `message` is English, for the page's developer. It is not a sentence to show a visitor: the screen shows its own.
120
132
 
121
133
  **What the screen asks of the API.** `GET/POST /v1/workspaces/{workspaceId}/workflows` and the routes under it (a
122
- workflow, its draft, publish, discard, versions, stats, composition options), always as the person: the token is
134
+ workflow, its draft, publish, discard, versions, stats, composition options, and the presets to start from: `GET …/workflows/presets`
135
+ and `POST …/workflows/from-preset`), always as the person: the token is
123
136
  the person's, and a call the person may not make is refused by the API. The screen holds no service key (a test fails the
124
137
  build if any code of the package that runs in a browser reads one). A change is sent with an `Idempotency-Key`, and a draft
125
- with the revision the editor was given, so a draft changed somewhere else is told, not overwritten.
138
+ with the revision the editor was given, so a draft changed somewhere else is told, not overwritten: the person is offered
139
+ two ways forward, to keep what is on the screen as a copy (a new workflow, named after the original) or to load the latest
140
+ version, and nothing is lost by accident.
141
+
142
+ **Who else is editing.** With `presence` on, the screen also asks the API for the claim on editing the open workflow
143
+ (`PUT /v1/edit-leases/workflow/{id}`, renewed every 20 seconds while the tab is shown, and given up with `DELETE` when the
144
+ workflow is closed; `POST …/take-over` and `GET` complete it). When a teammate holds the claim, the screen only looks and
145
+ offers two choices: take the editing over (their editing pauses, and what they saved stays) or look only. It is a courtesy,
146
+ never a lock: what keeps a draft from being overwritten is the revision check above, whatever `presence` says. The API
147
+ names a person only to a teammate of the same organization, so a personal workspace has nothing to show and `presence`
148
+ changes nothing there. The page decides whether to ask for it (the Widgetic site does for an organization's workspace).
126
149
 
127
150
  ## Look and feel
128
151
 
@@ -172,7 +195,7 @@ Every word a person reads is a message in a catalog of English sentences, `WORKF
172
195
  `workflows.<where>.<what>`. A page gives its own words with `messages`; what it leaves out stays English, so a language
173
196
  can be added a screen at a time.
174
197
 
175
- The catalog has 390 messages. They are grouped by the part of the screen that says them:
198
+ The catalog's messages are grouped by the part of the screen that says them:
176
199
 
177
200
  | Group | What it says |
178
201
  | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
@@ -59,7 +59,7 @@ export interface WorkflowDetail extends WorkflowListItem {
59
59
  graph: WorkflowGraph;
60
60
  /** The version visitors get, without its graph; null before the first publish. */
61
61
  liveVersion: WorkflowVersion | null;
62
- /** Whether this workflow was ever published (it can then be archived but not deleted). */
62
+ /** Whether this workflow was ever published (it then has versions and counts, which a delete takes with it). */
63
63
  everPublished: boolean;
64
64
  }
65
65
  export interface WorkflowList {
@@ -137,6 +137,27 @@ export interface CompositionOptionList {
137
137
  limit: number;
138
138
  offset: number;
139
139
  }
140
+ /** A widget a preset shows: what a card of the preset draws for it. */
141
+ export interface WorkflowPresetWidget {
142
+ name: string;
143
+ /** An http(s) address for an `<img>`, or `null` when the widget has no picture. */
144
+ thumbnailUrl: string | null;
145
+ }
146
+ /**
147
+ * A place to start a new workflow: a published workflow that Widgetic (or, for one of a partner's customers, the partner)
148
+ * offers. Starting from it gives the person their own copy of its widgets, a composition on each copy, and a draft workflow
149
+ * wired like it. It carries nothing about who made it and no id of its own: `key` is how a start names it.
150
+ */
151
+ export interface WorkflowPreset {
152
+ key: string;
153
+ title: string;
154
+ /** What the offerer wrote about it; `null` when they wrote nothing. */
155
+ description: string | null;
156
+ /** How many blocks it has (compositions, triggers and conditions). */
157
+ blockCount: number;
158
+ /** The widgets it shows, once each, in the order they first appear. */
159
+ widgets: WorkflowPresetWidget[];
160
+ }
140
161
  /** What the list asks for. Everything is optional: nothing asked is the first page, newest first, drafts, live and paused. */
141
162
  export interface WorkflowListQuery {
142
163
  search?: string;
@@ -164,5 +185,38 @@ export interface WorkflowStatsQuery {
164
185
  }
165
186
  /** The state changes a workflow goes through, one request each. */
166
187
  export type WorkflowStateAction = 'pause' | 'resume' | 'archive' | 'unarchive';
188
+ /**
189
+ * What the API says about who is editing a workflow (an "edit claim": presence, never a lock; see
190
+ * `readEditLeaseAnswer`):
191
+ *
192
+ * - `held`: this tab is the one editing (its claim lasts `ttlSeconds` from now and is renewed every `heartbeatSeconds`);
193
+ * - `held_by_other`: somebody else is editing (`holder`), in another window of the same account or in a teammate's;
194
+ * - `free`: nobody is editing (only a look says that: asking to edit answers `held`);
195
+ * - `not_applicable`: this workspace has no presence (a personal one, or the feature is off): edit freely, say nothing;
196
+ * - `unavailable`: the API could not tell right now: edit freely and ask again later.
197
+ */
198
+ export type EditLeaseOutcomeName = 'held' | 'held_by_other' | 'free' | 'not_applicable' | 'unavailable';
199
+ /** Whoever holds an edit claim. The API gives a name only for a teammate who is a person, never an email. */
200
+ export interface EditLeaseHolder {
201
+ id: string;
202
+ /** The holder's name, or `null` when the API had none to give (say "Someone"). */
203
+ name: string | null;
204
+ /** The holder is the signed-in person's own account, in another window. */
205
+ isYou: boolean;
206
+ /** When the holder began editing (an ISO date), when the API said. */
207
+ since: string | null;
208
+ }
209
+ export interface EditLeaseAnswer {
210
+ outcome: EditLeaseOutcomeName;
211
+ /** How long a claim lasts without a renewal, in seconds. */
212
+ ttlSeconds?: number;
213
+ /** How often to renew it, in seconds. */
214
+ heartbeatSeconds?: number;
215
+ since?: string | null;
216
+ /** Who holds the claim, for `held_by_other` (and for `held`: this person). */
217
+ holder?: EditLeaseHolder;
218
+ /** Who the claim was taken from, when taking over displaced somebody. */
219
+ tookOverFrom?: EditLeaseHolder;
220
+ }
167
221
  /** The token function the host gives the screen (see `AccessTokenFunction` of the ui-sdk modules). */
168
222
  export type AccessTokenFunction = (reason: 'initial' | 'expired', refusedToken?: string) => Promise<string> | string;
@@ -1,8 +1,14 @@
1
1
  import type { IssueCode, ValidationIssue, WorkflowGraph } from '@widgetic/workflows-engine';
2
- import { type AccessTokenFunction, type CompositionOption, type CompositionOptionList, type CompositionOptionsQuery, type WorkflowDetail, type WorkflowList, type WorkflowListItem, type WorkflowListQuery, type WorkflowPublishResult, type WorkflowStateAction, type WorkflowStats, type WorkflowStatsQuery, type WorkflowVersion, type WorkflowVersionDetail } from './types.js';
2
+ import { type AccessTokenFunction, type CompositionOption, type CompositionOptionList, type CompositionOptionsQuery, type EditLeaseAnswer, type WorkflowDetail, type WorkflowList, type WorkflowListItem, type WorkflowListQuery, type WorkflowPreset, type WorkflowPublishResult, type WorkflowStateAction, type WorkflowStats, type WorkflowStatsQuery, type WorkflowVersion, type WorkflowVersionDetail } from './types.js';
3
3
  /** How long a request may take before it is given up: the reads, and the writes (a publish reads every composition). */
4
4
  export declare const READ_TIMEOUT_MS = 15000;
5
5
  export declare const WRITE_TIMEOUT_MS = 30000;
6
+ /**
7
+ * A start from a preset copies every widget the preset chains, one after the other, so it is given longer than another write:
8
+ * a request that is given up while the gateway is still copying is asked again with the same `Idempotency-Key`, which replays
9
+ * the answer instead of copying twice, but a person would rather wait the seconds it takes.
10
+ */
11
+ export declare const START_FROM_PRESET_TIMEOUT_MS = 90000;
6
12
  /** What went wrong with a request, as far as the screens care. */
7
13
  export declare class WorkflowsApiError extends Error {
8
14
  /** The HTTP status; null when no answer came (offline, blocked by the page's policy, too slow, a token that could not be had). */
@@ -48,10 +54,19 @@ export interface WorkflowsApiOptions {
48
54
  /** For tests. */
49
55
  readTimeoutMs?: number;
50
56
  writeTimeoutMs?: number;
57
+ startFromPresetTimeoutMs?: number;
51
58
  }
52
59
  export interface RequestOptions {
53
60
  signal?: AbortSignal;
54
61
  }
62
+ /** Options of the call that gives an edit claim up. */
63
+ export interface ReleaseEditLeaseOptions extends RequestOptions {
64
+ /**
65
+ * Lets the request finish after the page is gone (`fetch` `keepalive`): for the moment a tab is closed, when the
66
+ * claim should end at once instead of expiring a minute later.
67
+ */
68
+ keepalive?: boolean;
69
+ }
55
70
  /** The writes that must not happen twice when an answer is lost. */
56
71
  export interface RetryableRequestOptions extends RequestOptions {
57
72
  /**
@@ -85,6 +100,27 @@ export interface WorkflowsApi {
85
100
  changeState(workflowId: string, action: WorkflowStateAction, options?: RequestOptions): Promise<WorkflowListItem>;
86
101
  getStats(workflowId: string, query?: WorkflowStatsQuery, options?: RequestOptions): Promise<WorkflowStats>;
87
102
  listCompositionOptions(query?: CompositionOptionsQuery, options?: RequestOptions): Promise<CompositionOptionList>;
103
+ /** The presets this workspace can start a workflow from, in the order their offerer set (an empty list when none is offered). */
104
+ listPresets(options?: RequestOptions): Promise<WorkflowPreset[]>;
105
+ /**
106
+ * Makes a workflow of the person's own from a preset: a copy of every widget it chains, a composition on each, and a draft
107
+ * wired like the preset. `name` is left out (or empty) to name it after the preset. It answers the new workflow, a draft.
108
+ */
109
+ startFromPreset(input: {
110
+ key: string;
111
+ name?: string | null;
112
+ }, options?: RetryableRequestOptions): Promise<WorkflowDetail>;
113
+ /**
114
+ * "This tab is editing this workflow", and the renewal of that claim. Presence, never a lock: it says who else is
115
+ * editing and never refuses a save. An answer that cannot be read is `unavailable`.
116
+ */
117
+ acquireEditLease(workflowId: string, sessionId: string, options?: RequestOptions): Promise<EditLeaseAnswer>;
118
+ /** Takes the claim from whoever holds it (the answer says who it was taken from). */
119
+ takeOverEditLease(workflowId: string, sessionId: string, options?: RequestOptions): Promise<EditLeaseAnswer>;
120
+ /** Who is editing, without claiming anything. */
121
+ peekEditLease(workflowId: string, options?: RequestOptions): Promise<EditLeaseAnswer>;
122
+ /** Gives this tab's claim up. */
123
+ releaseEditLease(workflowId: string, sessionId: string, options?: ReleaseEditLeaseOptions): Promise<void>;
88
124
  }
89
125
  /** A key the gateway accepts as an `Idempotency-Key` (`^[A-Za-z0-9_-]{8,50}$`). */
90
126
  export declare function makeIdempotencyKey(): string;
@@ -100,6 +136,16 @@ export declare function usableImageUrl(value: unknown): string | null;
100
136
  * capability model is the API's, and an answer that left a part out is treated as "this composition cannot do that".
101
137
  */
102
138
  export declare function readCompositionOption(data: unknown): CompositionOption;
139
+ /**
140
+ * One preset a workflow can be started from. The key and the title are what a card and a start cannot do without; the
141
+ * description may be missing (a preset its offerer wrote nothing about), and a count that is not a number is refused.
142
+ */
143
+ export declare function readWorkflowPreset(data: unknown): WorkflowPreset;
144
+ /**
145
+ * What the API answered about an edit claim, checked. An answer the screen cannot read is `unavailable`: presence is a
146
+ * convenience, so the editor goes on as if it were not there rather than failing.
147
+ */
148
+ export declare function readEditLeaseAnswer(data: unknown): EditLeaseAnswer;
103
149
  /** The query string of the list: only what was asked for. */
104
150
  export declare function buildListQueryString(query: WorkflowListQuery | undefined): string;
105
151
  export declare function buildCompositionOptionsQueryString(query: CompositionOptionsQuery | undefined): string;
@@ -5,9 +5,11 @@
5
5
  *
6
6
  * GET /workspaces/{workspaceId}/workflows the list
7
7
  * POST /workspaces/{workspaceId}/workflows a new workflow (Idempotency-Key)
8
+ * GET /workspaces/{workspaceId}/workflows/presets the presets a workflow can be started from
9
+ * POST /workspaces/{workspaceId}/workflows/from-preset a draft workflow of one's own from a preset (Idempotency-Key)
8
10
  * GET /workspaces/{workspaceId}/workflows/{id} one workflow with its draft
9
11
  * PUT /workspaces/{workspaceId}/workflows/{id} save the draft (the revision it started from)
10
- * DELETE /workspaces/{workspaceId}/workflows/{id} delete one that was never published
12
+ * DELETE /workspaces/{workspaceId}/workflows/{id} delete one, in any state, with its versions and counts
11
13
  * POST /workspaces/{workspaceId}/workflows/{id}/duplicate a copy (Idempotency-Key)
12
14
  * POST /workspaces/{workspaceId}/workflows/{id}/publish the draft becomes the next version (Idempotency-Key)
13
15
  * POST /workspaces/{workspaceId}/workflows/{id}/discard the draft goes back to what is live
@@ -16,6 +18,10 @@
16
18
  * POST /workspaces/{workspaceId}/workflows/{id}/{pause|resume|archive|unarchive}
17
19
  * GET /workspaces/{workspaceId}/workflows/{id}/stats the counts of the Runs tab
18
20
  * GET /workspaces/{workspaceId}/workflows/composition-options the compositions to choose from, with what each can do
21
+ * PUT /edit-leases/workflow/{id} "I am editing this" (body: the tab's `sessionId`)
22
+ * POST /edit-leases/workflow/{id}/take-over take the claim from whoever holds it
23
+ * GET /edit-leases/workflow/{id} who is editing, without claiming
24
+ * DELETE /edit-leases/workflow/{id}?sessionId= give the claim up
19
25
  *
20
26
  * The API never gives a refusal a sentence of ours to show: a screen reads `code` (and `details`) and says it in the person's
21
27
  * language. What the client never does: send cookies, put a token anywhere but the `Authorization` header, or keep one.
@@ -31,6 +37,12 @@ import { WORKFLOW_STATUSES } from './types.js';
31
37
  /** How long a request may take before it is given up: the reads, and the writes (a publish reads every composition). */
32
38
  export const READ_TIMEOUT_MS = 15_000;
33
39
  export const WRITE_TIMEOUT_MS = 30_000;
40
+ /**
41
+ * A start from a preset copies every widget the preset chains, one after the other, so it is given longer than another write:
42
+ * a request that is given up while the gateway is still copying is asked again with the same `Idempotency-Key`, which replays
43
+ * the answer instead of copying twice, but a person would rather wait the seconds it takes.
44
+ */
45
+ export const START_FROM_PRESET_TIMEOUT_MS = 90_000;
34
46
  /** What went wrong with a request, as far as the screens care. */
35
47
  export class WorkflowsApiError extends Error {
36
48
  /** The HTTP status; null when no answer came (offline, blocked by the page's policy, too slow, a token that could not be had). */
@@ -374,6 +386,103 @@ function readCompositionOptionList(data) {
374
386
  offset: readWholeNumber(data, 'offset', 'the compositions')
375
387
  };
376
388
  }
389
+ /** A widget a preset shows. A name that is not text is not a widget a card can say anything about, so the answer is refused. */
390
+ function readPresetWidget(data) {
391
+ if (!isRecord(data))
392
+ throw invalidResponse('a widget of a preset');
393
+ return {
394
+ name: readText(data, 'name', 'a widget of a preset'),
395
+ thumbnailUrl: usableImageUrl(data.thumbnailUrl)
396
+ };
397
+ }
398
+ /**
399
+ * One preset a workflow can be started from. The key and the title are what a card and a start cannot do without; the
400
+ * description may be missing (a preset its offerer wrote nothing about), and a count that is not a number is refused.
401
+ */
402
+ export function readWorkflowPreset(data) {
403
+ if (!isRecord(data))
404
+ throw invalidResponse('a preset');
405
+ const presetKey = readRequiredText(data, 'key', 'a preset');
406
+ const heading = readRequiredText(data, 'title', 'a preset');
407
+ if (data.widgets !== undefined && !Array.isArray(data.widgets))
408
+ throw invalidResponse('a preset (widgets)');
409
+ return {
410
+ key: presetKey,
411
+ title: heading,
412
+ description: readPresetDescription(data),
413
+ blockCount: readWholeNumber(data, 'blockCount', 'a preset'),
414
+ widgets: (data.widgets ?? []).map(readPresetWidget)
415
+ };
416
+ }
417
+ /** A text the answer cannot do without: it has to be text, and more than spaces. */
418
+ function readRequiredText(source, key, what) {
419
+ const value = readText(source, key, what);
420
+ if (value.trim() === '')
421
+ throw invalidResponse(`${what} (${key})`);
422
+ return value;
423
+ }
424
+ /** What the offerer wrote about a preset: none when they wrote nothing, or only spaces. */
425
+ function readPresetDescription(data) {
426
+ return nonEmptyText(readNullableText(data, 'description', 'a preset'));
427
+ }
428
+ function readWorkflowPresetList(data) {
429
+ if (!isRecord(data) || !Array.isArray(data.items))
430
+ throw invalidResponse('the presets');
431
+ return data.items.map(readWorkflowPreset);
432
+ }
433
+ /** What the API accepts as the id of an editor tab (an edit claim's `sessionId`). */
434
+ const EDIT_LEASE_SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/;
435
+ /** True for a number of seconds worth believing: a positive, finite number. */
436
+ function isSeconds(value) {
437
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
438
+ }
439
+ /** Whoever holds an edit claim, as the API wrote it; `undefined` when what came is no holder. */
440
+ function readEditLeaseHolder(value) {
441
+ if (!isRecord(value) || typeof value.id !== 'string' || value.id === '')
442
+ return undefined;
443
+ const name = typeof value.name === 'string' ? value.name.trim() : '';
444
+ return {
445
+ id: value.id,
446
+ // A name is what a person wrote, so it is cut to a length a banner can hold.
447
+ name: name === '' ? null : name.slice(0, 120),
448
+ isYou: value.isYou === true,
449
+ since: typeof value.since === 'string' ? value.since : null
450
+ };
451
+ }
452
+ const EDIT_LEASE_OUTCOMES = [
453
+ 'held',
454
+ 'held_by_other',
455
+ 'free',
456
+ 'not_applicable',
457
+ 'unavailable'
458
+ ];
459
+ /**
460
+ * What the API answered about an edit claim, checked. An answer the screen cannot read is `unavailable`: presence is a
461
+ * convenience, so the editor goes on as if it were not there rather than failing.
462
+ */
463
+ export function readEditLeaseAnswer(data) {
464
+ if (!isRecord(data))
465
+ return { outcome: 'unavailable' };
466
+ const outcome = EDIT_LEASE_OUTCOMES.find((name) => name === data.outcome);
467
+ if (!outcome)
468
+ return { outcome: 'unavailable' };
469
+ const answer = { outcome };
470
+ if (isSeconds(data.ttlSeconds))
471
+ answer.ttlSeconds = data.ttlSeconds;
472
+ if (isSeconds(data.heartbeatSeconds))
473
+ answer.heartbeatSeconds = data.heartbeatSeconds;
474
+ if (typeof data.since === 'string')
475
+ answer.since = data.since;
476
+ else if (data.since === null)
477
+ answer.since = null;
478
+ const holder = readEditLeaseHolder(data.holder);
479
+ if (holder)
480
+ answer.holder = holder;
481
+ const tookOverFrom = readEditLeaseHolder(data.tookOverFrom);
482
+ if (tookOverFrom)
483
+ answer.tookOverFrom = tookOverFrom;
484
+ return answer;
485
+ }
377
486
  /** The error code, sentence and details of an API error answer, when it has them. */
378
487
  function describeFailureBody(body) {
379
488
  if (!isRecord(body))
@@ -453,6 +562,7 @@ export function createWorkflowsApi(options) {
453
562
  const workspaceBase = `/workspaces/${encodeURIComponent(options.workspaceId)}/workflows`;
454
563
  const readTimeoutMs = options.readTimeoutMs ?? READ_TIMEOUT_MS;
455
564
  const writeTimeoutMs = options.writeTimeoutMs ?? WRITE_TIMEOUT_MS;
565
+ const startFromPresetTimeoutMs = options.startFromPresetTimeoutMs ?? START_FROM_PRESET_TIMEOUT_MS;
456
566
  const sendRequest = options.fetchImplementation ?? ((...parameters) => globalThis.fetch(...parameters));
457
567
  async function tokenFor(reason, refusedToken) {
458
568
  try {
@@ -519,6 +629,8 @@ export function createWorkflowsApi(options) {
519
629
  // The token is the credential; the gateway never allows cookies on these routes.
520
630
  credentials: 'omit',
521
631
  mode: 'cors',
632
+ ...(details.noStore ? { cache: 'no-store' } : {}),
633
+ ...(details.keepalive ? { keepalive: true } : {}),
522
634
  signal: attempt.signal
523
635
  });
524
636
  };
@@ -552,6 +664,20 @@ export function createWorkflowsApi(options) {
552
664
  }
553
665
  }
554
666
  const pathOfWorkflow = (workflowId) => `${workspaceBase}/${encodeURIComponent(workflowId)}`;
667
+ /** The address of a workflow's edit claim, with `suffix` after it (the claim routes are not under the workspace). */
668
+ function leasePath(workflowId, suffix = '') {
669
+ if (typeof workflowId !== 'string' || workflowId.trim() === '') {
670
+ throw new TypeError('A workflow id is needed');
671
+ }
672
+ return `/edit-leases/workflow/${encodeURIComponent(workflowId)}${suffix}`;
673
+ }
674
+ /** The tab's own id, which the API holds to a short plain alphabet; a bad one is a bug of the caller, never sent. */
675
+ function checkedSessionId(sessionId) {
676
+ if (typeof sessionId !== 'string' || !EDIT_LEASE_SESSION_ID_PATTERN.test(sessionId)) {
677
+ throw new TypeError('A session id is 8 to 64 letters, digits, dashes or underscores');
678
+ }
679
+ return sessionId;
680
+ }
555
681
  return {
556
682
  async listWorkflows(query, requestOptions = {}) {
557
683
  return readWorkflowList(await request('GET', `${workspaceBase}${buildListQueryString(query)}`, {
@@ -652,6 +778,58 @@ export function createWorkflowsApi(options) {
652
778
  signal: requestOptions.signal,
653
779
  timeoutMs: readTimeoutMs
654
780
  }));
781
+ },
782
+ async listPresets(requestOptions = {}) {
783
+ return readWorkflowPresetList(await request('GET', `${workspaceBase}/presets`, {
784
+ signal: requestOptions.signal,
785
+ timeoutMs: readTimeoutMs
786
+ }));
787
+ },
788
+ async startFromPreset(input, requestOptions = {}) {
789
+ const body = { key: input.key };
790
+ // A name that is only spaces is no name: the preset's title is used, as when none is given.
791
+ const name = input.name?.trim();
792
+ if (name)
793
+ body.name = name;
794
+ return readWorkflowDetail(await request('POST', `${workspaceBase}/from-preset`, {
795
+ body,
796
+ idempotencyKey: requestOptions.idempotencyKey ?? makeIdempotencyKey(),
797
+ signal: requestOptions.signal,
798
+ timeoutMs: startFromPresetTimeoutMs
799
+ }));
800
+ },
801
+ // The edit claim calls wait no longer than a read does: a claim is renewed every few seconds, and a renewal that
802
+ // takes longer than that has told what it will tell.
803
+ async acquireEditLease(workflowId, sessionId, requestOptions = {}) {
804
+ return readEditLeaseAnswer(await request('PUT', leasePath(workflowId), {
805
+ body: { sessionId: checkedSessionId(sessionId) },
806
+ signal: requestOptions.signal,
807
+ timeoutMs: readTimeoutMs,
808
+ noStore: true
809
+ }));
810
+ },
811
+ async takeOverEditLease(workflowId, sessionId, requestOptions = {}) {
812
+ return readEditLeaseAnswer(await request('POST', leasePath(workflowId, '/take-over'), {
813
+ body: { sessionId: checkedSessionId(sessionId) },
814
+ signal: requestOptions.signal,
815
+ timeoutMs: readTimeoutMs,
816
+ noStore: true
817
+ }));
818
+ },
819
+ async peekEditLease(workflowId, requestOptions = {}) {
820
+ return readEditLeaseAnswer(await request('GET', leasePath(workflowId), {
821
+ signal: requestOptions.signal,
822
+ timeoutMs: readTimeoutMs,
823
+ noStore: true
824
+ }));
825
+ },
826
+ async releaseEditLease(workflowId, sessionId, releaseOptions = {}) {
827
+ await request('DELETE', leasePath(workflowId, `?sessionId=${encodeURIComponent(checkedSessionId(sessionId))}`), {
828
+ signal: releaseOptions.signal,
829
+ timeoutMs: readTimeoutMs,
830
+ noStore: true,
831
+ keepalive: releaseOptions.keepalive
832
+ });
655
833
  }
656
834
  };
657
835
  }
@@ -35,6 +35,7 @@
35
35
  workflowId = null,
36
36
  onOpenWorkflow,
37
37
  onShowEmbedCode,
38
+ presence = false,
38
39
  locale = null,
39
40
  messages: languageMessages = null,
40
41
  dir = undefined,
@@ -100,6 +101,7 @@
100
101
  {workflowId}
101
102
  {onOpenWorkflow}
102
103
  {onShowEmbedCode}
104
+ {presence}
103
105
  onError={reportToPage}
104
106
  />
105
107
  {/key}
@@ -25,6 +25,7 @@
25
25
  workflowId?: WorkflowsProps['workflowId'];
26
26
  onOpenWorkflow?: WorkflowsProps['onOpenWorkflow'];
27
27
  onShowEmbedCode?: WorkflowsProps['onShowEmbedCode'];
28
+ presence?: WorkflowsProps['presence'];
28
29
  onError: (error: WorkflowsError) => void;
29
30
  }
30
31
 
@@ -36,6 +37,7 @@
36
37
  workflowId,
37
38
  onOpenWorkflow,
38
39
  onShowEmbedCode,
40
+ presence = false,
39
41
  onError
40
42
  }: Props = $props();
41
43
 
@@ -77,6 +79,7 @@
77
79
  onopenworkflow={(id) => open(id)}
78
80
  onerror={onError}
79
81
  onshowembedcode={onShowEmbedCode}
82
+ {presence}
80
83
  />
81
84
  {/key}
82
85
  </div>
@@ -7,6 +7,7 @@ interface Props {
7
7
  workflowId?: WorkflowsProps['workflowId'];
8
8
  onOpenWorkflow?: WorkflowsProps['onOpenWorkflow'];
9
9
  onShowEmbedCode?: WorkflowsProps['onShowEmbedCode'];
10
+ presence?: WorkflowsProps['presence'];
10
11
  onError: (error: WorkflowsError) => void;
11
12
  }
12
13
  declare const WorkflowsWorkspace: import("svelte").Component<Props, {}, "">;
@@ -0,0 +1,78 @@
1
+ <!--
2
+ The line above the canvas for a draft that somebody else saved first: what this person changed last was not saved, because
3
+ saving it would have written over the other person's work. Two ways forward, and neither loses anything by accident.
4
+
5
+ - Keep what is on this screen as a new workflow (a copy). Then the latest version can be loaded at no cost, or the copy
6
+ opened to carry on in it. The line says where the changes are kept.
7
+ - Load the latest version, which replaces what is on this screen. While the changes are kept nowhere the person is asked
8
+ once; after a copy was kept there is nothing to lose and nothing to ask.
9
+
10
+ The screen only shows and asks; making the copy and loading are the editor's (`keepCopyOfChanges`, `reloadDraft`).
11
+ -->
12
+ <script lang="ts">
13
+ import { useEditorState } from '../../editor/editorState.svelte.js';
14
+ import { useWorkflowsLanguage } from '../../i18n/language.js';
15
+ import ActionButton from '../ui/ActionButton.svelte';
16
+ import ConfirmDialog from '../ui/ConfirmDialog.svelte';
17
+ import Notice from '../ui/Notice.svelte';
18
+
19
+ const editor = useEditorState();
20
+ const { t } = useWorkflowsLanguage();
21
+
22
+ let isAskingToLoad = $state(false);
23
+
24
+ const keptCopy = $derived(editor.keptCopy);
25
+ const isKeepingCopy = $derived(editor.busy === 'keepingCopy');
26
+
27
+ /** Keeps a copy. The copy's name is the person's words around the workflow's name; the editor cuts it to fit. */
28
+ function keepCopy(): void {
29
+ void editor.keepCopyOfChanges((name) => $t('workflows.conflict.copyName', { name }));
30
+ }
31
+
32
+ /** Loading replaces what is on the screen: while that is kept nowhere, the person is asked first. */
33
+ function requestLoadLatest(): void {
34
+ if (keptCopy) void editor.reloadDraft();
35
+ else isAskingToLoad = true;
36
+ }
37
+
38
+ function loadLatest(): void {
39
+ isAskingToLoad = false;
40
+ void editor.reloadDraft();
41
+ }
42
+ </script>
43
+
44
+ <!-- Once the copy exists the worry is over, so the line stops being an alarm. -->
45
+ <Notice tone={keptCopy ? 'info' : 'problem'}>
46
+ {#if keptCopy}
47
+ {$t('workflows.conflict.copyKept', { name: keptCopy.name })}
48
+ {:else}
49
+ {$t('workflows.banner.conflict')}
50
+ {/if}
51
+ {#snippet action()}
52
+ {#if keptCopy}
53
+ <ActionButton
54
+ size="small"
55
+ disabled={editor.busy !== null}
56
+ onclick={() => editor.openKeptCopy()}>{$t('workflows.conflict.openCopy')}</ActionButton
57
+ >
58
+ {:else}
59
+ <ActionButton size="small" disabled={editor.busy !== null} onclick={keepCopy}>
60
+ {isKeepingCopy ? $t('workflows.conflict.keepingCopy') : $t('workflows.conflict.keepCopy')}
61
+ </ActionButton>
62
+ {/if}
63
+ <ActionButton size="small" disabled={editor.busy !== null} onclick={requestLoadLatest}
64
+ >{$t('workflows.banner.reload')}</ActionButton
65
+ >
66
+ {/snippet}
67
+ </Notice>
68
+
69
+ {#if isAskingToLoad}
70
+ <ConfirmDialog
71
+ title={$t('workflows.conflict.loadTitle')}
72
+ message={$t('workflows.conflict.loadMessage')}
73
+ confirmLabel={$t('workflows.banner.reload')}
74
+ tone="danger"
75
+ onconfirm={loadLatest}
76
+ oncancel={() => (isAskingToLoad = false)}
77
+ />
78
+ {/if}
@@ -0,0 +1,3 @@
1
+ declare const ConflictBanner: import("svelte").Component<Record<string, never>, {}, "">;
2
+ type ConflictBanner = ReturnType<typeof ConflictBanner>;
3
+ export default ConflictBanner;
@@ -11,6 +11,8 @@
11
11
  import ActionButton from '../ui/ActionButton.svelte';
12
12
  import ConfirmDialog from '../ui/ConfirmDialog.svelte';
13
13
  import Notice from '../ui/Notice.svelte';
14
+ import ConflictBanner from './ConflictBanner.svelte';
15
+ import PresenceBanner from './PresenceBanner.svelte';
14
16
 
15
17
  interface Props {
16
18
  /** The person pressed "Publish changes". */
@@ -37,6 +39,9 @@
37
39
  </script>
38
40
 
39
41
  <div class="flex flex-col gap-2">
42
+ <!-- First: a teammate who is editing decides what the rest of the screen lets the person do. -->
43
+ <PresenceBanner />
44
+
40
45
  {#if editor.notice}
41
46
  {@const notice = editor.notice}
42
47
  <Notice tone={notice.tone}>
@@ -50,14 +55,7 @@
50
55
  {/if}
51
56
 
52
57
  {#if editor.saveState === 'conflict'}
53
- <Notice tone="problem">
54
- {$t('workflows.banner.conflict')}
55
- {#snippet action()}
56
- <ActionButton size="small" onclick={() => void editor.reloadDraft()}
57
- >{$t('workflows.banner.reload')}</ActionButton
58
- >
59
- {/snippet}
60
- </Notice>
58
+ <ConflictBanner />
61
59
  {:else if editor.saveState === 'failed'}
62
60
  <Notice tone="problem">
63
61
  {$t(editor.saveFailure ?? 'workflows.error.generic')}
@@ -84,7 +82,7 @@
84
82
  {#snippet action()}
85
83
  <ActionButton
86
84
  size="small"
87
- disabled={editor.busy !== null}
85
+ disabled={!editor.canChangeWorkflow}
88
86
  onclick={() => void editor.changeState('unarchive')}
89
87
  >{$t('workflows.settings.unarchive')}</ActionButton
90
88
  >
@@ -96,7 +94,7 @@
96
94
  {#snippet action()}
97
95
  <ActionButton
98
96
  size="small"
99
- disabled={editor.busy !== null}
97
+ disabled={!editor.canChangeWorkflow}
100
98
  onclick={() => void editor.changeState('resume')}
101
99
  >{$t('workflows.settings.resume')}</ActionButton
102
100
  >
@@ -110,7 +108,7 @@
110
108
  {#snippet action()}
111
109
  <ActionButton
112
110
  size="small"
113
- disabled={editor.busy !== null}
111
+ disabled={editor.isReadOnly || editor.busy !== null}
114
112
  onclick={() => (isAskingToDiscard = true)}>{$t('workflows.banner.discard')}</ActionButton
115
113
  >
116
114
  <ActionButton