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/unstable/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 and may point at any repository on a host this environment has a project for; a
79 * bare `#123` can only mean the thread's own repository.
80 */
81export function resolveLinkPullRequestInput(input: {
82 readonly reference: string;
83 readonly project: {
84 readonly host: string;
85 readonly repository: string;
86 readonly webUrl: (number: number) => string | null;
87 } | null;
88 readonly hasProject: (reference: ResolvedLink) => boolean;
89}): { link: ResolvedLink } | { error: string } | null {
90 const parsed =
91 parseChangeRequestUrl(input.reference.trim()) !== null
92 ? input.reference.trim()
93 : parsePullRequestReference(input.reference);
94 if (parsed === null) return null;
95 const url = parseChangeRequestUrl(parsed);
96 if (url !== null) {
97 if (!input.hasProject({ ...url, url: parsed })) {
98 return { error: `No project in this environment can read ${url.host}/${url.repository}.` };
99 }
100 return {
101 link: { host: url.host, repository: url.repository, number: url.number, url: parsed },
102 };
103 }
104 const number = Number(parsed);
105 if (!Number.isSafeInteger(number) || number < 1) return null;
106 if (input.project === null) {
107 return { error: "Paste a full URL to link a pull request from another repository." };
108 }
109 const webUrl = input.project.webUrl(number);
110 const webReference = webUrl === null ? null : parseChangeRequestUrl(webUrl);
111 if (webUrl === null || webReference === null) {
112 return { error: "Paste a full URL; this project's host has no known pull request URL." };
113 }
114 return {
115 link: { ...webReference, url: webUrl },
116 };
117}
118
119function LinkPullRequestDialog({
120 open,
121 threadRef,
122 projectId,
123 onOpenChange,
124}: LinkPullRequestDialogProps) {
125 const inputRef = useRef<HTMLInputElement>(null);
126 const [reference, setReference] = useState("");
127 const [dirty, setDirty] = useState(false);
128 const [submitError, setSubmitError] = useState<string | null>(null);
129 const projects = useProjects();
130 const environmentProjects = useMemo(
131 () => projects.filter((project) => project.environmentId === threadRef.environmentId),
132 [projects, threadRef.environmentId],
133 );
134 const ownProject = useMemo(() => {
135 const project = environmentProjects.find((candidate) => candidate.id === projectId);
136 const identity = project?.repositoryIdentity;
137 if (!project || !identity) return null;
138 const repository =
139 identity.displayName ??
140 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
141 if (repository === null) return null;
142 const kind = identity.provider as SourceControlProviderKind;
143 const host = pullRequestHostOf(identity, kind);
144 return {
145 host,
146 repository,
147 webUrl: (number: number) =>
148 kind === "forgejo" && identity.webUrl
149 ? `${identity.webUrl.replace(/\/+$/, "")}/pulls/${number}`
150 : changeRequestWebUrl(kind, host, repository, number, identity.locator.remoteUrl),
151 };
152 }, [environmentProjects, projectId]);
153 const linking = usePullRequestLinking(threadRef.environmentId);
154 const [pending, setPending] = useState(false);
155
156 useEffect(() => {
157 if (!open) return;
158 setReference("");
159 setDirty(false);
160 setSubmitError(null);
161 const frame = window.requestAnimationFrame(() => inputRef.current?.focus());
162 return () => window.cancelAnimationFrame(frame);
163 }, [open]);
164
165 const resolved = useMemo(
166 () =>
167 resolveLinkPullRequestInput({
168 reference,
169 project: ownProject,
170 hasProject: (reference) => linking.canLink(reference.url),
171 }),
172 [linking, ownProject, reference],
173 );
174
175 const submit = useCallback(async () => {
176 setDirty(true);
177 if (resolved === null || "error" in resolved) return;
178 setSubmitError(null);
179 setPending(true);
180 try {
181 await linking.changeLink(threadRef, resolved.link.url, true);
182 } catch (error) {
183 setSubmitError(error instanceof Error ? error.message : "Could not link the pull request.");
184 return;
185 } finally {
186 setPending(false);
187 }
188 onOpenChange(false);
189 }, [linking, onOpenChange, resolved, threadRef]);
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. A full URL can point at any repository on a host
208 this environment has a project for.
209 </DialogDescription>
210 </DialogHeader>
211 <DialogPanel className="space-y-3">
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 );
257}