@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
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Who is editing this workflow right now, as one open editor lives it: the claim this tab keeps while it edits, and
3
+ * what it does when somebody else holds it. No user interface in it, and no dependency but the API's answers, so a test
4
+ * can drive it with a fake port and fake timers.
5
+ *
6
+ * This is the same controller as the composition editor's (`@widgetic/editor`, `editLeaseController.ts`), for a workflow
7
+ * instead of a composition. The two packages are published apart and share no code of their own, so it is a copy with the
8
+ * three differences a workflows screen has (where the answers' types come from, how a request that was cancelled shows,
9
+ * and the tab id). A change to the rules below belongs in both.
10
+ *
11
+ * It is presence, never a lock. The rules that keep it harmless:
12
+ *
13
+ * - Nothing here can make a save fail or take edits away. The only thing it does to the editor is ask it to stop
14
+ * taking NEW edits (`editsBlocked`) while a teammate holds the claim; everything edited before is still saved.
15
+ * - Every doubt means "edit freely". The API cannot tell, the network is down, the workspace has no presence
16
+ * (a personal one), the person may not write to it, the answer is unreadable: the editor behaves as if this feature
17
+ * did not exist, and tries again later (or, when the API refused for good, never).
18
+ * - The person always decides. When somebody else holds the claim the person may take over (their claim replaces the
19
+ * other's at once), or look only. Nobody is ever locked out: a claim that is not renewed ends by itself, and a
20
+ * take-over is always one click away.
21
+ * - A claim belongs to a tab (`sessionId`), not to a person: the same person in two windows is two holders, and the
22
+ * second window is told so ("you are editing this in another window").
23
+ * - A claim is kept up only while the tab is on screen. A tab left in the background all day does not keep a
24
+ * teammate out: its claim runs out after the time the API gave, and when the person comes back the tab asks again,
25
+ * and says so if somebody else has begun editing meanwhile.
26
+ * - One request at a time. A renewal never overlaps another call; a choice the person makes cancels the call on its
27
+ * way, and the answer of a cancelled call is ignored.
28
+ * - A claim is given up as soon as the editor closes (`dispose`) or the page goes (`pagehide`), with a request that
29
+ * outlives the page, so a teammate does not wait for it to run out.
30
+ * - After `dispose()` nothing more happens: no request goes out, and answers still on their way are ignored.
31
+ */
32
+ import type { EditLeaseAnswer, EditLeaseHolder } from '../api/types.js';
33
+ /** What the controller asks of the API, for one workflow. The editor builds it from its `WorkflowsApi`. */
34
+ export interface EditLeasePort {
35
+ acquire(sessionId: string, options?: {
36
+ signal?: AbortSignal;
37
+ }): Promise<EditLeaseAnswer>;
38
+ takeOver(sessionId: string, options?: {
39
+ signal?: AbortSignal;
40
+ }): Promise<EditLeaseAnswer>;
41
+ peek(options?: {
42
+ signal?: AbortSignal;
43
+ }): Promise<EditLeaseAnswer>;
44
+ release(sessionId: string, options?: {
45
+ keepalive?: boolean;
46
+ }): Promise<void>;
47
+ }
48
+ /**
49
+ * Where the tab is:
50
+ * - `off`: no presence (not started, none for this workflow, refused for good, or the API cannot tell): edit freely;
51
+ * - `editing`: this tab holds the claim;
52
+ * - `blocked`: somebody else holds it and the person has not chosen yet (a card asks);
53
+ * - `readOnly`: the person chose to only look (a slim bar says who is editing, or that nobody is).
54
+ */
55
+ export type PresencePhase = 'off' | 'editing' | 'blocked' | 'readOnly';
56
+ export interface PresenceState {
57
+ phase: PresencePhase;
58
+ /** Who holds the claim, in `blocked` and `readOnly` (`null` when the API gave nobody, or nobody holds it). */
59
+ holder: EditLeaseHolder | null;
60
+ /** `blocked` because the claim was taken from this tab (a teammate took over, or its claim ran out): not just arrived. */
61
+ lostIt: boolean;
62
+ /** In `readOnly`: the last look found nobody editing, so the person may start. */
63
+ nobodyIsEditing: boolean;
64
+ /** A choice of the person (take over, start editing) is on its way. */
65
+ working: boolean;
66
+ /** The last choice could not be carried out (the API could not be reached): the person may try again. */
67
+ actionFailed: boolean;
68
+ /** The editor should take no new edit: `blocked` or `readOnly`. */
69
+ editsBlocked: boolean;
70
+ }
71
+ /** What the controller needs from the page it lives in. The default is the browser's own. */
72
+ export interface PresenceEnvironment {
73
+ /** The tab is on screen. */
74
+ isVisible(): boolean;
75
+ /** Calls `callback` when the tab comes back to the screen, the network returns, or the page is restored from the cache. */
76
+ onWake(callback: () => void): () => void;
77
+ /** Calls `callback` when the page is about to go (closed, or navigated away from). */
78
+ onPageHide(callback: () => void): () => void;
79
+ }
80
+ export interface TimerFunctions {
81
+ setTimeout: (callback: () => void, milliseconds: number) => unknown;
82
+ clearTimeout: (handle: unknown) => void;
83
+ }
84
+ export interface EditLeaseControllerOptions {
85
+ port: EditLeasePort;
86
+ /** The id of this tab (8 to 64 letters, digits, dashes or underscores). Default: a random UUID. */
87
+ sessionId?: string;
88
+ /** How often to renew the claim until the API says otherwise, in milliseconds. Default: 20 seconds. */
89
+ heartbeatMs?: number;
90
+ timers?: TimerFunctions;
91
+ /** The clock, in milliseconds. Default: `Date.now`. */
92
+ now?: () => number;
93
+ environment?: PresenceEnvironment;
94
+ /** Writes the controller's own notes (a request refused as malformed, a listener that failed). Default: the console. */
95
+ logger?: Pick<Console, 'warn' | 'error'>;
96
+ }
97
+ /** How often to renew a claim when the API has not said (it says, with every answer). */
98
+ export declare const DEFAULT_HEARTBEAT_MS = 20000;
99
+ /** The browser's own environment; one that does nothing where there is no page (a server, a test). */
100
+ export declare function createBrowserPresenceEnvironment(): PresenceEnvironment;
101
+ /** The state of a tab with no presence: nothing is shown and nothing is blocked. What a page starts from, before the API has said. */
102
+ export declare const NO_PRESENCE: Readonly<PresenceState>;
103
+ export declare class EditLeaseController {
104
+ private state;
105
+ private readonly stateListeners;
106
+ private readonly port;
107
+ private readonly sessionId;
108
+ private readonly timers;
109
+ private readonly now;
110
+ private readonly environment;
111
+ private readonly logger;
112
+ private heartbeatMs;
113
+ private timerHandle;
114
+ private inFlight;
115
+ /** Which call is the current one: the answer of an older call is ignored. */
116
+ private generation;
117
+ private started;
118
+ /** The API refused for good (or said there is no presence): no more requests. */
119
+ private stopped;
120
+ private disposed;
121
+ /** This tab holds the claim as far as it knows, so it must give it up when it goes. */
122
+ private holding;
123
+ private failureStreak;
124
+ private lastAnswerAt;
125
+ private removeWakeListener;
126
+ private removeHideListener;
127
+ constructor(options: EditLeaseControllerOptions);
128
+ /** The state now. It is never changed in place: a change makes a new object. */
129
+ getState(): PresenceState;
130
+ /** Svelte store contract: calls `listener` with the state now, and again after every change. */
131
+ subscribe(listener: (state: PresenceState) => void): () => void;
132
+ /** The id of this tab, as the API knows it. */
133
+ get tabId(): string;
134
+ /** Asks to edit, and keeps asking while the tab is open. Asking again does nothing. */
135
+ start(): void;
136
+ /** The person chose to take the claim from whoever holds it. Only from `blocked` and `readOnly`. */
137
+ takeOver(): void;
138
+ /** The person chose to only look, for now. Only from `blocked`. */
139
+ openReadOnly(): void;
140
+ /** The person chose to begin editing after looking. Only from `readOnly`. */
141
+ startEditing(): void;
142
+ private canChoose;
143
+ /** Stops everything, gives the claim up, and ignores any answer still on its way. */
144
+ dispose(): void;
145
+ /** The renewal the timer asks for: only while the tab is on screen (a hidden tab's claim is left to run out). */
146
+ private beat;
147
+ /** The tab came back to the screen (or the network did): ask at once instead of waiting for the timer. */
148
+ private wake;
149
+ private call;
150
+ private send;
151
+ /** What an answer changes. `kind` and the phase tell which question it answers. */
152
+ private apply;
153
+ private fail;
154
+ /** The API said there is no presence here (or refused for good): edit freely, and stop asking. */
155
+ private stop;
156
+ private scheduleBeat;
157
+ private clearTimer;
158
+ /** Gives the claim up, if this tab holds it, with a request that outlives the page. Never throws, never waits. */
159
+ private releaseClaim;
160
+ /** Makes the next state out of the changes and tells the watchers, once, when something changed. */
161
+ private patch;
162
+ }
@@ -0,0 +1,459 @@
1
+ /**
2
+ * Who is editing this workflow right now, as one open editor lives it: the claim this tab keeps while it edits, and
3
+ * what it does when somebody else holds it. No user interface in it, and no dependency but the API's answers, so a test
4
+ * can drive it with a fake port and fake timers.
5
+ *
6
+ * This is the same controller as the composition editor's (`@widgetic/editor`, `editLeaseController.ts`), for a workflow
7
+ * instead of a composition. The two packages are published apart and share no code of their own, so it is a copy with the
8
+ * three differences a workflows screen has (where the answers' types come from, how a request that was cancelled shows,
9
+ * and the tab id). A change to the rules below belongs in both.
10
+ *
11
+ * It is presence, never a lock. The rules that keep it harmless:
12
+ *
13
+ * - Nothing here can make a save fail or take edits away. The only thing it does to the editor is ask it to stop
14
+ * taking NEW edits (`editsBlocked`) while a teammate holds the claim; everything edited before is still saved.
15
+ * - Every doubt means "edit freely". The API cannot tell, the network is down, the workspace has no presence
16
+ * (a personal one), the person may not write to it, the answer is unreadable: the editor behaves as if this feature
17
+ * did not exist, and tries again later (or, when the API refused for good, never).
18
+ * - The person always decides. When somebody else holds the claim the person may take over (their claim replaces the
19
+ * other's at once), or look only. Nobody is ever locked out: a claim that is not renewed ends by itself, and a
20
+ * take-over is always one click away.
21
+ * - A claim belongs to a tab (`sessionId`), not to a person: the same person in two windows is two holders, and the
22
+ * second window is told so ("you are editing this in another window").
23
+ * - A claim is kept up only while the tab is on screen. A tab left in the background all day does not keep a
24
+ * teammate out: its claim runs out after the time the API gave, and when the person comes back the tab asks again,
25
+ * and says so if somebody else has begun editing meanwhile.
26
+ * - One request at a time. A renewal never overlaps another call; a choice the person makes cancels the call on its
27
+ * way, and the answer of a cancelled call is ignored.
28
+ * - A claim is given up as soon as the editor closes (`dispose`) or the page goes (`pagehide`), with a request that
29
+ * outlives the page, so a teammate does not wait for it to run out.
30
+ * - After `dispose()` nothing more happens: no request goes out, and answers still on their way are ignored.
31
+ */
32
+ /**
33
+ * An id for this tab that the API accepts (8 to 64 letters, digits, dashes or underscores): a random UUID, or, where
34
+ * there is no `crypto.randomUUID`, the time and a random number, which is unique enough for one person's tabs.
35
+ */
36
+ function createTabId() {
37
+ const random = globalThis.crypto?.randomUUID?.();
38
+ if (random)
39
+ return random;
40
+ return `tab-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
41
+ }
42
+ /** How often to renew a claim when the API has not said (it says, with every answer). */
43
+ export const DEFAULT_HEARTBEAT_MS = 20_000;
44
+ /** The API's word is believed within these limits: a renewal more often than this is a flood, less often lets the claim run out. */
45
+ const MIN_HEARTBEAT_MS = 5_000;
46
+ const MAX_HEARTBEAT_MS = 120_000;
47
+ /** A tab that returns to the screen asks at once, unless it was answered this recently (one wake-up often reaches a page twice). */
48
+ const WAKE_MIN_GAP_MS = 3_000;
49
+ /** After failures the wait grows by one heartbeat each time, up to this many extra: a network that is down is not hammered. */
50
+ const MAX_BACKOFF_STEPS = 3;
51
+ /**
52
+ * What a failed call told, from the error the API client throws (a `WorkflowsApiError`, or the `AbortError` of a request
53
+ * that was cancelled), without depending on the classes.
54
+ */
55
+ function describeFailure(error) {
56
+ const record = typeof error === 'object' && error !== null ? error : {};
57
+ return {
58
+ // No answer came (offline, too slow, no token) is no status at all.
59
+ status: typeof record.status === 'number' ? record.status : 0,
60
+ cancelled: record.name === 'AbortError'
61
+ };
62
+ }
63
+ function clampHeartbeat(milliseconds) {
64
+ return Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, milliseconds));
65
+ }
66
+ /** The browser's own environment; one that does nothing where there is no page (a server, a test). */
67
+ export function createBrowserPresenceEnvironment() {
68
+ const hasDocument = typeof document !== 'undefined';
69
+ const hasWindow = typeof window !== 'undefined';
70
+ return {
71
+ isVisible: () => !hasDocument || document.visibilityState !== 'hidden',
72
+ onWake(callback) {
73
+ if (!hasDocument || !hasWindow)
74
+ return () => { };
75
+ const onVisibilityChange = () => {
76
+ if (document.visibilityState === 'visible')
77
+ callback();
78
+ };
79
+ // A page restored from the back-forward cache comes back with its timers stopped and its claim given up.
80
+ const onPageShow = (event) => {
81
+ if (event.persisted)
82
+ callback();
83
+ };
84
+ document.addEventListener('visibilitychange', onVisibilityChange);
85
+ window.addEventListener('online', callback);
86
+ window.addEventListener('pageshow', onPageShow);
87
+ return () => {
88
+ document.removeEventListener('visibilitychange', onVisibilityChange);
89
+ window.removeEventListener('online', callback);
90
+ window.removeEventListener('pageshow', onPageShow);
91
+ };
92
+ },
93
+ onPageHide(callback) {
94
+ if (!hasWindow)
95
+ return () => { };
96
+ window.addEventListener('pagehide', callback);
97
+ return () => window.removeEventListener('pagehide', callback);
98
+ }
99
+ };
100
+ }
101
+ const DEFAULT_TIMERS = {
102
+ setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
103
+ clearTimeout: (handle) => globalThis.clearTimeout(handle)
104
+ };
105
+ /** The state of a tab with no presence: nothing is shown and nothing is blocked. What a page starts from, before the API has said. */
106
+ export const NO_PRESENCE = Object.freeze({
107
+ phase: 'off',
108
+ holder: null,
109
+ lostIt: false,
110
+ nobodyIsEditing: false,
111
+ working: false,
112
+ actionFailed: false,
113
+ editsBlocked: false
114
+ });
115
+ function initialState() {
116
+ return { ...NO_PRESENCE };
117
+ }
118
+ /** `editsBlocked` follows the phase and nothing else, so the two can never disagree. */
119
+ function withDerived(state) {
120
+ return { ...state, editsBlocked: state.phase === 'blocked' || state.phase === 'readOnly' };
121
+ }
122
+ export class EditLeaseController {
123
+ state = initialState();
124
+ stateListeners = new Set();
125
+ port;
126
+ sessionId;
127
+ timers;
128
+ now;
129
+ environment;
130
+ logger;
131
+ heartbeatMs;
132
+ timerHandle = null;
133
+ inFlight = null;
134
+ /** Which call is the current one: the answer of an older call is ignored. */
135
+ generation = 0;
136
+ started = false;
137
+ /** The API refused for good (or said there is no presence): no more requests. */
138
+ stopped = false;
139
+ disposed = false;
140
+ /** This tab holds the claim as far as it knows, so it must give it up when it goes. */
141
+ holding = false;
142
+ failureStreak = 0;
143
+ lastAnswerAt = Number.NEGATIVE_INFINITY;
144
+ removeWakeListener = null;
145
+ removeHideListener = null;
146
+ constructor(options) {
147
+ this.port = options.port;
148
+ this.sessionId = options.sessionId ?? createTabId();
149
+ this.heartbeatMs = clampHeartbeat(options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
150
+ this.timers = options.timers ?? DEFAULT_TIMERS;
151
+ this.now = options.now ?? Date.now;
152
+ this.environment = options.environment ?? createBrowserPresenceEnvironment();
153
+ this.logger = options.logger ?? console;
154
+ }
155
+ // ---------------------------------------------------------------------------------------------
156
+ // Watching
157
+ // ---------------------------------------------------------------------------------------------
158
+ /** The state now. It is never changed in place: a change makes a new object. */
159
+ getState() {
160
+ return this.state;
161
+ }
162
+ /** Svelte store contract: calls `listener` with the state now, and again after every change. */
163
+ subscribe(listener) {
164
+ this.stateListeners.add(listener);
165
+ listener(this.state);
166
+ return () => {
167
+ this.stateListeners.delete(listener);
168
+ };
169
+ }
170
+ /** The id of this tab, as the API knows it. */
171
+ get tabId() {
172
+ return this.sessionId;
173
+ }
174
+ // ---------------------------------------------------------------------------------------------
175
+ // Starting and the person's choices
176
+ // ---------------------------------------------------------------------------------------------
177
+ /** Asks to edit, and keeps asking while the tab is open. Asking again does nothing. */
178
+ start() {
179
+ if (this.started || this.disposed)
180
+ return;
181
+ this.started = true;
182
+ this.removeWakeListener = this.environment.onWake(() => this.wake());
183
+ this.removeHideListener = this.environment.onPageHide(() => this.releaseClaim());
184
+ this.beat();
185
+ }
186
+ /** The person chose to take the claim from whoever holds it. Only from `blocked` and `readOnly`. */
187
+ takeOver() {
188
+ if (!this.canChoose() || (this.state.phase !== 'blocked' && this.state.phase !== 'readOnly')) {
189
+ return;
190
+ }
191
+ this.patch({ working: true, actionFailed: false });
192
+ void this.call('takeOver');
193
+ }
194
+ /** The person chose to only look, for now. Only from `blocked`. */
195
+ openReadOnly() {
196
+ if (!this.canChoose() || this.state.phase !== 'blocked')
197
+ return;
198
+ this.patch({ phase: 'readOnly', lostIt: false, nobodyIsEditing: false, actionFailed: false });
199
+ void this.call('look');
200
+ }
201
+ /** The person chose to begin editing after looking. Only from `readOnly`. */
202
+ startEditing() {
203
+ if (!this.canChoose() || this.state.phase !== 'readOnly')
204
+ return;
205
+ this.patch({ working: true, actionFailed: false });
206
+ void this.call('startEditing');
207
+ }
208
+ canChoose() {
209
+ return this.started && !this.disposed && !this.stopped;
210
+ }
211
+ // ---------------------------------------------------------------------------------------------
212
+ // Ending
213
+ // ---------------------------------------------------------------------------------------------
214
+ /** Stops everything, gives the claim up, and ignores any answer still on its way. */
215
+ dispose() {
216
+ if (this.disposed)
217
+ return;
218
+ this.disposed = true;
219
+ this.clearTimer();
220
+ this.inFlight?.abort();
221
+ this.inFlight = null;
222
+ this.removeWakeListener?.();
223
+ this.removeHideListener?.();
224
+ this.releaseClaim();
225
+ this.stateListeners.clear();
226
+ }
227
+ // ---------------------------------------------------------------------------------------------
228
+ // The calls
229
+ // ---------------------------------------------------------------------------------------------
230
+ /** The renewal the timer asks for: only while the tab is on screen (a hidden tab's claim is left to run out). */
231
+ beat() {
232
+ if (this.disposed || this.stopped)
233
+ return;
234
+ if (!this.environment.isVisible()) {
235
+ this.scheduleBeat();
236
+ return;
237
+ }
238
+ void this.call('beat');
239
+ }
240
+ /** The tab came back to the screen (or the network did): ask at once instead of waiting for the timer. */
241
+ wake() {
242
+ if (this.disposed || this.stopped || !this.started)
243
+ return;
244
+ if (!this.environment.isVisible())
245
+ return;
246
+ if (this.now() - this.lastAnswerAt < WAKE_MIN_GAP_MS)
247
+ return;
248
+ void this.call('beat');
249
+ }
250
+ async call(kind) {
251
+ if (this.disposed || this.stopped)
252
+ return;
253
+ if (this.inFlight) {
254
+ // A renewal never overlaps another call; a choice of the person takes the place of the one on its way.
255
+ if (kind === 'beat')
256
+ return;
257
+ this.inFlight.abort();
258
+ }
259
+ this.clearTimer();
260
+ const generation = ++this.generation;
261
+ const controller = new AbortController();
262
+ this.inFlight = controller;
263
+ try {
264
+ const answer = await this.send(kind, controller.signal);
265
+ if (this.disposed || generation !== this.generation)
266
+ return;
267
+ this.apply(kind, answer);
268
+ }
269
+ catch (error) {
270
+ if (this.disposed || generation !== this.generation)
271
+ return;
272
+ this.fail(kind, error);
273
+ }
274
+ finally {
275
+ if (generation === this.generation) {
276
+ this.inFlight = null;
277
+ this.scheduleBeat();
278
+ }
279
+ }
280
+ }
281
+ send(kind, signal) {
282
+ switch (kind) {
283
+ case 'takeOver':
284
+ return this.port.takeOver(this.sessionId, { signal });
285
+ case 'startEditing':
286
+ return this.port.acquire(this.sessionId, { signal });
287
+ case 'look':
288
+ return this.port.peek({ signal });
289
+ default:
290
+ // A tab that only looks asks who is editing; one that edits (or is asked to wait) asks to edit.
291
+ return this.state.phase === 'readOnly'
292
+ ? this.port.peek({ signal })
293
+ : this.port.acquire(this.sessionId, { signal });
294
+ }
295
+ }
296
+ /** What an answer changes. `kind` and the phase tell which question it answers. */
297
+ apply(kind, answer) {
298
+ // An answer that says "cannot tell" (or that nobody can read) counts as a failure for the pace of the next ask; an
299
+ // answer that tells ends the streak.
300
+ const tells = answer.outcome === 'held' ||
301
+ answer.outcome === 'held_by_other' ||
302
+ answer.outcome === 'free' ||
303
+ answer.outcome === 'not_applicable';
304
+ this.failureStreak = tells ? 0 : this.failureStreak + 1;
305
+ this.lastAnswerAt = this.now();
306
+ if (typeof answer.heartbeatSeconds === 'number' && answer.heartbeatSeconds > 0) {
307
+ this.heartbeatMs = clampHeartbeat(answer.heartbeatSeconds * 1000);
308
+ }
309
+ const phaseBefore = this.state.phase;
310
+ // Only a look (asked for, or the renewal of a tab that only looks) is answered about the others; the rest asked to edit.
311
+ const wasLooking = kind === 'look' || (kind === 'beat' && phaseBefore === 'readOnly');
312
+ if (answer.outcome === 'not_applicable') {
313
+ this.stop();
314
+ return;
315
+ }
316
+ if (wasLooking) {
317
+ if (answer.outcome === 'held_by_other') {
318
+ this.patch({ holder: answer.holder ?? null, nobodyIsEditing: false });
319
+ }
320
+ else if (answer.outcome === 'free') {
321
+ this.patch({ holder: null, nobodyIsEditing: true });
322
+ }
323
+ // `unavailable` (or an answer that makes no sense for a look): what was known stays.
324
+ return;
325
+ }
326
+ if (answer.outcome === 'held') {
327
+ this.holding = true;
328
+ this.patch({
329
+ phase: 'editing',
330
+ holder: null,
331
+ lostIt: false,
332
+ nobodyIsEditing: false,
333
+ working: false,
334
+ actionFailed: false
335
+ });
336
+ return;
337
+ }
338
+ if (answer.outcome === 'held_by_other') {
339
+ this.holding = false;
340
+ this.patch({
341
+ phase: 'blocked',
342
+ holder: answer.holder ?? null,
343
+ // A claim that was this tab's and is not any more is told so, unlike a tab that arrived to find it held; and
344
+ // once told, it stays told for as long as the card is up (the next renewal finds the same thing).
345
+ lostIt: phaseBefore === 'blocked'
346
+ ? this.state.lostIt
347
+ : phaseBefore === 'editing' && kind === 'beat',
348
+ nobodyIsEditing: false,
349
+ working: false,
350
+ actionFailed: false
351
+ });
352
+ return;
353
+ }
354
+ // `unavailable` (or `free`, which asking to edit never answers): the editor goes on as it was, and the person's choice
355
+ // that was waiting for this answer can be tried again.
356
+ if (kind === 'takeOver' || kind === 'startEditing') {
357
+ this.patch({ working: false, actionFailed: true });
358
+ }
359
+ }
360
+ fail(kind, error) {
361
+ const { status, cancelled } = describeFailure(error);
362
+ // A call this controller cancelled itself says nothing about the API.
363
+ if (cancelled)
364
+ return;
365
+ if (status === 400) {
366
+ // The API understood the request as malformed: a bug of this editor, not a condition to wait out.
367
+ this.logger.warn('[EditLease] The API refused the request as malformed; presence is off for this tab:', error);
368
+ this.stop();
369
+ return;
370
+ }
371
+ if (status === 403 || status === 404) {
372
+ // The person may not write to this workflow, or it is not theirs to see: no presence, and nothing to say.
373
+ this.stop();
374
+ return;
375
+ }
376
+ // A network that is down, a server that failed, a session that ended and may be renewed: presence is a convenience,
377
+ // so the editor goes on as it was and asks again later, further apart each time.
378
+ this.failureStreak += 1;
379
+ if (kind === 'takeOver' || kind === 'startEditing') {
380
+ this.patch({ working: false, actionFailed: true });
381
+ }
382
+ }
383
+ /** The API said there is no presence here (or refused for good): edit freely, and stop asking. */
384
+ stop() {
385
+ this.stopped = true;
386
+ this.clearTimer();
387
+ this.inFlight?.abort();
388
+ this.inFlight = null;
389
+ this.generation += 1;
390
+ this.patch({
391
+ phase: 'off',
392
+ holder: null,
393
+ lostIt: false,
394
+ nobodyIsEditing: false,
395
+ working: false,
396
+ actionFailed: false
397
+ });
398
+ }
399
+ // ---------------------------------------------------------------------------------------------
400
+ // Internals
401
+ // ---------------------------------------------------------------------------------------------
402
+ scheduleBeat() {
403
+ this.clearTimer();
404
+ if (this.disposed || this.stopped)
405
+ return;
406
+ const waits = this.heartbeatMs * (1 + Math.min(this.failureStreak, MAX_BACKOFF_STEPS));
407
+ this.timerHandle = this.timers.setTimeout(() => {
408
+ this.timerHandle = null;
409
+ this.beat();
410
+ }, waits);
411
+ }
412
+ clearTimer() {
413
+ if (this.timerHandle === null)
414
+ return;
415
+ this.timers.clearTimeout(this.timerHandle);
416
+ this.timerHandle = null;
417
+ }
418
+ /** Gives the claim up, if this tab holds it, with a request that outlives the page. Never throws, never waits. */
419
+ releaseClaim() {
420
+ if (!this.holding)
421
+ return;
422
+ this.holding = false;
423
+ try {
424
+ void this.port.release(this.sessionId, { keepalive: true }).catch(() => {
425
+ // The claim runs out by itself within the time the API gave: a failure to give it up costs a teammate seconds.
426
+ });
427
+ }
428
+ catch (error) {
429
+ this.logger.error('[EditLease] The claim could not be given up:', error);
430
+ }
431
+ }
432
+ /** Makes the next state out of the changes and tells the watchers, once, when something changed. */
433
+ patch(changes) {
434
+ const next = withDerived({ ...this.state, ...changes });
435
+ const unchanged = Object.keys(next).every((key) => key === 'holder' ? sameHolder(this.state.holder, next.holder) : this.state[key] === next[key]);
436
+ if (unchanged)
437
+ return;
438
+ this.state = next;
439
+ for (const listener of [...this.stateListeners]) {
440
+ try {
441
+ listener(this.state);
442
+ }
443
+ catch (error) {
444
+ this.logger.error('[EditLease] A state listener failed:', error);
445
+ }
446
+ }
447
+ }
448
+ }
449
+ /** Two holders are the same when nothing a person could see differs; an answer that repeats itself changes nothing. */
450
+ function sameHolder(left, right) {
451
+ if (left === right)
452
+ return true;
453
+ if (!left || !right)
454
+ return false;
455
+ return (left.id === right.id &&
456
+ left.name === right.name &&
457
+ left.isYou === right.isYou &&
458
+ left.since === right.since);
459
+ }