Open History to see the last commit
1import {
2 lazy,
3 Suspense,
4 useEffect,
5 useRef,
6 useState,
7 type ComponentType,
8 type KeyboardEvent,
9} from "react";
10import {
11 ArchiveIcon,
12 FlaskConicalIcon,
13 BotIcon,
14 createLucideIcon,
15 CalendarClockIcon,
16 FileDiffIcon,
17 FolderTreeIcon,
18 GitBranchIcon,
19 GlobeIcon,
20 InfoIcon,
21 MessageSquareTextIcon,
22 MessagesSquareIcon,
23 PanelsTopLeftIcon,
24 KeyboardIcon,
25 KeyRoundIcon,
26 PaletteIcon,
27 SearchIcon,
28 ServerIcon,
29 Settings2Icon,
30 ShieldCheckIcon,
31 SmartphoneIcon,
32 WrenchIcon,
33 XIcon,
34} from "lucide-react";
35import { useLocation, useNavigate } from "@tanstack/react-router";
36
37import { cn } from "../../lib/utils";
38import { Button } from "../ui/button";
39import { Kbd } from "../ui/kbd";
40import {
41 SidebarContent,
42 SidebarFooter,
43 SidebarGroup,
44 SidebarMenu,
45 SidebarMenuButton,
46 SidebarMenuItem,
47 SidebarInput,
48} from "../ui/sidebar";
49import { scrollToSettingsTarget } from "./settingsLayout";
50import {
51 searchSettings,
52 revealSettingsSearchTarget,
53 SETTINGS_NAV_GROUPS,
54 SETTINGS_SECTION_LABELS,
55 type SettingsPath,
56 type SettingsSearchItem,
57} from "./settingsSearch";
58import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";
59import { validateSettingsScopeSearch } from "./settingsScope";
60import { useSettingsSectionNavigation } from "./useSettingsSectionNavigation";
61import { workspaceAreaProps } from "../../lib/workspaceFocus";
62
63const SnapShotIcon = createLucideIcon("snap-shot", [
64 [
65 "path",
66 {
67 d: "M8 3H6a3 3 0 0 0-3 3v2M16 3h2a3 3 0 0 1 3 3v2M21 16v2a3 3 0 0 1-3 3h-2M8 21H6a3 3 0 0 1-3-3v-2",
68 key: "capture-frame",
69 },
70 ],
71 ["rect", { width: "10", height: "8", x: "7", y: "8", rx: "2", key: "window" }],
72 ["circle", { cx: "12", cy: "12", r: "1.5", key: "lens" }],
73]);
74
75const T3ConnectSidebarSignIn = lazy(() =>
76 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
77 default: module.T3ConnectSidebarSignIn,
78 })),
79);
80const T3ConnectSidebarAvatar = lazy(() =>
81 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
82 default: module.T3ConnectSidebarAvatar,
83 })),
84);
85
86const SETTINGS_SECTION_ICONS: Readonly<
87 Record<SettingsPath, ComponentType<{ className?: string }>>
88> = {
89 "/settings/general": Settings2Icon,
90 "/settings/diagnostics": WrenchIcon,
91 "/settings/appearance": PaletteIcon,
92 "/settings/chat": MessageSquareTextIcon,
93 "/settings/diffs": FileDiffIcon,
94 "/settings/projects": PanelsTopLeftIcon,
95 "/settings/keybindings": KeyboardIcon,
96 "/settings/snap-shot": SnapShotIcon,
97 "/settings/providers": BotIcon,
98 "/settings/threads": MessagesSquareIcon,
99 "/settings/browser": GlobeIcon,
100 "/settings/devices": SmartphoneIcon,
101 "/settings/scheduled-tasks": CalendarClockIcon,
102 "/settings/source-control": GitBranchIcon,
103 "/settings/worktrees": FolderTreeIcon,
104 "/settings/connections": ServerIcon,
105 "/settings/access": ShieldCheckIcon,
106 "/settings/secrets": KeyRoundIcon,
107 "/settings/maintenance": WrenchIcon,
108 "/settings/labs": FlaskConicalIcon,
109 "/settings/about": InfoIcon,
110 "/settings/archived": ArchiveIcon,
111};
112
113// Detail pages without a nav entry highlight the page that links to them.
114const SETTINGS_DETAIL_PAGE_PARENTS: Readonly<Record<string, SettingsPath>> = {
115 "/settings/diagnostics": "/settings/maintenance",
116 "/settings/open-source-licenses": "/settings/about",
117};
118
119// Attached only to the highlighted result, so it runs whenever the highlight lands on a row.
120function scrollResultIntoView(row: HTMLElement | null) {
121 row?.scrollIntoView({ block: "nearest" });
122}
123
124function SettingsSectionIcon({ to }: { to: SettingsPath }) {
125 const Icon = SETTINGS_SECTION_ICONS[to];
126 return <Icon className="size-4 shrink-0 text-(--sidebar-icon-color)" />;
127}
128
129export function SettingsSidebarNav({ pathname }: { pathname: string }) {
130 const navArea = workspaceAreaProps("settings-nav", 0, "Settings sections");
131 const navigate = useNavigate();
132 const currentHash = useLocation({ select: (location) => location.hash });
133 const currentSearch = useLocation({ select: (location) => location.search });
134 const scopeSearch = validateSettingsScopeSearch(currentSearch);
135 const activePath = SETTINGS_DETAIL_PAGE_PARENTS[pathname] ?? pathname;
136 const navPaths = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths);
137 const sectionNavigation = useSettingsSectionNavigation(
138 navPaths.find((to) => activePath === to || activePath.startsWith(`${to}/`)) ??
139 navPaths[0] ??
140 "",
141 );
142 const searchInputRef = useRef<HTMLInputElement>(null);
143 const [query, setQuery] = useState("");
144 // Below md the nav is an icon rail; searching expands it over the page.
145 const [compactSearchOpen, setCompactSearchOpen] = useState(false);
146 const [activeResultIndex, setActiveResultIndex] = useState(0);
147 const searchableItems = useAvailableSettingsSearchItems(scopeSearch);
148 const results = searchSettings(query, searchableItems);
149 const isSearching = query.trim().length > 0;
150 const hasResults = results.length > 0;
151 const maxResultIndex = Math.max(results.length - 1, 0);
152 // Persist the clamp so a shrink-then-recover of results keeps the clamped highlight.
153 if (activeResultIndex > maxResultIndex) {
154 setActiveResultIndex(maxResultIndex);
155 }
156
157 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener for the find and slash search shortcuts
158 useEffect(() => {
159 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
160 if (event.defaultPrevented || event.isComposing) return;
161 const isFindShortcut =
162 event.key.toLowerCase() === "f" &&
163 (event.metaKey || event.ctrlKey) &&
164 !event.altKey &&
165 !event.shiftKey;
166 const isSlashShortcut =
167 event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey;
168 if (!isFindShortcut && !isSlashShortcut) return;
169
170 const target = event.target;
171 if (
172 target instanceof HTMLElement &&
173 ((isSlashShortcut &&
174 (target.tagName === "INPUT" ||
175 target.tagName === "TEXTAREA" ||
176 target.isContentEditable)) ||
177 target.closest(
178 '[role="dialog"]:not([data-app-modal]), [aria-modal="true"]:not([data-app-modal]), [data-slot$="popup"]:not([data-app-modal]), [data-keybinding-capture]',
179 ) !== null)
180 ) {
181 return;
182 }
183
184 event.preventDefault();
185 setCompactSearchOpen(true);
186 searchInputRef.current?.focus();
187 searchInputRef.current?.select();
188 };
189 window.addEventListener("keydown", handleKeyDown);
190 return () => window.removeEventListener("keydown", handleKeyDown);
191 }, []);
192
193 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focuses the search input DOM node after the compact search opens
194 useEffect(() => {
195 if (compactSearchOpen) searchInputRef.current?.focus();
196 }, [compactSearchOpen]);
197
198 const handleSectionClick = (to: SettingsPath) => {
199 void navigate({
200 to,
201 hash: "",
202 replace: true,
203 hashScrollIntoView: false,
204 });
205 };
206
207 const clearSearch = () => {
208 setQuery("");
209 setActiveResultIndex(0);
210 };
211 const handleSearchResultClick = (item: SettingsSearchItem) => {
212 clearSearch();
213 setCompactSearchOpen(false);
214 const targetId = item.targetId ?? item.id;
215 revealSettingsSearchTarget(targetId);
216 if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
217 scrollToSettingsTarget(targetId);
218 return;
219 }
220 void navigate({
221 to: item.to,
222 hash: targetId,
223 replace: true,
224 hashScrollIntoView: false,
225 state: { settingsTargetHighlight: true },
226 });
227 };
228
229 const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
230 if (event.key === "Escape" && isSearching) {
231 event.preventDefault();
232 event.stopPropagation();
233 clearSearch();
234 return;
235 }
236 if (results.length === 0) return;
237 if (event.key === "ArrowDown") {
238 event.preventDefault();
239 setActiveResultIndex((activeResultIndex + 1) % results.length);
240 return;
241 }
242 if (event.key === "ArrowUp") {
243 event.preventDefault();
244 setActiveResultIndex((activeResultIndex - 1 + results.length) % results.length);
245 return;
246 }
247 if (event.key === "Enter") {
248 event.preventDefault();
249 const result = results[activeResultIndex];
250 if (result) handleSearchResultClick(result);
251 }
252 };
253
254 return (
255 <nav
256 {...navArea}
257 role="navigation"
258 className={cn(
259 "flex w-60 shrink-0 flex-col border-e bg-sidebar text-sidebar-foreground max-md:w-14",
260 compactSearchOpen &&
261 "max-md:absolute max-md:inset-y-0 max-md:start-0 max-md:z-10 max-md:w-full",
262 )}
263 >
264 <SidebarContent className="overflow-x-hidden">
265 <SidebarGroup>
266 <div className="flex flex-col gap-2">
267 <div
268 className={cn(
269 "flex h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
270 !compactSearchOpen && "max-md:hidden",
271 )}
272 >
273 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
274 <SidebarInput
275 ref={searchInputRef}
276 nativeInput
277 type="search"
278 value={query}
279 onChange={(event) => {
280 setQuery(event.currentTarget.value);
281 setActiveResultIndex(0);
282 }}
283 onKeyDown={handleSearchKeyDown}
284 onFocus={() => setCompactSearchOpen(true)}
285 onBlur={() => {
286 if (!isSearching) setCompactSearchOpen(false);
287 }}
288 placeholder="Search"
289 aria-label="Search settings"
290 role="combobox"
291 aria-autocomplete="list"
292 aria-expanded={isSearching && hasResults}
293 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
294 aria-activedescendant={
295 isSearching && results[activeResultIndex]
296 ? `settings-search-result-${results[activeResultIndex].id}`
297 : undefined
298 }
299 className="min-w-0 flex-1"
300 />
301 {isSearching ? (
302 <Button
303 type="button"
304 size="icon-micro"
305 variant="ghost-muted"
306 className="shrink-0"
307 aria-label="Clear settings search"
308 onClick={() => {
309 clearSearch();
310 searchInputRef.current?.focus();
311 }}
312 >
313 <XIcon className="size-3" />
314 </Button>
315 ) : (
316 <Kbd>/</Kbd>
317 )}
318 </div>
319 {isSearching && results.length === 0 ? (
320 <p
321 role="status"
322 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
323 >
324 No settings found
325 </p>
326 ) : null}
327 {isSearching ? (
328 <SidebarMenu
329 id={hasResults ? "settings-search-results" : undefined}
330 role={hasResults ? "listbox" : undefined}
331 aria-label={hasResults ? "Settings search results" : undefined}
332 >
333 {results.map((item, index) => (
334 <SidebarMenuItem
335 key={item.id}
336 role="presentation"
337 ref={index === activeResultIndex ? scrollResultIntoView : undefined}
338 >
339 <SidebarMenuButton
340 id={`settings-search-result-${item.id}`}
341 role="option"
342 aria-selected={index === activeResultIndex}
343 tabIndex={-1}
344 size="sm"
345 isActive={index === activeResultIndex}
346 className="h-auto min-h-10 items-start"
347 onMouseMove={() => setActiveResultIndex(index)}
348 onClick={() => handleSearchResultClick(item)}
349 >
350 <SettingsSectionIcon to={item.to} />
351 <span className="min-w-0 flex-1">
352 <span className="block truncate text-sm font-medium text-sidebar-foreground">
353 {item.title}
354 </span>
355 <span className="block truncate text-2xs text-sidebar-muted-foreground/75">
356 {SETTINGS_SECTION_LABELS[item.to]}
357 </span>
358 </span>
359 </SidebarMenuButton>
360 </SidebarMenuItem>
361 ))}
362 </SidebarMenu>
363 ) : (
364 <div className="flex flex-col gap-4">
365 {compactSearchOpen ? null : (
366 <SidebarMenu className="md:hidden">
367 <SidebarMenuItem>
368 <SidebarMenuButton
369 aria-label="Search settings"
370 onClick={() => setCompactSearchOpen(true)}
371 >
372 <SearchIcon />
373 </SidebarMenuButton>
374 </SidebarMenuItem>
375 </SidebarMenu>
376 )}
377 <div
378 {...sectionNavigation.containerProps}
379 role="tree"
380 aria-label="Settings sections"
381 className="flex flex-col gap-4"
382 >
383 {SETTINGS_NAV_GROUPS.map((group, index) => (
384 <div
385 key={group.heading ?? index}
386 role="group"
387 aria-label={group.heading ?? undefined}
388 className="flex flex-col gap-1 max-md:border-t max-md:border-sidebar-border max-md:pt-4 max-md:first:border-t-0 max-md:first:pt-0"
389 >
390 {group.heading ? (
391 // The group carries this label; a heading is not a valid tree child.
392 <h3
393 aria-hidden="true"
394 className={cn(
395 "px-2 text-xs font-medium text-sidebar-muted-foreground/80",
396 !compactSearchOpen && "max-md:hidden",
397 )}
398 >
399 {group.heading}
400 </h3>
401 ) : null}
402 <SidebarMenu role="presentation">
403 {group.paths.map((to) => {
404 const Icon = SETTINGS_SECTION_ICONS[to];
405 const isActive = activePath === to || activePath.startsWith(`${to}/`);
406 return (
407 <SidebarMenuItem key={to} role="presentation">
408 <SidebarMenuButton
409 data-settings-section={to}
410 role="treeitem"
411 tabIndex={sectionNavigation.tabIndexFor(to)}
412 aria-selected={isActive}
413 aria-current={isActive ? "page" : undefined}
414 isActive={isActive}
415 onClick={() => handleSectionClick(to)}
416 >
417 <Icon />
418 <span
419 className={cn("truncate", !compactSearchOpen && "max-md:sr-only")}
420 >
421 {SETTINGS_SECTION_LABELS[to]}
422 </span>
423 </SidebarMenuButton>
424 </SidebarMenuItem>
425 );
426 })}
427 </SidebarMenu>
428 </div>
429 ))}
430 </div>
431 </div>
432 )}
433 </div>
434 </SidebarGroup>
435 </SidebarContent>
436 <SidebarFooter className="max-md:hidden">
437 <Suspense fallback={null}>
438 <T3ConnectSidebarSignIn />
439 </Suspense>
440 <Suspense fallback={null}>
441 <T3ConnectSidebarAvatar />
442 </Suspense>
443 </SidebarFooter>
444 </nav>
445 );
446}