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