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

usePullRequestDiff.ts

247 lines9.5 KB

1import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
2import {
3 EnvironmentId,
4 ProjectId,
5 type PullRequestListEntry,
6 type PullRequestSummary,
7} from "@t3tools/contracts";
8import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
9import { Atom, type AsyncResult } from "effect/reactivity";
10import { useLocale, useMessages } from "gt-react-native";
11import { useContext, useLayoutEffect, useMemo, useState } from "react";
12​
13import { composerPullRequests } from "../../state/pull-requests";
14import { useEnvironmentQuery } from "../../state/query";
15import { usePullToRefresh } from "../../state/use-pull-to-refresh";
16import {
17 getCachedPullRequestDiffPages,
18 retainPullRequestDiffPage,
19 withWithheldFiles,
20 type PullRequestDiffPage,
21 type WithheldFileLoad,
22} from "./pullRequestDiffPages";
23​
24export type PullRequestParams = {
25 readonly environmentId: string;
26 readonly projectId: string;
27 readonly repository: string;
28 readonly number: number;
29 readonly host?: string;
30 readonly navigationUrl?: string;
31 readonly navigationId?: number;
32 readonly initialSummary?: PullRequestListEntry | PullRequestSummary;
33};
34​
35export type PullRequestDiffParams = PullRequestParams & { readonly commit?: string };
36​
37/** The pull request a route names, without whatever else arrived on that route. */
38export function pullRequestParams(params: PullRequestParams): PullRequestParams {
39 return {
40 environmentId: params.environmentId,
41 projectId: params.projectId,
42 repository: params.repository,
43 number: params.number,
44 ...(params.host === undefined ? {} : { host: params.host }),
45 ...(params.navigationUrl === undefined ? {} : { navigationUrl: params.navigationUrl }),
46 ...(params.navigationId === undefined ? {} : { navigationId: params.navigationId }),
47 ...(params.initialSummary === undefined ? {} : { initialSummary: params.initialSummary }),
48 };
50​
51export function pullRequestTarget(params: PullRequestParams) {
52 return {
53 environmentId: EnvironmentId.make(params.environmentId),
54 input: {
55 projectId: ProjectId.make(params.projectId),
56 repository: params.repository,
57 number: params.number,
58 ...(params.host ? { host: params.host } : {}),
59 },
60 };
62​
63const NO_PAGES: readonly PullRequestDiffPage[] = [];
64const NO_PATHS: readonly string[] = [];
65​
66type PullRequestDiffTarget = Parameters<typeof composerPullRequests.diff>[0];
67​
68// Keyed by the diff's serialized target, which the hook already holds as its scope.
69const withheldFileDiff = (targetKey: string, path: string) => {
70 const target = JSON.parse(targetKey) as PullRequestDiffTarget;
71 return composerPullRequests.diff({ ...target, input: { ...target.input, path } });
72};
73​
74// One read per withheld file the reader asked for, so only that file's diff crosses the wire.
75const withheldFileDiffsAtom = Atom.family((key: string) => {
76 const { targetKey, paths } = JSON.parse(key) as {
77 readonly targetKey: string;
78 readonly paths: readonly string[];
79 };
80 return Atom.make((get) => paths.map((path) => get(withheldFileDiff(targetKey, path)))).pipe(
81 Atom.withLabel(`mobile:pull-request-withheld-file-diffs:${key}`),
82 );
83});
84​
85export function usePullRequestDiffEntry(navigation: {
86 readonly addListener: (
87 type: "transitionStart" | "transitionEnd",
88 listener: (event: { readonly data: { readonly closing: boolean } }) => void,
89 ) => () => void;
90}) {
91 const [ready, setReady] = useState(false);
92 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to navigator transition events and frames to defer the diff until the opening transition ends
93 useLayoutEffect(() => {
94 if (ready) return;
95 let opening = false;
96 let closing = false;
97 const finish = () => {
98 if (!closing) setReady(true);
99 };
100 const removeStart = navigation.addListener("transitionStart", ({ data }) => {
101 closing = data.closing;
102 if (!closing) opening = true;
103 });
104 const removeEnd = navigation.addListener("transitionEnd", ({ data }) => {
105 closing = data.closing;
106 if (!closing) finish();
107 });
108 // Initial and unanimated presentations may have no transition events; let the shell paint first.
109 let frame = requestAnimationFrame(() => {
110 frame = requestAnimationFrame(() => {
111 if (!opening) finish();
112 });
113 });
114 // A missing native completion must not strand the route on its loading state.
115 const fallback = setTimeout(finish, 1_000);
116 return () => {
117 removeStart();
118 removeEnd();
119 cancelAnimationFrame(frame);
120 clearTimeout(fallback);
121 };
122 }, [navigation, ready]);
123 return ready;
125​
126export function usePullRequestDiff(
127 params: PullRequestDiffParams,
128 terminology: ChangeRequestTerminology,
129) {
130 const reference = pullRequestTarget(params);
131 const target = {
132 ...reference,
133 input: { ...reference.input, ...(params.commit ? { commit: params.commit } : {}) },
134 };
135 const key = JSON.stringify(target);
136 const messages = useMessages();
137 const locale = useLocale();
138 const firstPageAtom = composerPullRequests.diff(target);
139 const firstPage = useAtomValue(firstPageAtom);
140 const refreshFirstPage = useAtomRefresh(firstPageAtom);
141 const registry = useContext(RegistryContext);
142 const { refreshing, onRefresh } = usePullToRefresh(firstPageAtom);
143 const [state, setState] = useState<{
144 key: string;
145 cursor: string | null;
146 pages: readonly PullRequestDiffPage[];
147 /** The first page as it stood when a reload was asked for; unset until one is. */
148 reloadedFrom?: AsyncResult.AsyncResult<unknown, unknown>;
149 }>({ key, cursor: null, pages: NO_PAGES });
150 const cursor = state.key === key ? state.cursor : null;
151 const reloadedFrom = state.key === key ? state.reloadedFrom : undefined;
152 const pageAtom = (pageCursor: string | null) =>
153 composerPullRequests.diff({
154 ...target,
155 input: { ...target.input, ...(pageCursor ? { cursor: pageCursor } : {}) },
156 });
157 const query = useEnvironmentQuery(pageAtom(cursor));
158 const pages = useMemo(() => {
159 const loaded = state.key === key ? state.pages : NO_PAGES;
160 return query.data ? retainPullRequestDiffPage(loaded, cursor, query.data) : loaded;
161 }, [cursor, key, query.data, state.key, state.pages]);
162 if (state.key !== key || state.pages !== pages) setState({ key, cursor, pages, reloadedFrom });
163​
164 const [withheldLoads, setWithheldLoads] = useState<{
165 readonly key: string;
166 readonly paths: readonly string[];
167 }>({ key: "", paths: NO_PATHS });
168 const withheldPaths = withheldLoads.key === key ? withheldLoads.paths : NO_PATHS;
169 const withheldResults = useAtomValue(
170 withheldFileDiffsAtom(JSON.stringify({ targetKey: key, paths: withheldPaths })),
171 );
172 const refreshWithheldFiles = () => {
173 for (const path of withheldPaths) registry.refresh(withheldFileDiff(key, path));
174 };
175 const loadWithheldFile = (path: string) => {
176 // The read is keyed without the head, so even a first load must not reuse an older one.
177 registry.refresh(withheldFileDiff(key, path));
178 if (!withheldPaths.includes(path)) setWithheldLoads({ key, paths: [...withheldPaths, path] });
179 };
180 // A refetch keeps showing the last patch, whose lines may not exist at the new head.
181 const withheldRefetching = withheldResults.some((result) => result.waiting);
182 const loads = new Map<string, WithheldFileLoad>();
183 withheldPaths.forEach((path, index) => {
184 const result = withheldResults[index];
185 if (result === undefined) return;
186 // A failed refetch still carries the last patch; show the failure instead.
187 loads.set(
188 path,
189 result._tag === "Failure"
190 ? { status: "error" }
191 : result._tag === "Success"
192 ? { status: "loaded", result: result.value }
193 : { status: "loading" },
194 );
195 });
196 const pagesParsed = useMemo(
197 () => getCachedPullRequestDiffPages(pages, key, terminology, messages, locale),
198 [key, pages, terminology, messages, locale],
199 );
200 // The server says whether a withheld file can be read alone; GitHub may refuse the whole diff.
201 const withheldFilesReadable = pages[0]?.result.withheldFilesReadable === true;
202 const parsed = withWithheldFiles(
203 pagesParsed,
204 loads,
205 withheldFilesReadable,
206 key,
207 messages,
208 locale,
209 );
210 const patch = useMemo(() => pages.map((page) => page.result.patch).join("\n"), [pages]);
211 const nextCursor = pages.at(-1)?.result.nextCursor ?? null;
212 // Pull to refresh starts its refetch a tick later; until then the first page's cursor is the old one.
213 const reloadStarting = reloadedFrom !== undefined && firstPage === reloadedFrom;
214 const canLoadMore =
215 nextCursor !== null &&
216 nextCursor !== cursor &&
217 !query.isPending &&
218 query.error === null &&
219 !reloadStarting;
220 const loadMore = () => {
221 if (!canLoadMore) return;
222 // Cursors are page numbers, so a page cached before the reload may hold an older head's lines.
223 if (reloadedFrom !== undefined) registry.refresh(pageAtom(nextCursor));
224 setState({ key, cursor: nextCursor, pages, reloadedFrom });
225 };
226 const reload = (refreshFirst: () => void) => {
227 setState({ key, cursor: null, pages: NO_PAGES, reloadedFrom: firstPage });
228 refreshFirst();
229 refreshWithheldFiles();
230 };
231 return {
232 ...query,
233 /** Reads the whole diff again from page one, whichever page was showing or had failed. */
234 refresh: () => reload(refreshFirstPage),
235 /** Reads only the page that failed again, keeping the files already loaded. */
236 retry: query.refresh,
237 parsed,
238 loadWithheldFile,
239 withheldRefetching,
240 patch,
241 nextCursor,
242 canLoadMore,
243 loadMore,
244 refreshing,
245 onPullRefresh: () => reload(onRefresh),
246 };