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