Open History to see the last commit
1import { onCleanup } from 'solid-js'
2import type { Accessor, Setter } from 'solid-js'
3β
4/**
5 * Creates a registry of components subscribed to a cache, so each one only updates for the cache
6 * events it cares about.
7 * @returns The `register` and `notify` functions of the registry.
8 */
9export function createCacheSubscriptionRegistry<TCache, TEvent>() {
10 const subscriptions = new Map<
11 symbol,
12 {
13 shouldUpdate: (event: TEvent) => boolean
14 update: (cache: Accessor<TCache>) => void
15 }
16 >()
17β
18 /**
19 * Registers a subscription that is removed when the current owner is cleaned up.
20 * @param callback - Computes the value from the cache.
21 * @param setter - Receives the computed value on every update.
22 * @param shouldUpdate - Decides whether an event updates this subscription. Defaults to every
23 * event.
24 */
25 function register<T>(
26 callback: (
27 cache: Accessor<TCache>,
28 // oxlint-disable-next-line typescript/no-unsafe-function-type -- matches the 'Exclude<T, Function>' that Solid's 'Setter' accepts
29 ) => Exclude<T, Function>,
30 setter: Setter<T>,
31 shouldUpdate: (event: TEvent) => boolean = () => true,
32 ) {
33 const id = Symbol()
34 subscriptions.set(id, {
35 shouldUpdate,
36 update: (cache) => setter(callback(cache)),
37 })
38 onCleanup(() => subscriptions.delete(id))
39 }
40β
41 /**
42 * Updates every subscription whose `shouldUpdate` accepts the event.
43 * @param cache - The cache to compute the values from.
44 * @param event - The cache event.
45 * @param schedule - Runs each update. Defaults to running it right away.
46 */
47 function notify(
48 cache: Accessor<TCache>,
49 event: TEvent,
50 schedule: (update: () => void) => void = (update) => update(),
51 ) {
52 for (const [id, subscription] of subscriptions) {
53 if (!subscription.shouldUpdate(event)) continue
54 schedule(() => {
55 if (subscriptions.has(id)) subscription.update(cache)
56 })
57 }
58 }
59β
60 return { register, notify }
61}