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

IssueTrackerSettings.tsx

432 lines16.4 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 boundIssueTrackerScopes,
4 hasIssueTrackerTeams,
5 issueTrackerBindInput,
6 issueTrackerBindingFor,
7 issueTrackerBindings,
8 issueTrackerScopeOptions,
9 issueTrackerSummary,
10} from "@t3tools/client-runtime/state/issue-trackers";
11import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
12import { T, useGT, useMessages } from "gt-react";
13import { ChevronDownIcon, ExternalLinkIcon, PlusIcon, XIcon } from "lucide-react";
14import { useState, type ElementType } from "react";
15import type {
16 EnvironmentId,
17 IssueTrackerConnection,
18 IssueTrackerConnectionList,
19 ProjectId,
20} from "@t3tools/contracts";
21​
22import { useEnvironmentQuery } from "../../state/query";
23import { issueTrackerEnvironment } from "../../state/issueTrackers";
24import { useProjects, useServerConfigs } from "../../state/entities";
25import { useAtomCommand } from "../../state/use-atom-command";
26import { LinearIcon } from "../Icons";
27import { cn } from "~/lib/utils";
28​
29import { Badge } from "../ui/badge";
30import { CheckboxMark } from "../ui/checkbox";
31import { Button, InlineButton } from "../ui/button";
32import { Collapsible, CollapsibleContent } from "../ui/collapsible";
33import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
34import { Skeleton } from "../ui/skeleton";
35import { SecretInput } from "./SecretInput";
36import { SettingsRow, SettingsSection } from "./settingsLayout";
37import { useSearchableSetting } from "./settingsSearch";
38​
39type TrackerIcon = ElementType<{ className?: string }>;
40​
41/** Web art per tracker kind; the server supplies everything else about a tracker. */
42const TRACKER_ICONS: Partial<Record<string, TrackerIcon>> = {
43 linear: LinearIcon,
44};
45​
46/**
47 * Standalone issue trackers for one environment: connect each with a credential, and bind the
48 * environment's projects to the tracker's scopes so their issues list beside the git
49 * host's. Generic over the trackers the server reports; nothing here names Linear but its icon.
50 */
51export function IssueTrackerSettings({ environmentId }: { readonly environmentId: EnvironmentId }) {
52 const gt = useGT();
53 const searchableSetting = useSearchableSetting();
54 const title = gt("Issue trackers");
55 const query = useEnvironmentQuery(
56 issueTrackerEnvironment.connections({ environmentId, input: {} }),
57 );
58 const canAddAccounts =
59 useServerConfigs().get(environmentId)?.environment.capabilities.issueTrackerAccounts === true;
60 const trackers = query.data?.trackers ?? [];
61 const accounts = query.data?.accounts ?? [];
62 if (query.data === null && query.isPending) {
63 return (
64 <SettingsSection id={searchableSetting("issue-trackers").id} title={title}>
65 <div className="grid gap-3 px-4 py-3">
66 <Skeleton className="h-4 w-40" />
67 <Skeleton className="h-8 w-full" />
68 </div>
69 </SettingsSection>
70 );
71 }
72 if (query.data === null && query.error !== null) {
73 return (
74 <SettingsSection id={searchableSetting("issue-trackers").id} title={title}>
75 <SettingsRow
76 title={gt("Could not load issue trackers")}
77 description={query.error}
78 control={
79 <Button size="xs" variant="outline" onClick={query.refresh}>
80 <T>Retry</T>
81 </Button>
82 }
83 />
84 </SettingsSection>
85 );
86 }
87 if (trackers.length === 0) return null;
88 return (
89 <SettingsSection id={searchableSetting("issue-trackers").id} title={title}>
90 {trackers.flatMap((tracker) => {
91 const added = accounts.filter((account) => account.tracker === tracker.tracker);
92 // Another account is added from the first one's row, which stays while any is connected.
93 const canAddAccount = canAddAccounts && (tracker.connected || added.length > 0);
94 return [tracker, ...added].map((account) => (
95 <TrackerRow
96 // Drafts belong to one environment; switching must not carry them over.
97 key={`${tracker.tracker}-${account.accountId ?? ""}-${environmentId}`}
98 environmentId={environmentId}
99 tracker={account}
100 bindings={issueTrackerBindings(query.data)}
101 refreshing={query.isPending}
102 refreshFailed={query.error !== null}
103 canAddAccount={canAddAccount && account.accountId === undefined}
104 />
105 ));
106 })}
107 </SettingsSection>
108 );
110​
111function TrackerRow({
112 environmentId,
113 tracker,
114 bindings,
115 refreshing,
116 refreshFailed,
117 canAddAccount,
118}: {
119 readonly environmentId: EnvironmentId;
120 readonly tracker: IssueTrackerConnection;
121 readonly bindings: IssueTrackerConnectionList["bindings"];
122 readonly refreshing: boolean;
123 readonly refreshFailed: boolean;
124 readonly canAddAccount: boolean;
125}) {
126 const gt = useGT();
127 const messages = useMessages();
128 const Icon = TRACKER_ICONS[tracker.tracker];
129 const canEdit = useAtomValue(issueTrackerEnvironment.connect.permissionAtom(environmentId));
130 const connect = useAtomCommand(issueTrackerEnvironment.connect, {
131 label: `connect ${tracker.displayName}`,
132 });
133 const [busy, setBusy] = useState(false);
134 const [failure, setFailure] = useState<string | null>(null);
135 const [isExpanded, setIsExpanded] = useState(false);
136​
137 const submit = async (token: string | null, addAccount = false) => {
138 setBusy(true);
139 setFailure(null);
140 const result = await connect({
141 environmentId,
142 input: addAccount
143 ? { tracker: tracker.tracker, token, addAccount }
144 : { tracker: tracker.tracker, accountId: tracker.accountId, token },
145 });
146 setBusy(false);
147 if (result._tag === "Success") return true;
148 const error = squashAtomCommandFailure(result);
149 setFailure(error instanceof Error ? error.message : gt("The request failed."));
150 return false;
151 };
152​
153 const inputId = `issue-tracker-${tracker.tracker}-${tracker.accountId ?? ""}-${environmentId}`;
154 const usable = tracker.connected && tracker.account !== null;
155 const summary = issueTrackerSummary(tracker, bindings, messages);
156​
157 return (
158 <div className="first:rounded-t-xl last:rounded-b-xl transition-colors hover:bg-muted/20">
159 <div className="flex items-center justify-between gap-3 px-3 py-3 sm:px-4">
160 <div className="min-w-0 flex-1 space-y-1">
161 <div className="flex min-w-0 flex-wrap items-center gap-2">
162 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
163 {Icon ? <Icon className="size-4.5 text-foreground/80" /> : null}
164 <span
165 aria-hidden
166 className={cn(
167 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
168 usable ? "bg-success" : "bg-muted-foreground/35",
169 )}
170 />
171 </span>
172 <span className="truncate text-sm font-medium text-foreground">
173 {tracker.displayName}
174 </span>
175 {tracker.workspace ? (
176 <span className="truncate text-xs text-muted-foreground">{tracker.workspace}</span>
177 ) : null}
178 {tracker.connected && tracker.account === null ? (
179 <Badge variant="destructive" size="sm">
180 <T>Credential rejected</T>
181 </Badge>
182 ) : null}
183 </div>
184 <p className="text-xs leading-normal text-muted-foreground/80">{summary}</p>
185 </div>
186 <Button
187 size="icon-xs"
188 variant="ghost-muted"
189 onClick={() => setIsExpanded((open) => !open)}
190 aria-expanded={isExpanded}
191 aria-label={gt("Toggle {tracker} details", { tracker: tracker.displayName })}
192 >
193 <ChevronDownIcon
194 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
195 />
196 </Button>
197 </div>
198 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
199 {/* Kept mounted so a pick awaiting its refresh stays locked when the panel is reopened. */}
200 <CollapsibleContent keepMounted>
201 {/* Locked while saving, so an edit made mid-request is not overwritten by the saved value. */}
202 <fieldset disabled={!canEdit || busy} className="contents">
203 <div className="px-3 pb-4 pt-1 sm:px-4">
204 <SettingsRow
205 title={<label htmlFor={inputId}>{tracker.credential.label}</label>}
206 description={
207 <>
208 <T>Stored on the server.</T>
209 {tracker.credential.helpUrl ? (
210 <>
211 {" "}
212 <InlineButton
213 render={
214 <a
215 href={tracker.credential.helpUrl}
216 target="_blank"
217 rel="noreferrer noopener"
218 />
219 }
220 >
221 <T>Create one</T>
222 <ExternalLinkIcon aria-hidden className="size-3" />
223 </InlineButton>
224 </>
225 ) : null}
226 {failure ? <span className="block text-destructive">{failure}</span> : null}
227 </>
228 }
229 control={
230 <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
231 <SecretInput
232 id={inputId}
233 size="sm"
234 className="min-w-0 flex-1"
235 configured={tracker.connected}
236 value=""
237 onCommit={(next) => {
238 if (next.trim()) void submit(next.trim());
239 }}
240 />
241 {tracker.connected ? (
242 <Button
243 type="button"
244 size="icon-sm"
245 variant="ghost-destructive"
246 onClick={() => void submit(null)}
247 aria-label={gt("Disconnect {tracker}", { tracker: tracker.displayName })}
248 >
249 <XIcon className="size-3.5" />
250 </Button>
251 ) : null}
252 </div>
253 }
254 />
255 {usable ? (
256 <ProjectBindings
257 environmentId={environmentId}
258 tracker={tracker}
259 bindings={bindings}
260 refreshing={refreshing}
261 refreshFailed={refreshFailed}
262 />
263 ) : null}
264 {canAddAccount ? (
265 <AddAccountRow tracker={tracker} onAdd={(token) => submit(token, true)} />
266 ) : null}
267 </div>
268 </fieldset>
269 </CollapsibleContent>
270 </Collapsible>
271 </div>
272 );
274​
275/** One picker per project of this environment: which of the tracker's scopes it reads, if any. */
276function ProjectBindings({
277 environmentId,
278 tracker,
279 bindings,
280 refreshing,
281 refreshFailed,
282}: {
283 readonly environmentId: EnvironmentId;
284 readonly tracker: IssueTrackerConnection;
285 readonly bindings: IssueTrackerConnectionList["bindings"];
286 readonly refreshing: boolean;
287 readonly refreshFailed: boolean;
288}) {
289 const gt = useGT();
290 const projects = useProjects().filter((project) => project.environmentId === environmentId);
291 const bind = useAtomCommand(issueTrackerEnvironment.bindProject, {
292 label: `bind project to ${tracker.displayName}`,
293 });
294 const [picks, setPicks] = useState<Partial<Record<ProjectId, ReadonlyArray<string>>>>({});
295 const [saving, setSaving] = useState(false);
296 const held = Object.values(picks).some((scopes) => scopes !== undefined);
297 if (held && !saving && !refreshing && !refreshFailed) setPicks({});
298 const busy = saving || (held && refreshing);
299 const bound = (projectId: ProjectId) =>
300 picks[projectId] ?? boundIssueTrackerScopes(tracker, bindings[projectId]);
301 if (projects.length === 0 || !hasIssueTrackerTeams(tracker, bindings)) return null;
302​
303 const change = async (projectId: ProjectId, scopes: ReadonlyArray<string>) => {
304 if (busy) return;
305 const binding = issueTrackerBindingFor(tracker, bound(projectId), scopes);
306 const before = picks[projectId];
307 setSaving(true);
308 setPicks((current) => ({
309 ...current,
310 [projectId]: boundIssueTrackerScopes(tracker, binding ?? undefined),
311 }));
312 const result = await bind({
313 environmentId,
314 input: issueTrackerBindInput(projectId, tracker, binding),
315 });
316 if (result._tag !== "Success") setPicks((current) => ({ ...current, [projectId]: before }));
317 setSaving(false);
318 };
319​
320 return (
321 <>
322 <SettingsRow
323 title={gt("Projects")}
324 description={gt(
325 "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one unless asked for another.",
326 { tracker: tracker.displayName, scope: tracker.scopeNoun },
327 )}
328 />
329 {projects.map((project) => {
330 // A project bound to another tracker or account keeps that binding; this picker shows it unbound.
331 const value = bound(project.id);
332 const options = issueTrackerScopeOptions(tracker, value);
333 return (
334 <SettingsRow
335 key={project.id}
336 title={project.title}
337 control={
338 <Select
339 multiple
340 value={[...value]}
341 disabled={busy}
342 onValueChange={(next) => void change(project.id, next)}
343 >
344 <SelectTrigger
345 aria-label={gt("{tracker} {scope} for {project}", {
346 tracker: tracker.displayName,
347 scope: tracker.scopeNoun,
348 project: project.title,
349 })}
350 className="w-full @min-[32rem]/settings-row:w-56"
351 size="sm"
352 >
353 <SelectValue>
354 {value.length === 0
355 ? gt("Not bound")
356 : value
357 .map(
358 (key) => tracker.scopes.find((scope) => scope.key === key)?.name ?? key,
359 )
360 .join(", ")}
361 </SelectValue>
362 </SelectTrigger>
363 <SelectPopup>
364 {options.map((scope) => (
365 <SelectItem
366 key={scope.key}
367 value={scope.key}
368 disabled={!scope.addable}
369 // The checkbox marks each pick; Base UI's shading of selected rows reads as a cursor.
370 data-selected={undefined}
371 >
372 <span className="flex items-center gap-2">
373 <CheckboxMark checked={value.includes(scope.key)} />
374 {scope.name} ({scope.key})
375 </span>
376 </SelectItem>
377 ))}
378 </SelectPopup>
379 </Select>
380 }
381 />
382 );
383 })}
384 </>
385 );
387​
388/** A credential for another account of the tracker, kept beside this one. */
389function AddAccountRow({
390 tracker,
391 onAdd,
392}: {
393 readonly tracker: IssueTrackerConnection;
394 readonly onAdd: (token: string) => Promise<boolean>;
395}) {
396 const gt = useGT();
397 const [adding, setAdding] = useState(false);
398 const inputId = `issue-tracker-${tracker.tracker}-add-account`;
399 if (!adding) {
400 return (
401 <SettingsRow
402 title={gt("Another account")}
403 description={gt("Connect a second {tracker} workspace or user.", {
404 tracker: tracker.displayName,
405 })}
406 control={
407 <Button type="button" size="xs" variant="outline" onClick={() => setAdding(true)}>
408 <PlusIcon className="size-3.5" />
409 <T>Add account</T>
410 </Button>
411 }
412 />
413 );
414 }
415 return (
416 <SettingsRow
417 title={<label htmlFor={inputId}>{tracker.credential.label}</label>}
418 description={gt("For the new {tracker} account.", { tracker: tracker.displayName })}
419 control={
420 <SecretInput
421 id={inputId}
422 size="sm"
423 className="w-full min-w-0 @min-[32rem]/settings-row:w-56"
424 value=""
425 onCommit={(next) => {
426 if (next.trim()) void onAdd(next.trim()).then((added) => added && setAdding(false));
427 }}
428 />
429 }
430 />
431 );