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

SettingsSidebarNav.tsx

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