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

PullRequestThreadLinks.tsx

248 lines9.1 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 { 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;
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} />;
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 // Retain the last count while refresh temporarily clears query data.
72 const [lastRelations, setLastRelations] = useState(relations.data);
73 if (relations.data !== null && relations.data !== lastRelations) {
74 setLastRelations(relations.data);
75 }
76 const [pending, setPending] = useState(false);
77​
78 const changeLink = async (threadId: ThreadId, remove: boolean) => {
79 if (parsed === null || pending) return;
80 setPending(true);
81 const result = await settlePromise(() =>
82 linking.changeLink(scopeThreadRef(environmentId, threadId), url, !remove),
83 );
84 setPending(false);
85 if (result._tag === "Failure") {
86 const error = squashAtomCommandFailure(result);
87 toastManager.add({
88 type: "error",
89 title: remove ? `Could not unlink the ${term}` : `Could not link the ${term}`,
90 description: error instanceof Error ? error.message : String(error),
91 });
92 return;
93 }
94 if (linking.mode === "multiple") {
95 appAtomRegistry.refresh(
96 pullRequestEnvironment.linkedThreads({
97 environmentId,
98 input: { ...reference, ...normalizeThreadPullRequestKey(parsed) },
99 }),
100 );
101 }
102 onPickerOpenChange?.(false);
103 };
104​
105 if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
106 const linkedThreads =
107 linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [];
108 const linkedThreadsLabel =
109 linkedThreads.length > 0
110 ? `Linked from ${linkedThreads.length} ${linkedThreads.length === 1 ? "thread" : "threads"}`
111 : "Linked threads";
112 return (
113 <>
114 {display === "count" && (linkedThreads.length > 0 || relations.error !== null) ? (
115 <Tooltip>
116 <TooltipTrigger
117 render={
118 <Button
119 size="xs"
120 variant="ghost"
121 aria-label={linkedThreadsLabel}
122 onClick={() =>
123 openCommandPalette({
124 query: url,
125 ...((relations.data ?? lastRelations) === null
126 ? {}
127 : { linkedThreads: { environmentId, threads: linkedThreads } }),
128 })
129 }
130 >
131 <MessageSquareIcon aria-hidden className="size-3.5" />
132 <span aria-hidden>{linkedThreads.length || "?"}</span>
133 </Button>
134 }
135 />
136 <TooltipPopup>{linkedThreadsLabel}. Search in the command palette.</TooltipPopup>
137 </Tooltip>
138 ) : null}
139 {display === "menu-item" ? (
140 <MenuItem
141 disabled={pending}
142 onClick={() => {
143 if (currentThreadRef !== null) {
144 void changeLink(currentThreadRef.threadId, linkedHere);
145 } else {
146 onPickerOpenChange?.(true);
147 }
148 }}
149 >
150 {linkedHere ? (
151 <PullRequestGlyph.unlink aria-hidden className="size-3.5" />
152 ) : (
153 <PullRequestGlyph.link aria-hidden className="size-3.5" />
154 )}
155 {linkedHere
156 ? "Unlink from this thread"
157 : currentThreadRef
158 ? "Link to this thread"
159 : "Link to thread"}
160 </MenuItem>
161 ) : null}
162 {display === "picker" ? (
163 <Dialog open onOpenChange={onPickerOpenChange}>
164 <DialogPopup className="max-w-md" showCloseButton={false}>
165 <DialogTitle className="sr-only">Link {term} to a thread</DialogTitle>
166 <ThreadPicker
167 environmentId={environmentId}
168 url={url}
169 pending={pending}
170 onSelect={(threadId) => void changeLink(threadId, false)}
171 />
172 </DialogPopup>
173 </Dialog>
174 ) : null}
175 </>
176 );
178​
179function ThreadPicker({
180 environmentId,
181 url,
182 pending,
183 onSelect,
184}: {
185 environmentId: EnvironmentId;
186 url: string;
187 pending: boolean;
188 onSelect: (threadId: ThreadId) => void;
189}) {
190 const threads = useThreadShells();
191 const linking = usePullRequestLinking(environmentId);
192 const projects = useProjects();
193 const [query, setQuery] = useState("");
194 const projectNames = new Map(
195 projects
196 .filter((project) => project.environmentId === environmentId)
197 .map((project) => [project.id, project.title]),
198 );
199 const search = query.trim().toLocaleLowerCase();
200 const candidates = threads
201 .filter(
202 (thread) =>
203 thread.environmentId === environmentId &&
204 thread.archivedAt === null &&
205 `${thread.title} ${projectNames.get(thread.projectId) ?? ""}`
206 .toLocaleLowerCase()
207 .includes(search),
208 )
209 .toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt));
210 return (
211 <Command mode="none" value={query} onValueChange={setQuery} aria-label="Choose a thread">
212 <CommandInput placeholder="Search threads or projects..." disabled={pending} />
213 <CommandList className="max-h-80 overflow-y-auto">
214 {candidates.length === 0 ? (
215 <div className="px-3 py-6 text-center text-sm text-muted-foreground">
216 No active threads found.
217 </div>
218 ) : (
219 candidates.map((thread) => {
220 const linked = linking.isLinked(thread, url);
221 return (
222 <CommandItem
223 key={thread.id}
224 value={thread.id}
225 disabled={pending || linked}
226 onClick={() => onSelect(thread.id)}
227 >
228 <MessageSquareIcon aria-hidden className="size-4 shrink-0" />
229 <span className="flex min-w-0 flex-1 flex-col">
230 <span className="truncate">{thread.title || "Untitled thread"}</span>
231 <span className="truncate text-xs text-muted-foreground">
232 {projectNames.get(thread.projectId)}
233 </span>
234 </span>
235 {linked ? (
236 <>
237 <CheckIcon aria-hidden className="size-3.5" />
238 <span className="text-xs text-muted-foreground">Linked</span>
239 </>
240 ) : null}
241 </CommandItem>
242 );
243 })
244 )}
245 </CommandList>
246 </Command>
247 );