Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 createLinkedPullRequestSummaryAtomFamily,
4 createPullRequestEnvironmentAtoms,
5} from "@t3tools/client-runtime/state/pull-requests";
6import type {
7 EnvironmentId,
8 PullRequestListInput,
9 PullRequestListStatsInput,
10 PullRequestRef,
11 PullRequestSummary,
12} from "@t3tools/contracts";
13import * as Option from "effect/Option";
14import { AsyncResult, Atom } from "effect/unstable/reactivity";
15import { useCallback, useLayoutEffect, useMemo } from "react";
16
17import { connectionAtomRuntime } from "../connection/runtime";
18import { appAtomRegistry } from "../rpc/atomRegistry";
19import {
20 mergePullRequestLists,
21 type EnvironmentPullRequestStat,
22 type MergedPullRequestList,
23} from "../components/pullRequest/pullRequestList.logic";
24import { formatEnvironmentQueryError } from "./query";
25
26export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime);
27export const linkedPullRequestDetailAtom =
28 createLinkedPullRequestSummaryAtomFamily(connectionAtomRuntime);
29
30const observedPullRequestSummaryAtom = Atom.family((key: string) =>
31 Atom.make<PullRequestSummary | null>(null).pipe(
32 Atom.setIdleTTL(5 * 60_000),
33 Atom.withLabel(`web-pull-requests:observed-summary:${key}`),
34 ),
35);
36
37export function newestPullRequestSummary(
38 current: PullRequestSummary | null,
39 observed: PullRequestSummary | null,
40): PullRequestSummary | null {
41 if (current === null) return observed;
42 if (observed === null) return current;
43 if (current.state === "merged") return current;
44 if (observed.state === "merged") return observed;
45 return Date.parse(observed.updatedAt) >= Date.parse(current.updatedAt) ? observed : current;
46}
47
48export function useSharedPullRequestSummary(
49 environmentId: EnvironmentId | null,
50 reference: PullRequestRef | null,
51 current: PullRequestSummary | null,
52): PullRequestSummary | null {
53 const key =
54 environmentId === null || reference === null
55 ? "none"
56 : JSON.stringify([
57 environmentId,
58 reference.projectId,
59 reference.repository.toLowerCase(),
60 reference.number,
61 ]);
62 const atom = observedPullRequestSummaryAtom(key);
63 const observed = useAtomValue(atom);
64 useLayoutEffect(() => {
65 if (environmentId === null || current === null) return;
66 appAtomRegistry.modify(atom, (previous) => {
67 const next = newestPullRequestSummary(previous, current);
68 return next === previous ? [false, previous] : [true, next];
69 });
70 }, [atom, current, environmentId]);
71 return newestPullRequestSummary(current, observed);
72}
73
74export interface EnvironmentQueryTarget<Input> {
75 readonly environmentId: EnvironmentId;
76 readonly input: Input;
77}
78
79interface MergedEnvironmentQueryView<A> {
80 /** One entry per query target that has answered, in the order the targets were given. */
81 readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
82 /** The first environment that failed. Others may still have answered — this is not fatal. */
83 readonly error: string | null;
84 readonly isPending: boolean;
85}
86
87/**
88 * The same per-environment query read across several environments at once. React cannot subscribe
89 * to a list of atoms whose length changes, so the fan-out happens inside one derived atom keyed by
90 * the targets — the same shape the cross-environment thread search uses.
91 *
92 * An environment that fails contributes nothing rather than blanking the page: the pull request
93 * list is a union, and one unreachable machine should not hide the others' rows.
94 */
95function createMergedEnvironmentQuery<Input, A>(
96 label: string,
97 atomFor: (
98 target: EnvironmentQueryTarget<Input>,
99 ) => Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
100) {
101 const family = Atom.family((key: string) =>
102 Atom.make((get): MergedEnvironmentQueryView<A> => {
103 const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
104 const values: Array<readonly [EnvironmentId, A]> = [];
105 let error: string | null = null;
106 let isPending = false;
107 for (const target of targets) {
108 const result = get(atomFor(target));
109 isPending ||= result.waiting;
110 if (result._tag === "Failure" && error === null) {
111 error = formatEnvironmentQueryError(result.cause);
112 }
113 const value = Option.getOrNull(AsyncResult.value(result));
114 if (value !== null) values.push([target.environmentId, value]);
115 }
116 return { values, error, isPending };
117 }).pipe(Atom.withLabel(`${label}:${key}`)),
118 );
119 const empty = Atom.make<MergedEnvironmentQueryView<A>>({
120 values: [],
121 error: null,
122 isPending: false,
123 }).pipe(Atom.withLabel(`${label}:empty`));
124 return function useMergedQuery(targets: ReadonlyArray<EnvironmentQueryTarget<Input>>) {
125 const key = JSON.stringify(targets);
126 const view = useAtomValue(targets.length === 0 ? empty : family(key));
127 const refresh = useCallback(
128 (override?: ReadonlyArray<EnvironmentQueryTarget<Input>>) => {
129 const refreshTargets =
130 override ?? (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>);
131 for (const target of refreshTargets) {
132 appAtomRegistry.refresh(atomFor(target));
133 }
134 },
135 [key],
136 );
137 return { ...view, refresh };
138 };
139}
140
141const usePullRequestListsQuery = createMergedEnvironmentQuery(
142 "web-pull-requests:list",
143 pullRequestEnvironment.list,
144);
145
146const usePullRequestStatsQuery = createMergedEnvironmentQuery(
147 "web-pull-requests:list-stats",
148 pullRequestEnvironment.listStats,
149);
150
151export interface MergedPullRequestListView {
152 readonly data: MergedPullRequestList | null;
153 readonly error: string | null;
154 readonly isPending: boolean;
155 readonly refresh: () => void;
156}
157
158/** One listing per environment, merged into the single list the page renders. */
159export function usePullRequestList(
160 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
161): MergedPullRequestListView {
162 const query = usePullRequestListsQuery(targets);
163 const data = useMemo(() => mergePullRequestLists(query.values), [query.values]);
164 return { data, error: query.error, isPending: query.isPending, refresh: query.refresh };
165}
166
167/** The line counts for the rows on screen, asked of each environment for its own rows. */
168export function usePullRequestListStats(
169 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
170): {
171 readonly stats: ReadonlyArray<EnvironmentPullRequestStat> | null;
172 readonly isPending: boolean;
173 readonly refresh: (
174 targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
175 ) => void;
176} {
177 const query = usePullRequestStatsQuery(targets);
178 const stats = useMemo(
179 () =>
180 query.values.length === 0
181 ? null
182 : query.values.flatMap(([environmentId, result]) =>
183 result.stats.map((stat) => ({ ...stat, environmentId })),
184 ),
185 [query.values],
186 );
187 return { stats, isPending: query.isPending, refresh: query.refresh };
188}