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

LinkPullRequestDialog.tsx

254 lines8.7 KB

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);
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;
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 );
68​
69interface ResolvedLink {
70 readonly host: string;
71 readonly repository: string;
72 readonly number: number;
73 readonly url: string;
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 };
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) => changeRequestWebUrl(kind, host, repository, number),
148 };
149 }, [environmentProjects, projectId]);
150 const linking = usePullRequestLinking(threadRef.environmentId);
151 const [pending, setPending] = useState(false);
152​
153 useEffect(() => {
154 if (!open) return;
155 setReference("");
156 setDirty(false);
157 setSubmitError(null);
158 const frame = window.requestAnimationFrame(() => inputRef.current?.focus());
159 return () => window.cancelAnimationFrame(frame);
160 }, [open]);
161​
162 const resolved = useMemo(
163 () =>
164 resolveLinkPullRequestInput({
165 reference,
166 project: ownProject,
167 hasProject: (reference) => linking.canLink(reference.url),
168 }),
169 [linking, ownProject, reference],
170 );
171​
172 const submit = useCallback(async () => {
173 setDirty(true);
174 if (resolved === null || "error" in resolved) return;
175 setSubmitError(null);
176 setPending(true);
177 try {
178 await linking.changeLink(threadRef, resolved.link.url, true);
179 } catch (error) {
180 setSubmitError(error instanceof Error ? error.message : "Could not link the pull request.");
181 return;
182 } finally {
183 setPending(false);
184 }
185 onOpenChange(false);
186 }, [linking, onOpenChange, resolved, threadRef]);
187​
188 const validation = !dirty
189 ? null
190 : reference.trim().length === 0
191 ? "Paste a pull request URL or enter 123 / #123."
192 : resolved === null
193 ? "Use a pull request URL, 123, or #123."
194 : "error" in resolved
195 ? resolved.error
196 : null;
197​
198 return (
199 <Dialog open={open} onOpenChange={(next) => (pending ? undefined : onOpenChange(next))}>
200 <DialogPopup className="max-w-xl">
201 <DialogHeader>
202 <DialogTitle>Link pull request</DialogTitle>
203 <DialogDescription>
204 Attach a pull request to this thread. A full URL can point at any repository on a host
205 this environment has a project for.
206 </DialogDescription>
207 </DialogHeader>
208 <DialogPanel className="space-y-3">
209 <Input
210 ref={inputRef}
211 placeholder="Pull request URL or #42"
212 value={reference}
213 onChange={(event) => {
214 setDirty(true);
215 setReference(event.target.value);
216 }}
217 onKeyDown={(event) => {
218 if (event.key !== "Enter") return;
219 event.preventDefault();
220 void submit();
221 }}
222 />
223 {resolved !== null && "link" in resolved ? (
224 <p className="truncate text-muted-foreground text-xs">
225 {resolved.link.host}/{resolved.link.repository} #{resolved.link.number}
226 </p>
227 ) : null}
228 {(validation ?? submitError) ? (
229 <p className="text-destructive text-xs">{validation ?? submitError}</p>
230 ) : null}
231 </DialogPanel>
232 <DialogFooter>
233 <Button
234 type="button"
235 variant="outline"
236 size="sm"
237 onClick={() => onOpenChange(false)}
238 disabled={pending}
239 >
240 Cancel
241 </Button>
242 <Button
243 type="button"
244 size="sm"
245 onClick={() => void submit()}
246 disabled={pending || resolved === null || "error" in resolved}
247 >
248 {pending ? "Linking..." : "Link"}
249 </Button>
250 </DialogFooter>
251 </DialogPopup>
252 </Dialog>
253 );