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

SettingsSidebarNav.tsx

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