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

SourceControlSettings.tsx

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