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 BlocksIcon,
14 BotIcon,
15 createLucideIcon,
16 CalendarClockIcon,
17 GitBranchIcon,
18 HardDriveIcon,
19 PanelsTopLeftIcon,
20 KeyboardIcon,
21 Link2Icon,
22 PaletteIcon,
23 SearchIcon,
24 Settings2Icon,
25 XIcon,
26} from "lucide-react";
27import { useLocation, useNavigate } from "@tanstack/react-router";
28
29import { cn } from "../../lib/utils";
30import { Button } from "../ui/button";
31import { Kbd } from "../ui/kbd";
32import {
33 SidebarContent,
34 SidebarFooter,
35 SidebarGroup,
36 SidebarMenu,
37 SidebarMenuButton,
38 SidebarMenuItem,
39 SidebarInput,
40} from "../ui/sidebar";
41import { scrollToSettingsTarget } from "./settingsLayout";
42import {
43 searchSettings,
44 isSettingsOverviewVisible,
45 SETTINGS_SECTION_LABELS,
46 type SettingsPath,
47 type SettingsSearchItem,
48} from "./settingsSearch";
49import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";
50import { validateSettingsScopeSearch } from "./settingsScope";
51
52const SnapShotIcon = createLucideIcon("snap-shot", [
53 [
54 "path",
55 {
56 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",
57 key: "capture-frame",
58 },
59 ],
60 ["rect", { width: "10", height: "8", x: "7", y: "8", rx: "2", key: "window" }],
61 ["circle", { cx: "12", cy: "12", r: "1.5", key: "lens" }],
62]);
63
64const T3ConnectSidebarSignIn = lazy(() =>
65 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
66 default: module.T3ConnectSidebarSignIn,
67 })),
68);
69const T3ConnectSidebarAvatar = lazy(() =>
70 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
71 default: module.T3ConnectSidebarAvatar,
72 })),
73);
74
75const SETTINGS_SECTION_ICONS: Readonly<
76 Record<SettingsPath, ComponentType<{ className?: string }>>
77> = {
78 "/settings/general": Settings2Icon,
79 "/settings/diagnostics": Settings2Icon,
80 "/settings/appearance": PaletteIcon,
81 "/settings/projects": PanelsTopLeftIcon,
82 "/settings/keybindings": KeyboardIcon,
83 "/settings/snap-shot": SnapShotIcon,
84 "/settings/providers": BotIcon,
85 "/settings/integrations": BlocksIcon,
86 "/settings/scheduled-tasks": CalendarClockIcon,
87 "/settings/source-control": GitBranchIcon,
88 "/settings/storage": HardDriveIcon,
89 "/settings/connections": Link2Icon,
90 "/settings/beta": FlaskConicalIcon,
91 "/settings/archived": ArchiveIcon,
92};
93
94const SETTINGS_NAV_ITEMS: ReadonlyArray<{
95 label: string;
96 to: SettingsPath;
97 icon: ComponentType<{ className?: string }>;
98}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[])
99 .filter((to) => to !== "/settings/diagnostics")
100 .map((to) => ({
101 to,
102 label: SETTINGS_SECTION_LABELS[to],
103 icon: SETTINGS_SECTION_ICONS[to],
104 }));
105
106function SettingsSectionIcon({ to }: { to: SettingsPath }) {
107 const Icon = SETTINGS_SECTION_ICONS[to];
108 return <Icon className="size-4 shrink-0 text-(--sidebar-icon-color)" />;
109}
110
111export function SettingsSidebarNav({ pathname }: { pathname: string }) {
112 const navigate = useNavigate();
113 const currentHash = useLocation({ select: (location) => location.hash });
114 const currentSearch = useLocation({ select: (location) => location.search });
115 const scopeSearch = validateSettingsScopeSearch(currentSearch);
116 const navItems = SETTINGS_NAV_ITEMS.filter(
117 (item) => item.to !== "/settings/projects" || isSettingsOverviewVisible(scopeSearch),
118 );
119 const searchInputRef = useRef<HTMLInputElement>(null);
120 const [query, setQuery] = useState("");
121 // Below md the nav is an icon rail; searching expands it over the page.
122 const [compactSearchOpen, setCompactSearchOpen] = useState(false);
123 const [activeResultIndex, setActiveResultIndex] = useState(0);
124 const searchableItems = useAvailableSettingsSearchItems(scopeSearch);
125 const results = searchSettings(query, searchableItems);
126 const isSearching = query.trim().length > 0;
127 const hasResults = results.length > 0;
128 const maxResultIndex = Math.max(results.length - 1, 0);
129 // Persist the clamp so a shrink-then-recover of results keeps the clamped highlight.
130 if (activeResultIndex > maxResultIndex) {
131 setActiveResultIndex(maxResultIndex);
132 }
133
134 useEffect(() => {
135 const result = results[activeResultIndex];
136 if (!result) return;
137 document
138 .getElementById(`settings-search-result-${result.id}`)
139 ?.scrollIntoView({ block: "nearest" });
140 }, [activeResultIndex, results]);
141
142 useEffect(() => {
143 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
144 if (event.defaultPrevented || event.isComposing) return;
145 const isFindShortcut =
146 event.key.toLowerCase() === "f" &&
147 (event.metaKey || event.ctrlKey) &&
148 !event.altKey &&
149 !event.shiftKey;
150 const isSlashShortcut =
151 event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey;
152 if (!isFindShortcut && !isSlashShortcut) return;
153
154 const target = event.target;
155 if (
156 target instanceof HTMLElement &&
157 ((isSlashShortcut &&
158 (target.tagName === "INPUT" ||
159 target.tagName === "TEXTAREA" ||
160 target.isContentEditable)) ||
161 target.closest(
162 '[role="dialog"]:not([data-app-modal]), [aria-modal="true"]:not([data-app-modal]), [data-slot$="popup"]:not([data-app-modal]), [data-keybinding-capture]',
163 ) !== null)
164 ) {
165 return;
166 }
167
168 event.preventDefault();
169 setCompactSearchOpen(true);
170 searchInputRef.current?.focus();
171 searchInputRef.current?.select();
172 };
173 window.addEventListener("keydown", handleKeyDown);
174 return () => window.removeEventListener("keydown", handleKeyDown);
175 }, []);
176
177 useEffect(() => {
178 if (compactSearchOpen) searchInputRef.current?.focus();
179 }, [compactSearchOpen]);
180
181 const handleSectionClick = (to: SettingsPath) => {
182 void navigate({
183 to,
184 hash: "",
185 replace: true,
186 hashScrollIntoView: false,
187 });
188 };
189
190 const clearSearch = () => {
191 setQuery("");
192 setActiveResultIndex(0);
193 };
194 const handleSearchResultClick = (item: SettingsSearchItem) => {
195 clearSearch();
196 setCompactSearchOpen(false);
197 const targetId = item.targetId ?? item.id;
198 if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
199 scrollToSettingsTarget(targetId);
200 return;
201 }
202 void navigate({
203 to: item.to,
204 hash: targetId,
205 replace: true,
206 hashScrollIntoView: false,
207 state: { settingsTargetHighlight: true },
208 });
209 };
210
211 const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
212 if (event.key === "Escape" && isSearching) {
213 event.preventDefault();
214 event.stopPropagation();
215 clearSearch();
216 return;
217 }
218 if (results.length === 0) return;
219 if (event.key === "ArrowDown") {
220 event.preventDefault();
221 setActiveResultIndex((activeResultIndex + 1) % results.length);
222 return;
223 }
224 if (event.key === "ArrowUp") {
225 event.preventDefault();
226 setActiveResultIndex((activeResultIndex - 1 + results.length) % results.length);
227 return;
228 }
229 if (event.key === "Enter") {
230 event.preventDefault();
231 const result = results[activeResultIndex];
232 if (result) handleSearchResultClick(result);
233 }
234 };
235
236 return (
237 <nav
238 aria-label="Settings sections"
239 className={cn(
240 "flex w-60 shrink-0 flex-col border-e bg-sidebar text-sidebar-foreground max-md:w-14",
241 compactSearchOpen &&
242 "max-md:absolute max-md:inset-y-0 max-md:start-0 max-md:z-10 max-md:w-full",
243 )}
244 >
245 <SidebarContent className="overflow-x-hidden">
246 <SidebarGroup>
247 <div className="flex flex-col gap-2">
248 <div
249 className={cn(
250 "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",
251 !compactSearchOpen && "max-md:hidden",
252 )}
253 >
254 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
255 <SidebarInput
256 ref={searchInputRef}
257 nativeInput
258 type="search"
259 value={query}
260 onChange={(event) => {
261 setQuery(event.currentTarget.value);
262 setActiveResultIndex(0);
263 }}
264 onKeyDown={handleSearchKeyDown}
265 onFocus={() => setCompactSearchOpen(true)}
266 onBlur={() => {
267 if (!isSearching) setCompactSearchOpen(false);
268 }}
269 placeholder="Search"
270 aria-label="Search settings"
271 role="combobox"
272 aria-autocomplete="list"
273 aria-expanded={isSearching && hasResults}
274 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
275 aria-activedescendant={
276 isSearching && results[activeResultIndex]
277 ? `settings-search-result-${results[activeResultIndex].id}`
278 : undefined
279 }
280 className="min-w-0 flex-1"
281 />
282 {isSearching ? (
283 <Button
284 type="button"
285 size="icon-micro"
286 variant="ghost-muted"
287 className="shrink-0"
288 aria-label="Clear settings search"
289 onClick={() => {
290 clearSearch();
291 searchInputRef.current?.focus();
292 }}
293 >
294 <XIcon className="size-3" />
295 </Button>
296 ) : (
297 <Kbd>/</Kbd>
298 )}
299 </div>
300 {isSearching && results.length === 0 ? (
301 <p
302 role="status"
303 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
304 >
305 No settings found
306 </p>
307 ) : null}
308 {isSearching ? (
309 <SidebarMenu
310 id={hasResults ? "settings-search-results" : undefined}
311 role={hasResults ? "listbox" : undefined}
312 aria-label={hasResults ? "Settings search results" : undefined}
313 >
314 {results.map((item, index) => (
315 <SidebarMenuItem key={item.id} role="presentation">
316 <SidebarMenuButton
317 id={`settings-search-result-${item.id}`}
318 role="option"
319 aria-selected={index === activeResultIndex}
320 tabIndex={-1}
321 size="sm"
322 isActive={index === activeResultIndex}
323 className="h-auto min-h-10 items-start"
324 onMouseMove={() => setActiveResultIndex(index)}
325 onClick={() => handleSearchResultClick(item)}
326 >
327 <SettingsSectionIcon to={item.to} />
328 <span className="min-w-0 flex-1">
329 <span className="block truncate text-sm font-medium text-sidebar-foreground">
330 {item.title}
331 </span>
332 <span className="block truncate text-2xs text-sidebar-muted-foreground/75">
333 {SETTINGS_SECTION_LABELS[item.to]}
334 </span>
335 </span>
336 </SidebarMenuButton>
337 </SidebarMenuItem>
338 ))}
339 </SidebarMenu>
340 ) : (
341 <SidebarMenu>
342 {compactSearchOpen ? null : (
343 <SidebarMenuItem className="md:hidden">
344 <SidebarMenuButton
345 aria-label="Search settings"
346 onClick={() => setCompactSearchOpen(true)}
347 >
348 <SearchIcon />
349 </SidebarMenuButton>
350 </SidebarMenuItem>
351 )}
352 {navItems.map((item) => {
353 const Icon = item.icon;
354 const isGeneralDetailPage =
355 item.to === "/settings/general" &&
356 pathname === "/settings/open-source-licenses";
357 const isActive =
358 isGeneralDetailPage ||
359 pathname === item.to ||
360 pathname.startsWith(`${item.to}/`);
361 return (
362 <SidebarMenuItem key={item.to}>
363 <SidebarMenuButton
364 isActive={isActive}
365 onClick={() => handleSectionClick(item.to)}
366 >
367 <Icon />
368 <span className={cn("truncate", !compactSearchOpen && "max-md:sr-only")}>
369 {item.label}
370 </span>
371 </SidebarMenuButton>
372 </SidebarMenuItem>
373 );
374 })}
375 </SidebarMenu>
376 )}
377 </div>
378 </SidebarGroup>
379 </SidebarContent>
380 <SidebarFooter className="max-md:hidden">
381 <Suspense fallback={null}>
382 <T3ConnectSidebarSignIn />
383 </Suspense>
384 <Suspense fallback={null}>
385 <T3ConnectSidebarAvatar />
386 </Suspense>
387 </SidebarFooter>
388 </nav>
389 );
390}