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