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

LinkPullRequestDialog.tsx

257 lines8.4 KB

1import { pullRequestHostOf, type ScopedThreadRef } from "@t3tools/contracts";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import { useAtomValue } from "@effect/atom-react";
4import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import { useEffect, useRef, useState } from "react";
6​
7import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";
8import { parsePullRequestReference } from "~/pullRequestReference";
9import { useProjects, useThreadShell } from "~/state/entities";
10import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
11import { appAtomRegistry } from "~/rpc/atomRegistry";
12import { Atom } from "effect/reactivity";
13import { Button } from "../ui/button";
14import {
15 Dialog,
16 DialogDescription,
17 DialogFooter,
18 DialogHeader,
19 DialogPanel,
20 DialogPopup,
21 DialogTitle,
22} from "../ui/dialog";
23import { Input } from "../ui/input";
24​
25/**
26 * Which thread has the link dialog open, set by whichever entry point asked (command palette,
27 * pull-requests surface, detail panel) and rendered once by the chat view so the dialog outlives
28 * a palette that closes the moment its command runs.
29 */
30const linkPullRequestDialogThreadAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
31 Atom.keepAlive,
32 Atom.withLabel("pull-requests:link-dialog-thread"),
33);
34​
35export function openLinkPullRequestDialog(threadRef: ScopedThreadRef): void {
36 appAtomRegistry.set(linkPullRequestDialogThreadAtom, threadRef);
38​
39interface LinkPullRequestDialogProps {
40 open: boolean;
41 threadRef: ScopedThreadRef;
42 projectId: string | null;
43 onOpenChange: (open: boolean) => void;
45​
46export function LinkPullRequestDialogHost() {
47 const threadRef = useAtomValue(linkPullRequestDialogThreadAtom);
48 const thread = useThreadShell(threadRef);
49 const linking = usePullRequestLinking(threadRef?.environmentId);
50 if (threadRef === null || linking.mode === "unsupported") return null;
51 return (
52 <LinkPullRequestDialog
53 open
54 threadRef={threadRef}
55 projectId={thread?.projectId ?? null}
56 onOpenChange={(open) => {
57 if (!open) appAtomRegistry.set(linkPullRequestDialogThreadAtom, null);
58 }}
59 />
60 );
62​
63interface ResolvedLink {
64 readonly host: string;
65 readonly repository: string;
66 readonly number: number;
67 readonly url: string;
69​
70export function resolveLinkPullRequestInput(input: {
71 readonly reference: string;
72 readonly project: {
73 readonly host: string;
74 readonly repository: string;
75 readonly webUrl: (number: number) => string | null;
76 } | null;
77 readonly hasProject: (reference: ResolvedLink) => boolean;
78}): { link: ResolvedLink } | { error: string } | null {
79 const parsed =
80 parseChangeRequestUrl(input.reference.trim()) !== null
81 ? input.reference.trim()
82 : parsePullRequestReference(input.reference);
83 if (parsed === null) return null;
84 const url = parseChangeRequestUrl(parsed);
85 if (url !== null) {
86 if (!input.hasProject({ ...url, url: parsed })) {
87 return { error: `No project in this environment can read ${url.host}/${url.repository}.` };
88 }
89 return {
90 link: { host: url.host, repository: url.repository, number: url.number, url: parsed },
91 };
92 }
93 const number = Number(parsed);
94 if (!Number.isSafeInteger(number) || number < 1) return null;
95 if (input.project === null) {
96 return { error: "Paste a full URL to link a pull request from another repository." };
97 }
98 const webUrl = input.project.webUrl(number);
99 const webReference = webUrl === null ? null : parseChangeRequestUrl(webUrl);
100 if (webUrl === null || webReference === null) {
101 return { error: "Paste a full URL; this project's host has no known pull request URL." };
102 }
103 return {
104 link: { ...webReference, url: webUrl },
105 };
107​
108function resolveOwnProject(
109 environmentProjects: ReturnType<typeof useProjects>,
110 projectId: LinkPullRequestDialogProps["projectId"],
111) {
112 const project = environmentProjects.find((candidate) => candidate.id === projectId);
113 const identity = project?.repositoryIdentity;
114 if (!project || !identity) return null;
115 const repository =
116 identity.displayName ??
117 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
118 if (repository === null) return null;
119 const definition = sourceControlClients.get(identity.provider ?? "unknown");
120 const host = pullRequestHostOf(identity, definition.kind);
121 return {
122 host,
123 repository,
124 webUrl: (number: number) =>
125 definition.changeRequestUrl({
126 host,
127 repository,
128 number,
129 remoteUrl: identity.locator.remoteUrl,
130 webUrl: identity.webUrl,
131 }),
132 };
134​
135function LinkPullRequestDialog({
136 open,
137 threadRef,
138 projectId,
139 onOpenChange,
140}: LinkPullRequestDialogProps) {
141 const inputRef = useRef<HTMLInputElement>(null);
142 const [reference, setReference] = useState("");
143 const [dirty, setDirty] = useState(false);
144 const [submitError, setSubmitError] = useState<string | null>(null);
145 const projects = useProjects();
146 const ownProject = resolveOwnProject(
147 projects.filter((project) => project.environmentId === threadRef.environmentId),
148 projectId,
149 );
150 const linking = usePullRequestLinking(threadRef.environmentId);
151 const [pending, setPending] = useState(false);
152​
153 const [openSeen, setOpenSeen] = useState(open);
154 if (openSeen !== open) {
155 setOpenSeen(open);
156 if (open) {
157 setReference("");
158 setDirty(false);
159 setSubmitError(null);
160 }
161 }
162 useEffect(() => {
163 if (!open) return;
164 const frame = window.requestAnimationFrame(() => inputRef.current?.focus());
165 return () => window.cancelAnimationFrame(frame);
166 }, [open]);
167​
168 const resolved = resolveLinkPullRequestInput({
169 reference,
170 project: ownProject,
171 hasProject: (reference) => linking.canLink(reference.url),
172 });
173​
174 const submit = async () => {
175 setDirty(true);
176 if (resolved === null || "error" in resolved) return;
177 setSubmitError(null);
178 setPending(true);
179 const result = await settlePromise(() =>
180 linking.changeLink(threadRef, resolved.link.url, true),
181 );
182 setPending(false);
183 if (result._tag === "Failure") {
184 const error = squashAtomCommandFailure(result);
185 setSubmitError(error instanceof Error ? error.message : "Could not link the pull request.");
186 return;
187 }
188 onOpenChange(false);
189 };
190​
191 const validation = !dirty
192 ? null
193 : reference.trim().length === 0
194 ? "Paste a pull request URL or enter 123 / #123."
195 : resolved === null
196 ? "Use a pull request URL, 123, or #123."
197 : "error" in resolved
198 ? resolved.error
199 : null;
200​
201 return (
202 <Dialog open={open} onOpenChange={(next) => (pending ? undefined : onOpenChange(next))}>
203 <DialogPopup className="max-w-xl">
204 <DialogHeader>
205 <DialogTitle>Link pull request</DialogTitle>
206 <DialogDescription>
207 Attach a pull request to this thread by its URL, or by its number for this thread's
208 repository.
209 </DialogDescription>
210 </DialogHeader>
211 <DialogPanel>
212 <Input
213 ref={inputRef}
214 placeholder="Pull request URL or #42"
215 value={reference}
216 onChange={(event) => {
217 setDirty(true);
218 setReference(event.target.value);
219 }}
220 onKeyDown={(event) => {
221 if (event.key !== "Enter") return;
222 event.preventDefault();
223 void submit();
224 }}
225 />
226 {resolved !== null && "link" in resolved ? (
227 <p className="truncate text-muted-foreground text-xs">
228 {resolved.link.host}/{resolved.link.repository} #{resolved.link.number}
229 </p>
230 ) : null}
231 {(validation ?? submitError) ? (
232 <p className="text-destructive text-xs">{validation ?? submitError}</p>
233 ) : null}
234 </DialogPanel>
235 <DialogFooter>
236 <Button
237 type="button"
238 variant="outline"
239 size="sm"
240 onClick={() => onOpenChange(false)}
241 disabled={pending}
242 >
243 Cancel
244 </Button>
245 <Button
246 type="button"
247 size="sm"
248 onClick={() => void submit()}
249 disabled={pending || resolved === null || "error" in resolved}
250 >
251 {pending ? "Linking..." : "Link"}
252 </Button>
253 </DialogFooter>
254 </DialogPopup>
255 </Dialog>
256 );