Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 type EnvironmentId,
4 type ThreadId,
5} from "@t3tools/contracts";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
11import { m } from "../i18n/messages";
12import { useDebouncedValue } from "@tanstack/react-pacer";
13import { useRef, useState } from "react";
14import { T, useGT, Var, select, part } from "gt-react";
15import { changeRequestTermKind } from "./pullRequest/changeRequestTerm";
16
17import {
18 readCachedPullRequestResolution,
19 usePreparePullRequestThreadAction,
20 usePullRequestResolutionState,
21} from "~/state/sourceControlActions";
22import { cn } from "~/lib/utils";
23import { parsePullRequestReference } from "@t3tools/client-runtime/pull-request-link-input";
24import { getSourceControlPresentation } from "~/sourceControlPresentation";
25import { useEnvironmentQuery } from "~/state/query";
26import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
27import { vcsEnvironment } from "~/state/vcs";
28import { offHeadPullRequestCheckoutToast } from "./pullRequest/pullRequestCheckoutToast";
29import { Button } from "./ui/button";
30import {
31 Dialog,
32 DialogDescription,
33 DialogFooter,
34 DialogHeader,
35 DialogPanel,
36 DialogPopup,
37 DialogTitle,
38} from "./ui/dialog";
39import { Input } from "./ui/input";
40import { Spinner } from "./ui/spinner";
41import { toastManager } from "./ui/toast";
42
43interface PullRequestThreadDialogProps {
44 open: boolean;
45 environmentId: EnvironmentId;
46 threadId: ThreadId;
47 cwd: string | null;
48 initialReference: string | null;
49 onOpenChange: (open: boolean) => void;
50 onPrepared: (input: {
51 branch: string;
52 worktreePath: string | null;
53 pullRequestUrl: string;
54 }) => Promise<void> | void;
55}
56
57function pullRequestStatusTone(state: string | undefined): string {
58 switch (state) {
59 case "merged":
60 return "text-violet-600 dark:text-violet-300/90";
61 case "closed":
62 return "text-zinc-500 dark:text-zinc-400/80";
63 case "open":
64 return "text-emerald-600 dark:text-emerald-300/90";
65 default:
66 return "text-muted-foreground";
67 }
68}
69
70export function PullRequestThreadDialog({
71 open,
72 environmentId,
73 threadId,
74 cwd,
75 initialReference,
76 onOpenChange,
77 onPrepared,
78}: PullRequestThreadDialogProps) {
79 const gt = useGT();
80 const referenceInputRef = useRef<HTMLInputElement>(null);
81 const [reference, setReference] = useState(initialReference ?? "");
82 const [referenceDirty, setReferenceDirty] = useState(false);
83 const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
84 const [checkoutError, setCheckoutError] = useState<{ target: string; message: string } | null>(
85 null,
86 );
87 const [debouncedReference, referenceDebouncer] = useDebouncedValue(
88 reference,
89 { wait: 450 },
90 (debouncerState) => ({ isPending: debouncerState.isPending }),
91 );
92 const { data: gitStatus } = useEnvironmentQuery(
93 cwd === null
94 ? null
95 : vcsEnvironment.status({
96 environmentId,
97 input: { cwd },
98 }),
99 );
100 const sourceControlPresentation = getSourceControlPresentation(gitStatus?.sourceControlProvider);
101 const terminology = sourceControlPresentation.terminology;
102 const term = changeRequestTermKind(terminology);
103 const SourceControlIcon = sourceControlPresentation.Icon;
104
105 const parsedReference = parsePullRequestReference(reference);
106 const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
107 const pullRequestResolution = usePullRequestResolutionState({
108 environmentId,
109 cwd,
110 reference: open ? parsedDebouncedReference : null,
111 });
112 const cachedPullRequest =
113 readCachedPullRequestResolution({
114 environmentId,
115 cwd,
116 reference: parsedReference,
117 })?.pullRequest ?? null;
118 const preparePullRequestThreadAction = usePreparePullRequestThreadAction({ environmentId, cwd });
119 const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
120
121 const liveResolvedPullRequest =
122 parsedReference !== null && parsedReference === parsedDebouncedReference
123 ? (pullRequestResolution.data?.pullRequest ?? null)
124 : null;
125 const resolvedPullRequest = liveResolvedPullRequest ?? cachedPullRequest;
126 const checkoutTarget = JSON.stringify([environmentId, cwd, threadId, parsedReference]);
127 const isResolving =
128 open &&
129 parsedReference !== null &&
130 resolvedPullRequest === null &&
131 (referenceDebouncer.state.isPending ||
132 parsedReference !== parsedDebouncedReference ||
133 pullRequestResolution.isPending ||
134 pullRequestResolution.isFetching);
135 const statusTone = pullRequestStatusTone(resolvedPullRequest?.state);
136
137 const handleConfirm = async (mode: "local" | "worktree") => {
138 if (!preparePullRequestThreadAction.isAllowed) return;
139 if (
140 mode === "worktree" &&
141 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
142 ) {
143 return;
144 }
145 if (!parsedReference) {
146 setReferenceDirty(true);
147 return;
148 }
149 if (!parsedReference || !resolvedPullRequest || !cwd) {
150 return;
151 }
152 setCheckoutError(null);
153 setPreparingMode(mode);
154 const result = await preparePullRequestThreadAction.run({
155 reference: parsedReference,
156 mode,
157 ...(mode === "worktree" ? { threadId } : {}),
158 });
159 setPreparingMode(null);
160 if (result._tag === "Failure") {
161 if (!isAtomCommandInterrupted(result)) {
162 const error = squashAtomCommandFailure(result);
163 setCheckoutError({
164 target: checkoutTarget,
165 message:
166 thrownErrorMessage(error, m) ??
167 gt`Failed to prepare ${select(
168 { term },
169 {
170 mr: "merge request",
171 cr: "change request",
172 other: "pull request",
173 },
174 )} thread.`,
175 });
176 }
177 return;
178 }
179 await onPrepared({
180 branch: result.value.branch,
181 worktreePath: result.value.worktreePath,
182 pullRequestUrl: result.value.pullRequest.url,
183 });
184 if (!result.value.isOnPullRequestHead) {
185 toastManager.add(offHeadPullRequestCheckoutToast(terminology));
186 }
187 onOpenChange(false);
188 };
189
190 const validationMessage = !referenceDirty
191 ? null
192 : reference.trim().length === 0
193 ? gt`Paste a ${select(
194 { term },
195 {
196 mr: "merge request",
197 cr: "change request",
198 other: "pull request",
199 },
200 )} URL, checkout command, or enter 123 / #123.`
201 : parsedReference === null
202 ? gt`Use a ${select(
203 { term },
204 {
205 mr: "merge request",
206 cr: "change request",
207 other: "pull request",
208 },
209 )} URL, checkout command, 123, or #123.`
210 : null;
211 const errorMessage =
212 validationMessage ??
213 (checkoutError?.target === checkoutTarget ? checkoutError.message : null) ??
214 (!isResolving && resolvedPullRequest === null ? pullRequestResolution.error : null);
215
216 return (
217 <Dialog
218 open={open}
219 onOpenChange={(nextOpen) => {
220 if (!preparePullRequestThreadAction.isPending) {
221 onOpenChange(nextOpen);
222 }
223 }}
224 >
225 <DialogPopup
226 className="max-w-xl"
227 initialFocus={() => {
228 referenceInputRef.current?.focus();
229 referenceInputRef.current?.select();
230 return false;
231 }}
232 >
233 <DialogHeader>
234 <DialogTitle className="flex items-center">
235 <SourceControlIcon className="me-2 size-4" />
236 {gt`Checkout ${select(
237 { term },
238 {
239 mr: "merge request",
240 cr: "change request",
241 other: "pull request",
242 },
243 )}`}
244 </DialogTitle>
245 <DialogDescription>
246 {gt`Resolve a ${{ provider: sourceControlPresentation.providerName }} ${select(
247 { term },
248 {
249 mr: "merge request",
250 cr: "change request",
251 other: "pull request",
252 },
253 )}, then create the draft thread in the main repo or in a dedicated worktree.`}
254 </DialogDescription>
255 </DialogHeader>
256 <DialogPanel>
257 <label className="grid gap-1.5">
258 <span className="text-xs font-medium text-foreground capitalize">
259 {gt({ context: "field label, capitalized by CSS" })`${select(
260 { term },
261 {
262 mr: "merge request",
263 cr: "change request",
264 other: "pull request",
265 },
266 )}`}
267 </span>
268 <Input
269 ref={referenceInputRef}
270 placeholder={gt`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} URL, checkout command, or #42`}
271 value={reference}
272 onChange={(event) => {
273 setReferenceDirty(true);
274 setReference(event.target.value);
275 }}
276 onKeyDown={(event) => {
277 if (event.key !== "Enter") {
278 return;
279 }
280 if (event.nativeEvent.isComposing || event.keyCode === 229) {
281 return;
282 }
283 event.preventDefault();
284 if (!isResolving && !preparePullRequestThreadAction.isPending) {
285 void handleConfirm("worktree");
286 }
287 }}
288 />
289 </label>
290
291 {resolvedPullRequest ? (
292 <div className="rounded-xl border border-border/70 bg-muted/24 p-3">
293 <div className="flex items-start justify-between gap-3">
294 <div className="min-w-0">
295 <p className="truncate font-medium text-sm">{resolvedPullRequest.title}</p>
296 <p className="truncate text-muted-foreground text-xs">
297 <T>
298 #<Var>{resolvedPullRequest.number}</Var> ·{" "}
299 <Var>{resolvedPullRequest.headBranch}</Var> to{" "}
300 <Var>{resolvedPullRequest.baseBranch}</Var>
301 </T>
302 </p>
303 </div>
304 <span className={cn("shrink-0 text-xs capitalize", statusTone)}>
305 {gt({ context: "pull request state, capitalized by CSS" })`${select(
306 { state: resolvedPullRequest.state },
307 {
308 open: "open",
309 closed: "closed",
310 merged: "merged",
311 other: part`${{ state: resolvedPullRequest.state }}`,
312 },
313 )}`}
314 </span>
315 </div>
316 </div>
317 ) : null}
318
319 {isResolving ? (
320 <div className="flex items-center gap-2 text-muted-foreground text-xs">
321 <Spinner size="sm" />
322 {gt`Resolving ${select(
323 { term },
324 {
325 mr: "merge request",
326 cr: "change request",
327 other: "pull request",
328 },
329 )}...`}
330 </div>
331 ) : null}
332
333 {errorMessage ? <p className="text-destructive text-xs">{errorMessage}</p> : null}
334 </DialogPanel>
335 <DialogFooter>
336 <Button
337 type="button"
338 variant="outline"
339 size="sm"
340 onClick={() => onOpenChange(false)}
341 disabled={preparePullRequestThreadAction.isPending}
342 >
343 {gt`Cancel`}
344 </Button>
345 <Button
346 type="button"
347 size="sm"
348 variant="outline"
349 onClick={() => handleConfirm("local")}
350 disabled={
351 !preparePullRequestThreadAction.isAllowed ||
352 !cwd ||
353 !resolvedPullRequest ||
354 isResolving ||
355 preparePullRequestThreadAction.isPending
356 }
357 >
358 {preparingMode === "local"
359 ? gt`Preparing local...`
360 : gt({ context: "checkout in the main repo" })`Local`}
361 </Button>
362 <Button
363 type="button"
364 size="sm"
365 onClick={() => handleConfirm("worktree")}
366 disabled={
367 !preparePullRequestThreadAction.isAllowed ||
368 !canOperateThread ||
369 !cwd ||
370 !resolvedPullRequest ||
371 isResolving ||
372 preparePullRequestThreadAction.isPending
373 }
374 >
375 {preparingMode === "worktree"
376 ? gt`Preparing worktree...`
377 : gt({ context: "checkout in a new git worktree" })`Worktree`}
378 </Button>
379 </DialogFooter>
380 </DialogPopup>
381 </Dialog>
382 );
383}