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