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

SourceControlSettings.tsx

658 lines22.2 KB

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