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