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