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

SettingsSidebarNav.tsx

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