@inflatable-cookie/longhorn-poodle-svelte 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/package.json +4 -4
  2. package/src/bindings/drop-target.ts +39 -0
  3. package/src/bindings/element-geometry.ts +10 -0
  4. package/src/bindings/freeze-projection.ts +11 -0
  5. package/src/bindings/layout.svelte.ts +22 -25
  6. package/src/bindings/lifecycle.svelte.ts +32 -60
  7. package/src/bindings/mount.ts +18 -0
  8. package/src/bindings/optimistic.svelte.ts +6 -16
  9. package/src/bindings/sample-controller.svelte.ts +19 -0
  10. package/src/bindings/scheduler.ts +2 -0
  11. package/src/bindings/session-projection.svelte.ts +98 -0
  12. package/src/bindings/start-stop.ts +64 -0
  13. package/src/bindings/surface-transfer-actions.ts +54 -105
  14. package/src/bindings/surface-transfer.svelte.ts +85 -91
  15. package/src/bindings/surfaces.svelte.ts +34 -31
  16. package/src/bindings/teardown.ts +16 -0
  17. package/src/bindings/transfer-actions.ts +51 -45
  18. package/src/bindings/transfer-model.ts +9 -35
  19. package/src/bindings/transfer.svelte.ts +172 -144
  20. package/src/bindings/window-drag.ts +28 -20
  21. package/src/commands/poodle/CommandPaletteBinding.svelte +72 -13
  22. package/src/commands/poodle/KeybindingSettings.svelte +176 -93
  23. package/src/commands/poodle/projectors.ts +14 -15
  24. package/src/commands/svelte/lifecycle.ts +2 -9
  25. package/src/commands/svelte/session.svelte.ts +25 -35
  26. package/src/config/poodle/BackupSettingsPage.svelte +91 -103
  27. package/src/config/poodle/ConfigSnapshotState.svelte +26 -0
  28. package/src/config/poodle/RestoreSettingsPage.svelte +175 -162
  29. package/src/config/poodle/StorageSettingsPage.svelte +113 -120
  30. package/src/config/poodle/format.ts +15 -0
  31. package/src/config/poodle/page-state.svelte.ts +81 -0
  32. package/src/config/poodle/restore-model.ts +89 -22
  33. package/src/failures.ts +14 -0
  34. package/src/history/svelte/lifecycle.ts +2 -9
  35. package/src/history/svelte/session.svelte.ts +79 -42
  36. package/src/history-tree/svelte/lifecycle.ts +3 -8
  37. package/src/history-tree/svelte/session.svelte.ts +121 -19
  38. package/src/history-tree/svelte.ts +4 -1
  39. package/src/licence/poodle/LicenceActivation.svelte +50 -10
  40. package/src/licence/poodle/LicenceSurface.svelte.ts +36 -37
  41. package/src/native-content/lifecycle.ts +2 -9
  42. package/src/native-content/session.svelte.ts +116 -151
  43. package/src/native-content/viewport.ts +3 -1
  44. package/src/native-content/visibility.ts +1 -1
  45. package/src/notifications/poodle/NotificationPanel.svelte +98 -15
  46. package/src/notifications/poodle/NotificationToastHost.svelte +14 -23
  47. package/src/notifications/poodle/NotificationToastStack.svelte +8 -16
  48. package/src/notifications/poodle/projectors.ts +5 -3
  49. package/src/notifications/poodle/toasts.ts +34 -0
  50. package/src/notifications/svelte/lifecycle.ts +2 -7
  51. package/src/notifications/svelte/session.svelte.ts +116 -50
  52. package/src/operation/poodle/OperationPanel.svelte +22 -25
  53. package/src/operation/poodle/projectors.ts +8 -18
  54. package/src/operation/svelte/lifecycle.ts +2 -9
  55. package/src/operation/svelte/session.svelte.ts +70 -37
  56. package/src/poodle/LayoutDockRegion.svelte +11 -23
  57. package/src/poodle/LayoutSplitView.svelte +18 -14
  58. package/src/poodle/LayoutTabs.svelte +10 -18
  59. package/src/poodle/binding.ts +51 -92
  60. package/src/poodle/document.ts +12 -33
  61. package/src/poodle/index.ts +1 -4
  62. package/src/poodle/projectors.ts +21 -47
  63. package/src/poodle/transfer.ts +39 -90
  64. package/src/poodle/types.ts +6 -13
  65. package/src/settings/poodle/SettingsShell.svelte +168 -61
  66. package/src/settings/svelte/context.ts +6 -13
  67. package/src/settings/svelte/document.svelte.ts +65 -43
  68. package/src/settings/svelte/errors.ts +1 -4
  69. package/src/settings/svelte/lifecycle.ts +3 -1
  70. package/src/settings/svelte/page.svelte.ts +33 -39
  71. package/src/settings/svelte/runtime.svelte.ts +161 -81
  72. package/src/settings/svelte/scope.svelte.ts +47 -56
  73. package/src/settings/svelte/session.svelte.ts +30 -24
  74. package/src/settings/svelte/types.ts +4 -10
  75. package/src/update/poodle/UpdateCentre.svelte +14 -30
  76. package/src/update/poodle/UpdateSettings.svelte +10 -7
  77. package/src/update/poodle/UpdateStatus.svelte +12 -26
  78. package/src/update/poodle/UpdateSurface.svelte.ts +112 -72
  79. package/src/svelte.d.ts +0 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inflatable-cookie/longhorn-poodle-svelte",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -151,9 +151,9 @@
151
151
  "LICENSE"
152
152
  ],
153
153
  "peerDependencies": {
154
- "@inflatable-cookie/longhorn": "0.5.0",
155
- "@inflatable-cookie/poodle-core": ">=0.4.4 <0.5",
156
- "@inflatable-cookie/poodle-svelte": ">=0.4.4 <0.5",
154
+ "@inflatable-cookie/longhorn": "0.7.0",
155
+ "@inflatable-cookie/poodle-core": ">=0.5.0 <0.6",
156
+ "@inflatable-cookie/poodle-svelte": ">=0.5.0 <0.6",
157
157
  "svelte": ">=5.56.8 <6"
158
158
  },
159
159
  "peerDependenciesMeta": {
@@ -0,0 +1,39 @@
1
+ import type { TransferCommitSelector } from "@inflatable-cookie/longhorn/transfer";
2
+
3
+ export type DropSelector =
4
+ | { readonly kind: "explicit_zone"; readonly dropZoneId: string }
5
+ | { readonly kind: "screen_point" };
6
+
7
+ export function resolveDropSelector(
8
+ selector: DropSelector,
9
+ screenPoint: (() => { readonly x: number; readonly y: number }) | undefined,
10
+ ): TransferCommitSelector {
11
+ if (selector.kind === "explicit_zone") {
12
+ return { kind: "explicit_zone", drop_zone_id: selector.dropZoneId };
13
+ }
14
+ const point = screenPoint?.();
15
+ if (point === undefined || !Number.isSafeInteger(point.x) || !Number.isSafeInteger(point.y)) {
16
+ throw new RangeError("drop screen point must use integer screen DIPs");
17
+ }
18
+ return { kind: "screen_point", point: { x: point.x, y: point.y } };
19
+ }
20
+
21
+ export function reportError(reporter: (error: unknown) => void, error: unknown): void {
22
+ try {
23
+ reporter(error);
24
+ } catch {
25
+ // Reporting failure must not escape an event callback.
26
+ }
27
+ }
28
+
29
+ export function notify<Value>(
30
+ listener: ((value: Value) => void) | undefined,
31
+ value: Value,
32
+ reporter: (error: unknown) => void,
33
+ ): void {
34
+ try {
35
+ listener?.(value);
36
+ } catch (error) {
37
+ reportError(reporter, error);
38
+ }
39
+ }
@@ -0,0 +1,10 @@
1
+ /** Client rect origins can move when the window or a nested scroller scrolls. */
2
+ export function observeViewportMovement(node: HTMLElement, changed: () => void): () => void {
3
+ const view = node.ownerDocument.defaultView;
4
+ view?.addEventListener("scroll", changed, { capture: true, passive: true });
5
+ view?.addEventListener("resize", changed);
6
+ return () => {
7
+ view?.removeEventListener("scroll", changed, true);
8
+ view?.removeEventListener("resize", changed);
9
+ };
10
+ }
@@ -0,0 +1,11 @@
1
+ // Only call this on owned protocol data. Errors and other caller values stay opaque.
2
+ export function freezeProjection<Value>(value: Value): Value {
3
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
4
+ Object.freeze(value);
5
+ const children: Array<unknown> = Object.values(value);
6
+ for (const child of children) {
7
+ freezeProjection(child);
8
+ }
9
+ }
10
+ return value;
11
+ }
@@ -3,16 +3,10 @@ import type {
3
3
  LayoutMutationRequest,
4
4
  LayoutMutationReceipt,
5
5
  } from "@inflatable-cookie/longhorn/layout";
6
- import type {
7
- SurfaceDocument,
8
- } from "@inflatable-cookie/longhorn/surfaces";
6
+ import type { SurfaceDocument } from "@inflatable-cookie/longhorn/surfaces";
9
7
 
10
- import {
11
- OptimisticProjectionState,
12
- UnsupportedCapabilityError,
13
- type ClientStatus,
14
- type OptimisticProjector,
15
- } from "./index.ts";
8
+ import { OptimisticProjectionState, UnsupportedCapabilityError } from "./index.ts";
9
+ import type { ClientStatus, OptimisticProjector } from "./index.ts";
16
10
 
17
11
  export type LayoutDispatchResult =
18
12
  | { readonly status: "committed"; readonly receipt: LayoutMutationReceipt }
@@ -21,9 +15,7 @@ export type LayoutDispatchResult =
21
15
  readonly rejection: LayoutMutationRejection;
22
16
  };
23
17
 
24
- export type LayoutDispatcher = (
25
- request: LayoutMutationRequest,
26
- ) => Promise<LayoutDispatchResult>;
18
+ export type LayoutDispatcher = (request: LayoutMutationRequest) => Promise<LayoutDispatchResult>;
27
19
 
28
20
  export interface LayoutStateOptions {
29
21
  readonly dispatch?: LayoutDispatcher;
@@ -37,6 +29,7 @@ export class LayoutState {
37
29
  );
38
30
  #status = $state.raw<ClientStatus>({ kind: "idle" });
39
31
  #destroyed = false;
32
+ #generation = 0;
40
33
 
41
34
  constructor(options: LayoutStateOptions) {
42
35
  this.#options = options;
@@ -54,7 +47,7 @@ export class LayoutState {
54
47
  return this.#projection.projected;
55
48
  }
56
49
 
57
- get pendingRequestIds(): readonly string[] {
50
+ get pendingRequestIds(): ReadonlyArray<string> {
58
51
  return this.#projection.pendingRequestIds;
59
52
  }
60
53
 
@@ -64,9 +57,7 @@ export class LayoutState {
64
57
  this.#options.dispatch === undefined
65
58
  ? {
66
59
  kind: "unsupported",
67
- reason:
68
- this.#options.unsupportedReason ??
69
- "layout dispatch is unavailable",
60
+ reason: this.#options.unsupportedReason ?? "layout dispatch is unavailable",
70
61
  }
71
62
  : { kind: "loading" };
72
63
  }
@@ -74,7 +65,7 @@ export class LayoutState {
74
65
  accept(document: SurfaceDocument): boolean {
75
66
  this.#assertAlive();
76
67
  const accepted = this.#projection.accept(document);
77
- if (accepted) {
68
+ if (accepted && this.#status.kind !== "unsupported") {
78
69
  this.#status = { kind: "ready" };
79
70
  }
80
71
  return accepted;
@@ -82,10 +73,11 @@ export class LayoutState {
82
73
 
83
74
  reconnecting(): void {
84
75
  this.#assertAlive();
76
+ if (this.#status.kind === "unsupported") {
77
+ return;
78
+ }
85
79
  this.#status =
86
- this.#projection.authoritative === undefined
87
- ? { kind: "loading" }
88
- : { kind: "reconnecting" };
80
+ this.#projection.authoritative === undefined ? { kind: "loading" } : { kind: "reconnecting" };
89
81
  }
90
82
 
91
83
  async dispatch(
@@ -95,16 +87,18 @@ export class LayoutState {
95
87
  this.#assertAlive();
96
88
  const dispatch = this.#options.dispatch;
97
89
  if (dispatch === undefined) {
98
- const reason =
99
- this.#options.unsupportedReason ??
100
- "layout dispatch is unavailable";
90
+ const reason = this.#options.unsupportedReason ?? "layout dispatch is unavailable";
101
91
  this.#status = { kind: "unsupported", reason };
102
92
  throw new UnsupportedCapabilityError(reason);
103
93
  }
104
94
 
95
+ const generation = this.#generation;
105
96
  this.#projection.begin(request.request_id, project);
106
97
  try {
107
98
  const result = await dispatch(request);
99
+ if (generation !== this.#generation) {
100
+ return result;
101
+ }
108
102
  const document =
109
103
  result.status === "committed"
110
104
  ? result.receipt.authoritative_document
@@ -113,8 +107,10 @@ export class LayoutState {
113
107
  this.#status = { kind: "ready" };
114
108
  return result;
115
109
  } catch (error) {
116
- this.#projection.cancel(request.request_id);
117
- this.#status = { kind: "failed", error };
110
+ if (generation === this.#generation) {
111
+ this.#projection.cancel(request.request_id);
112
+ this.#status = { kind: "failed", error };
113
+ }
118
114
  throw error;
119
115
  }
120
116
  }
@@ -124,6 +120,7 @@ export class LayoutState {
124
120
  }
125
121
 
126
122
  async stop(): Promise<void> {
123
+ ++this.#generation;
127
124
  this.#projection.clear();
128
125
  this.#status = { kind: "idle" };
129
126
  }
@@ -1,10 +1,12 @@
1
- import { onMount } from "svelte";
1
+ import { useSessionLifecycle } from "./mount.ts";
2
2
 
3
3
  import type {
4
4
  ConnectionFailure,
5
5
  ConnectionFailureReporter,
6
6
  } from "@inflatable-cookie/longhorn/core";
7
7
 
8
+ import { StartStop } from "./start-stop.ts";
9
+
8
10
  export type ClientStatus =
9
11
  | { readonly kind: "idle" }
10
12
  | { readonly kind: "loading" }
@@ -42,16 +44,12 @@ export interface StartableClientState {
42
44
  stop(): Promise<void>;
43
45
  }
44
46
 
45
- export class ReactiveClientState<Snapshot>
46
- implements StartableClientState
47
- {
47
+ export class ReactiveClientState<Snapshot> implements StartableClientState {
48
48
  readonly #options: ReactiveClientStateOptions<Snapshot>;
49
49
  #status = $state.raw<ClientStatus>({ kind: "idle" });
50
50
  #snapshot = $state.raw<Snapshot | undefined>(undefined);
51
51
  #connection: ReactiveConnection<Snapshot> | undefined;
52
- #startTask: Promise<void> | undefined;
53
- #stopTask: Promise<void> | undefined;
54
- #generation = 0;
52
+ readonly #lifecycle = new StartStop();
55
53
  #destroyed = false;
56
54
 
57
55
  constructor(options: ReactiveClientStateOptions<Snapshot>) {
@@ -70,16 +68,7 @@ export class ReactiveClientState<Snapshot>
70
68
  if (this.#destroyed) {
71
69
  return Promise.reject(new ClientStateDestroyedError());
72
70
  }
73
- if (this.#startTask !== undefined) {
74
- return this.#startTask;
75
- }
76
-
77
- const afterStop = this.#stopTask;
78
- this.#startTask =
79
- afterStop === undefined
80
- ? this.#begin(false)
81
- : afterStop.then(() => this.#begin(false));
82
- return this.#startTask;
71
+ return this.#lifecycle.start((generation) => this.#begin(generation, false), true);
83
72
  }
84
73
 
85
74
  reconnect(): Promise<void> {
@@ -90,9 +79,8 @@ export class ReactiveClientState<Snapshot>
90
79
  return Promise.resolve();
91
80
  }
92
81
 
93
- const task = this.#stop(false).then(() => this.#begin(true));
94
- this.#startTask = task;
95
- return task;
82
+ void this.#stop(false).catch(() => undefined);
83
+ return this.#lifecycle.start((generation) => this.#begin(generation, true), true);
96
84
  }
97
85
 
98
86
  stop(): Promise<void> {
@@ -100,10 +88,6 @@ export class ReactiveClientState<Snapshot>
100
88
  }
101
89
 
102
90
  async destroy(): Promise<void> {
103
- if (this.#destroyed) {
104
- await this.#stopTask;
105
- return;
106
- }
107
91
  this.#destroyed = true;
108
92
  await this.#stop(true);
109
93
  }
@@ -114,7 +98,7 @@ export class ReactiveClientState<Snapshot>
114
98
  }
115
99
  }
116
100
 
117
- async #begin(reconnecting: boolean): Promise<void> {
101
+ async #begin(generation: number, reconnecting: boolean): Promise<void> {
118
102
  const capability = this.#options.capability;
119
103
  if (capability.kind === "unsupported") {
120
104
  this.#status = {
@@ -124,36 +108,35 @@ export class ReactiveClientState<Snapshot>
124
108
  return;
125
109
  }
126
110
 
127
- const generation = ++this.#generation;
128
111
  this.#status =
129
- reconnecting || this.#snapshot !== undefined
130
- ? { kind: "reconnecting" }
131
- : { kind: "loading" };
112
+ reconnecting || this.#snapshot !== undefined ? { kind: "reconnecting" } : { kind: "loading" };
132
113
 
133
114
  let connection: ReactiveConnection<Snapshot>;
134
115
  try {
135
116
  connection = capability.connect(
136
117
  (snapshot) => {
137
- if (generation === this.#generation && !this.#destroyed) {
118
+ if (generation === this.#lifecycle.generation && !this.#destroyed) {
138
119
  this.#accept(snapshot);
139
120
  }
140
121
  },
141
122
  (failure) => {
142
- if (generation === this.#generation && !this.#destroyed) {
123
+ if (generation === this.#lifecycle.generation && !this.#destroyed) {
143
124
  this.#status = { kind: "failed", error: failure.error };
144
125
  this.#options.onFailure?.(failure);
145
126
  }
146
127
  },
147
128
  );
148
129
  } catch (error) {
149
- this.#status = { kind: "failed", error };
130
+ if (generation === this.#lifecycle.generation) {
131
+ this.#status = { kind: "failed", error };
132
+ }
150
133
  throw error;
151
134
  }
152
135
  this.#connection = connection;
153
136
 
154
137
  try {
155
138
  await connection.ready;
156
- if (generation !== this.#generation || this.#destroyed) {
139
+ if (generation !== this.#lifecycle.generation || this.#destroyed) {
157
140
  return;
158
141
  }
159
142
  const snapshot = connection.current();
@@ -166,13 +149,14 @@ export class ReactiveClientState<Snapshot>
166
149
  this.#status = { kind: "ready" };
167
150
  }
168
151
  } catch (error) {
169
- if (generation === this.#generation && !this.#destroyed) {
152
+ if (generation === this.#lifecycle.generation) {
170
153
  this.#status = { kind: "failed", error };
171
- }
172
- try {
173
- await connection.dispose();
174
- } catch {
175
- // The connection retains exact teardown failure evidence.
154
+ this.#connection = undefined;
155
+ try {
156
+ await connection.dispose();
157
+ } catch {
158
+ // The connection retains exact teardown failure evidence.
159
+ }
176
160
  }
177
161
  throw error;
178
162
  }
@@ -185,30 +169,23 @@ export class ReactiveClientState<Snapshot>
185
169
  }
186
170
 
187
171
  #stop(clearSnapshot: boolean): Promise<void> {
188
- if (this.#stopTask !== undefined) {
189
- return this.#stopTask;
190
- }
191
-
192
- const connection = this.#connection;
193
- this.#connection = undefined;
194
- this.#startTask = undefined;
195
- ++this.#generation;
196
172
  if (clearSnapshot) {
197
173
  this.#snapshot = undefined;
198
174
  }
199
- this.#status = { kind: "idle" };
200
-
201
- this.#stopTask = (async () => {
175
+ this.#status = { kind: clearSnapshot ? "idle" : "reconnecting" };
176
+ return this.#lifecycle.stop(async () => {
177
+ // A synchronous connect callback can call stop before connect returns.
178
+ // Capture its connection after that call has finished publishing it.
179
+ await Promise.resolve();
180
+ const connection = this.#connection;
181
+ this.#connection = undefined;
202
182
  try {
203
183
  await connection?.dispose();
204
184
  } catch (error) {
205
185
  this.#status = { kind: "failed", error };
206
186
  throw error;
207
- } finally {
208
- this.#stopTask = undefined;
209
187
  }
210
- })();
211
- return this.#stopTask;
188
+ });
212
189
  }
213
190
  }
214
191
 
@@ -237,10 +214,5 @@ export function useClientState(
237
214
  state: StartableClientState,
238
215
  reportFailure?: (error: unknown) => void,
239
216
  ): void {
240
- onMount(() => {
241
- void state.start().catch((error) => reportFailure?.(error));
242
- return () => {
243
- void state.stop().catch((error) => reportFailure?.(error));
244
- };
245
- });
217
+ useSessionLifecycle(() => state, reportFailure, reportFailure);
246
218
  }
@@ -0,0 +1,18 @@
1
+ import { onMount } from "svelte";
2
+
3
+ import { reportFailure } from "../failures.ts";
4
+ import type { StartableClientState } from "./lifecycle.svelte.ts";
5
+
6
+ export function useSessionLifecycle(
7
+ getSession: () => StartableClientState,
8
+ onStartFailure: (error: unknown) => void = () => undefined,
9
+ onStopFailure: (error: unknown) => void = reportFailure,
10
+ ): void {
11
+ onMount(() => {
12
+ const session = getSession();
13
+ void session.start().catch(onStartFailure);
14
+ return () => {
15
+ void session.stop().catch(onStopFailure);
16
+ };
17
+ });
18
+ }
@@ -1,7 +1,5 @@
1
1
  export type RevisionOf<Document> = (document: Document) => number;
2
- export type OptimisticProjector<Document> = (
3
- authoritative: Document,
4
- ) => Document;
2
+ export type OptimisticProjector<Document> = (authoritative: Document) => Document;
5
3
 
6
4
  interface PendingProjection<Document> {
7
5
  readonly requestId: string;
@@ -11,7 +9,7 @@ interface PendingProjection<Document> {
11
9
  export class OptimisticProjectionState<Document> {
12
10
  readonly #revisionOf: RevisionOf<Document>;
13
11
  #authoritative = $state.raw<Document | undefined>(undefined);
14
- #pending = $state.raw<readonly PendingProjection<Document>[]>([]);
12
+ #pending = $state.raw<ReadonlyArray<PendingProjection<Document>>>([]);
15
13
 
16
14
  constructor(revisionOf: RevisionOf<Document>) {
17
15
  this.#revisionOf = revisionOf;
@@ -32,26 +30,20 @@ export class OptimisticProjectionState<Document> {
32
30
  return document;
33
31
  }
34
32
 
35
- get pendingRequestIds(): readonly string[] {
33
+ get pendingRequestIds(): ReadonlyArray<string> {
36
34
  return this.#pending.map(({ requestId }) => requestId);
37
35
  }
38
36
 
39
37
  accept(document: Document): boolean {
40
38
  const current = this.#authoritative;
41
- if (
42
- current !== undefined &&
43
- this.#revisionOf(document) < this.#revisionOf(current)
44
- ) {
39
+ if (current !== undefined && this.#revisionOf(document) < this.#revisionOf(current)) {
45
40
  return false;
46
41
  }
47
42
  this.#authoritative = document;
48
43
  return true;
49
44
  }
50
45
 
51
- begin(
52
- requestId: string,
53
- project: OptimisticProjector<Document>,
54
- ): void {
46
+ begin(requestId: string, project: OptimisticProjector<Document>): void {
55
47
  if (this.#pending.some((pending) => pending.requestId === requestId)) {
56
48
  throw new DuplicateOptimisticRequestError(requestId);
57
49
  }
@@ -70,9 +62,7 @@ export class OptimisticProjectionState<Document> {
70
62
  }
71
63
 
72
64
  cancel(requestId: string): void {
73
- this.#pending = this.#pending.filter(
74
- (pending) => pending.requestId !== requestId,
75
- );
65
+ this.#pending = this.#pending.filter((pending) => pending.requestId !== requestId);
76
66
  }
77
67
 
78
68
  clear(): void {
@@ -0,0 +1,19 @@
1
+ import { untrack } from "svelte";
2
+
3
+ /** Track reads from a plain controller. The owner manages its start and stop. */
4
+ export function sampleController<Controller extends { observe(callback: () => void): () => void }>(
5
+ getController: () => Controller,
6
+ ): () => Controller {
7
+ let revision = $state(0);
8
+
9
+ $effect(() =>
10
+ getController().observe(() => {
11
+ revision = untrack(() => revision) + 1;
12
+ }),
13
+ );
14
+
15
+ return () => {
16
+ void revision;
17
+ return getController();
18
+ };
19
+ }
@@ -1,4 +1,5 @@
1
1
  export interface TimerScheduler {
2
+ // oxlint-disable-next-line quality/no-unknown-returns -- Each scheduler owns the handle it gives back to clear().
2
3
  set(delayMs: number, callback: () => void): unknown;
3
4
  clear(handle: unknown): void;
4
5
  }
@@ -8,6 +9,7 @@ export const systemTimerScheduler: TimerScheduler = {
8
9
  return globalThis.setTimeout(callback, delayMs);
9
10
  },
10
11
  clear(handle) {
12
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- systemTimerScheduler clears handles from its own setTimeout call.
11
13
  globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>);
12
14
  },
13
15
  };
@@ -0,0 +1,98 @@
1
+ import { StartStop } from "./start-stop.ts";
2
+
3
+ interface ObservableController {
4
+ observe(listener: () => void): () => void;
5
+ start(): Promise<void>;
6
+ stop(): Promise<void>;
7
+ restart(): Promise<void>;
8
+ }
9
+
10
+ export class SessionProjection<Projection> {
11
+ readonly #controller: ObservableController;
12
+ readonly #unobserve: () => void;
13
+ readonly #observers = new Set<() => void>();
14
+ readonly #lifetime = new StartStop();
15
+ #current: Projection;
16
+ #retryFailure = $state.raw<{ readonly kind: "failed"; readonly error: unknown }>();
17
+
18
+ constructor(controller: ObservableController, project: () => Projection) {
19
+ this.#controller = controller;
20
+ this.#current = $state.raw(project());
21
+ this.#unobserve = controller.observe(() => {
22
+ this.#current = project();
23
+ this.#notify();
24
+ });
25
+ }
26
+
27
+ get current(): Projection {
28
+ return this.#current;
29
+ }
30
+
31
+ get retryFailure() {
32
+ return this.#retryFailure;
33
+ }
34
+
35
+ observe(observer: () => void): () => void {
36
+ this.#observers.add(observer);
37
+ return () => this.#observers.delete(observer);
38
+ }
39
+
40
+ #setRetryFailure(
41
+ failure: { readonly kind: "failed"; readonly error: unknown } | undefined,
42
+ ): void {
43
+ if (this.#retryFailure !== failure) {
44
+ this.#retryFailure = failure;
45
+ this.#notify();
46
+ }
47
+ }
48
+
49
+ #notify(): void {
50
+ for (const observer of this.#observers) {
51
+ observer();
52
+ }
53
+ }
54
+
55
+ start(): Promise<void> {
56
+ return this.#lifetime.start(() => {
57
+ this.#setRetryFailure(undefined);
58
+ return this.#controller.start();
59
+ }, true);
60
+ }
61
+
62
+ stop(): Promise<void> {
63
+ this.#setRetryFailure(undefined);
64
+ return this.#lifetime.stop(() => this.#controller.stop());
65
+ }
66
+
67
+ async retry(previousError: unknown): Promise<void> {
68
+ this.#setRetryFailure(undefined);
69
+ const teardown = this.#lifetime.stop(async () => {
70
+ try {
71
+ await this.#controller.stop();
72
+ } catch (error) {
73
+ // A checked subscription may repeat its startup failure at teardown.
74
+ if (!Object.is(error, previousError)) {
75
+ throw error;
76
+ }
77
+ }
78
+ });
79
+ const start = this.#lifetime.start(() => {
80
+ this.#setRetryFailure(undefined);
81
+ return this.#controller.restart();
82
+ }, true);
83
+ const generation = this.#lifetime.generation;
84
+ try {
85
+ await Promise.all([teardown, start]);
86
+ } catch (error) {
87
+ if (generation === this.#lifetime.generation) {
88
+ this.#setRetryFailure({ kind: "failed", error });
89
+ }
90
+ throw error;
91
+ }
92
+ }
93
+
94
+ async dispose(): Promise<void> {
95
+ this.#unobserve();
96
+ await this.stop();
97
+ }
98
+ }
@@ -0,0 +1,64 @@
1
+ // A stop invalidates both active callbacks and a start waiting for teardown.
2
+ export class StartStop {
3
+ #generation = 0;
4
+ #startTask: Promise<void> | undefined;
5
+ #stopTask: Promise<void> | undefined;
6
+
7
+ get generation(): number {
8
+ return this.#generation;
9
+ }
10
+
11
+ start(begin: (generation: number) => Promise<void>, retryOnFailure = false): Promise<void> {
12
+ if (this.#startTask !== undefined) {
13
+ return this.#startTask;
14
+ }
15
+
16
+ const generation = ++this.#generation;
17
+ const afterStop = this.#stopTask;
18
+ const { task, invoke } = reserve(async () => {
19
+ try {
20
+ if (afterStop !== undefined) {
21
+ await afterStop;
22
+ }
23
+ if (generation === this.#generation) {
24
+ await begin(generation);
25
+ }
26
+ } catch (error) {
27
+ if (retryOnFailure && generation === this.#generation) {
28
+ this.#startTask = undefined;
29
+ }
30
+ throw error;
31
+ }
32
+ });
33
+ this.#startTask = task;
34
+ invoke();
35
+ return task;
36
+ }
37
+
38
+ stop(end: () => Promise<void>): Promise<void> {
39
+ this.#startTask = undefined;
40
+ ++this.#generation;
41
+ if (this.#stopTask === undefined) {
42
+ const { task, invoke } = reserve(async () => {
43
+ try {
44
+ await end();
45
+ } finally {
46
+ this.#stopTask = undefined;
47
+ }
48
+ });
49
+ this.#stopTask = task;
50
+ invoke();
51
+ return task;
52
+ }
53
+ return this.#stopTask;
54
+ }
55
+ }
56
+
57
+ // StartStop needs to publish the promise before invoking synchronous hooks.
58
+ function reserve(run: () => Promise<void>) {
59
+ let invoke!: () => void;
60
+ const task = new Promise<void>((resolve, reject) => {
61
+ invoke = () => void run().then(resolve, reject);
62
+ });
63
+ return { task, invoke };
64
+ }