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

settingsLayout.tsx

565 lines19.0 KB

1import { SettingsGroup } from "./SettingsGroup";
2import { InfoIcon, Undo2Icon } from "lucide-react";
3import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
4import * as Equal from "effect/Equal";
5import { useLocation, useNavigate } from "@tanstack/react-router";
6import {
7 createContext,
8 type ComponentPropsWithoutRef,
9 type ReactNode,
10 useCallback,
11 useContext,
12 useEffect,
13 useMemo,
14 useState,
15} 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 { useOptionalSettingsScope } from "./SettingsScopeContext";
26import { SettingsScopeSentence } from "./SettingsScopeSentence";
27import {
28 isProjectScopedSettingKey,
29 listProjectOverrides,
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)[] = [];
41​
42declare module "@tanstack/react-router" {
43 interface HistoryState {
44 settingsTargetHighlight?: boolean;
45 }
47​
48interface SettingsSearchTargetContextValue {
49 readonly targetId: string | null;
50 readonly highlightTarget: boolean;
51 readonly onTargetHandled: () => void;
53​
54const noop = () => undefined;
55const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
56 targetId: null,
57 highlightTarget: true,
58 onTargetHandled: noop,
59});
60​
61function SettingsSearchTargetProvider({
62 targetId,
63 highlightTarget = true,
64 onTargetHandled = noop,
65 children,
66}: {
67 targetId: string | null;
68 highlightTarget?: boolean;
69 onTargetHandled?: () => void;
70 children: ReactNode;
71}) {
72 const value = useMemo(
73 () => ({ targetId, highlightTarget, onTargetHandled }),
74 [highlightTarget, onTargetHandled, targetId],
75 );
76 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
78​
79function scrollAndFocusSettingsTarget(target: HTMLElement, highlight = true): void {
80 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
81 const markedScrollTarget =
82 typeof target.querySelector === "function"
83 ? target.querySelector<HTMLElement>(":scope > [data-settings-scroll-target]")
84 : null;
85 const scrollTarget =
86 markedScrollTarget ??
87 (target.tagName === "SECTION" && target.firstElementChild
88 ? (target.firstElementChild as HTMLElement)
89 : target);
90​
91 scrollTarget.scrollIntoView({
92 behavior: prefersReducedMotion ? "auto" : "smooth",
93 block: "center",
94 });
95 target.focus({ preventScroll: true });
96 target.classList.remove("settings-search-target-pulse");
97 if (!highlight || prefersReducedMotion) return;
98 void target.offsetWidth;
99 target.classList.add("settings-search-target-pulse");
100 // The class also suppresses the focus outline (the pulse is the destination
101 // indicator), so drop it once the element is no longer the destination.
102 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
103 once: true,
104 });
106​
107/** The row id a settings-search jump is currently trying to reach, if any. */
108export function useSettingsSearchTargetId(): string | null {
109 return useContext(SettingsSearchTargetContext).targetId;
111​
112export function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
113 const { targetId, highlightTarget, onTargetHandled } = useContext(SettingsSearchTargetContext);
114 const isSearchTarget = id !== undefined && id === targetId;
115 const targetRef = useCallback(
116 (target: T | null) => {
117 if (target && isSearchTarget) {
118 scrollAndFocusSettingsTarget(target, highlightTarget);
119 onTargetHandled();
120 }
121 },
122 [highlightTarget, isSearchTarget, onTargetHandled],
123 );
124​
125 return targetRef;
127​
128export function SettingsSearchTarget({
129 children,
130 ...targetProps
131}: ComponentPropsWithoutRef<"div">) {
132 const targetRef = useSettingsSearchTarget<HTMLDivElement>(targetProps.id);
133 return (
134 <div {...targetProps} ref={targetRef} tabIndex={targetProps.id ? -1 : targetProps.tabIndex}>
135 {children}
136 </div>
137 );
139​
140/**
141 * Trigger classes for the composer model/traits pickers when they sit in a
142 * settings row: match the `sm` control box (the composer pins them to 28px at
143 * every breakpoint) and drop the composer's max-width.
144 */
145export const SETTINGS_PICKER_TRIGGER_CLASSNAME =
146 "h-8 min-h-8 min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground sm:h-7 sm:min-h-7";
147​
148/** Info affordance explaining how a setting interacts with the shared background policy. */
149export function PolicyTooltip({ children }: { readonly children: string }) {
150 return (
151 <Tooltip>
152 <TooltipTrigger
153 delay={200}
154 render={
155 <Button size="icon-micro" variant="ghost-muted" aria-label="Background policy details">
156 <InfoIcon className="size-3.5" />
157 </Button>
158 }
159 />
160 <TooltipPopup side="top">{children}</TooltipPopup>
161 </Tooltip>
162 );
164​
165/** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */
166export function useRelativeTimeTick(intervalMs = 1_000) {
167 const [nowMs, setNowMs] = useState(() => Date.now());
168 useEffect(() => {
169 const id = setInterval(() => setNowMs(Date.now()), intervalMs);
170 return () => clearInterval(id);
171 }, [intervalMs]);
172 return nowMs;
174​
175/** Muted section headings have no descriptions; explanatory copy belongs to individual settings. */
176export function SettingsSection({
177 title,
178 hideTitle = false,
179 icon,
180 headerAction,
181 variant = "grouped",
182 children,
183 className,
184 ...sectionProps
185}: ComponentPropsWithoutRef<"section"> & {
186 title: string;
187 hideTitle?: boolean;
188 icon?: ReactNode;
189 headerAction?: ReactNode;
190 variant?: "grouped" | "plain";
191 children: ReactNode;
192}) {
193 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
194​
195 return (
196 <section
197 {...sectionProps}
198 ref={targetRef}
199 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
200 className={cn(!hideTitle && "space-y-2.5", className)}
201 >
202 {hideTitle ? (
203 <h2 className="sr-only">{title}</h2>
204 ) : (
205 <div
206 data-settings-scroll-target
207 className="flex min-h-7 items-start justify-between gap-4 px-3 sm:px-4"
208 >
209 <div className="min-w-0">
210 <h2 className="flex min-h-7 items-center gap-2 text-sm font-normal tracking-[-0.005em] text-foreground/70">
211 {icon}
212 {title}
213 </h2>
214 </div>
215 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
216 </div>
217 )}
218 <SettingsGroup data-settings-scroll-target={hideTitle ? "" : undefined} variant={variant}>
219 {children}
220 </SettingsGroup>
221 </section>
222 );
224​
225export function SettingsUnavailableGroup({
226 children,
227 message,
228}: {
229 children: ReactNode;
230 message?: ReactNode;
231}) {
232 if (message === undefined) return children;
233​
234 return (
235 <div className="border-border/60 bg-muted/20 py-1.5">
236 <div className="flex items-start gap-2 px-3 py-2 text-[12px] leading-relaxed text-muted-foreground sm:px-4">
237 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
238 <p>{message}</p>
239 </div>
240 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
241 </div>
242 );
244​
245/**
246 * One setting. `serverScoped` marks rows whose value lives in the primary
247 * environment's settings.json; where there is no primary (the hosted app)
248 * the control goes inert with a tooltip instead of showing an editable
249 * default that would never save.
250 *
251 * Keep descriptions short enough for one line where possible. Allow wrapping
252 * for clarity or narrow screens instead of truncating or forcing no-wrap.
253 *
254 * Control sizing across settings follows three tiers so rows share a baseline:
255 * - `control` slot: `size="sm"` (Button, Select, Input, NumberField) or `icon-sm`.
256 * - Section `headerAction`s and buttons inside list items, cards, toolbars: `xs` / `icon-xs`.
257 * - Inline affordances (reset arrows, info tooltips, table-cell buttons): `icon-micro`.
258 * Dialog footers keep the app-wide default button size.
259 */
260export function SettingsRow({
261 title,
262 description,
263 status,
264 resetAction,
265 onResetOverride,
266 control,
267 serverScoped = false,
268 settingKeys = EMPTY_SETTING_KEYS,
269 mixed: mixedOverride,
270 children,
271 className,
272 ...rowProps
273}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
274 title: ReactNode;
275 description?: ReactNode;
276 status?: ReactNode;
277 resetAction?: ReactNode;
278 /** Replaces the default override clear for rows with side effects beyond the settings key. */
279 onResetOverride?: () => void;
280 control?: ReactNode;
281 serverScoped?: boolean;
282 settingKeys?: readonly (keyof ServerSettings)[];
283 mixed?: boolean;
284 children?: ReactNode;
285}) {
286 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
287 const primarySettingsAvailable = usePrimarySettingsAvailable();
288 const context = useOptionalSettingsScope();
289 const clearOverrides = useClearScopedSettings();
290 const clearProjectOverrides = useClearProjectOverrides();
291 const isProjectScope =
292 context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
293 const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
294 // A project scope can only edit keys that support overrides; the rest stay
295 // visible so the user sees the inherited value, but cannot change it here.
296 const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
297 const mixed =
298 mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
299 const source =
300 context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
301 const unavailable =
302 serverScoped &&
303 !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable);
304 const inheritedFrom =
305 source === "environment" && context?.scope.environmentIds.length === 1
306 ? (context.environments.find(
307 (environment) => environment.environmentId === context.scope.environmentIds[0],
308 )?.label ?? "environment")
309 : "environment";
310 const environmentSettingsById = useMemo(
311 () =>
312 new Map(
313 (context?.connectedEnvironments ?? []).flatMap((environment) =>
314 environment.serverConfig
315 ? [[environment.environmentId, environment.serverConfig.settings] as const]
316 : [],
317 ),
318 ),
319 [context?.connectedEnvironments],
320 );
321 // At environment scope, projects with their own value keep it when the
322 // environment default changes; the chain names them and can reset them.
323 const overridingProjects = useMemo((): SettingOverridingProject[] => {
324 if (context === null || isProjectScope || scopedKeys.length === 0) return [];
325 return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
326 const group = context.groups.find((candidate) =>
327 candidate.memberProjects.some(
328 (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
329 ),
330 );
331 if (!group) return [];
332 return [
333 {
334 ...entry,
335 label: group.displayName,
336 open: () =>
337 context.selectScope({
338 project: group.projectKey,
339 ...(context.search.machine ? { machine: context.search.machine } : {}),
340 }),
341 },
342 ];
343 });
344 }, [context, isProjectScope, scopedKeys]);
345 const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? (
346 source === "project" || source === "mixed" ? (
347 <SettingResetButton
348 label={typeof title === "string" ? title : "override"}
349 tooltip="Reset to inherited value"
350 onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
351 />
352 ) : null
353 ) : (
354 resetAction
355 );
356 const inertControl = (message: string) => (
357 <Tooltip>
358 <TooltipTrigger
359 render={
360 // Focusable so keyboard users can still reach the explanation.
361 <span
362 tabIndex={0}
363 className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring @min-[32rem]/settings-row:w-auto"
364 />
365 }
366 >
367 <div
368 inert
369 className="flex w-full items-center gap-2 opacity-50 @min-[32rem]/settings-row:w-auto"
370 >
371 {control}
372 </div>
373 </TooltipTrigger>
374 <TooltipPopup side="top">{message}</TooltipPopup>
375 </Tooltip>
376 );
377 // A mixed selection keeps the real control with "Mixed" as its placeholder
378 // (the multi-selection inspector convention): the popover shows who has
379 // what, and picking a value applies it to every target.
380 const renderedControl =
381 unavailable && control
382 ? inertControl(
383 context
384 ? "Reconnect the selected environment to change this setting."
385 : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
386 )
387 : environmentWide && control
388 ? inertControl("Environment-wide setting. Select an environment to change it.")
389 : control;
390 // Server rows get an indicator beside the title that opens the resolution
391 // chain per target at every scope; client rows keep a plain status only.
392 const customized =
393 context !== null &&
394 settingKeys.some((key) =>
395 context.targets.some((candidate) => {
396 const environmentSettings = environmentSettingsById.get(candidate.environmentId);
397 return (
398 environmentSettings !== undefined &&
399 !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
400 );
401 }),
402 );
403 const inheritance: { state: SettingInheritanceState; summary: string } = mixed
404 ? { state: "mixed", summary: "Mixed across selected environments" }
405 : source === "project"
406 ? { state: "overridden", summary: "Overridden for this project" }
407 : source === "t3.json"
408 ? { state: "inherited", summary: "Inherited from the repository's t3.json" }
409 : source === "environment" && scopedKeys.length > 0
410 ? { state: "inherited", summary: `Inherited from ${inheritedFrom}` }
411 : customized
412 ? { state: "environment", summary: "Set on the environment" }
413 : { state: "default", summary: "Built-in default" };
414 const renderedInheritance =
415 context && serverScoped && settingKeys.length > 0 ? (
416 <SettingInheritance
417 state={inheritance.state}
418 summary={inheritance.summary}
419 targets={context.targets}
420 environments={context.connectedEnvironments}
421 keys={settingKeys}
422 overridingProjects={overridingProjects}
423 onClearOverrides={(entries) => clearProjectOverrides(entries, scopedKeys)}
424 />
425 ) : null;
426 const renderedStatus = status;
427​
428 return (
429 <div
430 {...rowProps}
431 ref={targetRef}
432 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
433 data-slot="settings-row"
434 className={cn(
435 "@container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-50 aria-disabled:[&_*]:text-muted-foreground",
436 children ? "pt-3 pb-1" : "py-3",
437 className,
438 )}
439 >
440 <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">
441 <div className="min-w-0 flex-1 space-y-1">
442 <div className="flex min-h-5 items-center gap-1.5">
443 <h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">{title}</h3>
444 {renderedInheritance ? (
445 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
446 {renderedInheritance}
447 </span>
448 ) : null}
449 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
450 {renderedReset}
451 </span>
452 </div>
453 {description ? (
454 <p className="max-w-xl text-[13px] leading-[1.45] text-muted-foreground/80">
455 {description}
456 </p>
457 ) : null}
458 {renderedStatus ? (
459 <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
460 ) : null}
461 </div>
462 {renderedControl ? (
463 <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">
464 {renderedControl}
465 </div>
466 ) : null}
467 </div>
468 {unavailable && children ? (
469 <div inert className="opacity-50">
470 {children}
471 </div>
472 ) : (
473 children
474 )}
475 </div>
476 );
478​
479export function SettingResetButton({
480 label,
481 tooltip = "Reset to default",
482 disabled = false,
483 onClick,
484}: {
485 label: string;
486 tooltip?: string;
487 disabled?: boolean;
488 onClick: () => void;
489}) {
490 return (
491 <Tooltip>
492 <TooltipTrigger
493 render={
494 <Button
495 size="icon-micro"
496 variant="ghost-muted"
497 aria-label={`Reset ${label} to default`}
498 disabled={disabled}
499 onClick={(event) => {
500 event.stopPropagation();
501 onClick();
502 }}
503 >
504 <Undo2Icon className="size-3" />
505 </Button>
506 }
507 />
508 <TooltipPopup side="top">{tooltip}</TooltipPopup>
509 </Tooltip>
510 );
512​
513export function SettingsPageContainer({
514 children,
515 className,
516 width = "readable",
517}: {
518 children: ReactNode;
519 className?: string;
520 width?: WorkspacePageWidth;
521}) {
522 const navigate = useNavigate();
523 const hash = useLocation({ select: (location) => location.hash });
524 const highlightTarget = useLocation({
525 select: (location) => location.state.settingsTargetHighlight !== false,
526 });
527 const targetId = hash.replace(/^#/, "") || null;
528 const clearTargetHash = useCallback(() => {
529 void navigate({
530 hash: "",
531 replace: true,
532 resetScroll: false,
533 hashScrollIntoView: false,
534 state: { settingsTargetHighlight: true },
535 });
536 }, [navigate]);
537​
538 return (
539 <SettingsSearchTargetProvider
540 targetId={targetId}
541 highlightTarget={highlightTarget}
542 onTargetHandled={clearTargetHash}
543 >
544 <div
545 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
546 data-settings-page-scroll
547 >
548 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
549 <SettingsScopeSentence />
550 {children}
551 </WorkspacePageContainer>
552 </div>
553 </SettingsSearchTargetProvider>
554 );
556​
557export function scrollToSettingsTarget(
558 targetId: string,
559 { highlight = true }: { readonly highlight?: boolean } = {},
560): boolean {
561 const target = document.getElementById(targetId);
562 if (!target) return false;
563 scrollAndFocusSettingsTarget(target, highlight);
564 return true;