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

SourceControlSettings.tsx

601 lines20.1 KB

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