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

main
tsx 326 lines 12 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { issueTrackerSummary } from "@t3tools/client-runtime/state/issue-trackers";
3 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4 import { T, useGT, useMessages } from "gt-react";
5 import { ChevronDownIcon, ExternalLinkIcon, XIcon } from "lucide-react";
6 import { useState, type ElementType } from "react";
7 import type {
8 EnvironmentId,
9 IssueTrackerConnection,
10 IssueTrackerConnectionList,
11 ProjectId,
12 } from "@t3tools/contracts";
13
14 import { useEnvironmentQuery } from "../../state/query";
15 import { issueTrackerEnvironment } from "../../state/issueTrackers";
16 import { useProjects } from "../../state/entities";
17 import { useAtomCommand } from "../../state/use-atom-command";
18 import { LinearIcon } from "../Icons";
19 import { cn } from "~/lib/utils";
20
21 import { Badge } from "../ui/badge";
22 import { Button, InlineButton } from "../ui/button";
23 import { Collapsible, CollapsibleContent } from "../ui/collapsible";
24 import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
25 import { Skeleton } from "../ui/skeleton";
26 import { SecretInput } from "./SecretInput";
27 import { SettingsRow, SettingsSection } from "./settingsLayout";
28 import { useSearchableSetting } from "./settingsSearch";
29
30 type TrackerIcon = ElementType<{ className?: string }>;
31
32 /** Web art per tracker kind; the server supplies everything else about a tracker. */
33 const TRACKER_ICONS: Partial<Record<string, TrackerIcon>> = {
34 linear: LinearIcon,
35 };
36
37 const UNBOUND = "";
38
39 /**
40 * Standalone issue trackers for one environment: connect each with a credential, and bind the
41 * environment's projects to one of the tracker's scopes so their issues list beside the git
42 * host's. Generic over the trackers the server reports; nothing here names Linear but its icon.
43 */
44 export function IssueTrackerSettings({ environmentId }: { readonly environmentId: EnvironmentId }) {
45 const gt = useGT();
46 const searchableSetting = useSearchableSetting();
47 const title = gt("Issue trackers");
48 const query = useEnvironmentQuery(
49 issueTrackerEnvironment.connections({ environmentId, input: {} }),
50 );
51 const trackers = query.data?.trackers ?? [];
52 if (query.data === null && query.isPending) {
53 return (
54 <SettingsSection id={searchableSetting("issue-trackers").id} title={title}>
55 <div className="grid gap-3 px-4 py-3">
56 <Skeleton className="h-4 w-40" />
57 <Skeleton className="h-8 w-full" />
58 </div>
59 </SettingsSection>
60 );
61 }
62 if (query.data === null && query.error !== null) {
63 return (
64 <SettingsSection id={searchableSetting("issue-trackers").id} title={title}>
65 <SettingsRow
66 title={gt("Could not load issue trackers")}
67 description={query.error}
68 control={
69 <Button size="xs" variant="outline" onClick={query.refresh}>
70 <T>Retry</T>
71 </Button>
72 }
73 />
74 </SettingsSection>
75 );
76 }
77 if (trackers.length === 0) return null;
78 return (
79 <SettingsSection id={searchableSetting("issue-trackers").id} title={title}>
80 {trackers.map((tracker) => (
81 <TrackerRow
82 // Drafts belong to one environment; switching must not carry them over.
83 key={`${tracker.tracker}-${environmentId}`}
84 environmentId={environmentId}
85 tracker={tracker}
86 bindings={query.data?.bindings ?? {}}
87 />
88 ))}
89 </SettingsSection>
90 );
91 }
92
93 function TrackerRow({
94 environmentId,
95 tracker,
96 bindings,
97 }: {
98 readonly environmentId: EnvironmentId;
99 readonly tracker: IssueTrackerConnection;
100 readonly bindings: IssueTrackerConnectionList["bindings"];
101 }) {
102 const gt = useGT();
103 const messages = useMessages();
104 const Icon = TRACKER_ICONS[tracker.tracker];
105 const canEdit = useAtomValue(issueTrackerEnvironment.connect.permissionAtom(environmentId));
106 const connect = useAtomCommand(issueTrackerEnvironment.connect, {
107 label: `connect ${tracker.displayName}`,
108 });
109 const [busy, setBusy] = useState(false);
110 const [failure, setFailure] = useState<string | null>(null);
111 const [isExpanded, setIsExpanded] = useState(false);
112
113 const submit = async (token: string | null) => {
114 setBusy(true);
115 setFailure(null);
116 const result = await connect({
117 environmentId,
118 input: { tracker: tracker.tracker, token },
119 });
120 setBusy(false);
121 if (result._tag === "Success") return;
122 const error = squashAtomCommandFailure(result);
123 setFailure(error instanceof Error ? error.message : gt("The request failed."));
124 };
125
126 const inputId = `issue-tracker-${tracker.tracker}-${environmentId}`;
127 const usable = tracker.connected && tracker.account !== null;
128 const summary = issueTrackerSummary(tracker, bindings, messages);
129
130 return (
131 <div className="first:rounded-t-xl last:rounded-b-xl transition-colors hover:bg-muted/20">
132 <div className="flex items-center justify-between gap-3 px-3 py-3 sm:px-4">
133 <div className="min-w-0 flex-1 space-y-1">
134 <div className="flex min-w-0 flex-wrap items-center gap-2">
135 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
136 {Icon ? <Icon className="size-4.5 text-foreground/80" /> : null}
137 <span
138 aria-hidden
139 className={cn(
140 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
141 usable ? "bg-success" : "bg-muted-foreground/35",
142 )}
143 />
144 </span>
145 <span className="truncate text-sm font-medium text-foreground">
146 {tracker.displayName}
147 </span>
148 {tracker.connected && tracker.account === null ? (
149 <Badge variant="destructive" size="sm">
150 <T>Credential rejected</T>
151 </Badge>
152 ) : null}
153 </div>
154 <p className="text-xs leading-normal text-muted-foreground/80">{summary}</p>
155 </div>
156 <Button
157 size="icon-xs"
158 variant="ghost-muted"
159 onClick={() => setIsExpanded((open) => !open)}
160 aria-expanded={isExpanded}
161 aria-label={gt("Toggle {tracker} details", { tracker: tracker.displayName })}
162 >
163 <ChevronDownIcon
164 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
165 />
166 </Button>
167 </div>
168 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
169 <CollapsibleContent>
170 {/* Locked while saving, so an edit made mid-request is not overwritten by the saved value. */}
171 <fieldset disabled={!canEdit || busy} className="contents">
172 <div className="px-3 pb-4 pt-1 sm:px-4">
173 <SettingsRow
174 title={<label htmlFor={inputId}>{tracker.credential.label}</label>}
175 description={
176 <>
177 <T>Stored on the server.</T>
178 {tracker.credential.helpUrl ? (
179 <>
180 {" "}
181 <InlineButton
182 render={
183 <a
184 href={tracker.credential.helpUrl}
185 target="_blank"
186 rel="noreferrer noopener"
187 />
188 }
189 >
190 <T>Create one</T>
191 <ExternalLinkIcon aria-hidden className="size-3" />
192 </InlineButton>
193 </>
194 ) : null}
195 {failure ? <span className="block text-destructive">{failure}</span> : null}
196 </>
197 }
198 control={
199 <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
200 <SecretInput
201 id={inputId}
202 size="sm"
203 className="min-w-0 flex-1"
204 configured={tracker.connected}
205 value=""
206 onCommit={(next) => {
207 if (next.trim()) void submit(next.trim());
208 }}
209 />
210 {tracker.connected ? (
211 <Button
212 type="button"
213 size="icon-sm"
214 variant="ghost-destructive"
215 onClick={() => void submit(null)}
216 aria-label={gt("Disconnect {tracker}", { tracker: tracker.displayName })}
217 >
218 <XIcon className="size-3.5" />
219 </Button>
220 ) : null}
221 </div>
222 }
223 />
224 {usable ? (
225 <ProjectBindings
226 environmentId={environmentId}
227 tracker={tracker}
228 bindings={bindings}
229 />
230 ) : null}
231 </div>
232 </fieldset>
233 </CollapsibleContent>
234 </Collapsible>
235 </div>
236 );
237 }
238
239 /** One picker per project of this environment: which of the tracker's scopes it reads, if any. */
240 function ProjectBindings({
241 environmentId,
242 tracker,
243 bindings,
244 }: {
245 readonly environmentId: EnvironmentId;
246 readonly tracker: IssueTrackerConnection;
247 readonly bindings: IssueTrackerConnectionList["bindings"];
248 }) {
249 const gt = useGT();
250 const projects = useProjects().filter((project) => project.environmentId === environmentId);
251 const bind = useAtomCommand(issueTrackerEnvironment.bindProject, {
252 label: `bind project to ${tracker.displayName}`,
253 });
254 const [pending, setPending] = useState<ProjectId | null>(null);
255 if (projects.length === 0 || tracker.scopes.length === 0) return null;
256
257 const change = async (projectId: ProjectId, scope: string) => {
258 setPending(projectId);
259 await bind({
260 environmentId,
261 input: {
262 projectId,
263 binding: scope === UNBOUND ? null : { tracker: tracker.tracker, scope },
264 },
265 });
266 setPending(null);
267 };
268
269 return (
270 <>
271 <SettingsRow
272 title={gt("Projects")}
273 description={gt(
274 "Pick the {tracker} {scope} whose issues each project lists beside its repository's own.",
275 { tracker: tracker.displayName, scope: tracker.scopeNoun },
276 )}
277 />
278 {projects.map((project) => {
279 const bound = bindings[project.id];
280 // A project bound to another tracker keeps that binding; this picker shows it unbound.
281 const value = bound?.tracker === tracker.tracker ? bound.scope : UNBOUND;
282 return (
283 <SettingsRow
284 key={project.id}
285 title={project.title}
286 control={
287 <Select
288 value={value}
289 disabled={pending === project.id}
290 onValueChange={(next) => {
291 if (next !== null) void change(project.id, next);
292 }}
293 >
294 <SelectTrigger
295 aria-label={gt("{tracker} {scope} for {project}", {
296 tracker: tracker.displayName,
297 scope: tracker.scopeNoun,
298 project: project.title,
299 })}
300 className="w-full @min-[32rem]/settings-row:w-56"
301 size="sm"
302 >
303 <SelectValue>
304 {value === UNBOUND
305 ? gt("Not bound")
306 : (tracker.scopes.find((scope) => scope.key === value)?.name ?? value)}
307 </SelectValue>
308 </SelectTrigger>
309 <SelectPopup>
310 <SelectItem value={UNBOUND}>
311 <T>Not bound</T>
312 </SelectItem>
313 {tracker.scopes.map((scope) => (
314 <SelectItem key={scope.key} value={scope.key}>
315 {scope.name} ({scope.key})
316 </SelectItem>
317 ))}
318 </SelectPopup>
319 </Select>
320 }
321 />
322 );
323 })}
324 </>
325 );
326 }