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