Open History to see the last commit
1import {
2 useCallback,
3 useEffect,
4 useMemo,
5 useRef,
6 useState,
7 type ComponentType,
8 type KeyboardEvent,
9} from "react";
10import {
11 ArchiveIcon,
12 BlocksIcon,
13 BotIcon,
14 GitBranchIcon,
15 KeyboardIcon,
16 Link2Icon,
17 PaletteIcon,
18 SearchIcon,
19 Settings2Icon,
20 XIcon,
21} from "lucide-react";
22import { useLocation, useNavigate } from "@tanstack/react-router";
23
24import { Button } from "../ui/button";
25import { Input } from "../ui/input";
26import { Kbd } from "../ui/kbd";
27import {
28 SidebarContent,
29 SidebarFooter,
30 SidebarGroup,
31 SidebarMenu,
32 SidebarMenuButton,
33 SidebarMenuItem,
34 useSidebar,
35} from "../ui/sidebar";
36import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
37import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";
38import { scrollToSettingsTarget } from "./settingsLayout";
39import {
40 searchSettings,
41 SETTINGS_SECTION_LABELS,
42 type SettingsPath,
43 type SettingsSearchItem,
44} from "./settingsSearch";
45
46const SETTINGS_SECTION_ICONS: Readonly<
47 Record<SettingsPath, ComponentType<{ className?: string }>>
48> = {
49 "/settings/general": Settings2Icon,
50 "/settings/appearance": PaletteIcon,
51 "/settings/keybindings": KeyboardIcon,
52 "/settings/providers": BotIcon,
53 "/settings/integrations": BlocksIcon,
54 "/settings/source-control": GitBranchIcon,
55 "/settings/connections": Link2Icon,
56 "/settings/archived": ArchiveIcon,
57};
58
59export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
60 label: string;
61 to: SettingsPath;
62 icon: ComponentType<{ className?: string }>;
63}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[]).map((to) => ({
64 to,
65 label: SETTINGS_SECTION_LABELS[to],
66 icon: SETTINGS_SECTION_ICONS[to],
67}));
68
69function SettingsSectionIcon({ to }: { to: SettingsPath }) {
70 const Icon = SETTINGS_SECTION_ICONS[to];
71 return <Icon className="mt-0.5 size-3.5 shrink-0 text-sidebar-muted-foreground/60" />;
72}
73
74export function SettingsSidebarNav({ pathname }: { pathname: string }) {
75 const navigate = useNavigate();
76 const currentHash = useLocation({ select: (location) => location.hash });
77 const { isMobile, setOpenMobile, open, setOpen } = useSidebar();
78 const searchInputRef = useRef<HTMLInputElement>(null);
79 const [query, setQuery] = useState("");
80 const [activeResultIndex, setActiveResultIndex] = useState(0);
81 const results = useMemo(() => searchSettings(query), [query]);
82 const isSearching = query.trim().length > 0;
83 const hasResults = results.length > 0;
84
85 useEffect(() => {
86 const result = results[activeResultIndex];
87 if (!result) return;
88 document
89 .getElementById(`settings-search-result-${result.id}`)
90 ?.scrollIntoView({ block: "nearest" });
91 }, [activeResultIndex, results]);
92
93 useEffect(() => {
94 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
95 if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
96
97 const target = event.target;
98 if (
99 target instanceof HTMLElement &&
100 (target.tagName === "INPUT" ||
101 target.tagName === "TEXTAREA" ||
102 target.isContentEditable ||
103 // Keep focus inside open dialogs and popups instead of escaping
104 // their focus trap into the sidebar search.
105 target.closest('[role="dialog"], [aria-modal="true"], [data-slot$="popup"]') !== null)
106 ) {
107 return;
108 }
109
110 event.preventDefault();
111 if (isMobile) {
112 setOpenMobile(true);
113 } else if (!open) {
114 setOpen(true);
115 }
116 requestAnimationFrame(() => {
117 searchInputRef.current?.focus();
118 searchInputRef.current?.select();
119 });
120 };
121 window.addEventListener("keydown", handleKeyDown);
122 return () => window.removeEventListener("keydown", handleKeyDown);
123 }, [isMobile, open, setOpen, setOpenMobile]);
124
125 const handleSectionClick = useCallback(
126 (to: SettingsPath) => {
127 if (isMobile) {
128 setOpenMobile(false);
129 }
130 void navigate({ to, hash: "", replace: true, hashScrollIntoView: false });
131 },
132 [isMobile, navigate, setOpenMobile],
133 );
134 const clearSearch = useCallback(() => {
135 setQuery("");
136 setActiveResultIndex(0);
137 }, []);
138 const handleSearchResultClick = useCallback(
139 (item: SettingsSearchItem) => {
140 clearSearch();
141 if (isMobile) {
142 setOpenMobile(false);
143 }
144 const targetId = item.targetId ?? item.id;
145 if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
146 scrollToSettingsTarget(targetId);
147 return;
148 }
149 void navigate({ to: item.to, hash: targetId, replace: true, hashScrollIntoView: false });
150 },
151 [clearSearch, currentHash, isMobile, navigate, pathname, setOpenMobile],
152 );
153 const handleSearchKeyDown = useCallback(
154 (event: KeyboardEvent<HTMLInputElement>) => {
155 if (event.key === "Escape" && isSearching) {
156 event.preventDefault();
157 event.stopPropagation();
158 clearSearch();
159 return;
160 }
161 if (results.length === 0) return;
162 if (event.key === "ArrowDown") {
163 event.preventDefault();
164 setActiveResultIndex((index) => (index + 1) % results.length);
165 return;
166 }
167 if (event.key === "ArrowUp") {
168 event.preventDefault();
169 setActiveResultIndex((index) => (index - 1 + results.length) % results.length);
170 return;
171 }
172 if (event.key === "Enter") {
173 event.preventDefault();
174 const result = results[activeResultIndex];
175 if (result) handleSearchResultClick(result);
176 }
177 },
178 [activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],
179 );
180 return (
181 <>
182 <SidebarContent className="overflow-x-hidden">
183 <SidebarGroup className="gap-2 p-[var(--sidebar-content-inset)]">
184 <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">
185 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
186 <Input
187 ref={searchInputRef}
188 nativeInput
189 unstyled
190 type="search"
191 value={query}
192 onChange={(event) => {
193 setQuery(event.currentTarget.value);
194 setActiveResultIndex(0);
195 }}
196 onKeyDown={handleSearchKeyDown}
197 placeholder="Search"
198 aria-label="Search settings"
199 role="combobox"
200 aria-autocomplete="list"
201 aria-expanded={isSearching && hasResults}
202 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
203 aria-activedescendant={
204 isSearching && results[activeResultIndex]
205 ? `settings-search-result-${results[activeResultIndex].id}`
206 : undefined
207 }
208 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"
209 />
210 {isSearching ? (
211 <Button
212 type="button"
213 size="icon-micro"
214 variant="ghost"
215 className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
216 aria-label="Clear settings search"
217 onClick={() => {
218 clearSearch();
219 searchInputRef.current?.focus();
220 }}
221 >
222 <XIcon className="size-3" />
223 </Button>
224 ) : (
225 <Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">/</Kbd>
226 )}
227 </div>
228 {isSearching && results.length === 0 ? (
229 <p
230 role="status"
231 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
232 >
233 No settings found
234 </p>
235 ) : null}
236 <SidebarMenu
237 className="ps-px"
238 id={isSearching && hasResults ? "settings-search-results" : undefined}
239 role={isSearching && hasResults ? "listbox" : undefined}
240 aria-label={isSearching && hasResults ? "Settings search results" : undefined}
241 >
242 {isSearching
243 ? results.map((item, index) => (
244 <SidebarMenuItem key={item.id} role="presentation">
245 <SidebarMenuButton
246 id={`settings-search-result-${item.id}`}
247 role="option"
248 aria-selected={index === activeResultIndex}
249 tabIndex={-1}
250 size="sm"
251 isActive={index === activeResultIndex}
252 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"
253 onMouseMove={() => setActiveResultIndex(index)}
254 onClick={() => handleSearchResultClick(item)}
255 >
256 <SettingsSectionIcon to={item.to} />
257 <span className="min-w-0 flex-1">
258 <span className="block truncate text-sm font-medium text-sidebar-foreground">
259 {item.title}
260 </span>
261 <span className="block truncate text-[11px] text-sidebar-muted-foreground/75">
262 {SETTINGS_SECTION_LABELS[item.to]}
263 </span>
264 </span>
265 </SidebarMenuButton>
266 </SidebarMenuItem>
267 ))
268 : SETTINGS_NAV_ITEMS.map((item) => {
269 const Icon = item.icon;
270 const isActive = pathname === item.to || pathname.startsWith(`${item.to}/`);
271 return (
272 <SidebarMenuItem key={item.to}>
273 <SidebarMenuButton
274 isActive={isActive}
275 onClick={() => handleSectionClick(item.to)}
276 >
277 <Icon />
278 <span className="truncate">{item.label}</span>
279 </SidebarMenuButton>
280 </SidebarMenuItem>
281 );
282 })}
283 </SidebarMenu>
284 </SidebarGroup>
285 </SidebarContent>
286 <SidebarFooter className="p-[var(--sidebar-content-inset)]">
287 <T3ConnectSidebarSignIn />
288 <div className="flex items-center gap-1">
289 <div className="min-w-0 flex-1">
290 <SidebarUtilityMenu />
291 </div>
292 <T3ConnectSidebarAvatar />
293 </div>
294 </SidebarFooter>
295 </>
296 );
297}