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