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.nativeEvent.isComposing || event.keyCode === 229) return;
231 if (event.key === "Escape" && isSearching) {
232 event.preventDefault();
233 event.stopPropagation();
234 clearSearch();
235 return;
236 }
237 if (results.length === 0) return;
238 if (event.key === "ArrowDown") {
239 event.preventDefault();
240 setActiveResultIndex((activeResultIndex + 1) % results.length);
241 return;
242 }
243 if (event.key === "ArrowUp") {
244 event.preventDefault();
245 setActiveResultIndex((activeResultIndex - 1 + results.length) % results.length);
246 return;
247 }
248 if (event.key === "Enter") {
249 event.preventDefault();
250 const result = results[activeResultIndex];
251 if (result) handleSearchResultClick(result);
252 }
253 };
254
255 return (
256 <nav
257 {...navArea}
258 role="navigation"
259 className={cn(
260 "flex w-60 shrink-0 flex-col border-e bg-sidebar text-sidebar-foreground max-md:w-14",
261 compactSearchOpen &&
262 "max-md:absolute max-md:inset-y-0 max-md:start-0 max-md:z-10 max-md:w-full",
263 )}
264 >
265 <SidebarContent className="overflow-x-hidden">
266 <SidebarGroup>
267 <div className="flex flex-col gap-2">
268 <div
269 className={cn(
270 "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",
271 !compactSearchOpen && "max-md:hidden",
272 )}
273 >
274 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
275 {/* Native search inputs clear on Escape even during IME composition. */}
276 <SidebarInput
277 ref={searchInputRef}
278 nativeInput
279 type="text"
280 value={query}
281 onChange={(event) => {
282 setQuery(event.currentTarget.value);
283 setActiveResultIndex(0);
284 }}
285 onKeyDown={handleSearchKeyDown}
286 onFocus={() => setCompactSearchOpen(true)}
287 onBlur={() => {
288 if (!isSearching) setCompactSearchOpen(false);
289 }}
290 placeholder="Search"
291 aria-label="Search settings"
292 role="combobox"
293 aria-autocomplete="list"
294 aria-expanded={isSearching && hasResults}
295 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
296 aria-activedescendant={
297 isSearching && results[activeResultIndex]
298 ? `settings-search-result-${results[activeResultIndex].id}`
299 : undefined
300 }
301 className="min-w-0 flex-1"
302 />
303 {isSearching ? (
304 <Button
305 type="button"
306 size="icon-micro"
307 variant="ghost-muted"
308 className="shrink-0"
309 aria-label="Clear settings search"
310 onClick={() => {
311 clearSearch();
312 searchInputRef.current?.focus();
313 }}
314 >
315 <XIcon className="size-3" />
316 </Button>
317 ) : (
318 <Kbd>/</Kbd>
319 )}
320 </div>
321 {isSearching && results.length === 0 ? (
322 <p
323 role="status"
324 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
325 >
326 No settings found
327 </p>
328 ) : null}
329 {isSearching ? (
330 <SidebarMenu
331 id={hasResults ? "settings-search-results" : undefined}
332 role={hasResults ? "listbox" : undefined}
333 aria-label={hasResults ? "Settings search results" : undefined}
334 >
335 {results.map((item, index) => (
336 <SidebarMenuItem
337 key={item.id}
338 role="presentation"
339 ref={index === activeResultIndex ? scrollResultIntoView : undefined}
340 >
341 <SidebarMenuButton
342 id={`settings-search-result-${item.id}`}
343 role="option"
344 aria-selected={index === activeResultIndex}
345 tabIndex={-1}
346 size="sm"
347 isActive={index === activeResultIndex}
348 className="h-auto min-h-10 items-start"
349 onMouseMove={() => setActiveResultIndex(index)}
350 onClick={() => handleSearchResultClick(item)}
351 >
352 <SettingsSectionIcon to={item.to} />
353 <span className="min-w-0 flex-1">
354 <span className="block truncate text-sm font-medium text-sidebar-foreground">
355 {item.title}
356 </span>
357 <span className="block truncate text-2xs text-sidebar-muted-foreground/75">
358 {SETTINGS_SECTION_LABELS[item.to]}
359 </span>
360 </span>
361 </SidebarMenuButton>
362 </SidebarMenuItem>
363 ))}
364 </SidebarMenu>
365 ) : (
366 <div className="flex flex-col gap-4">
367 {compactSearchOpen ? null : (
368 <SidebarMenu className="md:hidden">
369 <SidebarMenuItem>
370 <SidebarMenuButton
371 aria-label="Search settings"
372 onClick={() => setCompactSearchOpen(true)}
373 >
374 <SearchIcon />
375 </SidebarMenuButton>
376 </SidebarMenuItem>
377 </SidebarMenu>
378 )}
379 <div
380 {...sectionNavigation.containerProps}
381 role="tree"
382 aria-label="Settings sections"
383 className="flex flex-col gap-4"
384 >
385 {SETTINGS_NAV_GROUPS.map((group, index) => (
386 <div
387 key={group.heading ?? index}
388 role="group"
389 aria-label={group.heading ?? undefined}
390 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"
391 >
392 {group.heading ? (
393 // The group carries this label; a heading is not a valid tree child.
394 <h3
395 aria-hidden="true"
396 className={cn(
397 "px-2 text-xs font-medium text-sidebar-muted-foreground/80",
398 !compactSearchOpen && "max-md:hidden",
399 )}
400 >
401 {group.heading}
402 </h3>
403 ) : null}
404 <SidebarMenu role="presentation">
405 {group.paths.map((to) => {
406 const Icon = SETTINGS_SECTION_ICONS[to];
407 const isActive = activePath === to || activePath.startsWith(`${to}/`);
408 return (
409 <SidebarMenuItem key={to} role="presentation">
410 <SidebarMenuButton
411 data-settings-section={to}
412 role="treeitem"
413 tabIndex={sectionNavigation.tabIndexFor(to)}
414 aria-selected={isActive}
415 aria-current={isActive ? "page" : undefined}
416 isActive={isActive}
417 onClick={() => handleSectionClick(to)}
418 >
419 <Icon />
420 <span
421 className={cn("truncate", !compactSearchOpen && "max-md:sr-only")}
422 >
423 {SETTINGS_SECTION_LABELS[to]}
424 </span>
425 </SidebarMenuButton>
426 </SidebarMenuItem>
427 );
428 })}
429 </SidebarMenu>
430 </div>
431 ))}
432 </div>
433 </div>
434 )}
435 </div>
436 </SidebarGroup>
437 </SidebarContent>
438 <SidebarFooter className="max-md:hidden">
439 <Suspense fallback={null}>
440 <T3ConnectSidebarSignIn />
441 </Suspense>
442 <Suspense fallback={null}>
443 <T3ConnectSidebarAvatar />
444 </Suspense>
445 </SidebarFooter>
446 </nav>
447 );
448}