Open History to see the last commit
1import { InfoIcon, Undo2Icon } from "lucide-react";
2import { useLocation, useNavigate } from "@tanstack/react-router";
3import {
4 createContext,
5 type ComponentPropsWithoutRef,
6 type ReactNode,
7 useCallback,
8 useContext,
9 useEffect,
10 useMemo,
11 useState,
12} from "react";
13
14import {
15 PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
16 usePrimarySettingsAvailable,
17} from "../../hooks/useSettings";
18import { cn } from "../../lib/utils";
19import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
20import { Button } from "../ui/button";
21import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
22
23interface SettingsSearchTargetContextValue {
24 readonly targetId: string | null;
25 readonly onTargetHandled: () => void;
26}
27
28const noop = () => undefined;
29const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
30 targetId: null,
31 onTargetHandled: noop,
32});
33
34export function SettingsSearchTargetProvider({
35 targetId,
36 onTargetHandled = noop,
37 children,
38}: {
39 targetId: string | null;
40 onTargetHandled?: () => void;
41 children: ReactNode;
42}) {
43 const value = useMemo(() => ({ targetId, onTargetHandled }), [onTargetHandled, targetId]);
44 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
45}
46
47function scrollAndFocusSettingsTarget(target: HTMLElement): void {
48 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
49 const scrollTarget =
50 target.tagName === "SECTION" && target.firstElementChild
51 ? (target.firstElementChild as HTMLElement)
52 : target;
53
54 scrollTarget.scrollIntoView({
55 behavior: prefersReducedMotion ? "auto" : "smooth",
56 block: "center",
57 });
58 target.focus({ preventScroll: true });
59 target.classList.remove("settings-search-target-pulse");
60 if (prefersReducedMotion) return;
61 void target.offsetWidth;
62 target.classList.add("settings-search-target-pulse");
63 // The class also suppresses the focus outline (the pulse is the destination
64 // indicator), so drop it once the element is no longer the destination.
65 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
66 once: true,
67 });
68}
69
70/** The row id a settings-search jump is currently trying to reach, if any. */
71export function useSettingsSearchTargetId(): string | null {
72 return useContext(SettingsSearchTargetContext).targetId;
73}
74
75function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
76 const { targetId, onTargetHandled } = useContext(SettingsSearchTargetContext);
77 const isSearchTarget = id !== undefined && id === targetId;
78 const targetRef = useCallback(
79 (target: T | null) => {
80 if (target && isSearchTarget) {
81 scrollAndFocusSettingsTarget(target);
82 onTargetHandled();
83 }
84 },
85 [isSearchTarget, onTargetHandled],
86 );
87
88 return targetRef;
89}
90
91export function SettingsSearchTarget({
92 children,
93 ...targetProps
94}: ComponentPropsWithoutRef<"div">) {
95 const targetRef = useSettingsSearchTarget<HTMLDivElement>(targetProps.id);
96 return (
97 <div {...targetProps} ref={targetRef} tabIndex={targetProps.id ? -1 : targetProps.tabIndex}>
98 {children}
99 </div>
100 );
101}
102
103/**
104 * Trigger classes for the composer model/traits pickers when they sit in a
105 * settings row: match the `sm` control box (the composer pins them to 28px at
106 * every breakpoint) and drop the composer's max-width.
107 */
108export const SETTINGS_PICKER_TRIGGER_CLASSNAME =
109 "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";
110
111/** Info affordance explaining how a setting interacts with the shared background policy. */
112export function PolicyTooltip({ children }: { readonly children: string }) {
113 return (
114 <Tooltip>
115 <TooltipTrigger
116 delay={200}
117 render={
118 <Button size="icon-micro" variant="ghost-muted" aria-label="Background policy details">
119 <InfoIcon className="size-3.5" />
120 </Button>
121 }
122 />
123 <TooltipPopup side="top" className="max-w-72">
124 {children}
125 </TooltipPopup>
126 </Tooltip>
127 );
128}
129
130/** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */
131export function useRelativeTimeTick(intervalMs = 1_000) {
132 const [nowMs, setNowMs] = useState(() => Date.now());
133 useEffect(() => {
134 const id = setInterval(() => setNowMs(Date.now()), intervalMs);
135 return () => clearInterval(id);
136 }, [intervalMs]);
137 return nowMs;
138}
139
140export function SettingsSection({
141 title,
142 icon,
143 headerAction,
144 children,
145 className,
146 ...sectionProps
147}: ComponentPropsWithoutRef<"section"> & {
148 title: string;
149 icon?: ReactNode;
150 headerAction?: ReactNode;
151 children: ReactNode;
152}) {
153 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
154
155 return (
156 <section
157 {...sectionProps}
158 ref={targetRef}
159 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
160 className={cn("space-y-3", className)}
161 >
162 <div className="flex min-h-8 items-center justify-between gap-4 px-3 sm:px-4">
163 <h2 className="flex items-center gap-2 text-lg font-semibold tracking-[-0.025em] text-foreground">
164 {icon}
165 {title}
166 </h2>
167 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
168 </div>
169 <div className="relative space-y-1 overflow-visible text-foreground">{children}</div>
170 </section>
171 );
172}
173
174/**
175 * One setting. `serverScoped` marks rows whose value lives in the primary
176 * environment's settings.json; where there is no primary (the hosted app)
177 * the control goes inert with a tooltip instead of showing an editable
178 * default that would never save.
179 *
180 * Control sizing across settings follows three tiers so rows share a baseline:
181 * - `control` slot: `size="sm"` (Button, Select, Input, NumberField) or `icon-sm`.
182 * - Section `headerAction`s and buttons inside list items, cards, toolbars: `xs` / `icon-xs`.
183 * - Inline affordances (reset arrows, info tooltips, table-cell buttons): `icon-micro`.
184 * Dialog footers keep the app-wide default button size.
185 */
186export function SettingsRow({
187 title,
188 description,
189 status,
190 resetAction,
191 control,
192 serverScoped = false,
193 children,
194 className,
195 ...rowProps
196}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
197 title: ReactNode;
198 description?: ReactNode;
199 status?: ReactNode;
200 resetAction?: ReactNode;
201 control?: ReactNode;
202 serverScoped?: boolean;
203 children?: ReactNode;
204}) {
205 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
206 const primarySettingsAvailable = usePrimarySettingsAvailable();
207 const unavailable = serverScoped && !primarySettingsAvailable;
208 const renderedReset = unavailable ? null : resetAction;
209 const renderedControl =
210 unavailable && control ? (
211 <Tooltip>
212 <TooltipTrigger
213 render={
214 // Focusable so keyboard users can still reach the explanation.
215 <span
216 tabIndex={0}
217 className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring sm:w-auto"
218 />
219 }
220 >
221 <div inert className="flex w-full items-center gap-2 opacity-50 sm:w-auto">
222 {control}
223 </div>
224 </TooltipTrigger>
225 <TooltipPopup side="top" className="max-w-72">
226 {PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE}
227 </TooltipPopup>
228 </Tooltip>
229 ) : (
230 control
231 );
232
233 return (
234 <div
235 {...rowProps}
236 ref={targetRef}
237 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
238 className={cn("rounded-xl px-3 sm:px-4", children ? "pt-3 pb-1" : "py-3", className)}
239 >
240 <div className="flex flex-col gap-3 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(10rem,auto)] sm:items-center sm:gap-8">
241 <div className="min-w-0 flex-1 space-y-1">
242 <div className="flex min-h-5 items-center gap-1.5">
243 <h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">{title}</h3>
244 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
245 {renderedReset}
246 </span>
247 </div>
248 {description ? (
249 <p className="max-w-xl text-[13px] leading-[1.45] text-muted-foreground/80">
250 {description}
251 </p>
252 ) : null}
253 {status ? <div className="pt-0.5 text-xs text-muted-foreground">{status}</div> : null}
254 </div>
255 {renderedControl ? (
256 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
257 {renderedControl}
258 </div>
259 ) : null}
260 </div>
261 {unavailable && children ? (
262 <div inert className="opacity-50">
263 {children}
264 </div>
265 ) : (
266 children
267 )}
268 </div>
269 );
270}
271
272export function SettingResetButton({
273 label,
274 disabled = false,
275 onClick,
276}: {
277 label: string;
278 disabled?: boolean;
279 onClick: () => void;
280}) {
281 return (
282 <Tooltip>
283 <TooltipTrigger
284 render={
285 <Button
286 size="icon-micro"
287 variant="ghost-muted"
288 aria-label={`Reset ${label} to default`}
289 disabled={disabled}
290 onClick={(event) => {
291 event.stopPropagation();
292 onClick();
293 }}
294 >
295 <Undo2Icon className="size-3" />
296 </Button>
297 }
298 />
299 <TooltipPopup side="top">Reset to default</TooltipPopup>
300 </Tooltip>
301 );
302}
303
304export function SettingsPageContainer({
305 children,
306 className,
307 width = "readable",
308}: {
309 children: ReactNode;
310 className?: string;
311 width?: WorkspacePageWidth;
312}) {
313 const navigate = useNavigate();
314 const hash = useLocation({ select: (location) => location.hash });
315 const targetId = hash.replace(/^#/, "") || null;
316 const clearTargetHash = useCallback(() => {
317 void navigate({ hash: "", replace: true, resetScroll: false, hashScrollIntoView: false });
318 }, [navigate]);
319
320 return (
321 <SettingsSearchTargetProvider targetId={targetId} onTargetHandled={clearTargetHash}>
322 <div
323 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
324 data-settings-page-scroll
325 >
326 <WorkspacePageContainer width={width} className={cn("gap-12", className)}>
327 {children}
328 </WorkspacePageContainer>
329 </div>
330 </SettingsSearchTargetProvider>
331 );
332}
333
334export function scrollToSettingsTarget(targetId: string): boolean {
335 const target = document.getElementById(targetId);
336 if (!target) return false;
337 scrollAndFocusSettingsTarget(target);
338 return true;
339}