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