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