Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

settingsLayout.tsx

427 lines13.0 KB

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​
23declare module "@tanstack/react-router" {
24 interface HistoryState {
25 settingsTargetHighlight?: boolean;
26 }
28​
29interface SettingsSearchTargetContextValue {
30 readonly targetId: string | null;
31 readonly highlightTarget: boolean;
32 readonly onTargetHandled: () => void;
34​
35const noop = () => undefined;
36const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
37 targetId: null,
38 highlightTarget: true,
39 onTargetHandled: noop,
40});
41​
42export function SettingsSearchTargetProvider({
43 targetId,
44 highlightTarget = true,
45 onTargetHandled = noop,
46 children,
47}: {
48 targetId: string | null;
49 highlightTarget?: boolean;
50 onTargetHandled?: () => void;
51 children: ReactNode;
52}) {
53 const value = useMemo(
54 () => ({ targetId, highlightTarget, onTargetHandled }),
55 [highlightTarget, onTargetHandled, targetId],
56 );
57 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
59​
60function scrollAndFocusSettingsTarget(target: HTMLElement, highlight = true): void {
61 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
62 const markedScrollTarget =
63 typeof target.querySelector === "function"
64 ? target.querySelector<HTMLElement>(":scope > [data-settings-scroll-target]")
65 : null;
66 const scrollTarget =
67 markedScrollTarget ??
68 (target.tagName === "SECTION" && target.firstElementChild
69 ? (target.firstElementChild as HTMLElement)
70 : target);
71​
72 scrollTarget.scrollIntoView({
73 behavior: prefersReducedMotion ? "auto" : "smooth",
74 block: "center",
75 });
76 target.focus({ preventScroll: true });
77 target.classList.remove("settings-search-target-pulse");
78 if (!highlight || prefersReducedMotion) return;
79 void target.offsetWidth;
80 target.classList.add("settings-search-target-pulse");
81 // The class also suppresses the focus outline (the pulse is the destination
82 // indicator), so drop it once the element is no longer the destination.
83 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
84 once: true,
85 });
87​
88/** The row id a settings-search jump is currently trying to reach, if any. */
89export function useSettingsSearchTargetId(): string | null {
90 return useContext(SettingsSearchTargetContext).targetId;
92​
93export function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
94 const { targetId, highlightTarget, onTargetHandled } = useContext(SettingsSearchTargetContext);
95 const isSearchTarget = id !== undefined && id === targetId;
96 const targetRef = useCallback(
97 (target: T | null) => {
98 if (target && isSearchTarget) {
99 scrollAndFocusSettingsTarget(target, highlightTarget);
100 onTargetHandled();
101 }
102 },
103 [highlightTarget, isSearchTarget, onTargetHandled],
104 );
105​
106 return targetRef;
108​
109export function SettingsSearchTarget({
110 children,
111 ...targetProps
112}: ComponentPropsWithoutRef<"div">) {
113 const targetRef = useSettingsSearchTarget<HTMLDivElement>(targetProps.id);
114 return (
115 <div {...targetProps} ref={targetRef} tabIndex={targetProps.id ? -1 : targetProps.tabIndex}>
116 {children}
117 </div>
118 );
120​
121/**
122 * Trigger classes for the composer model/traits pickers when they sit in a
123 * settings row: match the `sm` control box (the composer pins them to 28px at
124 * every breakpoint) and drop the composer's max-width.
125 */
126export const SETTINGS_PICKER_TRIGGER_CLASSNAME =
127 "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";
128​
129/** Info affordance explaining how a setting interacts with the shared background policy. */
130export function PolicyTooltip({ children }: { readonly children: string }) {
131 return (
132 <Tooltip>
133 <TooltipTrigger
134 delay={200}
135 render={
136 <Button size="icon-micro" variant="ghost-muted" aria-label="Background policy details">
137 <InfoIcon className="size-3.5" />
138 </Button>
139 }
140 />
141 <TooltipPopup side="top" className="max-w-72">
142 {children}
143 </TooltipPopup>
144 </Tooltip>
145 );
147​
148/** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */
149export function useRelativeTimeTick(intervalMs = 1_000) {
150 const [nowMs, setNowMs] = useState(() => Date.now());
151 useEffect(() => {
152 const id = setInterval(() => setNowMs(Date.now()), intervalMs);
153 return () => clearInterval(id);
154 }, [intervalMs]);
155 return nowMs;
157​
158/** Muted section headings have no descriptions; explanatory copy belongs to individual settings. */
159export function SettingsSection({
160 title,
161 hideTitle = false,
162 icon,
163 headerAction,
164 variant = "grouped",
165 children,
166 className,
167 ...sectionProps
168}: ComponentPropsWithoutRef<"section"> & {
169 title: string;
170 hideTitle?: boolean;
171 icon?: ReactNode;
172 headerAction?: ReactNode;
173 variant?: "grouped" | "plain";
174 children: ReactNode;
175}) {
176 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
177​
178 return (
179 <section
180 {...sectionProps}
181 ref={targetRef}
182 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
183 className={cn(!hideTitle && "space-y-2.5", className)}
184 >
185 {hideTitle ? (
186 <h2 className="sr-only">{title}</h2>
187 ) : (
188 <div
189 data-settings-scroll-target
190 className="flex min-h-7 items-start justify-between gap-4 px-3 sm:px-4"
191 >
192 <div className="min-w-0">
193 <h2 className="flex min-h-7 items-center gap-2 text-sm font-normal tracking-[-0.005em] text-foreground/70">
194 {icon}
195 {title}
196 </h2>
197 </div>
198 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
199 </div>
200 )}
201 <div
202 data-settings-scroll-target={hideTitle ? "" : undefined}
203 className={cn(
204 "relative overflow-visible text-foreground",
205 variant === "grouped"
206 ? "rounded-xl border border-border/60 bg-card/40 shadow-xs/5 [&>*+*]:border-t [&>*+*]:border-border/50 [&>[data-slot=settings-row]]:rounded-none"
207 : "space-y-1",
208 )}
209 >
210 {children}
211 </div>
212 </section>
213 );
215​
216export function SettingsUnavailableGroup({
217 children,
218 message,
219}: {
220 children: ReactNode;
221 message?: ReactNode;
222}) {
223 if (message === undefined) return children;
224​
225 return (
226 <div className="border-border/60 bg-muted/20 py-1.5">
227 <div className="flex items-start gap-2 px-3 py-2 text-[12px] leading-relaxed text-muted-foreground sm:px-4">
228 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
229 <p>{message}</p>
230 </div>
231 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
232 </div>
233 );
235​
236/**
237 * One setting. `serverScoped` marks rows whose value lives in the primary
238 * environment's settings.json; where there is no primary (the hosted app)
239 * the control goes inert with a tooltip instead of showing an editable
240 * default that would never save.
241 *
242 * Keep descriptions short enough for one line where possible. Allow wrapping
243 * for clarity or narrow screens instead of truncating or forcing no-wrap.
244 *
245 * Control sizing across settings follows three tiers so rows share a baseline:
246 * - `control` slot: `size="sm"` (Button, Select, Input, NumberField) or `icon-sm`.
247 * - Section `headerAction`s and buttons inside list items, cards, toolbars: `xs` / `icon-xs`.
248 * - Inline affordances (reset arrows, info tooltips, table-cell buttons): `icon-micro`.
249 * Dialog footers keep the app-wide default button size.
250 */
251export function SettingsRow({
252 title,
253 description,
254 status,
255 resetAction,
256 control,
257 serverScoped = false,
258 children,
259 className,
260 ...rowProps
261}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
262 title: ReactNode;
263 description?: ReactNode;
264 status?: ReactNode;
265 resetAction?: ReactNode;
266 control?: ReactNode;
267 serverScoped?: boolean;
268 children?: ReactNode;
269}) {
270 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
271 const primarySettingsAvailable = usePrimarySettingsAvailable();
272 const unavailable = serverScoped && !primarySettingsAvailable;
273 const renderedReset = unavailable ? null : resetAction;
274 const renderedControl =
275 unavailable && control ? (
276 <Tooltip>
277 <TooltipTrigger
278 render={
279 // Focusable so keyboard users can still reach the explanation.
280 <span
281 tabIndex={0}
282 className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring sm:w-auto"
283 />
284 }
285 >
286 <div inert className="flex w-full items-center gap-2 opacity-50 sm:w-auto">
287 {control}
288 </div>
289 </TooltipTrigger>
290 <TooltipPopup side="top" className="max-w-72">
291 {PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE}
292 </TooltipPopup>
293 </Tooltip>
294 ) : (
295 control
296 );
297​
298 return (
299 <div
300 {...rowProps}
301 ref={targetRef}
302 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
303 data-slot="settings-row"
304 className={cn(
305 "rounded-xl px-3 sm:px-4 aria-disabled:opacity-50 aria-disabled:[&_*]:text-muted-foreground",
306 children ? "pt-3 pb-1" : "py-3",
307 className,
308 )}
309 >
310 <div className="flex flex-col gap-3 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(10rem,auto)] sm:items-center sm:gap-8">
311 <div className="min-w-0 flex-1 space-y-1">
312 <div className="flex min-h-5 items-center gap-1.5">
313 <h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">{title}</h3>
314 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
315 {renderedReset}
316 </span>
317 </div>
318 {description ? (
319 <p className="max-w-xl text-[13px] leading-[1.45] text-muted-foreground/80">
320 {description}
321 </p>
322 ) : null}
323 {status ? <div className="pt-0.5 text-xs text-muted-foreground">{status}</div> : null}
324 </div>
325 {renderedControl ? (
326 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
327 {renderedControl}
328 </div>
329 ) : null}
330 </div>
331 {unavailable && children ? (
332 <div inert className="opacity-50">
333 {children}
334 </div>
335 ) : (
336 children
337 )}
338 </div>
339 );
341​
342export function SettingResetButton({
343 label,
344 tooltip = "Reset to default",
345 disabled = false,
346 onClick,
347}: {
348 label: string;
349 tooltip?: string;
350 disabled?: boolean;
351 onClick: () => void;
352}) {
353 return (
354 <Tooltip>
355 <TooltipTrigger
356 render={
357 <Button
358 size="icon-micro"
359 variant="ghost-muted"
360 aria-label={`Reset ${label} to default`}
361 disabled={disabled}
362 onClick={(event) => {
363 event.stopPropagation();
364 onClick();
365 }}
366 >
367 <Undo2Icon className="size-3" />
368 </Button>
369 }
370 />
371 <TooltipPopup side="top">{tooltip}</TooltipPopup>
372 </Tooltip>
373 );
375​
376export function SettingsPageContainer({
377 children,
378 className,
379 width = "readable",
380}: {
381 children: ReactNode;
382 className?: string;
383 width?: WorkspacePageWidth;
384}) {
385 const navigate = useNavigate();
386 const hash = useLocation({ select: (location) => location.hash });
387 const highlightTarget = useLocation({
388 select: (location) => location.state.settingsTargetHighlight !== false,
389 });
390 const targetId = hash.replace(/^#/, "") || null;
391 const clearTargetHash = useCallback(() => {
392 void navigate({
393 hash: "",
394 replace: true,
395 resetScroll: false,
396 hashScrollIntoView: false,
397 state: { settingsTargetHighlight: true },
398 });
399 }, [navigate]);
400​
401 return (
402 <SettingsSearchTargetProvider
403 targetId={targetId}
404 highlightTarget={highlightTarget}
405 onTargetHandled={clearTargetHash}
406 >
407 <div
408 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
409 data-settings-page-scroll
410 >
411 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
412 {children}
413 </WorkspacePageContainer>
414 </div>
415 </SettingsSearchTargetProvider>
416 );
418​
419export function scrollToSettingsTarget(
420 targetId: string,
421 { highlight = true }: { readonly highlight?: boolean } = {},
422): boolean {
423 const target = document.getElementById(targetId);
424 if (!target) return false;
425 scrollAndFocusSettingsTarget(target, highlight);
426 return true;