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

settingsLayout.tsx

572 lines19.1 KB

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