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