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

SettingsSidebarNav.tsx

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