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

SettingsSidebarNav.tsx

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