@praxisjs/core 2.1.0 → 2.2.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 (56) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/__tests__/batch.test.js +52 -1
  3. package/dist/__tests__/batch.test.js.map +1 -1
  4. package/dist/__tests__/computed.test.js +37 -0
  5. package/dist/__tests__/computed.test.js.map +1 -1
  6. package/dist/__tests__/effect.test.js +11 -0
  7. package/dist/__tests__/effect.test.js.map +1 -1
  8. package/dist/__tests__/persisted-signal.test.js +97 -1
  9. package/dist/__tests__/persisted-signal.test.js.map +1 -1
  10. package/dist/__tests__/reactive.test.js +35 -0
  11. package/dist/__tests__/reactive.test.js.map +1 -1
  12. package/dist/__tests__/signal.test.js +68 -0
  13. package/dist/__tests__/signal.test.js.map +1 -1
  14. package/dist/internal.d.ts +1 -1
  15. package/dist/internal.d.ts.map +1 -1
  16. package/dist/internal.js.map +1 -1
  17. package/dist/reactive/history.d.ts +2 -0
  18. package/dist/reactive/history.d.ts.map +1 -1
  19. package/dist/reactive/history.js +2 -1
  20. package/dist/reactive/history.js.map +1 -1
  21. package/dist/signal/batch.d.ts.map +1 -1
  22. package/dist/signal/batch.js +22 -8
  23. package/dist/signal/batch.js.map +1 -1
  24. package/dist/signal/computed.d.ts.map +1 -1
  25. package/dist/signal/computed.js +11 -0
  26. package/dist/signal/computed.js.map +1 -1
  27. package/dist/signal/effect.d.ts +3 -1
  28. package/dist/signal/effect.d.ts.map +1 -1
  29. package/dist/signal/effect.js +11 -2
  30. package/dist/signal/effect.js.map +1 -1
  31. package/dist/signal/index.d.ts +1 -1
  32. package/dist/signal/index.d.ts.map +1 -1
  33. package/dist/signal/index.js.map +1 -1
  34. package/dist/signal/persisted.d.ts +11 -1
  35. package/dist/signal/persisted.d.ts.map +1 -1
  36. package/dist/signal/persisted.js +39 -5
  37. package/dist/signal/persisted.js.map +1 -1
  38. package/dist/signal/signal.d.ts +2 -2
  39. package/dist/signal/signal.d.ts.map +1 -1
  40. package/dist/signal/signal.js +9 -20
  41. package/dist/signal/signal.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/__tests__/batch.test.ts +51 -0
  44. package/src/__tests__/computed.test.ts +43 -0
  45. package/src/__tests__/effect.test.ts +15 -0
  46. package/src/__tests__/persisted-signal.test.ts +112 -1
  47. package/src/__tests__/reactive.test.ts +38 -0
  48. package/src/__tests__/signal.test.ts +78 -0
  49. package/src/internal.ts +1 -0
  50. package/src/reactive/history.ts +4 -1
  51. package/src/signal/batch.ts +20 -6
  52. package/src/signal/computed.ts +11 -1
  53. package/src/signal/effect.ts +12 -3
  54. package/src/signal/index.ts +1 -1
  55. package/src/signal/persisted.ts +54 -5
  56. package/src/signal/signal.ts +8 -13
@@ -1,6 +1,7 @@
1
1
  import { describe, it, expect, vi } from "vitest";
2
2
 
3
3
  import { computed, writableComputed } from "../signal/computed";
4
+ import { effect } from "../signal/effect";
4
5
  import { signal } from "../signal/signal";
5
6
 
6
7
  describe("computed", () => {
@@ -288,3 +289,45 @@ describe("writableComputed", () => {
288
289
  expect(wc()).toBe(14);
289
290
  });
290
291
  });
292
+
293
+ describe("computed.dispose", () => {
294
+ type Disposable<T> = (() => T) & { dispose(): void };
295
+
296
+ it("does nothing while an effect still depends on it", async () => {
297
+ const s = signal(1);
298
+ const c = computed(() => s() * 2) as unknown as Disposable<number>;
299
+ let seen = 0;
300
+ effect(() => {
301
+ seen = c();
302
+ });
303
+ c.dispose();
304
+ s.set(2);
305
+ await Promise.resolve();
306
+ expect(seen).toBe(4);
307
+ });
308
+
309
+ it("does nothing while another computed depends on it", () => {
310
+ const s = signal(1);
311
+ const inner = computed(() => s() * 2) as unknown as Disposable<number>;
312
+ const outer = computed(() => inner() + 1);
313
+ expect(outer()).toBe(3);
314
+ inner.dispose();
315
+ s.set(2);
316
+ expect(outer()).toBe(5);
317
+ });
318
+
319
+ it("recomputes from scratch when read again after disposal", () => {
320
+ const getter = vi.fn(() => 42);
321
+ const c = computed(getter) as unknown as Disposable<number>;
322
+ c();
323
+ c.dispose();
324
+ expect(c()).toBe(42);
325
+ expect(getter).toHaveBeenCalledTimes(2);
326
+ });
327
+
328
+ it("is safe on a computed that was never read", () => {
329
+ const c = computed(() => 1) as unknown as Disposable<number>;
330
+ expect(() => { c.dispose(); }).not.toThrow();
331
+ expect(c()).toBe(1);
332
+ });
333
+ });
@@ -194,6 +194,21 @@ describe("effect", () => {
194
194
  expect(unmatchedArrayHolder.subs).toEqual([other]);
195
195
  });
196
196
 
197
+ it("cleanupEffectDeps handles Set dependency holders, emptying them to null", () => {
198
+ const tracked = vi.fn();
199
+ const other = vi.fn();
200
+ const sharedHolder: SubscriberHolder = { subs: new Set([tracked, other]) };
201
+ const soleHolder: SubscriberHolder = { subs: new Set([tracked]) };
202
+
203
+ recordDependency(tracked, sharedHolder);
204
+ recordDependency(tracked, soleHolder);
205
+
206
+ cleanupEffectDeps(tracked);
207
+
208
+ expect([...(sharedHolder.subs as Set<() => void>)]).toEqual([other]);
209
+ expect(soleHolder.subs).toBeNull();
210
+ });
211
+
197
212
  it("exception inside nested track() restores outer activeEffect", () => {
198
213
  const s = signal(0);
199
214
  const outer = vi.fn();
@@ -1,5 +1,5 @@
1
1
  // @vitest-environment jsdom
2
- import { describe, it, expect, beforeEach, vi } from "vitest";
2
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
3
3
 
4
4
  import { persistedSignal } from "../signal/persisted";
5
5
 
@@ -191,4 +191,115 @@ describe("persistedSignal", () => {
191
191
  // Should stay at 20 since the event is from sessionStorage, not localStorage
192
192
  expect(s()).toBe(20);
193
193
  });
194
+
195
+ it("close() stops storage-event syncing but keeps the signal working locally", () => {
196
+ const s = persistedSignal("close-key", 0);
197
+ s.close();
198
+ window.dispatchEvent(
199
+ new StorageEvent("storage", { key: "close-key", newValue: "5", storageArea: localStorage }),
200
+ );
201
+ expect(s()).toBe(0);
202
+ s.set(3);
203
+ expect(s()).toBe(3);
204
+ expect(localStorage.getItem("close-key")).toBe("3");
205
+ });
206
+
207
+ it("close() removes the window listener and is safe to call twice", () => {
208
+ const remove = vi.spyOn(window, "removeEventListener");
209
+ const s = persistedSignal("close-twice", 0);
210
+ s.close();
211
+ s.close();
212
+ expect(remove.mock.calls.filter(([type]) => type === "storage")).toHaveLength(1);
213
+ remove.mockRestore();
214
+ });
215
+
216
+ it("close() is a no-op when syncTabs is false", () => {
217
+ const remove = vi.spyOn(window, "removeEventListener");
218
+ const s = persistedSignal("close-nosync", 0, { syncTabs: false });
219
+ expect(() => { s.close(); }).not.toThrow();
220
+ expect(remove.mock.calls.filter(([type]) => type === "storage")).toHaveLength(0);
221
+ remove.mockRestore();
222
+ });
223
+ });
224
+
225
+ describe("persistedSignal writeDelay", () => {
226
+ afterEach(() => {
227
+ vi.useRealTimers();
228
+ });
229
+
230
+ it("writes immediately by default", () => {
231
+ const s = persistedSignal("wd-default", 0);
232
+ s.set(1);
233
+ expect(localStorage.getItem("wd-default")).toBe("1");
234
+ });
235
+
236
+ it("holds writes back and flushes the latest value once the delay elapses", () => {
237
+ vi.useFakeTimers();
238
+ const setItem = vi.spyOn(Storage.prototype, "setItem");
239
+ const s = persistedSignal("wd-burst", 0, { writeDelay: 100 });
240
+ s.set(1);
241
+ s.set(2);
242
+ s.update((n) => n + 1);
243
+ expect(s()).toBe(3);
244
+ expect(localStorage.getItem("wd-burst")).toBeNull();
245
+ vi.advanceTimersByTime(100);
246
+ expect(localStorage.getItem("wd-burst")).toBe("3");
247
+ expect(setItem.mock.calls.filter(([k]) => k === "wd-burst")).toHaveLength(1);
248
+ setItem.mockRestore();
249
+ });
250
+
251
+ it("starts a new window for writes after a flush", () => {
252
+ vi.useFakeTimers();
253
+ const s = persistedSignal("wd-next", 0, { writeDelay: 50 });
254
+ s.set(1);
255
+ vi.advanceTimersByTime(50);
256
+ s.set(2);
257
+ expect(localStorage.getItem("wd-next")).toBe("1");
258
+ vi.advanceTimersByTime(50);
259
+ expect(localStorage.getItem("wd-next")).toBe("2");
260
+ });
261
+
262
+ it("flushes pending data on pagehide", () => {
263
+ vi.useFakeTimers();
264
+ const s = persistedSignal("wd-hide", 0, { writeDelay: 1000 });
265
+ s.set(5);
266
+ window.dispatchEvent(new Event("pagehide"));
267
+ expect(localStorage.getItem("wd-hide")).toBe("5");
268
+ vi.advanceTimersByTime(1000);
269
+ expect(localStorage.getItem("wd-hide")).toBe("5");
270
+ });
271
+
272
+ it("close() flushes pending data and stops listening for pagehide", () => {
273
+ vi.useFakeTimers();
274
+ const s = persistedSignal("wd-close", 0, { writeDelay: 1000 });
275
+ s.set(7);
276
+ s.close();
277
+ expect(localStorage.getItem("wd-close")).toBe("7");
278
+ s.set(8);
279
+ window.dispatchEvent(new Event("pagehide"));
280
+ expect(localStorage.getItem("wd-close")).toBe("7");
281
+ });
282
+
283
+ it("a value arriving from another tab discards the pending local write", () => {
284
+ vi.useFakeTimers();
285
+ const s = persistedSignal("wd-remote", 0, { writeDelay: 100 });
286
+ s.set(1);
287
+ localStorage.setItem("wd-remote", "9");
288
+ window.dispatchEvent(
289
+ new StorageEvent("storage", { key: "wd-remote", newValue: "9", storageArea: localStorage }),
290
+ );
291
+ vi.advanceTimersByTime(100);
292
+ expect(s()).toBe(9);
293
+ expect(localStorage.getItem("wd-remote")).toBe("9");
294
+ });
295
+
296
+ it("removes null and undefined values when the write is flushed", () => {
297
+ vi.useFakeTimers();
298
+ const s = persistedSignal<number | null>("wd-null", 1, { writeDelay: 10 });
299
+ s.set(2);
300
+ vi.advanceTimersByTime(10);
301
+ s.set(null);
302
+ vi.advanceTimersByTime(10);
303
+ expect(localStorage.getItem("wd-null")).toBeNull();
304
+ });
194
305
  });
@@ -303,3 +303,41 @@ describe("history", () => {
303
303
  expect(snapshot1).not.toBe(snapshot2);
304
304
  });
305
305
  });
306
+
307
+ describe("history.destroy", () => {
308
+ it("stops recording changes but keeps what was recorded", () => {
309
+ const s = signal(0);
310
+ const h = history(s);
311
+ s.set(1);
312
+ h.destroy();
313
+ s.set(2);
314
+ s.set(3);
315
+ expect(h.values()).toEqual([0, 1]);
316
+ expect(h.current()).toBe(1);
317
+ });
318
+
319
+ it("can still undo recorded entries after destroy", () => {
320
+ const s = signal(0);
321
+ const h = history(s);
322
+ s.set(1);
323
+ h.destroy();
324
+ h.undo();
325
+ expect(s()).toBe(0);
326
+ });
327
+ });
328
+
329
+ describe("history with a computed source", () => {
330
+ it("undo and redo move the tracked value without writing back to the read-only source", async () => {
331
+ const s = signal(0);
332
+ const source = computed(() => s());
333
+ const h = history(source);
334
+ s.set(1);
335
+ await Promise.resolve();
336
+ h.undo();
337
+ expect(h.current()).toBe(0);
338
+ expect(s()).toBe(1);
339
+ h.redo();
340
+ expect(h.current()).toBe(1);
341
+ expect(s()).toBe(1);
342
+ });
343
+ });
@@ -1,6 +1,8 @@
1
1
  import { describe, it, expect } from "vitest";
2
2
 
3
3
  import { batch } from "../signal/batch";
4
+ import { SUBS_SET_THRESHOLD } from "../signal/effect";
5
+ import { effect } from "../signal/effect";
4
6
  import { signal, addSub, removeSub, type SubList } from "../signal/signal";
5
7
  import type { Effect } from "../signal/effect";
6
8
 
@@ -211,3 +213,79 @@ describe("signal", () => {
211
213
  expect(calls.length).toBe(before);
212
214
  });
213
215
  });
216
+
217
+ describe("large subscriber lists", () => {
218
+ function fns(count: number): Array<() => void> {
219
+ return Array.from({ length: count }, () => () => {});
220
+ }
221
+
222
+ it("keeps an array up to the threshold and promotes to a Set past it, preserving order", () => {
223
+ const holder: { subs: SubList } = { subs: null };
224
+ const list = fns(SUBS_SET_THRESHOLD);
225
+ for (const fn of list) addSub(holder, fn);
226
+ expect(Array.isArray(holder.subs)).toBe(true);
227
+
228
+ const extra = () => {};
229
+ addSub(holder, extra);
230
+ expect(holder.subs).toBeInstanceOf(Set);
231
+ expect([...(holder.subs as Set<() => void>)]).toEqual([...list, extra]);
232
+ });
233
+
234
+ it("addSub on a Set holder adds new subscribers and ignores duplicates", () => {
235
+ const list = fns(SUBS_SET_THRESHOLD + 1);
236
+ const holder: { subs: SubList } = { subs: new Set(list) };
237
+ addSub(holder, list[0]);
238
+ expect((holder.subs as Set<() => void>).size).toBe(list.length);
239
+ const extra = () => {};
240
+ addSub(holder, extra);
241
+ expect((holder.subs as Set<() => void>).size).toBe(list.length + 1);
242
+ });
243
+
244
+ it("removeSub on a Set holder removes one subscriber, ignores unknown ones, and normalizes to null when emptied", () => {
245
+ const [a, b, stranger] = fns(3);
246
+ const holder: { subs: SubList } = { subs: new Set([a, b]) };
247
+ removeSub(holder, stranger);
248
+ expect((holder.subs as Set<() => void>).size).toBe(2);
249
+ removeSub(holder, a);
250
+ expect([...(holder.subs as Set<() => void>)]).toEqual([b]);
251
+ removeSub(holder, b);
252
+ expect(holder.subs).toBeNull();
253
+ });
254
+
255
+ it("many effects on one signal all re-run once per change, in subscription order", () => {
256
+ const count = SUBS_SET_THRESHOLD * 3;
257
+ const s = signal(0);
258
+ const order: number[] = [];
259
+ const stops = Array.from({ length: count }, (_, i) =>
260
+ effect(() => {
261
+ void s();
262
+ order.push(i);
263
+ }),
264
+ );
265
+ order.length = 0;
266
+ s.set(1);
267
+ expect(order).toEqual(Array.from({ length: count }, (_, i) => i));
268
+ order.length = 0;
269
+ s.set(2);
270
+ expect(order).toEqual(Array.from({ length: count }, (_, i) => i));
271
+ stops.forEach((stop) => { stop(); });
272
+ order.length = 0;
273
+ s.set(3);
274
+ expect(order).toEqual([]);
275
+ });
276
+
277
+ it("an effect stopped while the signal holds a Set no longer runs, the others still do", () => {
278
+ const s = signal(0);
279
+ const runs = new Map<number, number>();
280
+ const stops = Array.from({ length: SUBS_SET_THRESHOLD + 4 }, (_, i) =>
281
+ effect(() => {
282
+ void s();
283
+ runs.set(i, (runs.get(i) ?? 0) + 1);
284
+ }),
285
+ );
286
+ stops[2]();
287
+ s.set(1);
288
+ expect(runs.get(2)).toBe(1);
289
+ expect(runs.get(3)).toBe(2);
290
+ });
291
+ });
package/src/internal.ts CHANGED
@@ -16,6 +16,7 @@ export {
16
16
  effect,
17
17
  untrack,
18
18
  type PersistedSignalOptions,
19
+ type PersistedSignal,
19
20
  type SyncedSignal,
20
21
  } from "./signal";
21
22
  export { RootComponent } from "./component";
@@ -12,6 +12,8 @@ export interface HistoryElement<T> {
12
12
  undo(): void;
13
13
  redo(): void;
14
14
  clear(): void;
15
+ /** Stops tracking the source. Existing entries stay readable; no new ones are recorded. */
16
+ destroy(): void;
15
17
  }
16
18
 
17
19
  export function history<T>(
@@ -25,7 +27,7 @@ export function history<T>(
25
27
  let _ignoreNext = false;
26
28
  let _initialized = false;
27
29
 
28
- effect(() => {
30
+ const stop = effect(() => {
29
31
  const value = source();
30
32
 
31
33
  if (!_initialized) {
@@ -83,5 +85,6 @@ export function history<T>(
83
85
  _past.set([]);
84
86
  _future.set([]);
85
87
  },
88
+ destroy: stop,
86
89
  };
87
90
  }
@@ -1,6 +1,6 @@
1
1
  import type { Effect } from "./effect";
2
2
 
3
- const batchEffects: Effect[] = [];
3
+ const batchEffects = new Set<Effect>();
4
4
  let batchDepth = 0;
5
5
 
6
6
  export function isBatching(): boolean {
@@ -8,7 +8,7 @@ export function isBatching(): boolean {
8
8
  }
9
9
 
10
10
  export function enqueueEffect(effect: Effect): void {
11
- if (!batchEffects.includes(effect)) batchEffects.push(effect);
11
+ batchEffects.add(effect);
12
12
  }
13
13
 
14
14
  export function batch(fn: () => void) {
@@ -16,10 +16,24 @@ export function batch(fn: () => void) {
16
16
  try {
17
17
  fn();
18
18
  } finally {
19
- if (--batchDepth === 0) {
20
- const n = batchEffects.length;
21
- for (let i = 0; i < n; i++) batchEffects[i]();
22
- batchEffects.length = 0;
19
+ if (--batchDepth === 0) flush();
20
+ }
21
+ }
22
+
23
+ // The queue is detached before running so a throwing effect can't leave stale entries behind,
24
+ // and every queued effect still runs — matching how notifySubs treats errors outside a batch.
25
+ function flush(): void {
26
+ const queued = [...batchEffects];
27
+ batchEffects.clear();
28
+ let lastError: unknown;
29
+ let hasError = false;
30
+ for (const effect of queued) {
31
+ try {
32
+ effect();
33
+ } catch (e) {
34
+ lastError = e;
35
+ hasError = true;
23
36
  }
24
37
  }
38
+ if (hasError) throw lastError;
25
39
  }
@@ -60,7 +60,17 @@ export function computed<T>(getter: () => T): Computed<T> {
60
60
  return cachedValue as T;
61
61
  }
62
62
 
63
- const c = read as Computed<T>;
63
+ const c = read as Computed<T> & { dispose(): void };
64
+
65
+ // Drops this computed's subscriptions to its sources so an unreachable one (e.g. an evicted
66
+ // @Memo entry) isn't kept alive by the signals it read. Does nothing while anything still
67
+ // depends on it: detaching then would leave those dependents silently stale.
68
+ c.dispose = () => {
69
+ if (leafHolder.subs !== null || computedHolder.subs !== null) return;
70
+ if (recompute !== null) cleanupEffectDeps(recompute);
71
+ dirty = true;
72
+ cachedValue = undefined;
73
+ };
64
74
 
65
75
  c.subscribe = (fn: (value: T) => void) => {
66
76
  const wrapped: Effect = () => { fn(read()); };
@@ -1,21 +1,30 @@
1
1
  export type Effect = () => void;
2
- export type SubList = Effect | Effect[] | null;
2
+ export type SubList = Effect | Effect[] | Set<Effect> | null;
3
3
  export interface SubscriberHolder {
4
4
  subs: SubList;
5
5
  }
6
6
 
7
+ // Past this many subscribers an array makes unsubscribing O(n) per effect re-run, which turns one
8
+ // signal with thousands of bindings into a quadratic update; a Set keeps removal O(1).
9
+ export const SUBS_SET_THRESHOLD = 16;
10
+
7
11
  type TrackedEffect = Effect & { __deps?: Set<SubscriberHolder> };
8
12
 
9
13
  export let activeEffect: Effect | null = null;
10
14
  const effectStack: Effect[] = [];
11
15
 
12
- function removeTrackedSub(holder: SubscriberHolder, eff: Effect): void {
16
+ export function removeSub(holder: SubscriberHolder, eff: Effect): void {
13
17
  const subs = holder.subs;
14
18
  if (subs === null) return;
15
19
  if (typeof subs === "function") {
16
20
  if (subs === eff) holder.subs = null;
17
21
  return;
18
22
  }
23
+ if (subs instanceof Set) {
24
+ subs.delete(eff);
25
+ if (subs.size === 0) holder.subs = null;
26
+ return;
27
+ }
19
28
  const idx = subs.indexOf(eff);
20
29
  if (idx >= 0) subs.splice(idx, 1);
21
30
  if (subs.length === 0) holder.subs = null;
@@ -31,7 +40,7 @@ export function cleanupEffectDeps(eff: Effect): void {
31
40
  const tracked = eff as TrackedEffect;
32
41
  const deps = tracked.__deps;
33
42
  if (!deps) return;
34
- for (const holder of deps) removeTrackedSub(holder, eff);
43
+ for (const holder of deps) removeSub(holder, eff);
35
44
  deps.clear();
36
45
  }
37
46
 
@@ -2,6 +2,6 @@ export { batch } from "./batch";
2
2
  export { peek } from "./peek";
3
3
  export { signal } from "./signal";
4
4
  export { computed, writableComputed } from "./computed";
5
- export { type PersistedSignalOptions, persistedSignal } from "./persisted";
5
+ export { type PersistedSignalOptions, type PersistedSignal, persistedSignal } from "./persisted";
6
6
  export { type SyncedSignal, syncedSignal } from "./synced";
7
7
  export { effect, untrack } from "./effect";
@@ -6,6 +6,17 @@ export interface PersistedSignalOptions<T> {
6
6
  serialize?: (value: T) => string;
7
7
  deserialize?: (value: string) => T;
8
8
  syncTabs?: boolean;
9
+ /**
10
+ * Milliseconds to hold back writes to `localStorage`. Writes within the window are coalesced
11
+ * into one, using the latest value; pending data is flushed on `pagehide` and `close()`.
12
+ * `0` (default) writes on every `set`.
13
+ */
14
+ writeDelay?: number;
15
+ }
16
+
17
+ export interface PersistedSignal<T> extends Signal<T> {
18
+ /** Stops listening for `storage` events from other tabs. The signal keeps working locally. */
19
+ close(): void;
9
20
  }
10
21
 
11
22
  export function persistedSignal<T>(
@@ -17,6 +28,7 @@ export function persistedSignal<T>(
17
28
  serialize = JSON.stringify,
18
29
  deserialize = JSON.parse as (value: string) => T,
19
30
  syncTabs = true,
31
+ writeDelay = 0,
20
32
  } = options;
21
33
 
22
34
  function getStoredValue(): T {
@@ -41,6 +53,29 @@ export function persistedSignal<T>(
41
53
  }
42
54
  }
43
55
 
56
+ let pendingWrite: { value: T } | undefined;
57
+ let writeTimer: ReturnType<typeof setTimeout> | undefined;
58
+
59
+ function flushWrite(): void {
60
+ clearTimeout(writeTimer);
61
+ writeTimer = undefined;
62
+ if (!pendingWrite) return;
63
+ const { value } = pendingWrite;
64
+ pendingWrite = undefined;
65
+ setStoredValue(value);
66
+ }
67
+
68
+ // The timer starts at the first write of a burst (throttle, not debounce) so a value that keeps
69
+ // changing still reaches storage within `writeDelay`.
70
+ function scheduleWrite(value: T): void {
71
+ if (writeDelay <= 0) {
72
+ setStoredValue(value);
73
+ return;
74
+ }
75
+ pendingWrite = { value };
76
+ writeTimer ??= setTimeout(flushWrite, writeDelay);
77
+ }
78
+
44
79
  const inner = signal(getStoredValue());
45
80
 
46
81
  function read() {
@@ -48,19 +83,23 @@ export function persistedSignal<T>(
48
83
  }
49
84
 
50
85
  function set(value: T) {
51
- setStoredValue(value);
86
+ scheduleWrite(value);
52
87
  inner.set(value);
53
88
  }
54
89
 
55
90
  function update(fh: (prev: T) => T) {
56
91
  const newValue = fh(inner());
57
- setStoredValue(newValue);
92
+ scheduleWrite(newValue);
58
93
  inner.set(newValue);
59
94
  }
60
95
 
96
+ let removeStorageListener: (() => void) | undefined;
97
+
61
98
  if (syncTabs) {
62
- window.addEventListener("storage", (event) => {
99
+ const onStorage = (event: StorageEvent): void => {
63
100
  if (event.key !== key || event.storageArea !== localStorage) return;
101
+ // Another tab's value wins; a still-pending local write would overwrite it later.
102
+ pendingWrite = undefined;
64
103
  try {
65
104
  const newValue = event.newValue
66
105
  ? deserialize(event.newValue)
@@ -73,14 +112,24 @@ export function persistedSignal<T>(
73
112
  );
74
113
  inner.set(initialValue);
75
114
  }
76
- });
115
+ };
116
+ window.addEventListener("storage", onStorage);
117
+ removeStorageListener = () => { window.removeEventListener("storage", onStorage); };
77
118
  }
78
119
 
79
- const source = read as Signal<T>;
120
+ if (writeDelay > 0) window.addEventListener("pagehide", flushWrite);
121
+
122
+ const source = read as PersistedSignal<T>;
80
123
  source.set = set;
81
124
  source.update = update;
82
125
  source.subscribe = inner.subscribe.bind(inner);
83
126
  source.__isSignal = true;
127
+ source.close = () => {
128
+ removeStorageListener?.();
129
+ removeStorageListener = undefined;
130
+ window.removeEventListener("pagehide", flushWrite);
131
+ flushWrite();
132
+ };
84
133
 
85
134
  return source;
86
135
  }
@@ -4,6 +4,8 @@ import { isBatching, enqueueEffect } from "./batch";
4
4
  import {
5
5
  activeEffect,
6
6
  recordDependency,
7
+ removeSub,
8
+ SUBS_SET_THRESHOLD,
7
9
  type Effect,
8
10
  type SubList,
9
11
  type SubscriberHolder,
@@ -17,23 +19,16 @@ export function addSub(holder: SubscriberHolder, eff: Effect): void {
17
19
  holder.subs = eff;
18
20
  } else if (typeof subs === "function") {
19
21
  if (subs !== eff) holder.subs = [subs, eff];
20
- } else {
21
- if (!subs.includes(eff)) subs.push(eff);
22
+ } else if (subs instanceof Set) {
23
+ subs.add(eff);
24
+ } else if (!subs.includes(eff)) {
25
+ subs.push(eff);
26
+ if (subs.length > SUBS_SET_THRESHOLD) holder.subs = new Set(subs);
22
27
  }
23
28
  recordDependency(eff, holder);
24
29
  }
25
30
 
26
- export function removeSub(holder: SubscriberHolder, eff: Effect): void {
27
- const subs = holder.subs;
28
- if (subs === null) return;
29
- if (typeof subs === "function") {
30
- if (subs === eff) holder.subs = null;
31
- } else {
32
- const idx = subs.indexOf(eff);
33
- if (idx >= 0) subs.splice(idx, 1);
34
- if (subs.length === 0) holder.subs = null;
35
- }
36
- }
31
+ export { removeSub };
37
32
 
38
33
  export function notifySubs(subs: Exclude<SubList, null>, batching: boolean): void {
39
34
  if (typeof subs === "function") {