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

SourceControlSettings.tsx

605 lines20.4 KB

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