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

usePullRequestList.ts

311 lines11.4 KB

1import { RegistryContext, useAtomValue } from "@effect/atom-react";
2import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import * as Option from "effect/Option";
6import { AsyncResult, Atom } from "effect/reactivity";
7import { use, useCallback, useEffect, useMemo, useRef, useState, useLayoutEffect } from "react";
8import { composerPullRequests } from "../../state/pull-requests";
9import {
10 appendPullRequestListPage,
11 mergeEnvironmentPullRequestPages,
12 nextPullRequestListInput,
13 pullRequestListHead,
14 pullRequestListKey,
15 scopedPullRequestListKey,
16 type EnvironmentPullRequestListEntry,
17 type PullRequestListPages,
18} from "./pullRequestList";
19​
20const pagesFamily = Atom.family((_key: string) =>
21 Atom.make<PullRequestListPages | null>(null).pipe(Atom.setIdleTTL(5 * 60_000)),
22);
23const statsFamily = Atom.family((_environmentId: string) =>
24 Atom.make<ReadonlyMap<string, PullRequestDiffStat>>(new Map()).pipe(Atom.setIdleTTL(5 * 60_000)),
25);
26const statKey = (row: Pick<PullRequestDiffStat, "projectId" | "repository" | "number">) =>
27 `${row.projectId}:${row.repository}:${row.number}`;
28​
29type ListTarget = { readonly environmentId: EnvironmentId; readonly input: PullRequestListInput };
30const sourcesFamily = Atom.family((key: string) => {
31 const targets: readonly ListTarget[] = JSON.parse(key);
32 return Atom.make((get) =>
33 targets.map((target) => {
34 const result = get(composerPullRequests.list(target));
35 const head = Option.getOrNull(AsyncResult.value(result));
36 const cached = get(pagesFamily(JSON.stringify(target)));
37 return {
38 target,
39 result,
40 pages: head ? pullRequestListHead(cached, head) : cached,
41 stats: get(statsFamily(target.environmentId)),
42 };
43 }),
44 );
45});
46​
47export function usePullRequestList(targets: readonly ListTarget[]) {
48 const registry = use(RegistryContext);
49 const scopeKey = JSON.stringify(targets);
50 const activeScope = useRef(scopeKey);
51 const sources = useAtomValue(sourcesFamily(scopeKey));
52 const requests = useRef<{ page?: AbortController; refresh?: AbortController }>({});
53 const [loading, setLoading] = useState({
54 key: scopeKey,
55 page: false,
56 refresh: false,
57 error: null as string | null,
58 });
59 const state = loading.key === scopeKey ? loading : { page: false, refresh: false, error: null };
60 useLayoutEffect(() => {
61 activeScope.current = scopeKey;
62 return () => {
63 requests.current.page?.abort();
64 requests.current.refresh?.abort();
65 requests.current = {};
66 };
67 }, [scopeKey, activeScope]);
68 useEffect(() => {
69 for (const { target, pages } of sources)
70 if (pages) registry.set(pagesFamily(JSON.stringify(target)), pages);
71 }, [registry, sources]);
72​
73 const loadMore = useCallback(
74 async (retry = false) => {
75 if (requests.current.page || requests.current.refresh || (!retry && state.error)) return;
76 const continuations = targets.flatMap((target) => {
77 const pagesAtom = pagesFamily(JSON.stringify(target));
78 const pages = registry.get(pagesAtom);
79 const input = pages && nextPullRequestListInput(pages, target.input);
80 return pages && input ? [{ target, pagesAtom, pages, input }] : [];
81 });
82 if (!continuations.length) return;
83 const controller = new AbortController();
84 requests.current.page = controller;
85 setLoading({ key: scopeKey, page: true, refresh: false, error: null });
86 const responses = await Promise.allSettled(
87 continuations.map(async ({ target, pagesAtom, pages, input }) => {
88 const response = await executeAtomQuery(
89 registry,
90 composerPullRequests.list({ ...target, input }),
91 {
92 signal: controller.signal,
93 refresh: retry,
94 reportFailure: false,
95 },
96 );
97 if (controller.signal.aborted || activeScope.current !== scopeKey) return;
98 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
99 if (response.value.errors.length)
100 throw new Error(response.value.errors.map((error) => error.message).join("\n"));
101 const next = appendPullRequestListPage(
102 registry.get(pagesAtom) ?? pages,
103 response.value,
104 input,
105 );
106 registry.set(pagesAtom, next);
107 if (
108 input.cursors &&
109 Object.keys(next.nextCursors).length &&
110 JSON.stringify(Object.entries(input.cursors).sort()) ===
111 JSON.stringify(Object.entries(next.nextCursors).sort())
112 )
113 throw new Error("Couldn't advance the list. Try again.");
114 }),
115 );
116 if (requests.current.page === controller) delete requests.current.page;
117 if (!controller.signal.aborted && activeScope.current === scopeKey)
118 setLoading({ key: scopeKey, page: false, refresh: false, error: requestErrors(responses) });
119 },
120 [targets, registry, scopeKey, state.error, activeScope],
121 );
122​
123 const onRefresh = async () => {
124 if (!targets.length || requests.current.refresh) return;
125 requests.current.page?.abort();
126 delete requests.current.page;
127 const controller = new AbortController();
128 requests.current.refresh = controller;
129 setLoading({ key: scopeKey, page: false, refresh: true, error: null });
130 const responses = await Promise.allSettled(
131 targets.map(async (target) => {
132 await composerPullRequests.invalidate.run(registry, {
133 environmentId: target.environmentId,
134 input: {},
135 });
136 if (controller.signal.aborted) return;
137 const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
138 refresh: true,
139 signal: controller.signal,
140 reportFailure: false,
141 });
142 if (controller.signal.aborted || activeScope.current !== scopeKey) return;
143 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
144 registry.set(
145 pagesFamily(JSON.stringify(target)),
146 pullRequestListHead(null, response.value),
147 );
148 }),
149 );
150 if (requests.current.refresh === controller) delete requests.current.refresh;
151 if (!controller.signal.aborted && activeScope.current === scopeKey)
152 setLoading({ key: scopeKey, page: false, refresh: false, error: requestErrors(responses) });
153 };
154​
155 const data = useMemo(
156 () =>
157 mergeEnvironmentPullRequestPages(
158 sources.flatMap(({ target, pages, stats }) =>
159 pages
160 ? [
161 {
162 environmentId: target.environmentId,
163 pages: {
164 ...pages,
165 entries: pages.entries.map((entry) => {
166 const stat = stats.get(statKey(entry));
167 return stat
168 ? { ...entry, additions: stat.additions, deletions: stat.deletions }
169 : entry;
170 }),
171 },
172 },
173 ]
174 : [],
175 ),
176 ),
177 [sources],
178 );
179 const [visible, setVisible] = useState<{
180 key: string;
181 rows: readonly EnvironmentPullRequestListEntry[];
182 }>({ key: scopeKey, rows: [] });
183 const onViewableItemsChanged = useCallback(
184 ({
185 viewableItems,
186 }: {
187 viewableItems: readonly { item: EnvironmentPullRequestListEntry; isViewable: boolean }[];
188 }) => {
189 const rows = viewableItems.filter((token) => token.isViewable).map((token) => token.item);
190 setVisible((previous) =>
191 previous.key === scopeKey &&
192 previous.rows.map(scopedPullRequestListKey).join() ===
193 rows.map(scopedPullRequestListKey).join()
194 ? previous
195 : { key: scopeKey, rows },
196 );
197 },
198 [scopeKey],
199 );
200 const visibleRows =
201 visible.key === scopeKey && visible.rows.length ? visible.rows : data.entries.slice(0, 8);
202 const statsKey = JSON.stringify(
203 targets.flatMap(({ environmentId }) => {
204 const refs = visibleRows
205 .filter(
206 (row) =>
207 row.environmentId === environmentId &&
208 row.provider === "github" &&
209 row.additions + row.deletions === 0,
210 )
211 .map(({ projectId, host, repository, number }) => ({
212 projectId,
213 host,
214 repository,
215 number,
216 }));
217 return refs.length ? [{ environmentId, input: { refs } }] : [];
218 }),
219 );
220 const statsAtom = useMemo(() => {
221 const queries: readonly Parameters<typeof composerPullRequests.listStats>[0][] =
222 JSON.parse(statsKey);
223 return Atom.make((get) =>
224 queries.map((target) => ({
225 environmentId: target.environmentId,
226 result: get(composerPullRequests.listStats(target)),
227 })),
228 );
229 }, [statsKey]);
230 const counts = useAtomValue(statsAtom);
231 useEffect(() => {
232 for (const { environmentId, result } of counts) {
233 if (result._tag !== "Success" || result.waiting) continue;
234 registry.update(statsFamily(environmentId), (previous) => {
235 const next = new Map(previous);
236 for (const row of result.value.stats) next.set(statKey(row), row);
237 return next;
238 });
239 }
240 }, [registry, counts]);
241​
242 const updateEntry = useCallback(
243 (entry: EnvironmentPullRequestListEntry, patch: Partial<EnvironmentPullRequestListEntry>) => {
244 const target = targets.find((target) => target.environmentId === entry.environmentId);
245 if (!target) return;
246 registry.update(pagesFamily(JSON.stringify(target)), (previous) =>
247 previous
248 ? {
249 ...previous,
250 entries: previous.entries.map((row) =>
251 pullRequestListKey(row) === pullRequestListKey(entry)
252 ? { ...row, ...patch, observedAt: Date.now() }
253 : row,
254 ),
255 }
256 : previous,
257 );
258 registry.refresh(composerPullRequests.list(target));
259 },
260 [registry, targets],
261 );
262 const errors = useMemo(
263 () =>
264 sources.flatMap(({ target, result }) => {
265 if (result._tag !== "Failure") return [];
266 const cause = Cause.squash(result.cause);
267 return [
268 {
269 environmentId: target.environmentId,
270 projectTitle: "",
271 message: cause instanceof Error ? cause.message : "Couldn't load pull requests.",
272 },
273 ];
274 }),
275 [sources],
276 );
277 const listing = useMemo(() => ({ ...data, errors: [...data.errors, ...errors] }), [data, errors]);
278 return {
279 data: listing,
280 entries: data.entries,
281 error: errors.map((error) => error.message).join("\n") || null,
282 isPending: sources.some(({ result }) => result.waiting) && !data.entries.length,
283 continued: data.continued,
284 loadMore,
285 onRefresh,
286 onViewableItemsChanged,
287 updateEntry,
288 refreshing: state.refresh,
289 loadingMore: state.page,
290 loadMoreError: state.error,
291 hasMore: sources.some(
292 ({ pages, target }) => pages && nextPullRequestListInput(pages, target.input),
293 ),
294 };
296​
297function requestErrors(results: readonly PromiseSettledResult<unknown>[]) {
298 return (
299 results
300 .flatMap((result) =>
301 result.status === "rejected"
302 ? [
303 result.reason instanceof Error
304 ? result.reason.message
305 : "Couldn't load pull requests.",
306 ]
307 : [],
308 )
309 .join("\n") || null
310 );