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

query.ts

108 lines4.0 KB

1import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import * as Cause from "effect/Cause";
3import * as Option from "effect/Option";
4import { AsyncResult, Atom } from "effect/reactivity";
5import { useContext } from "react";
6​
7const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
8 Atom.withLabel("web-environment-query:empty"),
9);
10​
11export interface EnvironmentQueryView<A, E = unknown> {
12 readonly data: A | null;
13 readonly dataUpdatedAt: number;
14 readonly error: string | null;
15 readonly failure: E | null;
16 readonly isPending: boolean;
17 readonly isSuccess: boolean;
18 readonly refresh: () => void;
20​
21export function formatEnvironmentQueryError(cause: Cause.Cause<unknown>): string {
22 const error = Cause.squash(cause);
23 return error instanceof Error && error.message.trim().length > 0
24 ? error.message
25 : "The environment request failed.";
27​
28function queryUpdatedAt(result: AsyncResult.AsyncResult<unknown, unknown>): number {
29 return result._tag === "Success"
30 ? result.timestamp
31 : result._tag === "Failure"
32 ? (Option.getOrNull(result.previousSuccess)?.timestamp ?? 0)
33 : 0;
35​
36export function useEnvironmentQuery<A, E>(
37 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
38): EnvironmentQueryView<A, E> {
39 const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
40 const result = useAtomValue(selectedAtom);
41 const refresh = useAtomRefresh(selectedAtom);
42 return {
43 data: Option.getOrNull(AsyncResult.value(result)),
44 dataUpdatedAt: queryUpdatedAt(result),
45 error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
46 failure:
47 result._tag === "Failure" ? Option.getOrNull(Cause.findErrorOption(result.cause)) : null,
48 isPending: atom !== null && result.waiting,
49 isSuccess: result._tag === "Success",
50 refresh,
51 };
53​
54/**
55 * Reads one part of a query's result. Every refetch publishes a new result (a
56 * new timestamp, `waiting` on and off), and this re-renders only when the
57 * selected part changes. `select` must be defined outside the component: a new
58 * function per render would rebuild the derived atom every render.
59 */
60export function useEnvironmentQuerySelector<A, E, B>(
61 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
62 select: (result: AsyncResult.AsyncResult<A, E>) => B,
63): B {
64 return useAtomValue(atom ?? EMPTY_ASYNC_RESULT_ATOM, select);
66​
67type QueryResultAtom = Atom.Atom<AsyncResult.AsyncResult<unknown, unknown>>;
68// Lives as long as both queries do, so a row keeps the same comparison atom across renders.
69const queryIsNewerAtoms = new WeakMap<
70 QueryResultAtom,
71 WeakMap<QueryResultAtom, Atom.Atom<boolean>>
72>();
73function queryIsNewerAtom(query: QueryResultAtom, than: QueryResultAtom): Atom.Atom<boolean> {
74 let byThan = queryIsNewerAtoms.get(query);
75 if (byThan === undefined) {
76 byThan = new WeakMap();
77 queryIsNewerAtoms.set(query, byThan);
78 }
79 let atom = byThan.get(than);
80 if (atom === undefined) {
81 atom = Atom.make((get) => queryUpdatedAt(get(query)) >= queryUpdatedAt(get(than)));
82 byThan.set(than, atom);
83 }
84 return atom;
86​
87/** Whether `query` last succeeded no earlier than `than`, without re-rendering on every refetch. */
88export function useEnvironmentQueryIsNewer(
89 query: QueryResultAtom | null,
90 than: QueryResultAtom | null,
91): boolean {
92 return useAtomValue(
93 queryIsNewerAtom(query ?? EMPTY_ASYNC_RESULT_ATOM, than ?? EMPTY_ASYNC_RESULT_ATOM),
94 );
96​
97/**
98 * The query's refresh, plus its pending state read when called rather than
99 * subscribed to, for callers that only gate a refresh on it.
100 */
101export function useEnvironmentQueryRefresh<A, E>(
102 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
103): { readonly refresh: () => void; readonly isPending: () => boolean } {
104 const registry = useContext(RegistryContext);
105 const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
106 const refresh = useAtomRefresh(selectedAtom);
107 return { refresh, isPending: () => atom !== null && registry.get(selectedAtom).waiting };