Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsSidebarNav.tsx

316 lines11.3 KB

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