Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestThreadDialog.tsx

364 lines12.5 KB

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, useMessages, Var } 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;
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 }
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 messages = useMessages();
81 const referenceInputRef = useRef<HTMLInputElement>(null);
82 const [reference, setReference] = useState(initialReference ?? "");
83 const [referenceDirty, setReferenceDirty] = useState(false);
84 const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
85 const [prepareErrorMessage, setPrepareErrorMessage] = useState<string | null>(null);
86 const [debouncedReference, referenceDebouncer] = useDebouncedValue(
87 reference,
88 { wait: 450 },
89 (debouncerState) => ({ isPending: debouncerState.isPending }),
90 );
91 const { data: gitStatus } = useEnvironmentQuery(
92 cwd === null
93 ? null
94 : vcsEnvironment.status({
95 environmentId,
96 input: { cwd },
97 }),
98 );
99 const sourceControlPresentation = getSourceControlPresentation(gitStatus?.sourceControlProvider);
100 const terminology = sourceControlPresentation.terminology;
101 const term = changeRequestTermKind(terminology);
102 const SourceControlIcon = sourceControlPresentation.Icon;
103​
104 const parsedReference = parsePullRequestReference(reference);
105 const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
106 const pullRequestResolution = usePullRequestResolutionState({
107 environmentId,
108 cwd,
109 reference: open ? parsedDebouncedReference : null,
110 });
111 const cachedPullRequest =
112 readCachedPullRequestResolution({
113 environmentId,
114 cwd,
115 reference: parsedReference,
116 })?.pullRequest ?? null;
117 const preparePullRequestThreadAction = usePreparePullRequestThreadAction({ environmentId, cwd });
118 const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
119​
120 const liveResolvedPullRequest =
121 parsedReference !== null && parsedReference === parsedDebouncedReference
122 ? (pullRequestResolution.data?.pullRequest ?? null)
123 : null;
124 const resolvedPullRequest = liveResolvedPullRequest ?? cachedPullRequest;
125 const isResolving =
126 open &&
127 parsedReference !== null &&
128 resolvedPullRequest === null &&
129 (referenceDebouncer.state.isPending ||
130 parsedReference !== parsedDebouncedReference ||
131 pullRequestResolution.isPending ||
132 pullRequestResolution.isFetching);
133 const statusTone = pullRequestStatusTone(resolvedPullRequest?.state);
134​
135 const handleConfirm = async (mode: "local" | "worktree") => {
136 if (!preparePullRequestThreadAction.isAllowed) return;
137 if (
138 mode === "worktree" &&
139 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
140 ) {
141 return;
142 }
143 if (!parsedReference) {
144 setReferenceDirty(true);
145 return;
146 }
147 if (!parsedReference || !resolvedPullRequest || !cwd) {
148 return;
149 }
150 setPrepareErrorMessage(null);
151 setPreparingMode(mode);
152 const result = await preparePullRequestThreadAction.run({
153 reference: parsedReference,
154 mode,
155 ...(mode === "worktree" ? { threadId } : {}),
156 });
157 setPreparingMode(null);
158 if (result._tag === "Failure") {
159 if (isAtomCommandInterrupted(result)) {
160 preparePullRequestThreadAction.resetError();
161 } else {
162 const error = squashAtomCommandFailure(result);
163 setPrepareErrorMessage(
164 thrownErrorMessage(error, m) ??
165 gt(
166 "Failed to prepare {term, select, mr {merge request} cr {change request} other {pull request}} thread.",
167 { term },
168 ),
169 );
170 }
171 return;
172 }
173 await onPrepared({
174 branch: result.value.branch,
175 worktreePath: result.value.worktreePath,
176 pullRequestUrl: result.value.pullRequest.url,
177 });
178 if (!result.value.isOnPullRequestHead) {
179 toastManager.add(offHeadPullRequestCheckoutToast(terminology));
180 }
181 onOpenChange(false);
182 };
183​
184 const validationMessage = !referenceDirty
185 ? null
186 : reference.trim().length === 0
187 ? gt(
188 "Paste a {term, select, mr {merge request} cr {change request} other {pull request}} URL, checkout command, or enter 123 / #123.",
189 { term },
190 )
191 : parsedReference === null
192 ? gt(
193 "Use a {term, select, mr {merge request} cr {change request} other {pull request}} URL, checkout command, 123, or #123.",
194 { term },
195 )
196 : null;
197 const errorMessage =
198 validationMessage ??
199 prepareErrorMessage ??
200 (resolvedPullRequest === null && pullRequestResolution.error
201 ? pullRequestResolution.error
202 : preparePullRequestThreadAction.error
203 ? (thrownErrorMessage(preparePullRequestThreadAction.error, messages) ??
204 gt(
205 "Failed to prepare {term, select, mr {merge request} cr {change request} other {pull request}} thread.",
206 { term },
207 ))
208 : null);
209​
210 return (
211 <Dialog
212 open={open}
213 onOpenChange={(nextOpen) => {
214 if (!preparePullRequestThreadAction.isPending) {
215 onOpenChange(nextOpen);
216 }
217 }}
218 >
219 <DialogPopup
220 className="max-w-xl"
221 initialFocus={() => {
222 referenceInputRef.current?.focus();
223 referenceInputRef.current?.select();
224 return false;
225 }}
226 >
227 <DialogHeader>
228 <DialogTitle className="flex items-center">
229 <SourceControlIcon className="me-2 size-4" />
230 {gt(
231 "Checkout {term, select, mr {merge request} cr {change request} other {pull request}}",
232 { term },
233 )}
234 </DialogTitle>
235 <DialogDescription>
236 {gt(
237 "Resolve a {provider} {term, select, mr {merge request} cr {change request} other {pull request}}, then create the draft thread in the main repo or in a dedicated worktree.",
238 { provider: sourceControlPresentation.providerName, term },
239 )}
240 </DialogDescription>
241 </DialogHeader>
242 <DialogPanel>
243 <label className="grid gap-1.5">
244 <span className="text-xs font-medium text-foreground capitalize">
245 {gt("{term, select, mr {merge request} cr {change request} other {pull request}}", {
246 term,
247 $context: "field label, capitalized by CSS",
248 })}
249 </span>
250 <Input
251 ref={referenceInputRef}
252 placeholder={gt(
253 "{term, select, mr {MR} cr {change request} other {PR}} URL, checkout command, or #42",
254 {
255 term,
256 },
257 )}
258 value={reference}
259 onChange={(event) => {
260 setReferenceDirty(true);
261 setReference(event.target.value);
262 }}
263 onKeyDown={(event) => {
264 if (event.key !== "Enter") {
265 return;
266 }
267 if (event.nativeEvent.isComposing || event.keyCode === 229) {
268 return;
269 }
270 event.preventDefault();
271 if (!isResolving && !preparePullRequestThreadAction.isPending) {
272 void handleConfirm("worktree");
273 }
274 }}
275 />
276 </label>
277​
278 {resolvedPullRequest ? (
279 <div className="rounded-xl border border-border/70 bg-muted/24 p-3">
280 <div className="flex items-start justify-between gap-3">
281 <div className="min-w-0">
282 <p className="truncate font-medium text-sm">{resolvedPullRequest.title}</p>
283 <p className="truncate text-muted-foreground text-xs">
284 <T>
285 #<Var>{resolvedPullRequest.number}</Var> ·{" "}
286 <Var>{resolvedPullRequest.headBranch}</Var> to{" "}
287 <Var>{resolvedPullRequest.baseBranch}</Var>
288 </T>
289 </p>
290 </div>
291 <span className={cn("shrink-0 text-xs capitalize", statusTone)}>
292 {gt(
293 "{state, select, open {open} closed {closed} merged {merged} other {{state}}}",
294 {
295 state: resolvedPullRequest.state,
296 $context: "pull request state, capitalized by CSS",
297 },
298 )}
299 </span>
300 </div>
301 </div>
302 ) : null}
303​
304 {isResolving ? (
305 <div className="flex items-center gap-2 text-muted-foreground text-xs">
306 <Spinner size="sm" />
307 {gt(
308 "Resolving {term, select, mr {merge request} cr {change request} other {pull request}}...",
309 { term },
310 )}
311 </div>
312 ) : null}
313​
314 {errorMessage ? <p className="text-destructive text-xs">{errorMessage}</p> : null}
315 </DialogPanel>
316 <DialogFooter>
317 <Button
318 type="button"
319 variant="outline"
320 size="sm"
321 onClick={() => onOpenChange(false)}
322 disabled={preparePullRequestThreadAction.isPending}
323 >
324 {gt("Cancel")}
325 </Button>
326 <Button
327 type="button"
328 size="sm"
329 variant="outline"
330 onClick={() => handleConfirm("local")}
331 disabled={
332 !preparePullRequestThreadAction.isAllowed ||
333 !cwd ||
334 !resolvedPullRequest ||
335 isResolving ||
336 preparePullRequestThreadAction.isPending
337 }
338 >
339 {preparingMode === "local"
340 ? gt("Preparing local...")
341 : gt("Local", { $context: "checkout in the main repo" })}
342 </Button>
343 <Button
344 type="button"
345 size="sm"
346 onClick={() => handleConfirm("worktree")}
347 disabled={
348 !preparePullRequestThreadAction.isAllowed ||
349 !canOperateThread ||
350 !cwd ||
351 !resolvedPullRequest ||
352 isResolving ||
353 preparePullRequestThreadAction.isPending
354 }
355 >
356 {preparingMode === "worktree"
357 ? gt("Preparing worktree...")
358 : gt("Worktree", { $context: "checkout in a new git worktree" })}
359 </Button>
360 </DialogFooter>
361 </DialogPopup>
362 </Dialog>
363 );