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

query.ts

135 lines4.8 KB

1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
3import * as Cause from "effect/Cause";
4import * as Equal from "effect/Equal";
5import * as Option from "effect/Option";
6import { AsyncResult, Atom } from "effect/reactivity";
7import { msg } from "gt-react";
8import { useContext } from "react";
9​
10import { m, type MessageResolver } from "../i18n/messages";
11​
12const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
13 Atom.withLabel("web-environment-query:empty"),
14);
15​
16export interface EnvironmentQueryView<A, E = unknown> {
17 readonly data: A | null;
18 readonly dataUpdatedAt: number;
19 readonly error: string | null;
20 readonly failure: E | null;
21 readonly isPending: boolean;
22 readonly isSuccess: boolean;
23 readonly refresh: () => void;
25​
26export function formatEnvironmentQueryError(
27 cause: Cause.Cause<unknown>,
28 resolve: MessageResolver = m,
29): string {
30 const error = Cause.squash(cause);
31 return (
32 (error instanceof Error ? errorDisplayMessage(error, resolve) : null) ??
33 resolve(msg("The environment request failed."))
34 );
36​
37function queryUpdatedAt(result: AsyncResult.AsyncResult<unknown, unknown>): number {
38 return result._tag === "Success"
39 ? result.timestamp
40 : result._tag === "Failure"
41 ? (Option.getOrNull(result.previousSuccess)?.timestamp ?? 0)
42 : 0;
44​
45export function useEnvironmentQuery<A, E>(
46 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
47 resolve: MessageResolver = m,
48): EnvironmentQueryView<A, E> {
49 const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
50 const result = useAtomValue(selectedAtom);
51 const refresh = useAtomRefresh(selectedAtom);
52 return {
53 data: AsyncResult.getOrElse(result, () => null),
54 dataUpdatedAt: queryUpdatedAt(result),
55 error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause, resolve) : null,
56 failure:
57 result._tag === "Failure" ? Option.getOrNull(Cause.findErrorOption(result.cause)) : null,
58 isPending: atom !== null && result.waiting,
59 isSuccess: result._tag === "Success",
60 refresh,
61 };
63​
64/** Keep select outside the component; a new function rebuilds the derived atom on every render. */
65export function useEnvironmentQuerySelector<A, E, B>(
66 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
67 select: (result: AsyncResult.AsyncResult<A, E>) => B,
68): B {
69 return useAtomValue(atom ?? EMPTY_ASYNC_RESULT_ATOM, select);
71​
72const queryDataAtoms = new WeakMap<object, Atom.Atom<unknown>>();
73​
74/**
75 * A query's data compared by value, so it holds through a refetch's `waiting` and `timestamp`
76 * changes and through a refetch that brings the same data back. For small results: comparing
77 * walks the whole value.
78 */
79export function environmentQueryDataAtom<A, E>(
80 query: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
81): Atom.Atom<A | null> {
82 let atom = queryDataAtoms.get(query) as Atom.Atom<A | null> | undefined;
83 if (atom === undefined) {
84 atom = Atom.map(query, (result): A | null => AsyncResult.getOrElse(result, () => null)).pipe(
85 Atom.withEquality<A | null>(Equal.equals),
86 );
87 queryDataAtoms.set(query, atom);
88 }
89 return atom;
91​
92/** Reads `environmentQueryDataAtom`: a reader of the data alone renders only when it changes. */
93export function useEnvironmentQueryData<A, E>(
94 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
95): A | null {
96 return useAtomValue(environmentQueryDataAtom<A, E>(atom ?? EMPTY_ASYNC_RESULT_ATOM));
98​
99type QueryResultAtom = Atom.Atom<AsyncResult.AsyncResult<unknown, unknown>>;
100const queryIsNewerAtoms = new WeakMap<
101 QueryResultAtom,
102 WeakMap<QueryResultAtom, Atom.Atom<boolean>>
103>();
104function queryIsNewerAtom(query: QueryResultAtom, than: QueryResultAtom): Atom.Atom<boolean> {
105 let byThan = queryIsNewerAtoms.get(query);
106 if (byThan === undefined) {
107 byThan = new WeakMap();
108 queryIsNewerAtoms.set(query, byThan);
109 }
110 let atom = byThan.get(than);
111 if (atom === undefined) {
112 atom = Atom.make((get) => queryUpdatedAt(get(query)) >= queryUpdatedAt(get(than)));
113 byThan.set(than, atom);
114 }
115 return atom;
117​
118export function useEnvironmentQueryIsNewer(
119 query: QueryResultAtom | null,
120 than: QueryResultAtom | null,
121): boolean {
122 return useAtomValue(
123 queryIsNewerAtom(query ?? EMPTY_ASYNC_RESULT_ATOM, than ?? EMPTY_ASYNC_RESULT_ATOM),
124 );
126​
127/** Returns refresh and call-time pending state without subscribing to it. */
128export function useEnvironmentQueryRefresh<A, E>(
129 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
130): { readonly refresh: () => void; readonly isPending: () => boolean } {
131 const registry = useContext(RegistryContext);
132 const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
133 const refresh = useAtomRefresh(selectedAtom);
134 return { refresh, isPending: () => atom !== null && registry.get(selectedAtom).waiting };