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

SettingsSidebarNav.tsx

381 lines12.9 KB

1import {
2 lazy,
3 Suspense,
4 useCallback,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 type ComponentType,
10 type KeyboardEvent,
11} from "react";
12import {
13 ArchiveIcon,
14 BlocksIcon,
15 BotIcon,
16 createLucideIcon,
17 CalendarClockIcon,
18 GitBranchIcon,
19 HardDriveIcon,
20 PanelsTopLeftIcon,
21 KeyboardIcon,
22 Link2Icon,
23 PaletteIcon,
24 SearchIcon,
25 Settings2Icon,
26 XIcon,
27} from "lucide-react";
28import { useLocation, useNavigate } from "@tanstack/react-router";
29​
30import { Button } from "../ui/button";
31import { Kbd } from "../ui/kbd";
32import {
33 SidebarContent,
34 SidebarFooter,
35 SidebarGroup,
36 SidebarMenu,
37 SidebarMenuButton,
38 SidebarMenuItem,
39 useSidebar,
40 SidebarInput,
41} from "../ui/sidebar";
42import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";
43import { scrollToSettingsTarget } from "./settingsLayout";
44import {
45 searchSettings,
46 isSettingsOverviewVisible,
47 SETTINGS_SECTION_LABELS,
48 type SettingsPath,
49 type SettingsSearchItem,
50} from "./settingsSearch";
51import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";
52import { validateSettingsScopeSearch } from "./settingsScope";
53​
54const SnapShotIcon = createLucideIcon("snap-shot", [
55 [
56 "path",
57 {
58 d: "M8 3H6a3 3 0 0 0-3 3v2M16 3h2a3 3 0 0 1 3 3v2M21 16v2a3 3 0 0 1-3 3h-2M8 21H6a3 3 0 0 1-3-3v-2",
59 key: "capture-frame",
60 },
61 ],
62 ["rect", { width: "10", height: "8", x: "7", y: "8", rx: "2", key: "window" }],
63 ["circle", { cx: "12", cy: "12", r: "1.5", key: "lens" }],
64]);
65​
66const T3ConnectSidebarSignIn = lazy(() =>
67 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
68 default: module.T3ConnectSidebarSignIn,
69 })),
70);
71const T3ConnectSidebarAvatar = lazy(() =>
72 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
73 default: module.T3ConnectSidebarAvatar,
74 })),
75);
76​
77const SETTINGS_SECTION_ICONS: Readonly<
78 Record<SettingsPath, ComponentType<{ className?: string }>>
79> = {
80 "/settings/general": Settings2Icon,
81 "/settings/diagnostics": Settings2Icon,
82 "/settings/appearance": PaletteIcon,
83 "/settings/projects": PanelsTopLeftIcon,
84 "/settings/keybindings": KeyboardIcon,
85 "/settings/snap-shot": SnapShotIcon,
86 "/settings/providers": BotIcon,
87 "/settings/integrations": BlocksIcon,
88 "/settings/scheduled-tasks": CalendarClockIcon,
89 "/settings/source-control": GitBranchIcon,
90 "/settings/storage": HardDriveIcon,
91 "/settings/connections": Link2Icon,
92 "/settings/archived": ArchiveIcon,
93};
94​
95const SETTINGS_NAV_ITEMS: ReadonlyArray<{
96 label: string;
97 to: SettingsPath;
98 icon: ComponentType<{ className?: string }>;
99}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[])
100 .filter((to) => to !== "/settings/diagnostics")
101 .map((to) => ({
102 to,
103 label: SETTINGS_SECTION_LABELS[to],
104 icon: SETTINGS_SECTION_ICONS[to],
105 }));
106​
107function SettingsSectionIcon({ to }: { to: SettingsPath }) {
108 const Icon = SETTINGS_SECTION_ICONS[to];
109 return <Icon className="mt-0.5 size-3.5 shrink-0 text-sidebar-muted-foreground/60" />;
111​
112export function SettingsSidebarNav({ pathname }: { pathname: string }) {
113 const navigate = useNavigate();
114 const currentHash = useLocation({ select: (location) => location.hash });
115 const currentSearch = useLocation({ select: (location) => location.search });
116 const scopeSearch = useMemo(() => validateSettingsScopeSearch(currentSearch), [currentSearch]);
117 const navItems = SETTINGS_NAV_ITEMS.filter(
118 (item) => item.to !== "/settings/projects" || isSettingsOverviewVisible(scopeSearch),
119 );
120 const { isMobile, setOpenMobile, open, setOpen } = useSidebar();
121 const searchInputRef = useRef<HTMLInputElement>(null);
122 const [query, setQuery] = useState("");
123 const [activeResultIndex, setActiveResultIndex] = useState(0);
124 const searchableItems = useAvailableSettingsSearchItems(scopeSearch);
125 const results = useMemo(() => searchSettings(query, searchableItems), [query, searchableItems]);
126 const isSearching = query.trim().length > 0;
127 const hasResults = results.length > 0;
128​
129 useEffect(() => {
130 setActiveResultIndex((index) => Math.min(index, Math.max(results.length - 1, 0)));
131 }, [results.length]);
132​
133 useEffect(() => {
134 const result = results[activeResultIndex];
135 if (!result) return;
136 document
137 .getElementById(`settings-search-result-${result.id}`)
138 ?.scrollIntoView({ block: "nearest" });
139 }, [activeResultIndex, results]);
140​
141 useEffect(() => {
142 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
143 if (event.defaultPrevented || event.isComposing) return;
144 const isFindShortcut =
145 event.key.toLowerCase() === "f" &&
146 (event.metaKey || event.ctrlKey) &&
147 !event.altKey &&
148 !event.shiftKey;
149 const isSlashShortcut =
150 event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey;
151 if (!isFindShortcut && !isSlashShortcut) return;
152​
153 const target = event.target;
154 if (
155 target instanceof HTMLElement &&
156 ((isSlashShortcut &&
157 (target.tagName === "INPUT" ||
158 target.tagName === "TEXTAREA" ||
159 target.isContentEditable)) ||
160 // Preserve dialog and popup focus traps, and let shortcut recorders
161 // capture the keypress without moving focus into the sidebar search.
162 target.closest(
163 '[role="dialog"], [aria-modal="true"], [data-slot$="popup"], [data-keybinding-capture]',
164 ) !== null)
165 ) {
166 return;
167 }
168​
169 event.preventDefault();
170 if (isMobile) {
171 setOpenMobile(true);
172 } else if (!open) {
173 setOpen(true);
174 }
175 requestAnimationFrame(() => {
176 searchInputRef.current?.focus();
177 searchInputRef.current?.select();
178 });
179 };
180 window.addEventListener("keydown", handleKeyDown);
181 return () => window.removeEventListener("keydown", handleKeyDown);
182 }, [isMobile, open, setOpen, setOpenMobile]);
183​
184 const handleSectionClick = useCallback(
185 (to: SettingsPath) => {
186 if (isMobile) {
187 setOpenMobile(false);
188 }
189 void navigate({
190 to,
191 hash: "",
192 replace: true,
193 hashScrollIntoView: false,
194 });
195 },
196 [isMobile, navigate, setOpenMobile],
197 );
198 const clearSearch = useCallback(() => {
199 setQuery("");
200 setActiveResultIndex(0);
201 }, []);
202 const handleSearchResultClick = useCallback(
203 (item: SettingsSearchItem) => {
204 clearSearch();
205 if (isMobile) {
206 setOpenMobile(false);
207 }
208 const targetId = item.targetId ?? item.id;
209 if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
210 scrollToSettingsTarget(targetId);
211 return;
212 }
213 void navigate({
214 to: item.to,
215 hash: targetId,
216 replace: true,
217 hashScrollIntoView: false,
218 state: { settingsTargetHighlight: true },
219 });
220 },
221 [clearSearch, currentHash, isMobile, navigate, pathname, setOpenMobile],
222 );
223 const handleSearchKeyDown = useCallback(
224 (event: KeyboardEvent<HTMLInputElement>) => {
225 if (event.key === "Escape" && isSearching) {
226 event.preventDefault();
227 event.stopPropagation();
228 clearSearch();
229 return;
230 }
231 if (results.length === 0) return;
232 if (event.key === "ArrowDown") {
233 event.preventDefault();
234 setActiveResultIndex((index) => (index + 1) % results.length);
235 return;
236 }
237 if (event.key === "ArrowUp") {
238 event.preventDefault();
239 setActiveResultIndex((index) => (index - 1 + results.length) % results.length);
240 return;
241 }
242 if (event.key === "Enter") {
243 event.preventDefault();
244 const result = results[activeResultIndex];
245 if (result) handleSearchResultClick(result);
246 }
247 },
248 [activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],
249 );
250 return (
251 <>
252 <SidebarContent className="overflow-x-hidden">
253 <SidebarGroup>
254 <div className="flex flex-col gap-2">
255 <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">
256 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
257 <SidebarInput
258 ref={searchInputRef}
259 nativeInput
260 type="search"
261 value={query}
262 onChange={(event) => {
263 setQuery(event.currentTarget.value);
264 setActiveResultIndex(0);
265 }}
266 onKeyDown={handleSearchKeyDown}
267 placeholder="Search"
268 aria-label="Search settings"
269 role="combobox"
270 aria-autocomplete="list"
271 aria-expanded={isSearching && hasResults}
272 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
273 aria-activedescendant={
274 isSearching && results[activeResultIndex]
275 ? `settings-search-result-${results[activeResultIndex].id}`
276 : undefined
277 }
278 className="min-w-0 flex-1"
279 />
280 {isSearching ? (
281 <Button
282 type="button"
283 size="icon-micro"
284 variant="ghost-muted"
285 className="shrink-0"
286 aria-label="Clear settings search"
287 onClick={() => {
288 clearSearch();
289 searchInputRef.current?.focus();
290 }}
291 >
292 <XIcon className="size-3" />
293 </Button>
294 ) : (
295 <Kbd>/</Kbd>
296 )}
297 </div>
298 {isSearching && results.length === 0 ? (
299 <p
300 role="status"
301 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
302 >
303 No settings found
304 </p>
305 ) : null}
306 {isSearching ? (
307 <SidebarMenu
308 id={hasResults ? "settings-search-results" : undefined}
309 role={hasResults ? "listbox" : undefined}
310 aria-label={hasResults ? "Settings search results" : undefined}
311 >
312 {results.map((item, index) => (
313 <SidebarMenuItem key={item.id} role="presentation">
314 <SidebarMenuButton
315 id={`settings-search-result-${item.id}`}
316 role="option"
317 aria-selected={index === activeResultIndex}
318 tabIndex={-1}
319 size="sm"
320 isActive={index === activeResultIndex}
321 className="h-auto min-h-10 items-start"
322 onMouseMove={() => setActiveResultIndex(index)}
323 onClick={() => handleSearchResultClick(item)}
324 >
325 <SettingsSectionIcon to={item.to} />
326 <span className="min-w-0 flex-1">
327 <span className="block truncate text-sm font-medium text-sidebar-foreground">
328 {item.title}
329 </span>
330 <span className="block truncate text-2xs text-sidebar-muted-foreground/75">
331 {SETTINGS_SECTION_LABELS[item.to]}
332 </span>
333 </span>
334 </SidebarMenuButton>
335 </SidebarMenuItem>
336 ))}
337 </SidebarMenu>
338 ) : (
339 <SidebarMenu>
340 {navItems.map((item) => {
341 const Icon = item.icon;
342 const isGeneralDetailPage =
343 item.to === "/settings/general" &&
344 pathname === "/settings/open-source-licenses";
345 const isActive =
346 isGeneralDetailPage ||
347 pathname === item.to ||
348 pathname.startsWith(`${item.to}/`);
349 return (
350 <SidebarMenuItem key={item.to}>
351 <SidebarMenuButton
352 isActive={isActive}
353 onClick={() => handleSectionClick(item.to)}
354 >
355 <Icon />
356 <span className="truncate">{item.label}</span>
357 </SidebarMenuButton>
358 </SidebarMenuItem>
359 );
360 })}
361 </SidebarMenu>
362 )}
363 </div>
364 </SidebarGroup>
365 </SidebarContent>
366 <SidebarFooter>
367 <Suspense fallback={null}>
368 <T3ConnectSidebarSignIn />
369 </Suspense>
370 <div className="flex items-center gap-1">
371 <div className="min-w-0 flex-1">
372 <SidebarUtilityMenu />
373 </div>
374 <Suspense fallback={null}>
375 <T3ConnectSidebarAvatar />
376 </Suspense>
377 </div>
378 </SidebarFooter>
379 </>
380 );