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

settingsLayout.tsx

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