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