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

main
tsx 298 lines 10.2 KB
Raw
1 /**
2 * The Pull requests tab (`/:owner/:repo/pulls`): GitHub-style list with
3 * open/closed/merged filter tabs and a "New pull request" form
4 * (base/head branch selectors from the refs advertisement) for
5 * signed-in users.
6 *
7 * Deliberately free of `@pierre/diffs` imports — this module is statically
8 * imported by `Repo.tsx` and lives in the initial bundle; the diff-heavy
9 * detail page (`Pull.tsx`) is a separate lazy chunk.
10 */
11 import { useEffect, useState } from "react";
12 import { createPull, listPulls, type Pull, type PullState } from "../client.ts";
13 import {
14 Button,
15 ErrorBox,
16 GitMergeIcon,
17 Input,
18 PullClosedIcon,
19 PullRequestIcon,
20 Spinner,
21 } from "../components.tsx";
22 import { timeAgo } from "../format.ts";
23 import { href, Link, useRouter } from "../router.tsx";
24 import type { RepoContext } from "./Repo.tsx";
25
26 // ── shared PR presentation atoms (also used by Pull.tsx) ────────────────────
27
28 /** `refs/heads/main` → `main` (display only; API calls keep full names). */
29 export const shortRef = (ref: string): string => ref.replace(/^refs\/(heads|tags)\//, "");
30
31 /** The octicon for a PR state (uncolored — callers pick the tone). */
32 export const PullStateGlyph = ({ state, className }: { state: PullState; className?: string }) =>
33 state === "open" ? (
34 <PullRequestIcon className={className} />
35 ) : state === "merged" ? (
36 <GitMergeIcon className={className} />
37 ) : (
38 <PullClosedIcon className={className} />
39 );
40
41 /** Foreground tone matching a PR state (list rows, inline glyphs). */
42 export const stateTone: Record<PullState, string> = {
43 open: "text-success",
44 merged: "text-done",
45 closed: "text-danger",
46 };
47
48 /** GitHub-style filled state pill: green Open, purple Merged, red Closed. */
49 export const PullStateBadge = ({ state }: { state: PullState }) => (
50 <span
51 className={`inline-flex shrink-0 items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium text-fg-on-emphasis ${
52 state === "open"
53 ? "bg-success-emphasis"
54 : state === "merged"
55 ? "bg-done-emphasis"
56 : "bg-danger-emphasis"
57 }`}
58 >
59 <PullStateGlyph state={state} className="size-3.5" />
60 {state === "open" ? "Open" : state === "merged" ? "Merged" : "Closed"}
61 </span>
62 );
63
64 // ── list row ────────────────────────────────────────────────────────────────
65
66 const PullRow = ({ context, pull }: { context: RepoContext; pull: Pull }) => {
67 const { owner, name } = context.repo;
68 return (
69 <li className="flex items-start gap-3 border-b border-border-muted px-4 py-3 last:border-b-0 hover:bg-canvas-subtle">
70 <PullStateGlyph state={pull.state} className={`mt-0.5 shrink-0 ${stateTone[pull.state]}`} />
71 <div className="min-w-0 grow">
72 <Link
73 to={href(owner, name, "pulls", String(pull.number))}
74 className="text-sm font-semibold hover:text-accent hover:underline"
75 >
76 {pull.title}
77 </Link>
78 <p className="mt-0.5 text-xs text-fg-muted">
79 #{pull.number}{" "}
80 {pull.state === "merged"
81 ? `merged ${timeAgo(pull.mergedAt ?? pull.updatedAt)}`
82 : pull.state === "closed"
83 ? `closed ${timeAgo(pull.updatedAt)}`
84 : `opened ${timeAgo(pull.createdAt)}`}{" "}
85 · <code className="font-mono">{shortRef(pull.baseRef)}</code>
86 {" ← "}
87 <code className="font-mono">{shortRef(pull.headRef)}</code>
88 </p>
89 </div>
90 </li>
91 );
92 };
93
94 // ── new pull request form ───────────────────────────────────────────────────
95
96 const BranchSelect = ({
97 label,
98 value,
99 onChange,
100 branches,
101 }: {
102 label: string;
103 value: string;
104 onChange: (value: string) => void;
105 branches: string[];
106 }) => (
107 <label className="inline-flex items-center gap-1.5 rounded-md border border-border-muted bg-canvas px-2.5 py-1.5 text-sm">
108 <span className="text-fg-muted">{label}:</span>
109 <select
110 value={value}
111 onChange={(event) => onChange(event.target.value)}
112 className="cursor-pointer appearance-none bg-transparent font-medium outline-none"
113 >
114 {branches.map((branch) => (
115 <option key={branch} value={branch}>
116 {branch}
117 </option>
118 ))}
119 </select>
120 </label>
121 );
122
123 const NewPullForm = ({
124 context,
125 onCreated,
126 }: {
127 context: RepoContext;
128 onCreated: (pull: Pull) => void;
129 }) => {
130 const branches = context.refs.refs
131 .filter((ref) => ref.name.startsWith("refs/heads/"))
132 .map((ref) => shortRef(ref.name));
133 const defaultBase = branches.includes(context.repo.defaultBranch)
134 ? context.repo.defaultBranch
135 : (branches[0] ?? "");
136 const [base, setBase] = useState(defaultBase);
137 const [head, setHead] = useState(
138 branches.find((branch) => branch !== defaultBase) ?? defaultBase,
139 );
140 const [title, setTitle] = useState("");
141 const [body, setBody] = useState("");
142 const [error, setError] = useState<unknown>(null);
143 const [busy, setBusy] = useState(false);
144 const { connection, repo } = context;
145
146 const submit = async () => {
147 setBusy(true);
148 setError(null);
149 try {
150 const pull = await createPull(connection, repo.owner, repo.name, {
151 title: title.trim(),
152 base,
153 head,
154 ...(body.trim() ? { body: body.trim() } : {}),
155 });
156 onCreated(pull);
157 } catch (cause) {
158 setError(cause);
159 } finally {
160 setBusy(false);
161 }
162 };
163
164 return (
165 <form
166 className="mb-4 space-y-3 rounded-md border border-border-muted bg-canvas-subtle p-4"
167 onSubmit={(event) => {
168 event.preventDefault();
169 void submit();
170 }}
171 >
172 <div className="flex flex-wrap items-center gap-2 text-sm">
173 <BranchSelect label="base" value={base} onChange={setBase} branches={branches} />
174 <span className="text-fg-muted">←</span>
175 <BranchSelect label="compare" value={head} onChange={setHead} branches={branches} />
176 {head === base && (
177 <span className="text-xs text-attention">choose two different branches</span>
178 )}
179 </div>
180 <Input value={title} onChange={setTitle} placeholder="Title" />
181 <textarea
182 value={body}
183 onChange={(event) => setBody(event.target.value)}
184 placeholder="Description (optional, Markdown)"
185 rows={5}
186 className="w-full rounded-md border border-border-muted bg-canvas px-3 py-1.5 text-sm outline-none focus:border-accent focus:ring-2 focus:ring-accent/30"
187 />
188 {error != null && <ErrorBox error={error} />}
189 <Button
190 kind="primary"
191 type="submit"
192 disabled={busy || title.trim().length === 0 || head === base}
193 >
194 {busy ? "Creating…" : "Create pull request"}
195 </Button>
196 </form>
197 );
198 };
199
200 // ── the tab ─────────────────────────────────────────────────────────────────
201
202 const FILTERS: PullState[] = ["open", "closed", "merged"];
203
204 export const PullsTab = ({ context }: { context: RepoContext }) => {
205 const [filter, setFilter] = useState<PullState>("open");
206 const [pulls, setPulls] = useState<Pull[] | null>(null);
207 const [cursor, setCursor] = useState<string | null>(null);
208 const [error, setError] = useState<unknown>(null);
209 const [showNew, setShowNew] = useState(false);
210 const { navigate } = useRouter();
211 const { connection, repo } = context;
212 const signedIn = context.user !== null;
213
214 const load = async (state: PullState, nextCursor?: string) => {
215 try {
216 const page = await listPulls(connection, repo.owner, repo.name, {
217 state,
218 limit: 50,
219 ...(nextCursor ? { cursor: nextCursor } : {}),
220 });
221 setPulls((existing) => (nextCursor ? [...(existing ?? []), ...page.items] : page.items));
222 setCursor(page.hasMore ? page.nextCursor : null);
223 } catch (cause) {
224 setError(cause);
225 }
226 };
227
228 useEffect(() => {
229 setPulls(null);
230 setError(null);
231 void load(filter);
232 // eslint-disable-next-line react-hooks/exhaustive-deps
233 }, [filter, repo.repoId]);
234
235 if (error != null) return <ErrorBox error={error} />;
236
237 return (
238 <div>
239 <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
240 <div className="flex items-center gap-1 rounded-md border border-border-muted p-0.5">
241 {FILTERS.map((state) => (
242 <button
243 key={state}
244 type="button"
245 onClick={() => setFilter(state)}
246 className={`inline-flex cursor-pointer items-center gap-1.5 rounded px-3 py-1 text-sm capitalize ${
247 filter === state
248 ? "bg-canvas-subtle font-semibold"
249 : "text-fg-muted hover:text-fg-default"
250 }`}
251 >
252 <PullStateGlyph
253 state={state}
254 className={`size-3.5 ${filter === state ? stateTone[state] : ""}`}
255 />
256 {state}
257 </button>
258 ))}
259 </div>
260 {signedIn && (
261 <Button kind="primary" onClick={() => setShowNew((value) => !value)}>
262 New pull request
263 </Button>
264 )}
265 </div>
266
267 {showNew && (
268 <NewPullForm
269 context={context}
270 onCreated={(pull) => navigate(href(repo.owner, repo.name, "pulls", String(pull.number)))}
271 />
272 )}
273
274 {pulls === null ? (
275 <Spinner />
276 ) : (
277 <>
278 <ul className="overflow-hidden rounded-md border border-border-muted">
279 {pulls.map((pull) => (
280 <PullRow key={pull.number} context={context} pull={pull} />
281 ))}
282 {pulls.length === 0 && (
283 <li className="px-4 py-12 text-center text-sm text-fg-muted">
284 No {filter} pull requests
285 {filter === "open" && signedIn && " — create one above."}
286 </li>
287 )}
288 </ul>
289 {cursor !== null && (
290 <div className="mt-4 flex justify-center">
291 <Button onClick={() => void load(filter, cursor)}>Load more</Button>
292 </div>
293 )}
294 </>
295 )}
296 </div>
297 );
298 };