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