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

SettingsSidebarNav.tsx

475 lines16.8 KB

1import {
2 lazy,
3 Suspense,
4 useCallback,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 type ComponentType,
10 type KeyboardEvent,
11 type ReactNode,
12} from "react";
13import {
14 ArchiveIcon,
15 BlocksIcon,
16 BotIcon,
17 GitBranchIcon,
18 PanelsTopLeftIcon,
19 KeyboardIcon,
20 Link2Icon,
21 PaletteIcon,
22 SearchIcon,
23 Settings2Icon,
24 XIcon,
25} from "lucide-react";
26import { useLocation, useNavigate, useRouterState } from "@tanstack/react-router";
27​
28import { Button } from "../ui/button";
29import { Collapsible, CollapsiblePanel } from "../ui/collapsible";
30import { Input } from "../ui/input";
31import { Kbd } from "../ui/kbd";
32import { cn } from "../../lib/utils";
33import {
34 SidebarContent,
35 SidebarFooter,
36 SidebarGroup,
37 SidebarMenu,
38 SidebarMenuButton,
39 SidebarMenuItem,
40 SidebarMenuSub,
41 SidebarMenuSubButton,
42 SidebarMenuSubItem,
43 useSidebar,
44} from "../ui/sidebar";
45import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";
46import { scrollToSettingsTarget } from "./settingsLayout";
47import {
48 getVisibleSettingsSectionIds,
49 observeSettingsSectionVisibility,
50 type SettingsSectionVisibilityState,
51} from "./settingsSectionVisibility";
52import {
53 searchSettings,
54 SETTINGS_SECTION_LABELS,
55 type SettingsPath,
56 type SettingsSearchItem,
57} from "./settingsSearch";
58import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";
59​
60const T3ConnectSidebarSignIn = lazy(() =>
61 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
62 default: module.T3ConnectSidebarSignIn,
63 })),
64);
65const T3ConnectSidebarAvatar = lazy(() =>
66 import("../clerk/T3ConnectSidebarSignIn").then((module) => ({
67 default: module.T3ConnectSidebarAvatar,
68 })),
69);
70​
71const SETTINGS_SECTION_ICONS: Readonly<
72 Record<SettingsPath, ComponentType<{ className?: string }>>
73> = {
74 "/settings/general": Settings2Icon,
75 "/settings/appearance": PaletteIcon,
76 "/settings/projects": PanelsTopLeftIcon,
77 "/settings/keybindings": KeyboardIcon,
78 "/settings/providers": BotIcon,
79 "/settings/integrations": BlocksIcon,
80 "/settings/source-control": GitBranchIcon,
81 "/settings/connections": Link2Icon,
82 "/settings/archived": ArchiveIcon,
83};
84​
85const SETTINGS_NAV_ITEMS: ReadonlyArray<{
86 label: string;
87 to: SettingsPath;
88 icon: ComponentType<{ className?: string }>;
89}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[]).map((to) => ({
90 to,
91 label: SETTINGS_SECTION_LABELS[to],
92 icon: SETTINGS_SECTION_ICONS[to],
93}));
94​
95const SETTINGS_PAGE_SECTIONS: Partial<
96 Readonly<Record<SettingsPath, ReadonlyArray<{ label: string; targetId: string }>>>
97> = {
98 "/settings/general": [
99 { label: "Organization", targetId: "organization" },
100 { label: "Behavior", targetId: "behavior" },
101 { label: "Projects & threads", targetId: "projects-and-threads" },
102 { label: "Confirmations", targetId: "confirmations" },
103 { label: "Text generation", targetId: "text-generation" },
104 { label: "About", targetId: "about" },
105 { label: "Legacy features", targetId: "legacy-features" },
106 ],
107 "/settings/appearance": [
108 { label: "Colors & themes", targetId: "appearance" },
109 { label: "Interface", targetId: "appearance-interface" },
110 { label: "Motion", targetId: "motion" },
111 { label: "Typography", targetId: "typography" },
112 ],
113 "/settings/source-control": [
114 { label: "Version control", targetId: "source-control" },
115 { label: "Text generation", targetId: "source-control-text-generation" },
116 ],
117 "/settings/connections": [
118 { label: "This environment", targetId: "connections-environment" },
119 { label: "Remote environments", targetId: "remote-environments" },
120 ],
121};
122​
123function SettingsSectionIcon({ to }: { to: SettingsPath }) {
124 const Icon = SETTINGS_SECTION_ICONS[to];
125 return <Icon className="mt-0.5 size-3.5 shrink-0 text-sidebar-muted-foreground/60" />;
127​
128function SettingsSubmenuCollapse({
129 open,
130 children,
131}: {
132 readonly open: boolean;
133 readonly children: ReactNode;
134}) {
135 return (
136 <Collapsible open={open}>
137 <CollapsiblePanel className="duration-150 ease-out motion-reduce:transition-none">
138 {children}
139 </CollapsiblePanel>
140 </Collapsible>
141 );
143​
144export function SettingsSidebarNav({ pathname }: { pathname: string }) {
145 const navigate = useNavigate();
146 const currentHash = useLocation({ select: (location) => location.hash });
147 const resolvedPathname = useRouterState({
148 select: (state) => state.resolvedLocation?.pathname,
149 });
150 const { isMobile, setOpenMobile, open, setOpen } = useSidebar();
151 const searchInputRef = useRef<HTMLInputElement>(null);
152 const [query, setQuery] = useState("");
153 const [activeResultIndex, setActiveResultIndex] = useState(0);
154 const [sectionVisibility, setSectionVisibility] = useState<SettingsSectionVisibilityState | null>(
155 null,
156 );
157 const searchableItems = useAvailableSettingsSearchItems();
158 const results = useMemo(() => searchSettings(query, searchableItems), [query, searchableItems]);
159 const isSearching = query.trim().length > 0;
160 const hasResults = results.length > 0;
161 const activeSettingsPath = SETTINGS_NAV_ITEMS.find(
162 (item) => pathname === item.to || pathname.startsWith(`${item.to}/`),
163 )?.to;
164 const observedVisibilityScope = useMemo(() => {
165 const path = SETTINGS_NAV_ITEMS.find(
166 (item) =>
167 resolvedPathname === item.to || resolvedPathname?.startsWith(`${item.to}/`) === true,
168 )?.to;
169 const pageSections = path ? SETTINGS_PAGE_SECTIONS[path] : undefined;
170 return path && pageSections ? { path, pageSections } : null;
171 }, [resolvedPathname]);
172 const visiblePageSectionIds = getVisibleSettingsSectionIds({
173 activePath: activeSettingsPath,
174 scope: observedVisibilityScope,
175 visibility: sectionVisibility,
176 });
177​
178 useEffect(() => {
179 if (!observedVisibilityScope) return;
180 const container = document.querySelector<HTMLElement>("[data-settings-page-layout]");
181 if (!container) return;
182​
183 return observeSettingsSectionVisibility({
184 container,
185 targetIds: observedVisibilityScope.pageSections.map((section) => section.targetId),
186 onChange(targetIds) {
187 setSectionVisibility({ scope: observedVisibilityScope, targetIds: new Set(targetIds) });
188 },
189 });
190 }, [observedVisibilityScope]);
191​
192 useEffect(() => {
193 setActiveResultIndex((index) => Math.min(index, Math.max(results.length - 1, 0)));
194 }, [results.length]);
195​
196 useEffect(() => {
197 const result = results[activeResultIndex];
198 if (!result) return;
199 document
200 .getElementById(`settings-search-result-${result.id}`)
201 ?.scrollIntoView({ block: "nearest" });
202 }, [activeResultIndex, results]);
203​
204 useEffect(() => {
205 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
206 if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
207​
208 const target = event.target;
209 if (
210 target instanceof HTMLElement &&
211 (target.tagName === "INPUT" ||
212 target.tagName === "TEXTAREA" ||
213 target.isContentEditable ||
214 // Keep focus inside open dialogs and popups instead of escaping
215 // their focus trap into the sidebar search.
216 target.closest('[role="dialog"], [aria-modal="true"], [data-slot$="popup"]') !== null)
217 ) {
218 return;
219 }
220​
221 event.preventDefault();
222 if (isMobile) {
223 setOpenMobile(true);
224 } else if (!open) {
225 setOpen(true);
226 }
227 requestAnimationFrame(() => {
228 searchInputRef.current?.focus();
229 searchInputRef.current?.select();
230 });
231 };
232 window.addEventListener("keydown", handleKeyDown);
233 return () => window.removeEventListener("keydown", handleKeyDown);
234 }, [isMobile, open, setOpen, setOpenMobile]);
235​
236 const handleSectionClick = useCallback(
237 (to: SettingsPath) => {
238 if (isMobile) {
239 setOpenMobile(false);
240 }
241 void navigate({
242 to,
243 hash: "",
244 replace: true,
245 hashScrollIntoView: false,
246 });
247 },
248 [isMobile, navigate, setOpenMobile],
249 );
250 const handlePageSectionClick = useCallback(
251 (to: SettingsPath, targetId: string) => {
252 if (isMobile) {
253 setOpenMobile(false);
254 }
255 if (pathname === to && scrollToSettingsTarget(targetId, { highlight: false })) {
256 return;
257 }
258 void navigate({
259 to,
260 hash: targetId,
261 replace: true,
262 hashScrollIntoView: false,
263 state: { settingsTargetHighlight: false },
264 });
265 },
266 [isMobile, navigate, pathname, setOpenMobile],
267 );
268 const clearSearch = useCallback(() => {
269 setQuery("");
270 setActiveResultIndex(0);
271 }, []);
272 const handleSearchResultClick = useCallback(
273 (item: SettingsSearchItem) => {
274 clearSearch();
275 if (isMobile) {
276 setOpenMobile(false);
277 }
278 const targetId = item.targetId ?? item.id;
279 if (
280 item.to !== "/settings/projects" &&
281 pathname === item.to &&
282 currentHash.replace(/^#/, "") === targetId
283 ) {
284 scrollToSettingsTarget(targetId);
285 return;
286 }
287 void navigate({
288 to: item.to,
289 search: (previous) =>
290 item.to === "/settings/projects" ? { ...previous, project: undefined } : previous,
291 hash: targetId,
292 replace: true,
293 hashScrollIntoView: false,
294 state: { settingsTargetHighlight: true },
295 });
296 },
297 [clearSearch, currentHash, isMobile, navigate, pathname, setOpenMobile],
298 );
299 const handleSearchKeyDown = useCallback(
300 (event: KeyboardEvent<HTMLInputElement>) => {
301 if (event.key === "Escape" && isSearching) {
302 event.preventDefault();
303 event.stopPropagation();
304 clearSearch();
305 return;
306 }
307 if (results.length === 0) return;
308 if (event.key === "ArrowDown") {
309 event.preventDefault();
310 setActiveResultIndex((index) => (index + 1) % results.length);
311 return;
312 }
313 if (event.key === "ArrowUp") {
314 event.preventDefault();
315 setActiveResultIndex((index) => (index - 1 + results.length) % results.length);
316 return;
317 }
318 if (event.key === "Enter") {
319 event.preventDefault();
320 const result = results[activeResultIndex];
321 if (result) handleSearchResultClick(result);
322 }
323 },
324 [activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],
325 );
326 return (
327 <>
328 <SidebarContent className="overflow-x-hidden">
329 <SidebarGroup className="gap-2 p-[var(--sidebar-content-inset)]">
330 <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">
331 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
332 <Input
333 ref={searchInputRef}
334 nativeInput
335 unstyled
336 type="search"
337 value={query}
338 onChange={(event) => {
339 setQuery(event.currentTarget.value);
340 setActiveResultIndex(0);
341 }}
342 onKeyDown={handleSearchKeyDown}
343 placeholder="Search"
344 aria-label="Search settings"
345 role="combobox"
346 aria-autocomplete="list"
347 aria-expanded={isSearching && hasResults}
348 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
349 aria-activedescendant={
350 isSearching && results[activeResultIndex]
351 ? `settings-search-result-${results[activeResultIndex].id}`
352 : undefined
353 }
354 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"
355 />
356 {isSearching ? (
357 <Button
358 type="button"
359 size="icon-micro"
360 variant="ghost"
361 className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
362 aria-label="Clear settings search"
363 onClick={() => {
364 clearSearch();
365 searchInputRef.current?.focus();
366 }}
367 >
368 <XIcon className="size-3" />
369 </Button>
370 ) : (
371 <Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">/</Kbd>
372 )}
373 </div>
374 {isSearching && results.length === 0 ? (
375 <p
376 role="status"
377 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
378 >
379 No settings found
380 </p>
381 ) : null}
382 {isSearching ? (
383 <SidebarMenu
384 className="ps-px"
385 id={hasResults ? "settings-search-results" : undefined}
386 role={hasResults ? "listbox" : undefined}
387 aria-label={hasResults ? "Settings search results" : undefined}
388 >
389 {results.map((item, index) => (
390 <SidebarMenuItem key={item.id} role="presentation">
391 <SidebarMenuButton
392 id={`settings-search-result-${item.id}`}
393 role="option"
394 aria-selected={index === activeResultIndex}
395 tabIndex={-1}
396 size="sm"
397 isActive={index === activeResultIndex}
398 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"
399 onMouseMove={() => setActiveResultIndex(index)}
400 onClick={() => handleSearchResultClick(item)}
401 >
402 <SettingsSectionIcon to={item.to} />
403 <span className="min-w-0 flex-1">
404 <span className="block truncate text-sm font-medium text-sidebar-foreground">
405 {item.title}
406 </span>
407 <span className="block truncate text-[11px] text-sidebar-muted-foreground/75">
408 {SETTINGS_SECTION_LABELS[item.to]}
409 </span>
410 </span>
411 </SidebarMenuButton>
412 </SidebarMenuItem>
413 ))}
414 </SidebarMenu>
415 ) : (
416 <SidebarMenu className="ps-px">
417 {SETTINGS_NAV_ITEMS.map((item) => {
418 const Icon = item.icon;
419 const pageSections = SETTINGS_PAGE_SECTIONS[item.to];
420 const isActive = activeSettingsPath === item.to;
421 return (
422 <SidebarMenuItem key={item.to}>
423 <SidebarMenuButton
424 isActive={isActive}
425 onClick={() => handleSectionClick(item.to)}
426 >
427 <Icon />
428 <span className="truncate">{item.label}</span>
429 </SidebarMenuButton>
430 {pageSections ? (
431 <SettingsSubmenuCollapse open={isActive}>
432 <SidebarMenuSub className="border-l-0">
433 {pageSections.map((section) => (
434 <SidebarMenuSubItem key={section.targetId}>
435 <SidebarMenuSubButton
436 render={<button type="button" />}
437 size="sm"
438 data-visible={visiblePageSectionIds.has(section.targetId)}
439 className={cn(
440 "w-full text-sidebar-muted-foreground/65",
441 visiblePageSectionIds.has(section.targetId) &&
442 "font-medium text-sidebar-foreground",
443 )}
444 onClick={() => handlePageSectionClick(item.to, section.targetId)}
445 >
446 <span className="ms-0.5">{section.label}</span>
447 </SidebarMenuSubButton>
448 </SidebarMenuSubItem>
449 ))}
450 </SidebarMenuSub>
451 </SettingsSubmenuCollapse>
452 ) : null}
453 </SidebarMenuItem>
454 );
455 })}
456 </SidebarMenu>
457 )}
458 </SidebarGroup>
459 </SidebarContent>
460 <SidebarFooter className="p-[var(--sidebar-content-inset)]">
461 <Suspense fallback={null}>
462 <T3ConnectSidebarSignIn />
463 </Suspense>
464 <div className="flex items-center gap-1">
465 <div className="min-w-0 flex-1">
466 <SidebarUtilityMenu />
467 </div>
468 <Suspense fallback={null}>
469 <T3ConnectSidebarAvatar />
470 </Suspense>
471 </div>
472 </SidebarFooter>
473 </>
474 );