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

SourceControlSettings.tsx

607 lines20.4 KB

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