Open History to see the last commit
1import { SettingsGroup } from "./SettingsGroup";
2import { AuthSettingsWriteScope } from "@t3tools/contracts";
3import { usePrimaryEnvironmentId, usePrimaryEnvironment } from "../../state/environments";
4import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
5import { useServerConfigs } from "../../state/entities";
6import { InfoIcon, Undo2Icon } from "lucide-react";
7import {
8 DEFAULT_SERVER_SETTINGS,
9 isManagedSettingPath,
10 type ServerSettings,
11} from "@t3tools/contracts";
12import * as Equal from "effect/Equal";
13import { useGT } from "gt-react";
14import { useLocation, useNavigate } from "@tanstack/react-router";
15import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContext } from "react";
16
17import {
18 PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
19 usePrimarySettingsAvailable,
20} from "../../hooks/useSettings";
21import { cn } from "../../lib/utils";
22import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
23import { Button } from "../ui/button";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25import { SharedTooltipTrigger } from "../ui/shared-tooltip";
26import { useOptionalSettingsScope } from "./SettingsScopeContext";
27import { SettingsScopeSentence } from "./SettingsScopeSentence";
28import {
29 isProjectScopedSettingKey,
30 listProjectOverrides,
31 type ProjectOverrideEntry,
32 scopedSettingsAreMixed,
33 scopedSettingsSource,
34} from "./scopedSettings";
35import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings";
36import {
37 SettingInheritance,
38 type SettingInheritanceState,
39 type SettingOverridingProject,
40} from "./SettingInheritance";
41
42const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = [];
43const EMPTY_MANAGED_PATHS: readonly string[] = [];
44
45declare module "@tanstack/react-router" {
46 interface HistoryState {
47 settingsTargetHighlight?: boolean;
48 }
49}
50
51interface SettingsSearchTargetContextValue {
52 readonly targetId: string | null;
53 readonly highlightTarget: boolean;
54 readonly onTargetHandled: () => void;
55}
56
57const noop = () => undefined;
58const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
59 targetId: null,
60 highlightTarget: true,
61 onTargetHandled: noop,
62});
63
64function SettingsSearchTargetProvider({
65 targetId,
66 highlightTarget = true,
67 onTargetHandled = noop,
68 children,
69}: {
70 targetId: string | null;
71 highlightTarget?: boolean;
72 onTargetHandled?: () => void;
73 children: ReactNode;
74}) {
75 const value = { targetId, highlightTarget, onTargetHandled };
76 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
77}
78
79let pendingTargetScroll: AbortController | undefined;
80
81function scrollAndFocusSettingsTarget(target: HTMLElement, highlight = true): void {
82 pendingTargetScroll?.abort();
83 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
84 const markedScrollTarget =
85 typeof target.querySelector === "function"
86 ? target.querySelector<HTMLElement>(":scope > [data-settings-scroll-target]")
87 : null;
88 const scrollTarget =
89 markedScrollTarget ??
90 (target.tagName === "SECTION" && target.firstElementChild
91 ? (target.firstElementChild as HTMLElement)
92 : target);
93
94 const scroll = () =>
95 scrollTarget.scrollIntoView({
96 behavior: prefersReducedMotion ? "auto" : "smooth",
97 block: "center",
98 });
99 scroll();
100 const panel = target.parentElement?.closest<HTMLElement>(
101 '[data-slot="collapsible-panel"][data-open]',
102 );
103 const heightTransition = () =>
104 panel
105 ?.getAnimations()
106 .find(
107 (animation) =>
108 animation instanceof CSSTransition && animation.transitionProperty === "height",
109 );
110 if (panel && (panel.hasAttribute("data-starting-style") || heightTransition())) {
111 const controller = new AbortController();
112 pendingTargetScroll = controller;
113 const { signal } = controller;
114 const finishScroll = () => {
115 if (signal.aborted) return;
116 controller.abort();
117 if (
118 panel.hasAttribute("data-open") &&
119 target.isConnected &&
120 document.activeElement === target
121 ) {
122 scroll();
123 }
124 };
125 const waitForHeight = () => {
126 const transition = heightTransition();
127 if (transition) {
128 void transition.finished.then(finishScroll, () => controller.abort());
129 } else {
130 finishScroll();
131 }
132 };
133 // Base UI clears the starting style before the height transition finishes.
134 if (panel.hasAttribute("data-starting-style")) {
135 const observer = new MutationObserver(() => {
136 if (!panel.hasAttribute("data-starting-style")) {
137 observer.disconnect();
138 waitForHeight();
139 }
140 });
141 observer.observe(panel, { attributes: true, attributeFilter: ["data-starting-style"] });
142 signal.addEventListener("abort", () => observer.disconnect(), { once: true });
143 } else {
144 waitForHeight();
145 }
146 target.addEventListener("blur", () => controller.abort(), { once: true, signal });
147 }
148 target.focus({ preventScroll: true });
149 target.classList.remove("settings-search-target-pulse");
150 if (!highlight || prefersReducedMotion) return;
151 void target.offsetWidth;
152 target.classList.add("settings-search-target-pulse");
153 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
154 once: true,
155 });
156}
157
158export function useSettingsSearchTargetId(): string | null {
159 return useContext(SettingsSearchTargetContext).targetId;
160}
161
162export function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
163 const { targetId, highlightTarget, onTargetHandled } = useContext(SettingsSearchTargetContext);
164 const isSearchTarget = id !== undefined && id === targetId;
165 const targetRef = (target: T | null) => {
166 if (target && isSearchTarget) {
167 scrollAndFocusSettingsTarget(target, highlightTarget);
168 onTargetHandled();
169 }
170 };
171
172 return targetRef;
173}
174
175export function SettingsSearchTarget({
176 children,
177 // `searchableSetting` names the target for search; as an HTML title it shows a native tooltip.
178 title: _searchTitle,
179 ...targetProps
180}: ComponentPropsWithoutRef<"div">) {
181 const targetRef = useSettingsSearchTarget<HTMLDivElement>(targetProps.id);
182 return (
183 <div {...targetProps} ref={targetRef} tabIndex={targetProps.id ? -1 : targetProps.tabIndex}>
184 {children}
185 </div>
186 );
187}
188
189// Settings pickers reuse composer controls but match the bordered selects beside them.
190export const SETTINGS_PICKER_TRIGGER_CLASSNAME =
191 "min-w-0 max-w-none shrink-0 border-input bg-background font-normal text-foreground shadow-xs/5 hover:bg-accent/50 dark:bg-input/32 [&_svg[data-composer-control-chevron]]:stroke-[1.75] [&_svg[data-composer-control-chevron]]:opacity-70";
192
193export function PolicyTooltip({ children }: { readonly children: string }) {
194 const gt = useGT();
195 return (
196 <Tooltip>
197 <TooltipTrigger
198 delay={200}
199 render={
200 <Button
201 size="icon-micro"
202 variant="ghost-muted"
203 aria-label={gt("Background policy details")}
204 >
205 <InfoIcon className="size-3.5" />
206 </Button>
207 }
208 />
209 <TooltipPopup side="top">{children}</TooltipPopup>
210 </Tooltip>
211 );
212}
213
214export function SettingsSection({
215 title,
216 hideTitle = false,
217 icon,
218 titleAction,
219 headerAction,
220 variant = "grouped",
221 children,
222 className,
223 ...sectionProps
224}: ComponentPropsWithoutRef<"section"> & {
225 title: string;
226 hideTitle?: boolean;
227 icon?: ReactNode;
228 titleAction?: ReactNode;
229 headerAction?: ReactNode;
230 variant?: "grouped" | "plain";
231 children: ReactNode;
232}) {
233 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
234
235 return (
236 <section
237 {...sectionProps}
238 ref={targetRef}
239 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
240 className={cn(!hideTitle && "space-y-2.5", className)}
241 >
242 {hideTitle ? (
243 <h2 className="sr-only">{title}</h2>
244 ) : (
245 <div
246 data-settings-scroll-target
247 className="flex min-h-7 flex-wrap items-start justify-between gap-x-4 gap-y-1 px-3 sm:px-4"
248 >
249 <div className="flex min-w-0 items-center gap-1">
250 <h2 className="flex min-h-7 items-center gap-2 text-base font-semibold text-foreground">
251 {icon}
252 {title}
253 </h2>
254 {titleAction}
255 </div>
256 {headerAction ? (
257 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
258 ) : null}
259 </div>
260 )}
261 <SettingsGroup data-settings-scroll-target={hideTitle ? "" : undefined} variant={variant}>
262 {children}
263 </SettingsGroup>
264 </section>
265 );
266}
267
268export function SettingsUnavailableGroup({
269 children,
270 message,
271}: {
272 children: ReactNode;
273 message?: ReactNode;
274}) {
275 if (message === undefined) return children;
276
277 return (
278 <div className="border-border/60 bg-muted/20 py-1.5">
279 <div className="flex items-start gap-2 px-3 py-2 text-xs leading-relaxed text-muted-foreground sm:px-4">
280 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
281 <p>{message}</p>
282 </div>
283 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
284 </div>
285 );
286}
287
288function projectOverrides(
289 context: ReturnType<typeof useOptionalSettingsScope>,
290 scopedKeys: ReadonlyArray<keyof ServerSettings>,
291): SettingOverridingProject[] {
292 if (context === null || scopedKeys.length === 0) return [];
293 return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
294 const group = context.groups.find((candidate) =>
295 candidate.memberProjects.some(
296 (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
297 ),
298 );
299 if (!group) return [];
300 return [
301 {
302 ...entry,
303 label: group.displayName,
304 open: () =>
305 context.selectScope({
306 project: group.projectKey,
307 ...(context.search.machine ? { machine: context.search.machine } : {}),
308 }),
309 },
310 ];
311 });
312}
313
314export function SettingsRow({
315 title,
316 description,
317 status,
318 resetAction,
319 onResetOverride,
320 control,
321 serverScoped = false,
322 devicePreference = false,
323 settingKeys = EMPTY_SETTING_KEYS,
324 managedPaths = EMPTY_MANAGED_PATHS,
325 mixed: mixedOverride,
326 managed,
327 children,
328 className,
329 ...rowProps
330}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
331 title: ReactNode;
332 description?: ReactNode;
333 status?: ReactNode;
334 resetAction?: ReactNode;
335 onResetOverride?: () => void;
336 control?: ReactNode;
337 serverScoped?: boolean;
338 /** Saved on this device, so a project cannot override it and the row is read-only there. */
339 devicePreference?: boolean;
340 settingKeys?: readonly (keyof ServerSettings)[];
341 /** Dot paths inside a setting, such as `storageCleanup.logsAfterDays`, an administrator can lock. */
342 managedPaths?: readonly string[];
343 mixed?: boolean;
344 /** Why an administrator's policy turns this row's control off, from the contract's denial helpers. */
345 managed?: string | undefined;
346 children?: ReactNode;
347}) {
348 const gt = useGT();
349 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
350 const primarySettingsAvailable = usePrimarySettingsAvailable();
351 const context = useOptionalSettingsScope();
352 const primaryEnvironmentId = usePrimaryEnvironmentId();
353 const primaryEnvironment = usePrimaryEnvironment();
354 const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);
355 const writableIds = useEnvironmentsWithScope(
356 context?.connectedEnvironments ?? [],
357 AuthSettingsWriteScope,
358 );
359 const canWriteSettings = context
360 ? context.connectedEnvironments.length > 0 &&
361 context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
362 : primaryCanWrite;
363 const serverConfigs = useServerConfigs();
364 // An administrator's lock on any target wins over every other reason a control is inert.
365 const lockablePaths = [...settingKeys, ...managedPaths];
366 const managedBy =
367 lockablePaths.length === 0
368 ? undefined
369 : (context
370 ? context.connectedEnvironments.map((environment) => environment.serverConfig)
371 : [primaryEnvironmentId === null ? undefined : serverConfigs.get(primaryEnvironmentId)]
372 )
373 .map((config) => config?.managedPolicy)
374 .find(
375 (policy) =>
376 policy !== undefined &&
377 lockablePaths.some((path) => isManagedSettingPath(policy, path)),
378 )?.organization;
379 const clearOverrides = useClearScopedSettings();
380 const clearProjectOverrides = useClearProjectOverrides();
381 const isProjectScope =
382 context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
383 const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
384 const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
385 const deviceReadOnly = isProjectScope && devicePreference;
386 const mixed =
387 mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
388 const source =
389 context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
390 const unavailable =
391 serverScoped &&
392 (!canWriteSettings ||
393 !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable));
394 const inheritedFrom =
395 source === "environment" && context?.scope.environmentIds.length === 1
396 ? (context.environments.find(
397 (environment) => environment.environmentId === context.scope.environmentIds[0],
398 )?.label ?? null)
399 : null;
400 const environmentSettingsById = new Map(
401 (context?.connectedEnvironments ?? []).flatMap((environment) =>
402 environment.serverConfig
403 ? [[environment.environmentId, environment.serverConfig.settings] as const]
404 : [],
405 ),
406 );
407 const overridingProjects = isProjectScope ? [] : projectOverrides(context, scopedKeys);
408 const renderedReset =
409 unavailable ||
410 deviceReadOnly ||
411 managedBy !== undefined ||
412 managed !== undefined ? null : isProjectScope && scopedKeys.length > 0 ? (
413 source === "project" || source === "mixed" ? (
414 <SettingResetButton
415 ariaLabel={
416 typeof title === "string"
417 ? gt("Reset {title} to default", { title })
418 : gt("Reset override to default")
419 }
420 tooltip={gt("Reset to inherited value")}
421 onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
422 />
423 ) : null
424 ) : (
425 resetAction
426 );
427 const inertControl = (message: string) => (
428 <SharedTooltipTrigger
429 render={
430 <span
431 tabIndex={0}
432 className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring @min-[32rem]/settings-row:w-auto"
433 />
434 }
435 label={message}
436 >
437 <div
438 inert
439 className="flex w-full items-center gap-2 opacity-50 @min-[32rem]/settings-row:w-auto"
440 >
441 {control}
442 </div>
443 </SharedTooltipTrigger>
444 );
445 const lackingPermissionMessage = () => {
446 const environments = context
447 ? context.connectedEnvironments
448 .filter((target) => !writableIds.has(target.environmentId))
449 .map((target) => target.label)
450 .join(", ")
451 : primaryEnvironment?.label;
452 return environments
453 ? gt("This connection lacks permission to change settings on {environments}.", {
454 environments,
455 })
456 : context
457 ? gt("This connection lacks permission to change settings on the selected environment.")
458 : gt("This connection lacks permission to change settings on the primary environment.");
459 };
460 const renderedControl =
461 managed !== undefined && control
462 ? inertControl(managed)
463 : managedBy !== undefined && control
464 ? inertControl(gt("Managed by {organization}.", { organization: managedBy }))
465 : unavailable && control
466 ? inertControl(
467 !canWriteSettings
468 ? lackingPermissionMessage()
469 : context
470 ? gt("Reconnect the selected environment to change this setting.")
471 : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
472 )
473 : environmentWide && control
474 ? inertControl(gt("Environment-wide setting. Select an environment to change it."))
475 : deviceReadOnly && control
476 ? inertControl(gt("Saved on this device. Select All projects to change it."))
477 : control;
478 const customized =
479 context !== null &&
480 settingKeys.some((key) =>
481 context.targets.some((candidate) => {
482 const environmentSettings = environmentSettingsById.get(candidate.environmentId);
483 return (
484 environmentSettings !== undefined &&
485 !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
486 );
487 }),
488 );
489 const inheritance: { state: SettingInheritanceState; summary: string } = mixed
490 ? { state: "mixed", summary: gt("Mixed across selected environments") }
491 : source === "project"
492 ? { state: "overridden", summary: gt("Overridden for this project") }
493 : source === "t3.json"
494 ? { state: "inherited", summary: gt("Inherited from the repository's t3.json") }
495 : source === "environment" && scopedKeys.length > 0
496 ? {
497 state: "inherited",
498 summary:
499 inheritedFrom === null
500 ? gt("Inherited from environment")
501 : gt("Inherited from {environment}", { environment: inheritedFrom }),
502 }
503 : customized
504 ? { state: "environment", summary: gt("Set on the environment") }
505 : { state: "default", summary: gt("Built-in default") };
506 const renderedInheritance =
507 context && serverScoped && settingKeys.length > 0 ? (
508 <SettingInheritance
509 state={inheritance.state}
510 summary={inheritance.summary}
511 targets={context.targets}
512 environments={context.connectedEnvironments}
513 keys={settingKeys}
514 overridingProjects={overridingProjects}
515 {...(canWriteSettings
516 ? {
517 onClearOverrides: (entries: readonly ProjectOverrideEntry[]) =>
518 clearProjectOverrides(entries, scopedKeys),
519 }
520 : {})}
521 />
522 ) : null;
523 const renderedStatus = status;
524
525 return (
526 <div
527 {...rowProps}
528 ref={targetRef}
529 tabIndex={rowProps.tabIndex ?? -1}
530 data-slot="settings-row"
531 className={cn(
532 "group/settings-row @container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-64 aria-disabled:[&_*]:text-muted-foreground",
533 children ? "pt-3 pb-1" : "py-3",
534 className,
535 )}
536 >
537 <div className="flex flex-col gap-3 @min-[32rem]/settings-row:grid @min-[32rem]/settings-row:grid-cols-[minmax(0,1fr)_auto] @min-[32rem]/settings-row:items-center @min-[32rem]/settings-row:gap-8">
538 <div className="min-w-0 flex-1 space-y-1">
539 <div className="flex min-h-5 items-center gap-1.5">
540 <h3 className="text-sm font-medium text-foreground">{title}</h3>
541 {renderedInheritance ? (
542 <span
543 className={cn(
544 "inline-flex h-5 w-5 shrink-0 items-center justify-center",
545 // Values set right here explain nothing new, so their marker waits for hover or focus.
546 (inheritance.state === "default" || inheritance.state === "environment") &&
547 overridingProjects.length === 0 &&
548 "opacity-0 group-hover/settings-row:opacity-100 has-focus-visible:opacity-100 has-data-popup-open:opacity-100",
549 )}
550 >
551 {renderedInheritance}
552 </span>
553 ) : null}
554 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
555 {renderedReset}
556 </span>
557 </div>
558 {description ? (
559 <p className="max-w-2xl text-pretty text-xs leading-normal text-muted-foreground">
560 {description}
561 </p>
562 ) : null}
563 {renderedStatus ? (
564 <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
565 ) : null}
566 </div>
567 {renderedControl ? (
568 <div className="flex w-full min-w-0 shrink-0 items-center gap-2 @min-[32rem]/settings-row:w-auto @min-[32rem]/settings-row:justify-end @min-[32rem]/settings-row:[&_[data-slot=select-trigger]]:min-w-40">
569 {renderedControl}
570 </div>
571 ) : null}
572 </div>
573 {unavailable && children ? (
574 <div inert className="opacity-50">
575 {children}
576 </div>
577 ) : (
578 children
579 )}
580 </div>
581 );
582}
583
584export function SettingResetButton({
585 ariaLabel,
586 tooltip,
587 disabled = false,
588 onClick,
589}: {
590 ariaLabel: string;
591 tooltip?: string;
592 disabled?: boolean;
593 onClick: () => void;
594}) {
595 const gt = useGT();
596 return (
597 <Tooltip>
598 <TooltipTrigger
599 render={
600 <Button
601 size="icon-micro"
602 variant="ghost-muted"
603 aria-label={ariaLabel}
604 disabled={disabled}
605 onClick={(event) => {
606 event.stopPropagation();
607 // A reset usually unmounts this button. Keep focus beside the setting, or focus
608 // recovery sends it to the area's default control and scrolls that into view.
609 event.currentTarget.parentElement
610 ?.closest<HTMLElement>("[tabindex]")
611 ?.focus({ preventScroll: true });
612 onClick();
613 }}
614 >
615 <Undo2Icon className="size-3" />
616 </Button>
617 }
618 />
619 <TooltipPopup side="top">{tooltip ?? gt("Reset to default")}</TooltipPopup>
620 </Tooltip>
621 );
622}
623
624export function SettingsPageContainer({
625 children,
626 className,
627 width = "readable",
628 searchTargetFallbacks,
629}: {
630 children: ReactNode;
631 className?: string;
632 width?: WorkspacePageWidth;
633 searchTargetFallbacks?: Readonly<Record<string, string | undefined>>;
634}) {
635 const navigate = useNavigate();
636 const hash = useLocation({ select: (location) => location.hash });
637 const highlightTarget = useLocation({
638 select: (location) => location.state.settingsTargetHighlight !== false,
639 });
640 const targetId = hash.replace(/^#/, "") || null;
641 const clearTargetHash = () => {
642 void navigate({
643 hash: "",
644 replace: true,
645 resetScroll: false,
646 hashScrollIntoView: false,
647 state: { settingsTargetHighlight: true },
648 });
649 };
650
651 return (
652 <SettingsSearchTargetProvider
653 targetId={targetId === null ? null : (searchTargetFallbacks?.[targetId] ?? targetId)}
654 highlightTarget={highlightTarget}
655 onTargetHandled={clearTargetHash}
656 >
657 <div
658 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
659 data-settings-page-scroll
660 >
661 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
662 <SettingsScopeSentence />
663 {children}
664 </WorkspacePageContainer>
665 </div>
666 </SettingsSearchTargetProvider>
667 );
668}
669
670export function scrollToSettingsTarget(
671 targetId: string,
672 { highlight = true }: { readonly highlight?: boolean } = {},
673): boolean {
674 const target = document.getElementById(targetId);
675 if (!target) return false;
676 scrollAndFocusSettingsTarget(target, highlight);
677 return true;
678}