Open History to see the last commit
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 }
50}
51
52interface SettingsSearchTargetContextValue {
53 readonly targetId: string | null;
54 readonly highlightTarget: boolean;
55 readonly onTargetHandled: () => void;
56}
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>;
81}
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 });
109}
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;
114}
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;
130}
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 );
142}
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 );
162}
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;
172}
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 headerAction,
180 variant = "grouped",
181 children,
182 className,
183 ...sectionProps
184}: ComponentPropsWithoutRef<"section"> & {
185 title: string;
186 hideTitle?: boolean;
187 icon?: ReactNode;
188 headerAction?: ReactNode;
189 variant?: "grouped" | "plain";
190 children: ReactNode;
191}) {
192 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
193
194 return (
195 <section
196 {...sectionProps}
197 ref={targetRef}
198 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
199 className={cn(!hideTitle && "space-y-2.5", className)}
200 >
201 {hideTitle ? (
202 <h2 className="sr-only">{title}</h2>
203 ) : (
204 <div
205 data-settings-scroll-target
206 className="flex min-h-7 items-start justify-between gap-4 px-3 sm:px-4"
207 >
208 <div className="min-w-0">
209 <h2 className="flex min-h-7 items-center gap-2 text-sm font-normal text-foreground/70">
210 {icon}
211 {title}
212 </h2>
213 </div>
214 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
215 </div>
216 )}
217 <SettingsGroup data-settings-scroll-target={hideTitle ? "" : undefined} variant={variant}>
218 {children}
219 </SettingsGroup>
220 </section>
221 );
222}
223
224export function SettingsUnavailableGroup({
225 children,
226 message,
227}: {
228 children: ReactNode;
229 message?: ReactNode;
230}) {
231 if (message === undefined) return children;
232
233 return (
234 <div className="border-border/60 bg-muted/20 py-1.5">
235 <div className="flex items-start gap-2 px-3 py-2 text-xs leading-relaxed text-muted-foreground sm:px-4">
236 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
237 <p>{message}</p>
238 </div>
239 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
240 </div>
241 );
242}
243
244/**
245 * One setting. `serverScoped` marks rows whose value lives in the primary
246 * environment's settings.json; where there is no primary (the hosted app)
247 * the control goes inert with a tooltip instead of showing an editable
248 * default that would never save.
249 *
250 * Keep descriptions short enough for one line where possible. Allow wrapping
251 * for clarity or narrow screens instead of truncating or forcing no-wrap.
252 *
253 * Control sizing across settings follows three tiers so rows share a baseline:
254 * - `control` slot: `size="sm"` (Button, Select, Input, NumberField) or `icon-sm`.
255 * - Section `headerAction`s and buttons inside list items, cards, toolbars: `xs` / `icon-xs`.
256 * - Inline affordances (reset arrows, info tooltips, table-cell buttons): `icon-micro`.
257 * Dialog footers keep the app-wide default button size.
258 */
259export function SettingsRow({
260 title,
261 description,
262 status,
263 resetAction,
264 onResetOverride,
265 control,
266 serverScoped = false,
267 settingKeys = EMPTY_SETTING_KEYS,
268 mixed: mixedOverride,
269 children,
270 className,
271 ...rowProps
272}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
273 title: ReactNode;
274 description?: ReactNode;
275 status?: ReactNode;
276 resetAction?: ReactNode;
277 /** Replaces the default override clear for rows with side effects beyond the settings key. */
278 onResetOverride?: () => void;
279 control?: ReactNode;
280 serverScoped?: boolean;
281 settingKeys?: readonly (keyof ServerSettings)[];
282 mixed?: boolean;
283 children?: ReactNode;
284}) {
285 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
286 const primarySettingsAvailable = usePrimarySettingsAvailable();
287 const context = useOptionalSettingsScope();
288 const primaryEnvironmentId = usePrimaryEnvironmentId();
289 const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);
290 const writableIds = useEnvironmentsWithScope(
291 context?.connectedEnvironments ?? [],
292 AuthSettingsWriteScope,
293 );
294 const canWriteSettings = context
295 ? context.connectedEnvironments.length > 0 &&
296 context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
297 : primaryCanWrite;
298 const clearOverrides = useClearScopedSettings();
299 const clearProjectOverrides = useClearProjectOverrides();
300 const isProjectScope =
301 context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
302 const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
303 // A project scope can only edit keys that support overrides; the rest stay
304 // visible so the user sees the inherited value, but cannot change it here.
305 const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
306 const mixed =
307 mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
308 const source =
309 context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
310 const unavailable =
311 serverScoped &&
312 (!canWriteSettings ||
313 !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable));
314 const inheritedFrom =
315 source === "environment" && context?.scope.environmentIds.length === 1
316 ? (context.environments.find(
317 (environment) => environment.environmentId === context.scope.environmentIds[0],
318 )?.label ?? "environment")
319 : "environment";
320 const environmentSettingsById = useMemo(
321 () =>
322 new Map(
323 (context?.connectedEnvironments ?? []).flatMap((environment) =>
324 environment.serverConfig
325 ? [[environment.environmentId, environment.serverConfig.settings] as const]
326 : [],
327 ),
328 ),
329 [context?.connectedEnvironments],
330 );
331 // At environment scope, projects with their own value keep it when the
332 // environment default changes; the chain names them and can reset them.
333 const overridingProjects = useMemo((): SettingOverridingProject[] => {
334 if (context === null || isProjectScope || scopedKeys.length === 0) return [];
335 return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
336 const group = context.groups.find((candidate) =>
337 candidate.memberProjects.some(
338 (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
339 ),
340 );
341 if (!group) return [];
342 return [
343 {
344 ...entry,
345 label: group.displayName,
346 open: () =>
347 context.selectScope({
348 project: group.projectKey,
349 ...(context.search.machine ? { machine: context.search.machine } : {}),
350 }),
351 },
352 ];
353 });
354 }, [context, isProjectScope, scopedKeys]);
355 const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? (
356 source === "project" || source === "mixed" ? (
357 <SettingResetButton
358 label={typeof title === "string" ? title : "override"}
359 tooltip="Reset to inherited value"
360 onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
361 />
362 ) : null
363 ) : (
364 resetAction
365 );
366 const inertControl = (message: string) => (
367 <Tooltip>
368 <TooltipTrigger
369 render={
370 // Focusable so keyboard users can still reach the explanation.
371 <span
372 tabIndex={0}
373 className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring @min-[32rem]/settings-row:w-auto"
374 />
375 }
376 >
377 <div
378 inert
379 className="flex w-full items-center gap-2 opacity-50 @min-[32rem]/settings-row:w-auto"
380 >
381 {control}
382 </div>
383 </TooltipTrigger>
384 <TooltipPopup side="top">{message}</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 !canWriteSettings
394 ? "This connection does not have permission to change environment settings."
395 : context
396 ? "Reconnect the selected environment to change this setting."
397 : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
398 )
399 : environmentWide && control
400 ? inertControl("Environment-wide setting. Select an environment to change it.")
401 : control;
402 // Server rows get an indicator beside the title that opens the resolution
403 // chain per target at every scope; client rows keep a plain status only.
404 const customized =
405 context !== null &&
406 settingKeys.some((key) =>
407 context.targets.some((candidate) => {
408 const environmentSettings = environmentSettingsById.get(candidate.environmentId);
409 return (
410 environmentSettings !== undefined &&
411 !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
412 );
413 }),
414 );
415 const inheritance: { state: SettingInheritanceState; summary: string } = mixed
416 ? { state: "mixed", summary: "Mixed across selected environments" }
417 : source === "project"
418 ? { state: "overridden", summary: "Overridden for this project" }
419 : source === "t3.json"
420 ? { state: "inherited", summary: "Inherited from the repository's t3.json" }
421 : source === "environment" && scopedKeys.length > 0
422 ? { state: "inherited", summary: `Inherited from ${inheritedFrom}` }
423 : customized
424 ? { state: "environment", summary: "Set on the environment" }
425 : { state: "default", summary: "Built-in default" };
426 const renderedInheritance =
427 context && serverScoped && settingKeys.length > 0 ? (
428 <SettingInheritance
429 state={inheritance.state}
430 summary={inheritance.summary}
431 targets={context.targets}
432 environments={context.connectedEnvironments}
433 keys={settingKeys}
434 overridingProjects={overridingProjects}
435 {...(canWriteSettings
436 ? {
437 onClearOverrides: (entries: readonly ProjectOverrideEntry[]) =>
438 clearProjectOverrides(entries, scopedKeys),
439 }
440 : {})}
441 />
442 ) : null;
443 const renderedStatus = status;
444
445 return (
446 <div
447 {...rowProps}
448 ref={targetRef}
449 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
450 data-slot="settings-row"
451 className={cn(
452 "@container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-64 aria-disabled:[&_*]:text-muted-foreground",
453 children ? "pt-3 pb-1" : "py-3",
454 className,
455 )}
456 >
457 <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">
458 <div className="min-w-0 flex-1 space-y-1">
459 <div className="flex min-h-5 items-center gap-1.5">
460 <h3 className="text-sm font-medium text-foreground">{title}</h3>
461 {renderedInheritance ? (
462 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
463 {renderedInheritance}
464 </span>
465 ) : null}
466 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
467 {renderedReset}
468 </span>
469 </div>
470 {description ? (
471 <p className="max-w-xl text-xs leading-normal text-muted-foreground/80">
472 {description}
473 </p>
474 ) : null}
475 {renderedStatus ? (
476 <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
477 ) : null}
478 </div>
479 {renderedControl ? (
480 <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">
481 {renderedControl}
482 </div>
483 ) : null}
484 </div>
485 {unavailable && children ? (
486 <div inert className="opacity-50">
487 {children}
488 </div>
489 ) : (
490 children
491 )}
492 </div>
493 );
494}
495
496export function SettingResetButton({
497 label,
498 tooltip = "Reset to default",
499 disabled = false,
500 onClick,
501}: {
502 label: string;
503 tooltip?: string;
504 disabled?: boolean;
505 onClick: () => void;
506}) {
507 return (
508 <Tooltip>
509 <TooltipTrigger
510 render={
511 <Button
512 size="icon-micro"
513 variant="ghost-muted"
514 aria-label={`Reset ${label} to default`}
515 disabled={disabled}
516 onClick={(event) => {
517 event.stopPropagation();
518 onClick();
519 }}
520 >
521 <Undo2Icon className="size-3" />
522 </Button>
523 }
524 />
525 <TooltipPopup side="top">{tooltip}</TooltipPopup>
526 </Tooltip>
527 );
528}
529
530export function SettingsPageContainer({
531 children,
532 className,
533 width = "readable",
534}: {
535 children: ReactNode;
536 className?: string;
537 width?: WorkspacePageWidth;
538}) {
539 const navigate = useNavigate();
540 const hash = useLocation({ select: (location) => location.hash });
541 const highlightTarget = useLocation({
542 select: (location) => location.state.settingsTargetHighlight !== false,
543 });
544 const targetId = hash.replace(/^#/, "") || null;
545 const clearTargetHash = useCallback(() => {
546 void navigate({
547 hash: "",
548 replace: true,
549 resetScroll: false,
550 hashScrollIntoView: false,
551 state: { settingsTargetHighlight: true },
552 });
553 }, [navigate]);
554
555 return (
556 <SettingsSearchTargetProvider
557 targetId={targetId}
558 highlightTarget={highlightTarget}
559 onTargetHandled={clearTargetHash}
560 >
561 <div
562 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
563 data-settings-page-scroll
564 >
565 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
566 <SettingsScopeSentence />
567 {children}
568 </WorkspacePageContainer>
569 </div>
570 </SettingsSearchTargetProvider>
571 );
572}
573
574export function scrollToSettingsTarget(
575 targetId: string,
576 { highlight = true }: { readonly highlight?: boolean } = {},
577): boolean {
578 const target = document.getElementById(targetId);
579 if (!target) return false;
580 scrollAndFocusSettingsTarget(target, highlight);
581 return true;
582}