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

PullRequestThreadLinks.tsx

251 lines9.3 KB

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 { useThreadSearch } from "~/state/queries";
16import { appAtomRegistry } from "~/rpc/atomRegistry";
17import { openCommandPalette } from "~/commandPaletteBus";
18import { Button } from "../ui/button";
19import { Command, CommandInput, CommandItem, CommandList } from "../ui/command";
20import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
21import { MenuItem } from "../ui/menu";
22import { toastManager } from "../ui/toast";
23import { PullRequestGlyph } from "./pullRequestIcons";
24​
25interface PullRequestThreadLinksProps {
26 environmentId: EnvironmentId;
27 reference: PullRequestRef;
28 url: string;
29 threadRef: ScopedThreadRef | null;
30 display: "count" | "menu-item" | "picker";
31 onPickerOpenChange?: (open: boolean) => void;
33​
34export function PullRequestThreadLinks(props: PullRequestThreadLinksProps) {
35 const configs = useServerConfigs();
36 if (
37 threadPullRequestLinkMode(configs.get(props.environmentId)?.environment.capabilities) ===
38 "unsupported"
39 ) {
40 return null;
41 }
42 return <EnabledPullRequestThreadLinks key={`${props.environmentId}:${props.url}`} {...props} />;
44​
45function EnabledPullRequestThreadLinks({
46 environmentId,
47 reference,
48 url,
49 threadRef,
50 display,
51 onPickerOpenChange,
52}: PullRequestThreadLinksProps) {
53 const parsedUrl = sourceControlClients.parseChangeRequestUrl(url);
54 const parsed = parsedUrl?.link ?? null;
55 const term = (parsedUrl?.definition ?? sourceControlClients.get(undefined)).changeRequest
56 .singular;
57 const thread = useThreadShell(threadRef?.environmentId === environmentId ? threadRef : null);
58 const currentThreadRef = thread === null ? null : threadRef;
59 const linking = usePullRequestLinking(environmentId);
60 const linkedHere = linking.isLinked(thread, url);
61 const relations = useEnvironmentQuery(
62 linking.mode === "multiple" && display !== "menu-item"
63 ? pullRequestEnvironment.linkedThreads({
64 environmentId,
65 input:
66 parsed === null
67 ? reference
68 : { ...reference, ...normalizeThreadPullRequestKey(parsed) },
69 })
70 : null,
71 );
72 // Retain the last count while refresh temporarily clears query data.
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 );
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 // Mounts older settled threads matching the query, which shells may leave out.
196 useThreadSearch([environmentId], query, { titlesOnly: true });
197 const projectNames = new Map(
198 projects
199 .filter((project) => project.environmentId === environmentId)
200 .map((project) => [project.id, project.title]),
201 );
202 const search = query.trim().toLocaleLowerCase();
203 const candidates = threads
204 .filter(
205 (thread) =>
206 thread.environmentId === environmentId &&
207 thread.archivedAt === null &&
208 `${thread.title} ${projectNames.get(thread.projectId) ?? ""}`
209 .toLocaleLowerCase()
210 .includes(search),
211 )
212 .toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt));
213 return (
214 <Command mode="none" value={query} onValueChange={setQuery} aria-label="Choose a thread">
215 <CommandInput placeholder="Search threads or projects..." disabled={pending} />
216 <CommandList className="max-h-80 overflow-y-auto">
217 {candidates.length === 0 ? (
218 <div className="px-3 py-6 text-center text-sm text-muted-foreground">
219 No active threads found.
220 </div>
221 ) : (
222 candidates.map((thread) => {
223 const linked = linking.isLinked(thread, url);
224 return (
225 <CommandItem
226 key={thread.id}
227 value={thread.id}
228 disabled={pending || linked}
229 onClick={() => onSelect(thread.id)}
230 >
231 <MessageSquareIcon aria-hidden className="size-4 shrink-0" />
232 <span className="flex min-w-0 flex-1 flex-col">
233 <span className="truncate">{thread.title || "Untitled thread"}</span>
234 <span className="truncate text-xs text-muted-foreground">
235 {projectNames.get(thread.projectId)}
236 </span>
237 </span>
238 {linked ? (
239 <>
240 <CheckIcon aria-hidden className="size-3.5" />
241 <span className="text-xs text-muted-foreground">Linked</span>
242 </>
243 ) : null}
244 </CommandItem>
245 );
246 })
247 )}
248 </CommandList>
249 </Command>
250 );