Open History to see the last commit
1import { SettingsGroup } from "./SettingsGroup";
2import { AuthSettingsWriteScope } from "@t3tools/contracts";
3import { usePrimaryEnvironmentId, usePrimaryEnvironment } 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 { createContext, type ComponentPropsWithoutRef, type ReactNode, useContext } from "react";
10
11import {
12 PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
13 usePrimarySettingsAvailable,
14} from "../../hooks/useSettings";
15import { cn } from "../../lib/utils";
16import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
17import { Button } from "../ui/button";
18import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
19import { useOptionalSettingsScope } from "./SettingsScopeContext";
20import { SettingsScopeSentence } from "./SettingsScopeSentence";
21import {
22 isProjectScopedSettingKey,
23 listProjectOverrides,
24 type ProjectOverrideEntry,
25 scopedSettingsAreMixed,
26 scopedSettingsSource,
27} from "./scopedSettings";
28import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings";
29import {
30 SettingInheritance,
31 type SettingInheritanceState,
32 type SettingOverridingProject,
33} from "./SettingInheritance";
34
35const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = [];
36
37declare module "@tanstack/react-router" {
38 interface HistoryState {
39 settingsTargetHighlight?: boolean;
40 }
41}
42
43interface SettingsSearchTargetContextValue {
44 readonly targetId: string | null;
45 readonly highlightTarget: boolean;
46 readonly onTargetHandled: () => void;
47}
48
49const noop = () => undefined;
50const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
51 targetId: null,
52 highlightTarget: true,
53 onTargetHandled: noop,
54});
55
56function SettingsSearchTargetProvider({
57 targetId,
58 highlightTarget = true,
59 onTargetHandled = noop,
60 children,
61}: {
62 targetId: string | null;
63 highlightTarget?: boolean;
64 onTargetHandled?: () => void;
65 children: ReactNode;
66}) {
67 const value = { targetId, highlightTarget, onTargetHandled };
68 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
69}
70
71let pendingTargetScroll: AbortController | undefined;
72
73function scrollAndFocusSettingsTarget(target: HTMLElement, highlight = true): void {
74 pendingTargetScroll?.abort();
75 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
76 const markedScrollTarget =
77 typeof target.querySelector === "function"
78 ? target.querySelector<HTMLElement>(":scope > [data-settings-scroll-target]")
79 : null;
80 const scrollTarget =
81 markedScrollTarget ??
82 (target.tagName === "SECTION" && target.firstElementChild
83 ? (target.firstElementChild as HTMLElement)
84 : target);
85
86 const scroll = () =>
87 scrollTarget.scrollIntoView({
88 behavior: prefersReducedMotion ? "auto" : "smooth",
89 block: "center",
90 });
91 scroll();
92 const panel = target.parentElement?.closest<HTMLElement>(
93 '[data-slot="collapsible-panel"][data-open]',
94 );
95 const heightTransition = () =>
96 panel
97 ?.getAnimations()
98 .find(
99 (animation) =>
100 animation instanceof CSSTransition && animation.transitionProperty === "height",
101 );
102 if (panel && (panel.hasAttribute("data-starting-style") || heightTransition())) {
103 const controller = new AbortController();
104 pendingTargetScroll = controller;
105 const { signal } = controller;
106 const finishScroll = () => {
107 if (signal.aborted) return;
108 controller.abort();
109 if (
110 panel.hasAttribute("data-open") &&
111 target.isConnected &&
112 document.activeElement === target
113 ) {
114 scroll();
115 }
116 };
117 const waitForHeight = () => {
118 const transition = heightTransition();
119 if (transition) {
120 void transition.finished.then(finishScroll, () => controller.abort());
121 } else {
122 finishScroll();
123 }
124 };
125 // Base UI clears the starting style before the height transition finishes.
126 if (panel.hasAttribute("data-starting-style")) {
127 const observer = new MutationObserver(() => {
128 if (!panel.hasAttribute("data-starting-style")) {
129 observer.disconnect();
130 waitForHeight();
131 }
132 });
133 observer.observe(panel, { attributes: true, attributeFilter: ["data-starting-style"] });
134 signal.addEventListener("abort", () => observer.disconnect(), { once: true });
135 } else {
136 waitForHeight();
137 }
138 target.addEventListener("blur", () => controller.abort(), { once: true, signal });
139 }
140 target.focus({ preventScroll: true });
141 target.classList.remove("settings-search-target-pulse");
142 if (!highlight || prefersReducedMotion) return;
143 void target.offsetWidth;
144 target.classList.add("settings-search-target-pulse");
145 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
146 once: true,
147 });
148}
149
150export function useSettingsSearchTargetId(): string | null {
151 return useContext(SettingsSearchTargetContext).targetId;
152}
153
154export function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
155 const { targetId, highlightTarget, onTargetHandled } = useContext(SettingsSearchTargetContext);
156 const isSearchTarget = id !== undefined && id === targetId;
157 const targetRef = (target: T | null) => {
158 if (target && isSearchTarget) {
159 scrollAndFocusSettingsTarget(target, highlightTarget);
160 onTargetHandled();
161 }
162 };
163
164 return targetRef;
165}
166
167export function SettingsSearchTarget({
168 children,
169 ...targetProps
170}: ComponentPropsWithoutRef<"div">) {
171 const targetRef = useSettingsSearchTarget<HTMLDivElement>(targetProps.id);
172 return (
173 <div {...targetProps} ref={targetRef} tabIndex={targetProps.id ? -1 : targetProps.tabIndex}>
174 {children}
175 </div>
176 );
177}
178
179// Settings pickers reuse composer controls but match the bordered selects beside them.
180export const SETTINGS_PICKER_TRIGGER_CLASSNAME =
181 "min-w-0 max-w-none shrink-0 border-input bg-background font-normal text-foreground shadow-xs/5 hover:bg-accent/50 dark:bg-input/32 [&_svg[data-composer-control-chevron]]:stroke-[1.75] [&_svg[data-composer-control-chevron]]:opacity-70";
182
183export function PolicyTooltip({ children }: { readonly children: string }) {
184 return (
185 <Tooltip>
186 <TooltipTrigger
187 delay={200}
188 render={
189 <Button size="icon-micro" variant="ghost-muted" aria-label="Background policy details">
190 <InfoIcon className="size-3.5" />
191 </Button>
192 }
193 />
194 <TooltipPopup side="top">{children}</TooltipPopup>
195 </Tooltip>
196 );
197}
198
199export function SettingsSection({
200 title,
201 hideTitle = false,
202 icon,
203 titleAction,
204 headerAction,
205 variant = "grouped",
206 children,
207 className,
208 ...sectionProps
209}: ComponentPropsWithoutRef<"section"> & {
210 title: string;
211 hideTitle?: boolean;
212 icon?: ReactNode;
213 titleAction?: ReactNode;
214 headerAction?: ReactNode;
215 variant?: "grouped" | "plain";
216 children: ReactNode;
217}) {
218 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
219
220 return (
221 <section
222 {...sectionProps}
223 ref={targetRef}
224 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
225 className={cn(!hideTitle && "space-y-2.5", className)}
226 >
227 {hideTitle ? (
228 <h2 className="sr-only">{title}</h2>
229 ) : (
230 <div
231 data-settings-scroll-target
232 className="flex min-h-7 items-start justify-between gap-4 px-3 sm:px-4"
233 >
234 <div className="flex min-w-0 items-center gap-1">
235 <h2 className="flex min-h-7 items-center gap-2 text-base font-semibold text-foreground">
236 {icon}
237 {title}
238 </h2>
239 {titleAction}
240 </div>
241 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
242 </div>
243 )}
244 <SettingsGroup data-settings-scroll-target={hideTitle ? "" : undefined} variant={variant}>
245 {children}
246 </SettingsGroup>
247 </section>
248 );
249}
250
251export function SettingsUnavailableGroup({
252 children,
253 message,
254}: {
255 children: ReactNode;
256 message?: ReactNode;
257}) {
258 if (message === undefined) return children;
259
260 return (
261 <div className="border-border/60 bg-muted/20 py-1.5">
262 <div className="flex items-start gap-2 px-3 py-2 text-xs leading-relaxed text-muted-foreground sm:px-4">
263 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
264 <p>{message}</p>
265 </div>
266 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
267 </div>
268 );
269}
270
271function projectOverrides(
272 context: ReturnType<typeof useOptionalSettingsScope>,
273 scopedKeys: ReadonlyArray<keyof ServerSettings>,
274): SettingOverridingProject[] {
275 if (context === null || scopedKeys.length === 0) return [];
276 return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
277 const group = context.groups.find((candidate) =>
278 candidate.memberProjects.some(
279 (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
280 ),
281 );
282 if (!group) return [];
283 return [
284 {
285 ...entry,
286 label: group.displayName,
287 open: () =>
288 context.selectScope({
289 project: group.projectKey,
290 ...(context.search.machine ? { machine: context.search.machine } : {}),
291 }),
292 },
293 ];
294 });
295}
296
297export function SettingsRow({
298 title,
299 description,
300 status,
301 resetAction,
302 onResetOverride,
303 control,
304 serverScoped = false,
305 settingKeys = EMPTY_SETTING_KEYS,
306 mixed: mixedOverride,
307 children,
308 className,
309 ...rowProps
310}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
311 title: ReactNode;
312 description?: ReactNode;
313 status?: ReactNode;
314 resetAction?: ReactNode;
315 onResetOverride?: () => void;
316 control?: ReactNode;
317 serverScoped?: boolean;
318 settingKeys?: readonly (keyof ServerSettings)[];
319 mixed?: boolean;
320 children?: ReactNode;
321}) {
322 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
323 const primarySettingsAvailable = usePrimarySettingsAvailable();
324 const context = useOptionalSettingsScope();
325 const primaryEnvironmentId = usePrimaryEnvironmentId();
326 const primaryEnvironment = usePrimaryEnvironment();
327 const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);
328 const writableIds = useEnvironmentsWithScope(
329 context?.connectedEnvironments ?? [],
330 AuthSettingsWriteScope,
331 );
332 const canWriteSettings = context
333 ? context.connectedEnvironments.length > 0 &&
334 context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
335 : primaryCanWrite;
336 const clearOverrides = useClearScopedSettings();
337 const clearProjectOverrides = useClearProjectOverrides();
338 const isProjectScope =
339 context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
340 const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
341 const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
342 const mixed =
343 mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
344 const source =
345 context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
346 const unavailable =
347 serverScoped &&
348 (!canWriteSettings ||
349 !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable));
350 const inheritedFrom =
351 source === "environment" && context?.scope.environmentIds.length === 1
352 ? (context.environments.find(
353 (environment) => environment.environmentId === context.scope.environmentIds[0],
354 )?.label ?? "environment")
355 : "environment";
356 const environmentSettingsById = new Map(
357 (context?.connectedEnvironments ?? []).flatMap((environment) =>
358 environment.serverConfig
359 ? [[environment.environmentId, environment.serverConfig.settings] as const]
360 : [],
361 ),
362 );
363 const overridingProjects = isProjectScope ? [] : projectOverrides(context, scopedKeys);
364 const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? (
365 source === "project" || source === "mixed" ? (
366 <SettingResetButton
367 label={typeof title === "string" ? title : "override"}
368 tooltip="Reset to inherited value"
369 onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
370 />
371 ) : null
372 ) : (
373 resetAction
374 );
375 const inertControl = (message: string) => (
376 <Tooltip>
377 <TooltipTrigger
378 render={
379 <span
380 tabIndex={0}
381 className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring @min-[32rem]/settings-row:w-auto"
382 />
383 }
384 >
385 <div
386 inert
387 className="flex w-full items-center gap-2 opacity-50 @min-[32rem]/settings-row:w-auto"
388 >
389 {control}
390 </div>
391 </TooltipTrigger>
392 <TooltipPopup side="top">{message}</TooltipPopup>
393 </Tooltip>
394 );
395 const renderedControl =
396 unavailable && control
397 ? inertControl(
398 !canWriteSettings
399 ? `This connection lacks permission to change settings on ${
400 context
401 ? context.connectedEnvironments
402 .filter((target) => !writableIds.has(target.environmentId))
403 .map((target) => target.label)
404 .join(", ") || "the selected environment"
405 : (primaryEnvironment?.label ?? "the primary environment")
406 }.`
407 : context
408 ? "Reconnect the selected environment to change this setting."
409 : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
410 )
411 : environmentWide && control
412 ? inertControl("Environment-wide setting. Select an environment to change it.")
413 : control;
414 const customized =
415 context !== null &&
416 settingKeys.some((key) =>
417 context.targets.some((candidate) => {
418 const environmentSettings = environmentSettingsById.get(candidate.environmentId);
419 return (
420 environmentSettings !== undefined &&
421 !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
422 );
423 }),
424 );
425 const inheritance: { state: SettingInheritanceState; summary: string } = mixed
426 ? { state: "mixed", summary: "Mixed across selected environments" }
427 : source === "project"
428 ? { state: "overridden", summary: "Overridden for this project" }
429 : source === "t3.json"
430 ? { state: "inherited", summary: "Inherited from the repository's t3.json" }
431 : source === "environment" && scopedKeys.length > 0
432 ? { state: "inherited", summary: `Inherited from ${inheritedFrom}` }
433 : customized
434 ? { state: "environment", summary: "Set on the environment" }
435 : { state: "default", summary: "Built-in default" };
436 const renderedInheritance =
437 context && serverScoped && settingKeys.length > 0 ? (
438 <SettingInheritance
439 state={inheritance.state}
440 summary={inheritance.summary}
441 targets={context.targets}
442 environments={context.connectedEnvironments}
443 keys={settingKeys}
444 overridingProjects={overridingProjects}
445 {...(canWriteSettings
446 ? {
447 onClearOverrides: (entries: readonly ProjectOverrideEntry[]) =>
448 clearProjectOverrides(entries, scopedKeys),
449 }
450 : {})}
451 />
452 ) : null;
453 const renderedStatus = status;
454
455 return (
456 <div
457 {...rowProps}
458 ref={targetRef}
459 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
460 data-slot="settings-row"
461 className={cn(
462 "group/settings-row @container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-64 aria-disabled:[&_*]:text-muted-foreground",
463 children ? "pt-3 pb-1" : "py-3",
464 className,
465 )}
466 >
467 <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">
468 <div className="min-w-0 flex-1 space-y-1">
469 <div className="flex min-h-5 items-center gap-1.5">
470 <h3 className="text-sm font-medium text-foreground">{title}</h3>
471 {renderedInheritance ? (
472 <span
473 className={cn(
474 "inline-flex h-5 w-5 shrink-0 items-center justify-center",
475 // Values set right here explain nothing new, so their marker waits for hover or focus.
476 (inheritance.state === "default" || inheritance.state === "environment") &&
477 overridingProjects.length === 0 &&
478 "opacity-0 group-hover/settings-row:opacity-100 has-focus-visible:opacity-100 has-data-popup-open:opacity-100",
479 )}
480 >
481 {renderedInheritance}
482 </span>
483 ) : null}
484 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
485 {renderedReset}
486 </span>
487 </div>
488 {description ? (
489 <p className="max-w-2xl text-balance text-xs leading-normal text-muted-foreground">
490 {description}
491 </p>
492 ) : null}
493 {renderedStatus ? (
494 <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
495 ) : null}
496 </div>
497 {renderedControl ? (
498 <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">
499 {renderedControl}
500 </div>
501 ) : null}
502 </div>
503 {unavailable && children ? (
504 <div inert className="opacity-50">
505 {children}
506 </div>
507 ) : (
508 children
509 )}
510 </div>
511 );
512}
513
514export function SettingResetButton({
515 label,
516 tooltip = "Reset to default",
517 disabled = false,
518 onClick,
519}: {
520 label: string;
521 tooltip?: string;
522 disabled?: boolean;
523 onClick: () => void;
524}) {
525 return (
526 <Tooltip>
527 <TooltipTrigger
528 render={
529 <Button
530 size="icon-micro"
531 variant="ghost-muted"
532 aria-label={`Reset ${label} to default`}
533 disabled={disabled}
534 onClick={(event) => {
535 event.stopPropagation();
536 onClick();
537 }}
538 >
539 <Undo2Icon className="size-3" />
540 </Button>
541 }
542 />
543 <TooltipPopup side="top">{tooltip}</TooltipPopup>
544 </Tooltip>
545 );
546}
547
548export function SettingsPageContainer({
549 children,
550 className,
551 width = "readable",
552}: {
553 children: ReactNode;
554 className?: string;
555 width?: WorkspacePageWidth;
556}) {
557 const navigate = useNavigate();
558 const hash = useLocation({ select: (location) => location.hash });
559 const highlightTarget = useLocation({
560 select: (location) => location.state.settingsTargetHighlight !== false,
561 });
562 const targetId = hash.replace(/^#/, "") || null;
563 const clearTargetHash = () => {
564 void navigate({
565 hash: "",
566 replace: true,
567 resetScroll: false,
568 hashScrollIntoView: false,
569 state: { settingsTargetHighlight: true },
570 });
571 };
572
573 return (
574 <SettingsSearchTargetProvider
575 targetId={targetId}
576 highlightTarget={highlightTarget}
577 onTargetHandled={clearTargetHash}
578 >
579 <div
580 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
581 data-settings-page-scroll
582 >
583 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
584 <SettingsScopeSentence />
585 {children}
586 </WorkspacePageContainer>
587 </div>
588 </SettingsSearchTargetProvider>
589 );
590}
591
592export function scrollToSettingsTarget(
593 targetId: string,
594 { highlight = true }: { readonly highlight?: boolean } = {},
595): boolean {
596 const target = document.getElementById(targetId);
597 if (!target) return false;
598 scrollAndFocusSettingsTarget(target, highlight);
599 return true;
600}