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