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

PullRequestThreadLinks.tsx

237 lines8.6 KB

1import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import type { EnvironmentId, PullRequestRef, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
4import { CheckIcon, LinkIcon, MessageSquareIcon, UnlinkIcon } from "lucide-react";
5import { useState } from "react";
6import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
7import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
8​
9import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";
10import { useProjects, useServerConfigs, useThreadShell, useThreadShells } from "~/state/entities";
11import { pullRequestEnvironment } from "~/state/pullRequests";
12import { useEnvironmentQuery } from "~/state/query";
13import { appAtomRegistry } from "~/rpc/atomRegistry";
14import { openCommandPalette } from "~/commandPaletteBus";
15import { Button } from "../ui/button";
16import { Command, CommandInput, CommandItem, CommandList } from "../ui/command";
17import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
18import { MenuItem } from "../ui/menu";
19import { toastManager } from "../ui/toast";
20​
21interface PullRequestThreadLinksProps {
22 environmentId: EnvironmentId;
23 reference: PullRequestRef;
24 url: string;
25 threadRef: ScopedThreadRef | null;
26 display: "count" | "menu-item" | "picker";
27 onPickerOpenChange?: (open: boolean) => void;
29​
30/** Thread relations belong to the detail environment, including when another environment is active. */
31export function PullRequestThreadLinks(props: PullRequestThreadLinksProps) {
32 const configs = useServerConfigs();
33 if (
34 threadPullRequestLinkMode(configs.get(props.environmentId)?.environment.capabilities) ===
35 "unsupported"
36 ) {
37 return null;
38 }
39 return <EnabledPullRequestThreadLinks key={`${props.environmentId}:${props.url}`} {...props} />;
41​
42function EnabledPullRequestThreadLinks({
43 environmentId,
44 reference,
45 url,
46 threadRef,
47 display,
48 onPickerOpenChange,
49}: PullRequestThreadLinksProps) {
50 const parsed = parseChangeRequestUrl(url);
51 const currentThreadRef = threadRef?.environmentId === environmentId ? threadRef : null;
52 const thread = useThreadShell(currentThreadRef);
53 const linking = usePullRequestLinking(environmentId);
54 const linkedHere = linking.isLinked(thread, url);
55 const relations = useEnvironmentQuery(
56 linking.mode === "multiple" && display !== "menu-item"
57 ? pullRequestEnvironment.linkedThreads({
58 environmentId,
59 input: parsed === null ? reference : { ...reference, ...parsed },
60 })
61 : null,
62 );
63 // Refreshes can briefly clear the query value. Keep the last response so polling
64 // does not hide the linked-thread count between responses.
65 const [lastRelations, setLastRelations] = useState(relations.data);
66 if (relations.data !== null && relations.data !== lastRelations) {
67 setLastRelations(relations.data);
68 }
69 const [pending, setPending] = useState(false);
70​
71 const changeLink = async (threadId: ThreadId, remove: boolean) => {
72 if (parsed === null || pending) return;
73 setPending(true);
74 try {
75 await linking.changeLink(scopeThreadRef(environmentId, threadId), url, !remove);
76 } catch (error) {
77 toastManager.add({
78 type: "error",
79 title: remove ? "Could not unlink the pull request" : "Could not link the pull request",
80 description: error instanceof Error ? error.message : String(error),
81 });
82 return;
83 } finally {
84 setPending(false);
85 }
86 if (linking.mode === "multiple") {
87 appAtomRegistry.refresh(
88 pullRequestEnvironment.linkedThreads({ environmentId, input: { ...reference, ...parsed } }),
89 );
90 }
91 onPickerOpenChange?.(false);
92 };
93​
94 if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
95 const linkedThreads =
96 linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [];
97 const linkedThreadsLabel =
98 linkedThreads.length > 0
99 ? `Linked from ${linkedThreads.length} ${linkedThreads.length === 1 ? "thread" : "threads"}`
100 : "Linked threads";
101 return (
102 <>
103 {display === "count" && (linkedThreads.length > 0 || relations.error !== null) ? (
104 <Tooltip>
105 <TooltipTrigger
106 render={
107 <Button
108 size="xs"
109 variant="ghost"
110 aria-label={linkedThreadsLabel}
111 onClick={() =>
112 openCommandPalette({
113 query: url,
114 ...((relations.data ?? lastRelations) === null
115 ? {}
116 : { linkedThreads: { environmentId, threads: linkedThreads } }),
117 })
118 }
119 >
120 <MessageSquareIcon aria-hidden className="size-3.5" />
121 <span aria-hidden>{linkedThreads.length || "?"}</span>
122 </Button>
123 }
124 />
125 <TooltipPopup>{linkedThreadsLabel}. Search in the command palette.</TooltipPopup>
126 </Tooltip>
127 ) : null}
128 {display === "menu-item" ? (
129 <MenuItem
130 disabled={pending}
131 onClick={() => {
132 if (currentThreadRef !== null) {
133 void changeLink(currentThreadRef.threadId, linkedHere);
134 } else {
135 onPickerOpenChange?.(true);
136 }
137 }}
138 >
139 {linkedHere ? (
140 <UnlinkIcon aria-hidden className="size-3.5" />
141 ) : (
142 <LinkIcon aria-hidden className="size-3.5" />
143 )}
144 {linkedHere
145 ? "Unlink from this thread"
146 : currentThreadRef
147 ? "Link to this thread"
148 : "Link to thread"}
149 </MenuItem>
150 ) : null}
151 {display === "picker" ? (
152 <Dialog open onOpenChange={onPickerOpenChange}>
153 <DialogPopup className="max-w-md" showCloseButton={false}>
154 <DialogTitle className="sr-only">Link pull request to a thread</DialogTitle>
155 <ThreadPicker
156 environmentId={environmentId}
157 url={url}
158 pending={pending}
159 onSelect={(threadId) => void changeLink(threadId, false)}
160 />
161 </DialogPopup>
162 </Dialog>
163 ) : null}
164 </>
165 );
167​
168function ThreadPicker({
169 environmentId,
170 url,
171 pending,
172 onSelect,
173}: {
174 environmentId: EnvironmentId;
175 url: string;
176 pending: boolean;
177 onSelect: (threadId: ThreadId) => void;
178}) {
179 const threads = useThreadShells();
180 const linking = usePullRequestLinking(environmentId);
181 const projects = useProjects();
182 const [query, setQuery] = useState("");
183 const projectNames = new Map(
184 projects
185 .filter((project) => project.environmentId === environmentId)
186 .map((project) => [project.id, project.title]),
187 );
188 const search = query.trim().toLocaleLowerCase();
189 const candidates = threads
190 .filter(
191 (thread) =>
192 thread.environmentId === environmentId &&
193 thread.archivedAt === null &&
194 `${thread.title} ${projectNames.get(thread.projectId) ?? ""}`
195 .toLocaleLowerCase()
196 .includes(search),
197 )
198 .toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt));
199 return (
200 <Command mode="none" value={query} onValueChange={setQuery} aria-label="Choose a thread">
201 <CommandInput placeholder="Search threads or projects..." disabled={pending} />
202 <CommandList className="max-h-80 overflow-y-auto">
203 {candidates.length === 0 ? (
204 <div className="px-3 py-6 text-center text-sm text-muted-foreground">
205 No active threads found.
206 </div>
207 ) : (
208 candidates.map((thread) => {
209 const linked = linking.isLinked(thread, url);
210 return (
211 <CommandItem
212 key={thread.id}
213 value={thread.id}
214 disabled={pending || linked}
215 onClick={() => onSelect(thread.id)}
216 >
217 <MessageSquareIcon aria-hidden className="size-4 shrink-0" />
218 <span className="flex min-w-0 flex-1 flex-col">
219 <span className="truncate">{thread.title || "Untitled thread"}</span>
220 <span className="truncate text-xs text-muted-foreground">
221 {projectNames.get(thread.projectId)}
222 </span>
223 </span>
224 {linked ? (
225 <>
226 <CheckIcon aria-hidden className="size-3.5" />
227 <span className="text-xs text-muted-foreground">Linked</span>
228 </>
229 ) : null}
230 </CommandItem>
231 );
232 })
233 )}
234 </CommandList>
235 </Command>
236 );