Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

revisionedQuery.ts

66 lines2.7 KB

1import * as Option from "effect/Option";
2import { Atom, type AtomRegistry } from "effect/reactivity";
3​
4// Outside the nodes: a node is dropped once unmounted, and the next read must
5// still compare against the revision the query was last read under.
6const readRevisions = new WeakMap<AtomRegistry.AtomRegistry, WeakMap<object, string | null>>();
7​
8// The registry keys serializable atoms' nodes by their key, not the atom.
9const queryKey = (query: Atom.Atom<unknown>) =>
10 Atom.isSerializable(query) ? query[Atom.SerializableTypeId].key : query;
11​
12const makeRevisionedFamily = (query: Atom.Atom<unknown>) =>
13 Atom.family((revision: string | null) =>
14 Atom.readable(
15 (get) => {
16 // Only a node's first build compares: a node still mounted under the old
17 // revision rebuilds when the query refetches, and must not refetch it again.
18 if (Option.isNone(get.self())) {
19 let revisions = readRevisions.get(get.registry);
20 if (revisions === undefined) {
21 revisions = new WeakMap();
22 readRevisions.set(get.registry, revisions);
23 }
24 const stale = revisions.has(query)
25 ? revisions.get(query) !== revision
26 : // A reader without a revision may have cached it before the latest
27 // workspace change; a query nobody has read yet fetches fresh anyway.
28 revision !== null && get.registry.getNodes().has(queryKey(query));
29 if (stale) get.refresh(query);
30 revisions.set(query, revision);
31 }
32 return get(query);
33 },
34 // Refreshing the reader refetches the query it reads.
35 (refresh) => refresh(query),
36 ),
37 );
38​
39// Held as long as the query lives, so one (query, revision) pair keeps one atom; an
40// `Atom.family` would hold the inner family only weakly and could swap the atom under a reader.
41const revisionedFamilies = new WeakMap<
42 Atom.Atom<unknown>,
43 ReturnType<typeof makeRevisionedFamily>
44>();
45const revisionedFamily = (query: Atom.Atom<unknown>) => {
46 let family = revisionedFamilies.get(query);
47 if (family === undefined) {
48 family = makeRevisionedFamily(query);
49 revisionedFamilies.set(query, family);
50 }
51 return family;
52};
53​
54/**
55 * Reads `query` under a workspace revision (latest mutation id); a different
56 * revision than the last read refetches it. The first read records the revision,
57 * and refetches only a query that a reader without a revision already cached.
58 * `undefined` reads without taking part, for readers that must not refetch now.
59 */
60export function revisionedQuery<A>(
61 query: Atom.Atom<A>,
62 revision: string | null | undefined,
63): Atom.Atom<A> {
64 if (revision === undefined) return query;
65 return revisionedFamily(query)(revision) as Atom.Atom<A>;