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