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

settingsLayout.tsx

586 lines19.9 KB

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