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

SettingsSidebarNav.tsx

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