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