Open History to see the last commit
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 CalendarClockIcon,
18 GitBranchIcon,
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/keybindings": KeyboardIcon,
77 "/settings/providers": BotIcon,
78 "/settings/integrations": BlocksIcon,
79 "/settings/scheduled-tasks": CalendarClockIcon,
80 "/settings/source-control": GitBranchIcon,
81 "/settings/connections": Link2Icon,
82 "/settings/archived": ArchiveIcon,
83};
84
85export const 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" />;
126}
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 );
142}
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 (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
280 scrollToSettingsTarget(targetId);
281 return;
282 }
283 void navigate({
284 to: item.to,
285 hash: targetId,
286 replace: true,
287 hashScrollIntoView: false,
288 state: { settingsTargetHighlight: true },
289 });
290 },
291 [clearSearch, currentHash, isMobile, navigate, pathname, setOpenMobile],
292 );
293 const handleSearchKeyDown = useCallback(
294 (event: KeyboardEvent<HTMLInputElement>) => {
295 if (event.key === "Escape" && isSearching) {
296 event.preventDefault();
297 event.stopPropagation();
298 clearSearch();
299 return;
300 }
301 if (results.length === 0) return;
302 if (event.key === "ArrowDown") {
303 event.preventDefault();
304 setActiveResultIndex((index) => (index + 1) % results.length);
305 return;
306 }
307 if (event.key === "ArrowUp") {
308 event.preventDefault();
309 setActiveResultIndex((index) => (index - 1 + results.length) % results.length);
310 return;
311 }
312 if (event.key === "Enter") {
313 event.preventDefault();
314 const result = results[activeResultIndex];
315 if (result) handleSearchResultClick(result);
316 }
317 },
318 [activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],
319 );
320 return (
321 <>
322 <SidebarContent className="overflow-x-hidden">
323 <SidebarGroup className="gap-2 p-[var(--sidebar-content-inset)]">
324 <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">
325 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
326 <Input
327 ref={searchInputRef}
328 nativeInput
329 unstyled
330 type="search"
331 value={query}
332 onChange={(event) => {
333 setQuery(event.currentTarget.value);
334 setActiveResultIndex(0);
335 }}
336 onKeyDown={handleSearchKeyDown}
337 placeholder="Search"
338 aria-label="Search settings"
339 role="combobox"
340 aria-autocomplete="list"
341 aria-expanded={isSearching && hasResults}
342 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
343 aria-activedescendant={
344 isSearching && results[activeResultIndex]
345 ? `settings-search-result-${results[activeResultIndex].id}`
346 : undefined
347 }
348 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"
349 />
350 {isSearching ? (
351 <Button
352 type="button"
353 size="icon-micro"
354 variant="ghost"
355 className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
356 aria-label="Clear settings search"
357 onClick={() => {
358 clearSearch();
359 searchInputRef.current?.focus();
360 }}
361 >
362 <XIcon className="size-3" />
363 </Button>
364 ) : (
365 <Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">/</Kbd>
366 )}
367 </div>
368 {isSearching && results.length === 0 ? (
369 <p
370 role="status"
371 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
372 >
373 No settings found
374 </p>
375 ) : null}
376 {isSearching ? (
377 <SidebarMenu
378 className="ps-px"
379 id={hasResults ? "settings-search-results" : undefined}
380 role={hasResults ? "listbox" : undefined}
381 aria-label={hasResults ? "Settings search results" : undefined}
382 >
383 {results.map((item, index) => (
384 <SidebarMenuItem key={item.id} role="presentation">
385 <SidebarMenuButton
386 id={`settings-search-result-${item.id}`}
387 role="option"
388 aria-selected={index === activeResultIndex}
389 tabIndex={-1}
390 size="sm"
391 isActive={index === activeResultIndex}
392 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"
393 onMouseMove={() => setActiveResultIndex(index)}
394 onClick={() => handleSearchResultClick(item)}
395 >
396 <SettingsSectionIcon to={item.to} />
397 <span className="min-w-0 flex-1">
398 <span className="block truncate text-sm font-medium text-sidebar-foreground">
399 {item.title}
400 </span>
401 <span className="block truncate text-[11px] text-sidebar-muted-foreground/75">
402 {SETTINGS_SECTION_LABELS[item.to]}
403 </span>
404 </span>
405 </SidebarMenuButton>
406 </SidebarMenuItem>
407 ))}
408 </SidebarMenu>
409 ) : (
410 <SidebarMenu className="ps-px">
411 {SETTINGS_NAV_ITEMS.map((item) => {
412 const Icon = item.icon;
413 const pageSections = SETTINGS_PAGE_SECTIONS[item.to];
414 const isActive = activeSettingsPath === item.to;
415 return (
416 <SidebarMenuItem key={item.to}>
417 <SidebarMenuButton
418 isActive={isActive}
419 onClick={() => handleSectionClick(item.to)}
420 >
421 <Icon />
422 <span className="truncate">{item.label}</span>
423 </SidebarMenuButton>
424 {pageSections ? (
425 <SettingsSubmenuCollapse open={isActive}>
426 <SidebarMenuSub className="border-l-0">
427 {pageSections.map((section) => (
428 <SidebarMenuSubItem key={section.targetId}>
429 <SidebarMenuSubButton
430 render={<button type="button" />}
431 size="sm"
432 data-visible={visiblePageSectionIds.has(section.targetId)}
433 className={cn(
434 "w-full text-sidebar-muted-foreground/65",
435 visiblePageSectionIds.has(section.targetId) &&
436 "font-medium text-sidebar-foreground",
437 )}
438 onClick={() => handlePageSectionClick(item.to, section.targetId)}
439 >
440 <span className="ms-0.5">{section.label}</span>
441 </SidebarMenuSubButton>
442 </SidebarMenuSubItem>
443 ))}
444 </SidebarMenuSub>
445 </SettingsSubmenuCollapse>
446 ) : null}
447 </SidebarMenuItem>
448 );
449 })}
450 </SidebarMenu>
451 )}
452 </SidebarGroup>
453 </SidebarContent>
454 <SidebarFooter className="p-[var(--sidebar-content-inset)]">
455 <Suspense fallback={null}>
456 <T3ConnectSidebarSignIn />
457 </Suspense>
458 <div className="flex items-center gap-1">
459 <div className="min-w-0 flex-1">
460 <SidebarUtilityMenu />
461 </div>
462 <Suspense fallback={null}>
463 <T3ConnectSidebarAvatar />
464 </Suspense>
465 </div>
466 </SidebarFooter>
467 </>
468 );
469}