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

SettingsSidebarNav.tsx

458 lines16.8 KB

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