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