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

SettingsSidebarNav.tsx

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