The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 402 lines 15 KB
Raw
1 /**
2 * The pull-request view (`/:owner/:repo/pulls/:number`): GitHub-style
3 * title/state header, branch line, Markdown body, mergeability box with
4 * Merge/Close/Reopen actions, and tabbed Commits + Files changed from
5 * the three-dot `/compare` endpoint.
6 *
7 * `React.lazy`-loaded from `Repo.tsx` — the Files-changed tab renders
8 * through the shared `FileDiffList` (diffs+shiki runtime), which must
9 * stay out of the initial bundle.
10 */
11 import { useEffect, useState } from "react";
12 import {
13 ApiError,
14 compareCommits,
15 getPull,
16 mergePull,
17 updatePull,
18 type Comparison,
19 type PullDetail,
20 } from "../client.ts";
21 import { Button, CopyButton, ErrorBox, Markdown, Spinner } from "../components.tsx";
22 import { shortOid, subject, timeAgo } from "../format.ts";
23 import { href, Link } from "../router.tsx";
24 import FileDiffList from "./DiffList.tsx";
25 import { PullStateBadge, shortRef } from "./Pulls.tsx";
26 import type { RepoContext } from "./Repo.tsx";
27
28 // ── typed-error presentation ────────────────────────────────────────────────
29
30 /** Maps the service's typed merge/update errors to inline messages. */
31 const friendlyError = (cause: unknown): string => {
32 if (!(cause instanceof ApiError)) {
33 return cause instanceof Error ? cause.message : String(cause);
34 }
35 switch (cause.tag) {
36 case "MergeConflict":
37 return "Merge conflict — files were changed on both branches relative to the merge base. Resolve the conflict locally and push, or close this pull request.";
38 case "BranchMissing":
39 return "The base or head branch no longer exists.";
40 case "NothingToMerge":
41 return "Nothing to merge — the head branch is already part of the base branch.";
42 case "RefConflict":
43 return "A branch moved while merging (force-push or concurrent update) — review the new tip and try again.";
44 case "PullStateConflict":
45 return "The pull request's state changed underneath this page — it has been refreshed.";
46 case "ReadOnlyRepo":
47 return "This repository is read-only — merging is disabled.";
48 case "Forbidden":
49 return "Your token does not have write access to this repository.";
50 default:
51 return `${cause.tag}: ${cause.message}`;
52 }
53 };
54
55 // ── mergeability box ────────────────────────────────────────────────────────
56
57 const mergeStatus = (
58 detail: PullDetail,
59 ): { tone: "success" | "danger" | "muted"; text: string } => {
60 if (detail.mergeable === true) {
61 return {
62 tone: "success",
63 text:
64 detail.mergeableReason === "ff"
65 ? "This branch has no conflicts with the base branch — it can be fast-forwarded."
66 : "This branch has no conflicts with the base branch — a merge commit will be created.",
67 };
68 }
69 if (detail.mergeable === false) {
70 return detail.mergeableReason === "up-to-date"
71 ? {
72 tone: "muted",
73 text: "Nothing to merge — the head branch is already part of the base branch.",
74 }
75 : {
76 tone: "danger",
77 text: "This branch has conflicts with the base branch — the same files were changed on both sides.",
78 };
79 }
80 return {
81 tone: "muted",
82 text:
83 detail.baseOid === null || detail.headOid === null
84 ? "Mergeability unknown — the base or head branch no longer exists."
85 : "Mergeability could not be computed for this pull request.",
86 };
87 };
88
89 // ── the page ────────────────────────────────────────────────────────────────
90
91 type CompareState = Comparison | "unavailable" | null; // null = loading
92
93 const PullPage = ({ context, number }: { context: RepoContext; number: number }) => {
94 const [detail, setDetail] = useState<PullDetail | null>(null);
95 const [compare, setCompare] = useState<CompareState>(null);
96 const [error, setError] = useState<unknown>(null);
97 const [tab, setTab] = useState<"files" | "commits">("files");
98 const [actionError, setActionError] = useState<string | null>(null);
99 const [busy, setBusy] = useState(false);
100 const [generation, setGeneration] = useState(0);
101 const { connection, repo } = context;
102 const signedIn = context.user !== null;
103
104 useEffect(() => {
105 let cancelled = false;
106 setDetail(null);
107 setCompare(null);
108 setError(null);
109 void (async () => {
110 try {
111 const pull = await getPull(connection, repo.owner, repo.name, number);
112 if (cancelled) return;
113 setDetail(pull);
114 // Live compare only when both branches still exist (merged PRs
115 // return null tips — their record is the merge commit).
116 if (pull.baseOid !== null && pull.headOid !== null) {
117 const comparison = await compareCommits(connection, repo.owner, repo.name, {
118 base: pull.baseRef,
119 head: pull.headRef,
120 });
121 if (!cancelled) setCompare(comparison);
122 } else {
123 setCompare("unavailable");
124 }
125 } catch (cause) {
126 if (!cancelled) setError(cause);
127 }
128 })();
129 return () => {
130 cancelled = true;
131 };
132 // eslint-disable-next-line react-hooks/exhaustive-deps
133 }, [number, repo.repoId, generation]);
134
135 const act = (run: () => Promise<unknown>) => {
136 setBusy(true);
137 setActionError(null);
138 void run()
139 .then(() => setGeneration((value) => value + 1))
140 .catch((cause: unknown) => {
141 setActionError(friendlyError(cause));
142 // The state/tips this page shows are stale — reload them so the
143 // message matches what the user now sees.
144 if (
145 cause instanceof ApiError &&
146 (cause.tag === "PullStateConflict" || cause.tag === "RefConflict")
147 ) {
148 setGeneration((value) => value + 1);
149 }
150 })
151 .finally(() => setBusy(false));
152 };
153
154 if (error != null) return <ErrorBox error={error} />;
155 if (detail === null) return <Spinner />;
156
157 const { owner, name } = repo;
158 const status = mergeStatus(detail);
159 const boxTone =
160 status.tone === "success"
161 ? "border-success/40 bg-success/5"
162 : status.tone === "danger"
163 ? "border-danger/40 bg-danger/5"
164 : "border-border-muted bg-canvas-subtle";
165
166 return (
167 <div>
168 {/* header */}
169 <div className="mb-4 border-b border-border-muted pb-4">
170 <h1 className="text-xl font-semibold">
171 {detail.title} <span className="font-normal text-fg-muted">#{detail.number}</span>
172 </h1>
173 <div className="mt-2 flex flex-wrap items-center gap-2 text-sm text-fg-muted">
174 <PullStateBadge state={detail.state} />
175 {detail.state === "merged" ? (
176 <span>
177 merged {timeAgo(detail.mergedAt ?? detail.updatedAt)}
178 {detail.mergeCommit !== null && (
179 <>
180 {" as "}
181 <Link
182 to={href(owner, name, "commit", detail.mergeCommit)}
183 className="font-mono text-accent hover:underline"
184 >
185 {shortOid(detail.mergeCommit)}
186 </Link>
187 </>
188 )}
189 {" — "}
190 <code className="font-mono">{shortRef(detail.headRef)}</code>
191 {" into "}
192 <code className="font-mono">{shortRef(detail.baseRef)}</code>
193 </span>
194 ) : (
195 <span>
196 wants to merge{" "}
197 <code className="rounded bg-canvas-subtle px-1.5 py-0.5 font-mono">
198 {shortRef(detail.headRef)}
199 </code>{" "}
200 into{" "}
201 <code className="rounded bg-canvas-subtle px-1.5 py-0.5 font-mono">
202 {shortRef(detail.baseRef)}
203 </code>
204 {" · opened "}
205 {timeAgo(detail.createdAt)}
206 {detail.aheadBy !== null && detail.behindBy !== null && (
207 <>
208 {" · "}
209 {detail.aheadBy} commit{detail.aheadBy === 1 ? "" : "s"} ahead, {detail.behindBy}{" "}
210 behind
211 </>
212 )}
213 </span>
214 )}
215 </div>
216 </div>
217
218 {/* body */}
219 {detail.body !== null && detail.body.trim().length > 0 && (
220 <div className="mb-4 rounded-md border border-border-muted p-4">
221 <Markdown source={detail.body} />
222 </div>
223 )}
224
225 {/* mergeability + actions */}
226 {detail.state === "open" && (
227 <div className={`mb-4 rounded-md border px-4 py-3 text-sm ${boxTone}`}>
228 <p
229 className={
230 status.tone === "success"
231 ? "text-success"
232 : status.tone === "danger"
233 ? "text-danger"
234 : "text-fg-muted"
235 }
236 >
237 {status.text}
238 </p>
239 {signedIn && (
240 <div className="mt-3 flex flex-wrap items-center gap-2">
241 <Button
242 kind="primary"
243 disabled={busy || detail.mergeable !== true}
244 onClick={() =>
245 act(() =>
246 mergePull(connection, owner, name, number, {
247 // Race guard: fail 409 RefConflict if the head tip
248 // moved since this page loaded.
249 ...(detail.headOid !== null ? { expectedHeadOid: detail.headOid } : {}),
250 }),
251 )
252 }
253 >
254 {busy ? "Working…" : "Merge pull request"}
255 </Button>
256 <Button
257 disabled={busy}
258 onClick={() =>
259 act(() =>
260 updatePull(connection, owner, name, number, {
261 state: "closed",
262 }),
263 )
264 }
265 >
266 Close
267 </Button>
268 {detail.mergeable !== true && (
269 <span className="text-xs text-fg-muted">
270 merging is disabled until the branch is mergeable
271 </span>
272 )}
273 </div>
274 )}
275 {actionError !== null && <p className="mt-2 text-sm text-danger">{actionError}</p>}
276 </div>
277 )}
278 {detail.state === "closed" && (
279 <div className="mb-4 rounded-md border border-border-muted bg-canvas-subtle px-4 py-3 text-sm">
280 <p className="text-fg-muted">This pull request is closed without being merged.</p>
281 {signedIn && (
282 <div className="mt-3">
283 <Button
284 disabled={busy}
285 onClick={() =>
286 act(() =>
287 updatePull(connection, owner, name, number, {
288 state: "open",
289 }),
290 )
291 }
292 >
293 Reopen
294 </Button>
295 </div>
296 )}
297 {actionError !== null && <p className="mt-2 text-sm text-danger">{actionError}</p>}
298 </div>
299 )}
300
301 {/* compare: commits + files changed */}
302 {compare === null ? (
303 <Spinner />
304 ) : compare === "unavailable" ? (
305 <div className="rounded-md border border-border-muted px-4 py-8 text-center text-sm text-fg-muted">
306 {detail.state === "merged" && detail.mergeCommit !== null ? (
307 <>
308 Live comparison is not available for merged pull requests — see the{" "}
309 <Link
310 to={href(owner, name, "commit", detail.mergeCommit)}
311 className="font-mono text-accent hover:underline"
312 >
313 merge commit
314 </Link>
315 .
316 </>
317 ) : (
318 "Comparison unavailable — the base or head branch no longer exists."
319 )}
320 </div>
321 ) : (
322 <>
323 <div className="mb-4 flex gap-1 border-b border-border-muted text-sm">
324 {(
325 [
326 ["files", `Files changed (${compare.files.length})`],
327 ["commits", `Commits (${compare.commits.length})`],
328 ] as const
329 ).map(([key, label]) => (
330 <button
331 key={key}
332 type="button"
333 onClick={() => setTab(key)}
334 className={`cursor-pointer border-b-2 px-3 py-2 ${
335 tab === key
336 ? "border-tab-active font-semibold"
337 : "border-transparent text-fg-muted hover:border-border-muted"
338 }`}
339 >
340 {label}
341 </button>
342 ))}
343 </div>
344
345 {tab === "commits" ? (
346 <ul className="overflow-hidden rounded-md border border-border-muted">
347 {compare.commits.map((commit) => (
348 <li
349 key={commit.oid}
350 className="flex items-start justify-between gap-4 border-b border-border-muted px-4 py-3 last:border-b-0"
351 >
352 <div className="min-w-0">
353 <Link
354 to={href(owner, name, "commit", commit.oid)}
355 className="text-sm font-semibold hover:text-accent hover:underline"
356 >
357 {subject(commit.message)}
358 </Link>
359 <p className="mt-0.5 text-xs text-fg-muted">
360 {commit.author.name} committed {timeAgo(commit.author.date * 1000)}
361 </p>
362 </div>
363 <div className="flex shrink-0 items-center gap-1">
364 <Link
365 to={href(owner, name, "commit", commit.oid)}
366 className="rounded border border-border-muted px-2 py-0.5 font-mono text-xs text-accent hover:underline"
367 >
368 {shortOid(commit.oid)}
369 </Link>
370 <CopyButton text={commit.oid} />
371 </div>
372 </li>
373 ))}
374 {compare.commits.length === 0 && (
375 <li className="px-4 py-8 text-center text-sm text-fg-muted">
376 No commits — the head branch is not ahead of the base.
377 </li>
378 )}
379 {compare.commitsTruncated && (
380 <li className="border-t border-border-muted bg-canvas-subtle px-4 py-2 text-center text-xs text-fg-muted">
381 Commit list truncated by the server.
382 </li>
383 )}
384 </ul>
385 ) : (
386 <>
387 {compare.filesTruncated && (
388 <div className="mb-3 rounded-md border border-attention/40 bg-attention/5 px-4 py-2 text-sm text-attention">
389 This pull request changes more files than shown — the list was truncated at{" "}
390 {compare.files.length} files by the server.
391 </div>
392 )}
393 <FileDiffList context={context} files={compare.files} />
394 </>
395 )}
396 </>
397 )}
398 </div>
399 );
400 };
401
402 export default PullPage;