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