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

SourceControlSettings.tsx

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