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

SourceControlSettings.tsx

518 lines17.0 KB

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