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