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

LinkPullRequestDialog.tsx

249 lines8.2 KB

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