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