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

SourceControlSettings.tsx

521 lines17.2 KB

1import { ChevronDownIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
2import * as Duration from "effect/Duration";
3import * as Option from "effect/Option";
4import { useState, type ReactNode } from "react";
5import type {
6 SourceControlProviderKind,
7 SourceControlDiscoveryResult,
8 SourceControlProviderAuth,
9 SourceControlProviderDiscoveryItem,
10 VcsDriverKind,
11 VcsDiscoveryItem,
12} from "@t3tools/contracts";
13import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
14​
15import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
16import { cn } from "../../lib/utils";
17import { usePrimaryEnvironment } from "../../state/environments";
18import { useEnvironmentQuery } from "../../state/query";
19import { sourceControlEnvironment } from "../../state/sourceControl";
20import { Badge } from "../ui/badge";
21import { Button } from "../ui/button";
22import { Collapsible, CollapsibleContent } from "../ui/collapsible";
23import {
24 Empty,
25 EmptyContent,
26 EmptyDescription,
27 EmptyHeader,
28 EmptyMedia,
29 EmptyTitle,
30} from "../ui/empty";
31import { Skeleton } from "../ui/skeleton";
32import {
33 NumberField,
34 NumberFieldDecrement,
35 NumberFieldGroup,
36 NumberFieldIncrement,
37 NumberFieldInput,
38} from "../ui/number-field";
39import { Switch } from "../ui/switch";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41import {
42 AzureDevOpsIcon,
43 BitbucketIcon,
44 GitHubIcon,
45 GitIcon,
46 GitLabIcon,
47 JujutsuIcon,
48 type Icon,
49} from "../Icons";
50import { RedactedSensitiveText } from "./RedactedSensitiveText";
51import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
52import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
53​
54const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
55 versionControlSystems: [],
56 sourceControlProviders: [],
57};
58​
59const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {
60 github: GitHubIcon,
61 gitlab: GitLabIcon,
62 "azure-devops": AzureDevOpsIcon,
63 bitbucket: BitbucketIcon,
64};
65​
66const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
67 git: GitIcon,
68 jj: JujutsuIcon,
69};
70​
71const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
72const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
73​
74function durationToSeconds(duration: Duration.Duration): number {
75 return Math.round(Duration.toMillis(duration) / 1_000);
77​
78function normalizeFetchIntervalSeconds(value: number | null): number {
79 if (value === null || !Number.isFinite(value)) {
80 return 0;
81 }
82 return Math.max(0, Math.round(value));
84​
85function optionLabel(value: Option.Option<string>): string | null {
86 return Option.getOrNull(value);
88​
89function isProviderDiscoveryItem(
90 item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem,
91): item is SourceControlProviderDiscoveryItem {
92 return "auth" in item;
94​
95function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): boolean {
96 return !isProviderDiscoveryItem(item) && !item.implemented;
98​
99function authPresentation(auth: SourceControlProviderAuth): {
100 readonly label: string;
101 readonly badge: "warning" | null;
102} {
103 if (auth.status === "authenticated") {
104 return { label: "Authenticated", badge: null };
105 }
106 if (auth.status === "unauthenticated") {
107 return { label: "Not authenticated", badge: "warning" };
108 }
109 return { label: "Status unknown", badge: null };
111​
112function RedactedAccount(props: { readonly account: string | null }) {
113 return (
114 <RedactedSensitiveText
115 value={props.account}
116 ariaLabel="Toggle source control account visibility"
117 revealTooltip="Click to reveal account"
118 hideTooltip="Click to hide account"
119 />
120 );
122​
123function itemStatusDot(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): string {
124 if (isVcsNotReady(item)) return "bg-muted-foreground/35";
125 if (item.status !== "available") return "bg-warning";
126 if (isProviderDiscoveryItem(item) && item.auth.status !== "authenticated") return "bg-warning";
127 return "bg-success";
129​
130function SourceControlItemMark({
131 item,
132}: {
133 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
134}) {
135 const dotClassName = itemStatusDot(item);
136 const Icon = isProviderDiscoveryItem(item)
137 ? SOURCE_CONTROL_PROVIDER_ICONS[item.kind]
138 : VCS_ICONS[item.kind];
139​
140 if (!Icon) {
141 return <span className={cn("size-2 shrink-0 rounded-full", dotClassName)} aria-hidden />;
142 }
143​
144 return (
145 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
146 <Icon className="size-4.5 text-foreground/80" aria-hidden />
147 <span
148 className={cn(
149 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
150 dotClassName,
151 )}
152 aria-hidden
153 />
154 </span>
155 );
157​
158function itemSummary({
159 item,
160 auth,
161 authAccount,
162}: {
163 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
164 readonly auth: SourceControlProviderAuth | null;
165 readonly authAccount: string | null;
166}) {
167 if (isVcsNotReady(item)) {
168 return <span>Support for {item.label} is coming soon.</span>;
169 }
170​
171 if (item.status !== "available") {
172 return <span>Not available on this server: {item.installHint}</span>;
173 }
174​
175 if (auth) {
176 if (auth.status === "authenticated") {
177 return (
178 <>
179 <span>Authenticated</span>
180 {authAccount ? (
181 <>
182 <span aria-hidden>as</span>
183 <RedactedAccount account={authAccount} />
184 </>
185 ) : null}
186 </>
187 );
188 }
189​
190 if (!item.executable) {
191 return <span>Available. {item.installHint}</span>;
192 }
193​
194 if (auth.status === "unauthenticated") {
195 return (
196 <span>
197 {item.label} is not authenticated on this server. Sign in or configure credentials using
198 the <code className="rounded bg-muted px-1 py-px text-[11px]">{item.executable}</code>{" "}
199 tool on the server host to enable change request features.
200 </span>
201 );
202 }
203 return (
204 <span>
205 Could not verify {item.label}. {item.installHint}
206 </span>
207 );
208 }
209​
210 return <span>Available</span>;
212​
213function DiscoveryItemRow({
214 item,
215 children,
216}: {
217 readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
218 readonly children?: ReactNode;
219}) {
220 const version = optionLabel(item.version);
221 const enabled = isProviderDiscoveryItem(item)
222 ? item.status === "available" && item.auth.status === "authenticated"
223 : item.status === "available" && item.implemented;
224 const auth = isProviderDiscoveryItem(item) ? item.auth : null;
225 const authStatus = auth ? authPresentation(auth) : null;
226 const authAccount = auth ? optionLabel(auth.account) : null;
227 const [isExpanded, setIsExpanded] = useState(false);
228 const hasDetails = children !== undefined;
229​
230 return (
231 <div
232 className={cn(
233 "rounded-xl transition-colors hover:bg-muted/20",
234 isVcsNotReady(item) && "opacity-80",
235 )}
236 >
237 <div className="px-3 py-3 sm:px-4">
238 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
239 <div className="min-w-0 flex-1 space-y-1">
240 <div className="flex min-w-0 flex-wrap items-center gap-2">
241 <SourceControlItemMark item={item} />
242 <span className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
243 {item.label}
244 </span>
245 {version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
246 {isVcsNotReady(item) ? (
247 <Badge variant="warning" size="sm">
248 Coming Soon
249 </Badge>
250 ) : null}
251 {authStatus?.badge ? (
252 <Badge variant={authStatus.badge} size="sm">
253 {authStatus.label}
254 </Badge>
255 ) : null}
256 </div>
257 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-[13px] leading-[1.45] text-muted-foreground/80">
258 {itemSummary({ item, auth, authAccount })}
259 </p>
260 </div>
261 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
262 {hasDetails ? (
263 <Button
264 size="sm"
265 variant="ghost"
266 className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
267 onClick={() => setIsExpanded((open) => !open)}
268 aria-expanded={isExpanded}
269 aria-label={`Toggle ${item.label} details`}
270 >
271 <ChevronDownIcon
272 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
273 />
274 </Button>
275 ) : null}
276 {!isVcsNotReady(item) ? (
277 <Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
278 ) : null}
279 </div>
280 </div>
281 </div>
282​
283 {hasDetails ? (
284 <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
285 <CollapsibleContent>
286 <div className="px-3 pb-4 pt-1 sm:px-4">{children}</div>
287 </CollapsibleContent>
288 </Collapsible>
289 ) : null}
290 </div>
291 );
293​
294function GitFetchIntervalSettings() {
295 const automaticGitFetchInterval = usePrimarySettings(
296 (settings) => settings.automaticGitFetchInterval,
297 );
298 const updateSettings = useUpdatePrimarySettings();
299 const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
300 const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
301 DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
302 );
303 const canResetFetchInterval =
304 automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
305​
306 return (
307 <div className="grid gap-3">
308 <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
309 <div className="min-w-0 space-y-1">
310 <div className="flex min-w-0 items-center gap-1">
311 <span className="text-xs font-medium text-foreground">Fetch interval</span>
312 <span
313 className={cn(
314 "inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
315 canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
316 )}
317 aria-hidden={!canResetFetchInterval}
318 >
319 {canResetFetchInterval ? (
320 <SettingResetButton
321 label="fetch interval"
322 onClick={() =>
323 updateSettings({
324 automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
325 })
326 }
327 />
328 ) : null}
329 </span>
330 </div>
331 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
332 Refresh remote branch status in the background. Set this to 0 seconds if Git credentials
333 or security keys should only be prompted by explicit Git actions.
334 </p>
335 </div>
336 <div className="flex shrink-0 items-center gap-2">
337 <NumberField
338 value={automaticGitFetchIntervalSeconds}
339 min={0}
340 step={GIT_FETCH_INTERVAL_STEP_SECONDS}
341 size="sm"
342 className="w-32"
343 onValueChange={(value) =>
344 updateSettings({
345 automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
346 })
347 }
348 >
349 <NumberFieldGroup>
350 <NumberFieldDecrement aria-label="Decrease fetch interval" />
351 <NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
352 <NumberFieldIncrement aria-label="Increase fetch interval" />
353 </NumberFieldGroup>
354 </NumberField>
355 <span className="text-xs text-muted-foreground">seconds</span>
356 </div>
357 </div>
358 </div>
359 );
361​
362function SourceControlSectionSkeleton({
363 title,
364 headerAction,
365}: {
366 readonly title: string;
367 readonly headerAction?: ReactNode;
368}) {
369 return (
370 <SettingsSection title={title} headerAction={headerAction}>
371 {SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
372 <div key={row} className="rounded-xl px-3 py-3 sm:px-4">
373 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
374 <div className="min-w-0 flex-1 space-y-2">
375 <div className="flex items-center gap-2">
376 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
377 <Skeleton className="size-4.5 rounded-md" />
378 <Skeleton
379 className="pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background"
380 aria-hidden
381 />
382 </span>
383 <Skeleton className="h-4 w-28 rounded-full" />
384 <Skeleton className="h-5 w-14 rounded-full" />
385 </div>
386 <Skeleton className="h-3 w-full max-w-xs rounded-full" />
387 </div>
388 <div className="flex shrink-0 items-center gap-2">
389 <Skeleton className="size-7 rounded-md" />
390 <Skeleton className="h-5 w-9 rounded-full" />
391 </div>
392 </div>
393 </div>
394 ))}
395 </SettingsSection>
396 );
398​
399function EmptySourceControlDiscovery({
400 error,
401 isPending,
402 onScan,
403}: {
404 readonly error: string | null;
405 readonly isPending: boolean;
406 readonly onScan: () => void;
407}) {
408 const hasError = error !== null;
409​
410 return (
411 <SettingsSection title="Server environment">
412 <Empty className="min-h-88">
413 <EmptyMedia variant="icon">
414 <GitPullRequestIcon />
415 </EmptyMedia>
416 <EmptyHeader>
417 <EmptyTitle>
418 {hasError ? "Could not scan the server environment" : "Nothing detected yet"}
419 </EmptyTitle>
420 <EmptyDescription>
421 {hasError
422 ? error
423 : "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
424 </EmptyDescription>
425 </EmptyHeader>
426 <EmptyContent>
427 <Button
428 size="sm"
429 variant="outline"
430 className="h-8 gap-1.5 px-3 text-xs"
431 onClick={onScan}
432 disabled={isPending}
433 >
434 <RefreshCwIcon className={cn("size-3.5", isPending && "animate-spin")} />
435 Scan
436 </Button>
437 </EmptyContent>
438 </Empty>
439 </SettingsSection>
440 );
442​
443export function SourceControlSettingsPanel() {
444 const environmentId = usePrimaryEnvironment()?.environmentId ?? null;
445 const discovery = useEnvironmentQuery(
446 environmentId === null
447 ? null
448 : sourceControlEnvironment.discovery({
449 environmentId,
450 input: {},
451 }),
452 );
453 const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
454 const hasDiscoveryItems =
455 result.versionControlSystems.length > 0 || result.sourceControlProviders.length > 0;
456 const isInitialScanPending = discovery.isPending && discovery.data === null;
457 const handleScan = () => {
458 discovery.refresh();
459 };
460 const scanButton = (
461 <Tooltip>
462 <TooltipTrigger
463 render={
464 <Button
465 size="icon-xs"
466 variant="ghost"
467 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
468 onClick={handleScan}
469 disabled={discovery.isPending}
470 aria-label="Rescan server environment"
471 >
472 <RefreshCwIcon className={cn("size-3", discovery.isPending && "animate-spin")} />
473 </Button>
474 }
475 />
476 <TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
477 </Tooltip>
478 );
479​
480 return (
481 <SettingsPageContainer>
482 {isInitialScanPending ? (
483 <>
484 <SourceControlSectionSkeleton title="Version Control" headerAction={scanButton} />
485 <SourceControlSectionSkeleton title="Source Control Providers" />
486 </>
487 ) : hasDiscoveryItems ? (
488 <>
489 {result.versionControlSystems.length > 0 ? (
490 <SettingsSection title="Version Control" headerAction={scanButton}>
491 {result.versionControlSystems.map((item) => (
492 <DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
493 {item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
494 </DiscoveryItemRow>
495 ))}
496 </SettingsSection>
497 ) : null}
498​
499 {result.sourceControlProviders.length > 0 ? (
500 <SettingsSection
501 title="Source Control Providers"
502 headerAction={result.versionControlSystems.length === 0 ? scanButton : null}
503 >
504 {result.sourceControlProviders.map((item) => (
505 <DiscoveryItemRow key={`provider:${item.kind}`} item={item} />
506 ))}
507 </SettingsSection>
508 ) : null}
509 </>
510 ) : (
511 <EmptySourceControlDiscovery
512 error={discovery.error}
513 isPending={discovery.isPending}
514 onScan={handleScan}
515 />
516 )}
517​
518 {environmentId !== null ? <SourceControlWritingSettingsSection /> : null}
519 </SettingsPageContainer>
520 );