The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 228 lines 8.16 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
3 import { useAtomValue } from "@effect/atom-react";
4 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
5 import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
6 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
7 import type { EnvironmentId, PullRequestRef, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
8 import { MessageSquareIcon } from "lucide-react";
9 import { Branch, msg, T, useGT } from "gt-react";
10 import { useState } from "react";
11
12 import { m } from "~/i18n/messages";
13 import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
14 import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
15
16 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
17 import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
18 import {
19 useAnyEnvironmentHiding,
20 useEnvironmentThreadRefs,
21 useServerConfigs,
22 useThreadShell,
23 } from "~/state/entities";
24 import { pullRequestEnvironment } from "~/state/pullRequests";
25 import { environmentThreadShells } from "~/state/threads";
26 import { useEnvironmentQuery } from "~/state/query";
27 import { appAtomRegistry } from "~/rpc/atomRegistry";
28 import { openCommandPalette } from "~/commandPaletteBus";
29 import { Button } from "../ui/button";
30 import { ThreadLinkPicker } from "../ThreadLinkPicker";
31 import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
32 import { MenuItem } from "../ui/menu";
33 import { toastManager } from "../ui/toast";
34 import { PullRequestGlyph } from "./pullRequestIcons";
35
36 import { changeRequestTermKind } from "./changeRequestTerm";
37
38 interface 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;
45 }
46
47 export 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} />;
56 }
57
58 function 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(
111 "Could not unlink the {term, select, mr {merge request} cr {change request} other {pull request}}",
112 { term },
113 ),
114 )
115 : m(
116 msg(
117 "Could not link the {term, select, mr {merge request} cr {change request} other {pull request}}",
118 { term },
119 ),
120 ),
121 description: thrownErrorMessage(error, m) ?? String(error),
122 });
123 return;
124 }
125 if (linking.mode === "multiple") {
126 appAtomRegistry.refresh(
127 pullRequestEnvironment.linkedThreads({
128 environmentId,
129 input: { ...reference, ...normalizeThreadPullRequestKey(parsed) },
130 }),
131 );
132 }
133 onPickerOpenChange?.(false);
134 };
135
136 if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
137 const linkedThreads = visibleLinkedThreads(
138 linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [],
139 environmentId,
140 loadedThreadRefs,
141 hiddenKeys,
142 hidingAnywhere,
143 );
144 const linkedThreadsLabel =
145 linkedThreads.length > 0
146 ? gt(
147 "{count, plural, one {Linked from {count} thread} other {Linked from {count} threads}}",
148 {
149 count: linkedThreads.length,
150 },
151 )
152 : gt("Linked threads");
153 return (
154 <>
155 {display === "count" && (linkedThreads.length > 0 || relations.error !== null) ? (
156 <Tooltip>
157 <TooltipTrigger
158 render={
159 <Button
160 size="xs"
161 variant="ghost"
162 aria-label={linkedThreadsLabel}
163 onClick={() =>
164 openCommandPalette({
165 query: url,
166 ...((relations.data ?? lastRelations) === null
167 ? {}
168 : { linkedThreads: { environmentId, threads: linkedThreads } }),
169 })
170 }
171 >
172 <MessageSquareIcon aria-hidden className="size-3.5" />
173 <span aria-hidden>{linkedThreads.length || "?"}</span>
174 </Button>
175 }
176 />
177 <TooltipPopup>
178 {gt("{label}. Search in the command palette.", { label: linkedThreadsLabel })}
179 </TooltipPopup>
180 </Tooltip>
181 ) : null}
182 {display === "menu-item" ? (
183 <MenuItem
184 disabled={pending}
185 onClick={() => {
186 if (currentThreadRef !== null) {
187 void changeLink(currentThreadRef.threadId, linkedHere);
188 } else {
189 onPickerOpenChange?.(true);
190 }
191 }}
192 >
193 {linkedHere ? (
194 <PullRequestGlyph.unlink aria-hidden className="size-3.5" />
195 ) : (
196 <PullRequestGlyph.link aria-hidden className="size-3.5" />
197 )}
198 {linkedHere
199 ? gt("Unlink from this thread")
200 : currentThreadRef
201 ? gt("Link to this thread")
202 : gt("Link to thread")}
203 </MenuItem>
204 ) : null}
205 {display === "picker" ? (
206 <Dialog open onOpenChange={onPickerOpenChange}>
207 <DialogPopup className="max-w-md" showCloseButton={false}>
208 <DialogTitle className="sr-only">
209 <T>
210 Link{" "}
211 <Branch branch={term} mr="merge request" cr="change request">
212 pull request
213 </Branch>{" "}
214 to a thread
215 </T>
216 </DialogTitle>
217 <ThreadLinkPicker
218 environmentId={environmentId}
219 pending={pending}
220 isLinked={(candidate) => linking.isLinked(candidate, url)}
221 onSelect={(threadId) => void changeLink(threadId, false)}
222 />
223 </DialogPopup>
224 </Dialog>
225 ) : null}
226 </>
227 );
228 }