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

settingsLayout.tsx

268 lines8.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 { cn } from "../../lib/utils";
15import { Button } from "../ui/button";
16import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
17​
18interface SettingsSearchTargetContextValue {
19 readonly targetId: string | null;
20 readonly onTargetHandled: () => void;
22​
23const noop = () => undefined;
24const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
25 targetId: null,
26 onTargetHandled: noop,
27});
28​
29export function SettingsSearchTargetProvider({
30 targetId,
31 onTargetHandled = noop,
32 children,
33}: {
34 targetId: string | null;
35 onTargetHandled?: () => void;
36 children: ReactNode;
37}) {
38 const value = useMemo(() => ({ targetId, onTargetHandled }), [onTargetHandled, targetId]);
39 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
41​
42function scrollAndFocusSettingsTarget(target: HTMLElement): void {
43 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
44 const scrollTarget =
45 target.tagName === "SECTION" && target.firstElementChild
46 ? (target.firstElementChild as HTMLElement)
47 : target;
48​
49 scrollTarget.scrollIntoView({
50 behavior: prefersReducedMotion ? "auto" : "smooth",
51 block: "center",
52 });
53 target.focus({ preventScroll: true });
54 target.classList.remove("settings-search-target-pulse");
55 if (prefersReducedMotion) return;
56 void target.offsetWidth;
57 target.classList.add("settings-search-target-pulse");
58 // The class also suppresses the focus outline (the pulse is the destination
59 // indicator), so drop it once the element is no longer the destination.
60 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
61 once: true,
62 });
64​
65/** The row id a settings-search jump is currently trying to reach, if any. */
66export function useSettingsSearchTargetId(): string | null {
67 return useContext(SettingsSearchTargetContext).targetId;
69​
70function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
71 const { targetId, onTargetHandled } = useContext(SettingsSearchTargetContext);
72 const isSearchTarget = id !== undefined && id === targetId;
73 const targetRef = useCallback(
74 (target: T | null) => {
75 if (target && isSearchTarget) {
76 scrollAndFocusSettingsTarget(target);
77 onTargetHandled();
78 }
79 },
80 [isSearchTarget, onTargetHandled],
81 );
82​
83 return targetRef;
85​
86/** Info affordance explaining how a setting interacts with the shared background policy. */
87export function PolicyTooltip({ children }: { readonly children: string }) {
88 return (
89 <Tooltip>
90 <TooltipTrigger
91 delay={200}
92 render={
93 <button
94 type="button"
95 className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground"
96 aria-label="Background policy details"
97 >
98 <InfoIcon className="size-3.5" />
99 </button>
100 }
101 />
102 <TooltipPopup side="top" className="max-w-72">
103 {children}
104 </TooltipPopup>
105 </Tooltip>
106 );
108​
109/** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */
110export function useRelativeTimeTick(intervalMs = 1_000) {
111 const [nowMs, setNowMs] = useState(() => Date.now());
112 useEffect(() => {
113 const id = setInterval(() => setNowMs(Date.now()), intervalMs);
114 return () => clearInterval(id);
115 }, [intervalMs]);
116 return nowMs;
118​
119export function SettingsSection({
120 title,
121 icon,
122 headerAction,
123 children,
124 className,
125 ...sectionProps
126}: ComponentPropsWithoutRef<"section"> & {
127 title: string;
128 icon?: ReactNode;
129 headerAction?: ReactNode;
130 children: ReactNode;
131}) {
132 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
133​
134 return (
135 <section
136 {...sectionProps}
137 ref={targetRef}
138 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
139 className={cn("space-y-3", className)}
140 >
141 <div className="flex min-h-8 items-center justify-between gap-4 px-3 sm:px-4">
142 <h2 className="flex items-center gap-2 text-lg font-semibold tracking-[-0.025em] text-foreground">
143 {icon}
144 {title}
145 </h2>
146 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
147 </div>
148 <div className="relative space-y-1 overflow-visible text-foreground">{children}</div>
149 </section>
150 );
152​
153export function SettingsRow({
154 title,
155 description,
156 status,
157 resetAction,
158 control,
159 children,
160 className,
161 ...rowProps
162}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
163 title: ReactNode;
164 description?: ReactNode;
165 status?: ReactNode;
166 resetAction?: ReactNode;
167 control?: ReactNode;
168 children?: ReactNode;
169}) {
170 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
171​
172 return (
173 <div
174 {...rowProps}
175 ref={targetRef}
176 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
177 className={cn("rounded-xl px-3 sm:px-4", children ? "pt-3 pb-1" : "py-3", className)}
178 >
179 <div className="flex flex-col gap-3 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(10rem,auto)] sm:items-center sm:gap-8">
180 <div className="min-w-0 flex-1 space-y-1">
181 <div className="flex min-h-5 items-center gap-1.5">
182 <h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">{title}</h3>
183 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
184 {resetAction}
185 </span>
186 </div>
187 {description ? (
188 <p className="max-w-xl text-[13px] leading-[1.45] text-muted-foreground/80">
189 {description}
190 </p>
191 ) : null}
192 {status ? <div className="pt-0.5 text-xs text-muted-foreground">{status}</div> : null}
193 </div>
194 {control ? (
195 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
196 {control}
197 </div>
198 ) : null}
199 </div>
200 {children}
201 </div>
202 );
204​
205export function SettingResetButton({
206 label,
207 disabled = false,
208 onClick,
209}: {
210 label: string;
211 disabled?: boolean;
212 onClick: () => void;
213}) {
214 return (
215 <Tooltip>
216 <TooltipTrigger
217 render={
218 <Button
219 size="icon-xs"
220 variant="ghost"
221 aria-label={`Reset ${label} to default`}
222 disabled={disabled}
223 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
224 onClick={(event) => {
225 event.stopPropagation();
226 onClick();
227 }}
228 >
229 <Undo2Icon className="size-3" />
230 </Button>
231 }
232 />
233 <TooltipPopup side="top">Reset to default</TooltipPopup>
234 </Tooltip>
235 );
237​
238export function SettingsPageContainer({
239 children,
240 className,
241}: {
242 children: ReactNode;
243 className?: string;
244}) {
245 const navigate = useNavigate();
246 const hash = useLocation({ select: (location) => location.hash });
247 const targetId = hash.replace(/^#/, "") || null;
248 const clearTargetHash = useCallback(() => {
249 void navigate({ hash: "", replace: true, resetScroll: false, hashScrollIntoView: false });
250 }, [navigate]);
251​
252 return (
253 <SettingsSearchTargetProvider targetId={targetId} onTargetHandled={clearTargetHash}>
254 <div className="settings-page-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto px-4 pt-10 pb-7 sm:px-8 sm:pt-12 sm:pb-10">
255 <div className={cn("mx-auto flex w-full max-w-4xl flex-col gap-12", className)}>
256 {children}
257 </div>
258 </div>
259 </SettingsSearchTargetProvider>
260 );
262​
263export function scrollToSettingsTarget(targetId: string): boolean {
264 const target = document.getElementById(targetId);
265 if (!target) return false;
266 scrollAndFocusSettingsTarget(target);
267 return true;