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

PullRequestThreadLinks.tsx

307 lines10.9 KB

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