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

settingsLayout.tsx

638 lines21.8 KB

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 }
48​
49interface SettingsSearchTargetContextValue {
50 readonly targetId: string | null;
51 readonly highlightTarget: boolean;
52 readonly onTargetHandled: () => void;
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>;
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 });
155​
156export function useSettingsSearchTargetId(): string | null {
157 return useContext(SettingsSearchTargetContext).targetId;
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;
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 );
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 );
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 items-start justify-between gap-4 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 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
250 </div>
251 )}
252 <SettingsGroup data-settings-scroll-target={hideTitle ? "" : undefined} variant={variant}>
253 {children}
254 </SettingsGroup>
255 </section>
256 );
258​
259export function SettingsUnavailableGroup({
260 children,
261 message,
262}: {
263 children: ReactNode;
264 message?: ReactNode;
265}) {
266 if (message === undefined) return children;
267​
268 return (
269 <div className="border-border/60 bg-muted/20 py-1.5">
270 <div className="flex items-start gap-2 px-3 py-2 text-xs leading-relaxed text-muted-foreground sm:px-4">
271 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
272 <p>{message}</p>
273 </div>
274 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
275 </div>
276 );
278​
279function projectOverrides(
280 context: ReturnType<typeof useOptionalSettingsScope>,
281 scopedKeys: ReadonlyArray<keyof ServerSettings>,
282): SettingOverridingProject[] {
283 if (context === null || scopedKeys.length === 0) return [];
284 return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
285 const group = context.groups.find((candidate) =>
286 candidate.memberProjects.some(
287 (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
288 ),
289 );
290 if (!group) return [];
291 return [
292 {
293 ...entry,
294 label: group.displayName,
295 open: () =>
296 context.selectScope({
297 project: group.projectKey,
298 ...(context.search.machine ? { machine: context.search.machine } : {}),
299 }),
300 },
301 ];
302 });
304​
305export function SettingsRow({
306 title,
307 description,
308 status,
309 resetAction,
310 onResetOverride,
311 control,
312 serverScoped = false,
313 settingKeys = EMPTY_SETTING_KEYS,
314 managedPaths = EMPTY_MANAGED_PATHS,
315 mixed: mixedOverride,
316 managed,
317 children,
318 className,
319 ...rowProps
320}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
321 title: ReactNode;
322 description?: ReactNode;
323 status?: ReactNode;
324 resetAction?: ReactNode;
325 onResetOverride?: () => void;
326 control?: ReactNode;
327 serverScoped?: boolean;
328 settingKeys?: readonly (keyof ServerSettings)[];
329 /** Dot paths inside a setting, such as `storageCleanup.logsAfterDays`, an administrator can lock. */
330 managedPaths?: readonly string[];
331 mixed?: boolean;
332 /** Why an administrator's policy turns this row's control off, from the contract's denial helpers. */
333 managed?: string | undefined;
334 children?: ReactNode;
335}) {
336 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
337 const primarySettingsAvailable = usePrimarySettingsAvailable();
338 const context = useOptionalSettingsScope();
339 const primaryEnvironmentId = usePrimaryEnvironmentId();
340 const primaryEnvironment = usePrimaryEnvironment();
341 const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);
342 const writableIds = useEnvironmentsWithScope(
343 context?.connectedEnvironments ?? [],
344 AuthSettingsWriteScope,
345 );
346 const canWriteSettings = context
347 ? context.connectedEnvironments.length > 0 &&
348 context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
349 : primaryCanWrite;
350 const serverConfigs = useServerConfigs();
351 // An administrator's lock on any target wins over every other reason a control is inert.
352 const lockablePaths = [...settingKeys, ...managedPaths];
353 const managedBy =
354 lockablePaths.length === 0
355 ? undefined
356 : (context
357 ? context.connectedEnvironments.map((environment) => environment.serverConfig)
358 : [primaryEnvironmentId === null ? undefined : serverConfigs.get(primaryEnvironmentId)]
359 )
360 .map((config) => config?.managedPolicy)
361 .find(
362 (policy) =>
363 policy !== undefined &&
364 lockablePaths.some((path) => isManagedSettingPath(policy, path)),
365 )?.organization;
366 const clearOverrides = useClearScopedSettings();
367 const clearProjectOverrides = useClearProjectOverrides();
368 const isProjectScope =
369 context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
370 const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
371 const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
372 const mixed =
373 mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
374 const source =
375 context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
376 const unavailable =
377 serverScoped &&
378 (!canWriteSettings ||
379 !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable));
380 const inheritedFrom =
381 source === "environment" && context?.scope.environmentIds.length === 1
382 ? (context.environments.find(
383 (environment) => environment.environmentId === context.scope.environmentIds[0],
384 )?.label ?? "environment")
385 : "environment";
386 const environmentSettingsById = new Map(
387 (context?.connectedEnvironments ?? []).flatMap((environment) =>
388 environment.serverConfig
389 ? [[environment.environmentId, environment.serverConfig.settings] as const]
390 : [],
391 ),
392 );
393 const overridingProjects = isProjectScope ? [] : projectOverrides(context, scopedKeys);
394 const renderedReset =
395 unavailable || managedBy !== undefined || managed !== undefined ? null : isProjectScope &&
396 scopedKeys.length > 0 ? (
397 source === "project" || source === "mixed" ? (
398 <SettingResetButton
399 label={typeof title === "string" ? title : "override"}
400 tooltip="Reset to inherited value"
401 onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
402 />
403 ) : null
404 ) : (
405 resetAction
406 );
407 const inertControl = (message: string) => (
408 <Tooltip>
409 <TooltipTrigger
410 render={
411 <span
412 tabIndex={0}
413 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"
414 />
415 }
416 >
417 <div
418 inert
419 className="flex w-full items-center gap-2 opacity-50 @min-[32rem]/settings-row:w-auto"
420 >
421 {control}
422 </div>
423 </TooltipTrigger>
424 <TooltipPopup side="top">{message}</TooltipPopup>
425 </Tooltip>
426 );
427 const renderedControl =
428 managed !== undefined && control
429 ? inertControl(managed)
430 : managedBy !== undefined && control
431 ? inertControl(`Managed by ${managedBy}.`)
432 : unavailable && control
433 ? inertControl(
434 !canWriteSettings
435 ? `This connection lacks permission to change settings on ${
436 context
437 ? context.connectedEnvironments
438 .filter((target) => !writableIds.has(target.environmentId))
439 .map((target) => target.label)
440 .join(", ") || "the selected environment"
441 : (primaryEnvironment?.label ?? "the primary environment")
442 }.`
443 : context
444 ? "Reconnect the selected environment to change this setting."
445 : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
446 )
447 : environmentWide && control
448 ? inertControl("Environment-wide setting. Select an environment to change it.")
449 : control;
450 const customized =
451 context !== null &&
452 settingKeys.some((key) =>
453 context.targets.some((candidate) => {
454 const environmentSettings = environmentSettingsById.get(candidate.environmentId);
455 return (
456 environmentSettings !== undefined &&
457 !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
458 );
459 }),
460 );
461 const inheritance: { state: SettingInheritanceState; summary: string } = mixed
462 ? { state: "mixed", summary: "Mixed across selected environments" }
463 : source === "project"
464 ? { state: "overridden", summary: "Overridden for this project" }
465 : source === "t3.json"
466 ? { state: "inherited", summary: "Inherited from the repository's t3.json" }
467 : source === "environment" && scopedKeys.length > 0
468 ? { state: "inherited", summary: `Inherited from ${inheritedFrom}` }
469 : customized
470 ? { state: "environment", summary: "Set on the environment" }
471 : { state: "default", summary: "Built-in default" };
472 const renderedInheritance =
473 context && serverScoped && settingKeys.length > 0 ? (
474 <SettingInheritance
475 state={inheritance.state}
476 summary={inheritance.summary}
477 targets={context.targets}
478 environments={context.connectedEnvironments}
479 keys={settingKeys}
480 overridingProjects={overridingProjects}
481 {...(canWriteSettings
482 ? {
483 onClearOverrides: (entries: readonly ProjectOverrideEntry[]) =>
484 clearProjectOverrides(entries, scopedKeys),
485 }
486 : {})}
487 />
488 ) : null;
489 const renderedStatus = status;
490​
491 return (
492 <div
493 {...rowProps}
494 ref={targetRef}
495 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
496 data-slot="settings-row"
497 className={cn(
498 "group/settings-row @container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-64 aria-disabled:[&_*]:text-muted-foreground",
499 children ? "pt-3 pb-1" : "py-3",
500 className,
501 )}
502 >
503 <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">
504 <div className="min-w-0 flex-1 space-y-1">
505 <div className="flex min-h-5 items-center gap-1.5">
506 <h3 className="text-sm font-medium text-foreground">{title}</h3>
507 {renderedInheritance ? (
508 <span
509 className={cn(
510 "inline-flex h-5 w-5 shrink-0 items-center justify-center",
511 // Values set right here explain nothing new, so their marker waits for hover or focus.
512 (inheritance.state === "default" || inheritance.state === "environment") &&
513 overridingProjects.length === 0 &&
514 "opacity-0 group-hover/settings-row:opacity-100 has-focus-visible:opacity-100 has-data-popup-open:opacity-100",
515 )}
516 >
517 {renderedInheritance}
518 </span>
519 ) : null}
520 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
521 {renderedReset}
522 </span>
523 </div>
524 {description ? (
525 <p className="max-w-2xl text-pretty text-xs leading-normal text-muted-foreground">
526 {description}
527 </p>
528 ) : null}
529 {renderedStatus ? (
530 <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
531 ) : null}
532 </div>
533 {renderedControl ? (
534 <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">
535 {renderedControl}
536 </div>
537 ) : null}
538 </div>
539 {unavailable && children ? (
540 <div inert className="opacity-50">
541 {children}
542 </div>
543 ) : (
544 children
545 )}
546 </div>
547 );
549​
550export function SettingResetButton({
551 label,
552 tooltip = "Reset to default",
553 disabled = false,
554 onClick,
555}: {
556 label: string;
557 tooltip?: string;
558 disabled?: boolean;
559 onClick: () => void;
560}) {
561 return (
562 <Tooltip>
563 <TooltipTrigger
564 render={
565 <Button
566 size="icon-micro"
567 variant="ghost-muted"
568 aria-label={`Reset ${label} to default`}
569 disabled={disabled}
570 onClick={(event) => {
571 event.stopPropagation();
572 onClick();
573 }}
574 >
575 <Undo2Icon className="size-3" />
576 </Button>
577 }
578 />
579 <TooltipPopup side="top">{tooltip}</TooltipPopup>
580 </Tooltip>
581 );
583​
584export function SettingsPageContainer({
585 children,
586 className,
587 width = "readable",
588 searchTargetFallbacks,
589}: {
590 children: ReactNode;
591 className?: string;
592 width?: WorkspacePageWidth;
593 searchTargetFallbacks?: Readonly<Record<string, string | undefined>>;
594}) {
595 const navigate = useNavigate();
596 const hash = useLocation({ select: (location) => location.hash });
597 const highlightTarget = useLocation({
598 select: (location) => location.state.settingsTargetHighlight !== false,
599 });
600 const targetId = hash.replace(/^#/, "") || null;
601 const clearTargetHash = () => {
602 void navigate({
603 hash: "",
604 replace: true,
605 resetScroll: false,
606 hashScrollIntoView: false,
607 state: { settingsTargetHighlight: true },
608 });
609 };
610​
611 return (
612 <SettingsSearchTargetProvider
613 targetId={targetId === null ? null : (searchTargetFallbacks?.[targetId] ?? targetId)}
614 highlightTarget={highlightTarget}
615 onTargetHandled={clearTargetHash}
616 >
617 <div
618 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
619 data-settings-page-scroll
620 >
621 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
622 <SettingsScopeSentence />
623 {children}
624 </WorkspacePageContainer>
625 </div>
626 </SettingsSearchTargetProvider>
627 );
629​
630export function scrollToSettingsTarget(
631 targetId: string,
632 { highlight = true }: { readonly highlight?: boolean } = {},
633): boolean {
634 const target = document.getElementById(targetId);
635 if (!target) return false;
636 scrollAndFocusSettingsTarget(target, highlight);
637 return true;