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

SettingsSidebarNav.tsx

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