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

PullRequestThreadLinks.tsx

233 lines8.3 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { SharedTooltipTrigger } from "../ui/shared-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 { MessageSquareIcon } from "lucide-react";
9import { Select, msg, T, useGT, select, plural, part } 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 useServerConfigs,
22 useThreadShell,
23} from "~/state/entities";
24import { pullRequestEnvironment } from "~/state/pullRequests";
25import { environmentThreadShells } from "~/state/threads";
26import { useEnvironmentQuery } from "~/state/query";
27import { appAtomRegistry } from "~/rpc/atomRegistry";
28import { openCommandPalette } from "~/commandPaletteBus";
29import { Button } from "../ui/button";
30import { ThreadLinkPicker } from "../ThreadLinkPicker";
31import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
32import { MenuItem } from "../ui/menu";
33import { toastManager } from "../ui/toast";
34import { PullRequestGlyph } from "./pullRequestIcons";
35​
36import { changeRequestTermKind } from "./changeRequestTerm";
37​
38interface PullRequestThreadLinksProps {
39 environmentId: EnvironmentId;
40 reference: PullRequestRef;
41 url: string;
42 threadRef: ScopedThreadRef | null;
43 display: "count" | "menu-item" | "picker";
44 onPickerOpenChange?: (open: boolean) => void;
46​
47export function PullRequestThreadLinks(props: PullRequestThreadLinksProps) {
48 const configs = useServerConfigs();
49 if (
50 threadPullRequestLinkMode(configs.get(props.environmentId)?.environment.capabilities) ===
51 "unsupported"
52 ) {
53 return null;
54 }
55 return <EnabledPullRequestThreadLinks key={`${props.environmentId}:${props.url}`} {...props} />;
57​
58function EnabledPullRequestThreadLinks({
59 environmentId,
60 reference,
61 url,
62 threadRef,
63 display,
64 onPickerOpenChange,
65}: PullRequestThreadLinksProps) {
66 const parsedUrl = sourceControlClients.parseChangeRequestUrl(url);
67 const parsed = parsedUrl?.link ?? null;
68 const term = changeRequestTermKind(
69 (parsedUrl?.definition ?? sourceControlClients.get(undefined)).changeRequest,
70 );
71 const thread = useThreadShell(threadRef?.environmentId === environmentId ? threadRef : null);
72 const currentThreadRef = thread === null ? null : threadRef;
73 const linking = usePullRequestLinking(environmentId);
74 const linkedHere = linking.isLinked(thread, url);
75 const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
76 const hidingAnywhere = useAnyEnvironmentHiding();
77 const loadedThreadRefs = useEnvironmentThreadRefs(environmentId);
78 const relations = useEnvironmentQuery(
79 linking.mode === "multiple" && display !== "menu-item"
80 ? pullRequestEnvironment.linkedThreads({
81 environmentId,
82 input:
83 parsed === null
84 ? reference
85 : { ...reference, ...normalizeThreadPullRequestKey(parsed) },
86 })
87 : null,
88 );
89 // Retain the last count while refresh temporarily clears query data.
90 const gt = useGT();
91 const [lastRelations, setLastRelations] = useState(relations.data);
92 if (relations.data !== null && relations.data !== lastRelations) {
93 setLastRelations(relations.data);
94 }
95 const [pending, setPending] = useState(false);
96​
97 const changeLink = async (threadId: ThreadId, remove: boolean) => {
98 if (parsed === null || pending) return;
99 setPending(true);
100 const result = await settlePromise(() =>
101 linking.changeLink(scopeThreadRef(environmentId, threadId), url, !remove),
102 );
103 setPending(false);
104 if (result._tag === "Failure") {
105 const error = squashAtomCommandFailure(result);
106 toastManager.add({
107 type: "error",
108 title: remove
109 ? m(
110 msg`Could not unlink the ${select(
111 { term },
112 {
113 mr: "merge request",
114 cr: "change request",
115 other: "pull request",
116 },
117 )}`,
118 )
119 : m(
120 msg`Could not link the ${select(
121 { term },
122 {
123 mr: "merge request",
124 cr: "change request",
125 other: "pull request",
126 },
127 )}`,
128 ),
129 description: thrownErrorMessage(error, m) ?? String(error),
130 });
131 return;
132 }
133 if (linking.mode === "multiple") {
134 appAtomRegistry.refresh(
135 pullRequestEnvironment.linkedThreads({
136 environmentId,
137 input: { ...reference, ...normalizeThreadPullRequestKey(parsed) },
138 }),
139 );
140 }
141 onPickerOpenChange?.(false);
142 };
143​
144 if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
145 const linkedThreads = visibleLinkedThreads(
146 linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [],
147 environmentId,
148 loadedThreadRefs,
149 hiddenKeys,
150 hidingAnywhere,
151 );
152 const linkedThreadsLabel =
153 linkedThreads.length > 0
154 ? gt`${plural(
155 { count: linkedThreads.length },
156 {
157 one: part`Linked from ${{ count: linkedThreads.length }} thread`,
158 other: part`Linked from ${{ count: linkedThreads.length }} threads`,
159 },
160 )}`
161 : gt`Linked threads`;
162 return (
163 <>
164 {display === "count" && (linkedThreads.length > 0 || relations.error !== null) ? (
165 <SharedTooltipTrigger
166 render={
167 <Button
168 size="xs"
169 variant="ghost"
170 aria-label={linkedThreadsLabel}
171 onClick={() =>
172 openCommandPalette({
173 query: url,
174 ...((relations.data ?? lastRelations) === null
175 ? {}
176 : { linkedThreads: { environmentId, threads: linkedThreads } }),
177 })
178 }
179 >
180 <MessageSquareIcon aria-hidden className="size-3.5" />
181 <span aria-hidden>{linkedThreads.length || "?"}</span>
182 </Button>
183 }
184 label={gt`${{ label: linkedThreadsLabel }}. Search in the command palette.`}
185 />
186 ) : null}
187 {display === "menu-item" ? (
188 <MenuItem
189 disabled={pending}
190 onClick={() => {
191 if (currentThreadRef !== null) {
192 void changeLink(currentThreadRef.threadId, linkedHere);
193 } else {
194 onPickerOpenChange?.(true);
195 }
196 }}
197 >
198 {linkedHere ? (
199 <PullRequestGlyph.unlink aria-hidden className="size-3.5" />
200 ) : (
201 <PullRequestGlyph.link aria-hidden className="size-3.5" />
202 )}
203 {linkedHere
204 ? gt`Unlink from this thread`
205 : currentThreadRef
206 ? gt`Link to this thread`
207 : gt`Link to thread`}
208 </MenuItem>
209 ) : null}
210 {display === "picker" ? (
211 <Dialog open onOpenChange={onPickerOpenChange}>
212 <DialogPopup className="max-w-md" showCloseButton={false}>
213 <DialogTitle className="sr-only">
214 <T>
215 Link{" "}
216 <Select value={term} mr="merge request" cr="change request">
217 pull request
218 </Select>{" "}
219 to a thread
220 </T>
221 </DialogTitle>
222 <ThreadLinkPicker
223 environmentId={environmentId}
224 pending={pending}
225 isLinked={(candidate) => linking.isLinked(candidate, url)}
226 onSelect={(threadId) => void changeLink(threadId, false)}
227 />
228 </DialogPopup>
229 </Dialog>
230 ) : null}
231 </>
232 );