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

PullRequestThreadLinks.tsx

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