import { SettingsGroup } from "./SettingsGroup"; import { AuthSettingsWriteScope } from "@t3tools/contracts"; import { usePrimaryEnvironmentId, usePrimaryEnvironment } from "../../state/environments"; import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session"; import { InfoIcon, Undo2Icon } from "lucide-react"; import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts"; import * as Equal from "effect/Equal"; import { useLocation, useNavigate } from "@tanstack/react-router"; import { createContext, type ComponentPropsWithoutRef, type ReactNode, useCallback, useContext, useEffect, useMemo, useState, } from "react"; import { PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE, usePrimarySettingsAvailable, } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer"; import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useOptionalSettingsScope } from "./SettingsScopeContext"; import { SettingsScopeSentence } from "./SettingsScopeSentence"; import { isProjectScopedSettingKey, listProjectOverrides, type ProjectOverrideEntry, scopedSettingsAreMixed, scopedSettingsSource, } from "./scopedSettings"; import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings"; import { SettingInheritance, type SettingInheritanceState, type SettingOverridingProject, } from "./SettingInheritance"; const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = []; declare module "@tanstack/react-router" { interface HistoryState { settingsTargetHighlight?: boolean; } } interface SettingsSearchTargetContextValue { readonly targetId: string | null; readonly highlightTarget: boolean; readonly onTargetHandled: () => void; } const noop = () => undefined; const SettingsSearchTargetContext = createContext({ targetId: null, highlightTarget: true, onTargetHandled: noop, }); function SettingsSearchTargetProvider({ targetId, highlightTarget = true, onTargetHandled = noop, children, }: { targetId: string | null; highlightTarget?: boolean; onTargetHandled?: () => void; children: ReactNode; }) { const value = useMemo( () => ({ targetId, highlightTarget, onTargetHandled }), [highlightTarget, onTargetHandled, targetId], ); return {children}; } function scrollAndFocusSettingsTarget(target: HTMLElement, highlight = true): void { const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; const markedScrollTarget = typeof target.querySelector === "function" ? target.querySelector(":scope > [data-settings-scroll-target]") : null; const scrollTarget = markedScrollTarget ?? (target.tagName === "SECTION" && target.firstElementChild ? (target.firstElementChild as HTMLElement) : target); scrollTarget.scrollIntoView({ behavior: prefersReducedMotion ? "auto" : "smooth", block: "center", }); target.focus({ preventScroll: true }); target.classList.remove("settings-search-target-pulse"); if (!highlight || prefersReducedMotion) return; void target.offsetWidth; target.classList.add("settings-search-target-pulse"); // The class also suppresses the focus outline (the pulse is the destination // indicator), so drop it once the element is no longer the destination. target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), { once: true, }); } /** The row id a settings-search jump is currently trying to reach, if any. */ export function useSettingsSearchTargetId(): string | null { return useContext(SettingsSearchTargetContext).targetId; } export function useSettingsSearchTarget(id: string | undefined) { const { targetId, highlightTarget, onTargetHandled } = useContext(SettingsSearchTargetContext); const isSearchTarget = id !== undefined && id === targetId; const targetRef = useCallback( (target: T | null) => { if (target && isSearchTarget) { scrollAndFocusSettingsTarget(target, highlightTarget); onTargetHandled(); } }, [highlightTarget, isSearchTarget, onTargetHandled], ); return targetRef; } export function SettingsSearchTarget({ children, ...targetProps }: ComponentPropsWithoutRef<"div">) { const targetRef = useSettingsSearchTarget(targetProps.id); return (
{children}
); } /** Layout for the composer model/traits pickers in a settings row: drop the composer's max-width. */ export const SETTINGS_PICKER_TRIGGER_CLASSNAME = "min-w-0 max-w-none shrink-0"; /** Info affordance explaining how a setting interacts with the shared background policy. */ export function PolicyTooltip({ children }: { readonly children: string }) { return ( } /> {children} ); } /** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */ export function useRelativeTimeTick(intervalMs = 1_000) { const [nowMs, setNowMs] = useState(() => Date.now()); useEffect(() => { const id = setInterval(() => setNowMs(Date.now()), intervalMs); return () => clearInterval(id); }, [intervalMs]); return nowMs; } /** Muted section headings have no descriptions; explanatory copy belongs to individual settings. */ export function SettingsSection({ title, hideTitle = false, icon, titleAction, headerAction, variant = "grouped", children, className, ...sectionProps }: ComponentPropsWithoutRef<"section"> & { title: string; hideTitle?: boolean; icon?: ReactNode; /** Small control shown right after the title, such as an add button. */ titleAction?: ReactNode; headerAction?: ReactNode; variant?: "grouped" | "plain"; children: ReactNode; }) { const targetRef = useSettingsSearchTarget(sectionProps.id); return (
{hideTitle ? (

{title}

) : (

{icon} {title}

{titleAction}
{headerAction}
)} {children}
); } export function SettingsUnavailableGroup({ children, message, }: { children: ReactNode; message?: ReactNode; }) { if (message === undefined) return children; return (

{message}

{children}
); } /** * One setting. `serverScoped` marks rows whose value lives in the primary * environment's settings.json; where there is no primary (the hosted app) * the control goes inert with a tooltip instead of showing an editable * default that would never save. * * Keep descriptions short enough for one line where possible. Allow wrapping * for clarity or narrow screens instead of truncating or forcing no-wrap. * * Control sizing across settings follows three tiers so rows share a baseline: * - `control` slot: `size="sm"` (Button, Select, Input, NumberField) or `icon-sm`. * - Section `headerAction`s and buttons inside list items, cards, toolbars: `xs` / `icon-xs`. * - Inline affordances (reset arrows, info tooltips, table-cell buttons): `icon-micro`. * Dialog footers keep the app-wide default button size. */ export function SettingsRow({ title, description, status, resetAction, onResetOverride, control, serverScoped = false, settingKeys = EMPTY_SETTING_KEYS, mixed: mixedOverride, children, className, ...rowProps }: Omit, "title"> & { title: ReactNode; description?: ReactNode; status?: ReactNode; resetAction?: ReactNode; /** Replaces the default override clear for rows with side effects beyond the settings key. */ onResetOverride?: () => void; control?: ReactNode; serverScoped?: boolean; settingKeys?: readonly (keyof ServerSettings)[]; mixed?: boolean; children?: ReactNode; }) { const targetRef = useSettingsSearchTarget(rowProps.id); const primarySettingsAvailable = usePrimarySettingsAvailable(); const context = useOptionalSettingsScope(); const primaryEnvironmentId = usePrimaryEnvironmentId(); const primaryEnvironment = usePrimaryEnvironment(); const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope); const writableIds = useEnvironmentsWithScope( context?.connectedEnvironments ?? [], AuthSettingsWriteScope, ); const canWriteSettings = context ? context.connectedEnvironments.length > 0 && context.connectedEnvironments.every((target) => writableIds.has(target.environmentId)) : primaryCanWrite; const clearOverrides = useClearScopedSettings(); const clearProjectOverrides = useClearProjectOverrides(); const isProjectScope = context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout"); const scopedKeys = settingKeys.filter(isProjectScopedSettingKey); // A project scope can only edit keys that support overrides; the rest stay // visible so the user sees the inherited value, but cannot change it here. const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0; const mixed = mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys)); const source = context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null; const unavailable = serverScoped && (!canWriteSettings || !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable)); const inheritedFrom = source === "environment" && context?.scope.environmentIds.length === 1 ? (context.environments.find( (environment) => environment.environmentId === context.scope.environmentIds[0], )?.label ?? "environment") : "environment"; const environmentSettingsById = useMemo( () => new Map( (context?.connectedEnvironments ?? []).flatMap((environment) => environment.serverConfig ? [[environment.environmentId, environment.serverConfig.settings] as const] : [], ), ), [context?.connectedEnvironments], ); // At environment scope, projects with their own value keep it when the // environment default changes; the chain names them and can reset them. const overridingProjects = useMemo((): SettingOverridingProject[] => { if (context === null || isProjectScope || scopedKeys.length === 0) return []; return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => { const group = context.groups.find((candidate) => candidate.memberProjects.some( (member) => member.environmentId === entry.environmentId && member.id === entry.projectId, ), ); if (!group) return []; return [ { ...entry, label: group.displayName, open: () => context.selectScope({ project: group.projectKey, ...(context.search.machine ? { machine: context.search.machine } : {}), }), }, ]; }); }, [context, isProjectScope, scopedKeys]); const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? ( source === "project" || source === "mixed" ? ( (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))} /> ) : null ) : ( resetAction ); const inertControl = (message: string) => ( } >
{control}
{message}
); // A mixed selection keeps the real control with "Mixed" as its placeholder // (the multi-selection inspector convention): the popover shows who has // what, and picking a value applies it to every target. const renderedControl = unavailable && control ? inertControl( !canWriteSettings ? `This connection lacks permission to change settings on ${ context ? context.connectedEnvironments .filter((target) => !writableIds.has(target.environmentId)) .map((target) => target.label) .join(", ") || "the selected environment" : (primaryEnvironment?.label ?? "the primary environment") }.` : context ? "Reconnect the selected environment to change this setting." : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE, ) : environmentWide && control ? inertControl("Environment-wide setting. Select an environment to change it.") : control; // Server rows get an indicator beside the title that opens the resolution // chain per target at every scope; client rows keep a plain status only. const customized = context !== null && settingKeys.some((key) => context.targets.some((candidate) => { const environmentSettings = environmentSettingsById.get(candidate.environmentId); return ( environmentSettings !== undefined && !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key]) ); }), ); const inheritance: { state: SettingInheritanceState; summary: string } = mixed ? { state: "mixed", summary: "Mixed across selected environments" } : source === "project" ? { state: "overridden", summary: "Overridden for this project" } : source === "t3.json" ? { state: "inherited", summary: "Inherited from the repository's t3.json" } : source === "environment" && scopedKeys.length > 0 ? { state: "inherited", summary: `Inherited from ${inheritedFrom}` } : customized ? { state: "environment", summary: "Set on the environment" } : { state: "default", summary: "Built-in default" }; const renderedInheritance = context && serverScoped && settingKeys.length > 0 ? ( clearProjectOverrides(entries, scopedKeys), } : {})} /> ) : null; const renderedStatus = status; return (

{title}

{renderedInheritance ? ( {renderedInheritance} ) : null} {renderedReset}
{description ? (

{description}

) : null} {renderedStatus ? (
{renderedStatus}
) : null}
{renderedControl ? (
{renderedControl}
) : null}
{unavailable && children ? (
{children}
) : ( children )}
); } export function SettingResetButton({ label, tooltip = "Reset to default", disabled = false, onClick, }: { label: string; tooltip?: string; disabled?: boolean; onClick: () => void; }) { return ( { event.stopPropagation(); onClick(); }} > } /> {tooltip} ); } export function SettingsPageContainer({ children, className, width = "readable", }: { children: ReactNode; className?: string; width?: WorkspacePageWidth; }) { const navigate = useNavigate(); const hash = useLocation({ select: (location) => location.hash }); const highlightTarget = useLocation({ select: (location) => location.state.settingsTargetHighlight !== false, }); const targetId = hash.replace(/^#/, "") || null; const clearTargetHash = useCallback(() => { void navigate({ hash: "", replace: true, resetScroll: false, hashScrollIntoView: false, state: { settingsTargetHighlight: true }, }); }, [navigate]); return (
{children}
); } export function scrollToSettingsTarget( targetId: string, { highlight = true }: { readonly highlight?: boolean } = {}, ): boolean { const target = document.getElementById(targetId); if (!target) return false; scrollAndFocusSettingsTarget(target, highlight); return true; }