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

SettingsSidebarNav.tsx

318 lines11.6 KB

1import {
2 useCallback,
3 useEffect,
4 useMemo,
5 useRef,
6 useState,
7 type ComponentType,
8 type KeyboardEvent,
9} from "react";
10import { useEnvironmentQuery } from "~/state/query";
11import { desktopWslStateAtom } from "~/state/desktopWslState";
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 { isElectron } from "~/env";
27import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic";
28import { Button } from "../ui/button";
29import { Input } from "../ui/input";
30import { Kbd } from "../ui/kbd";
31import {
32 SidebarContent,
33 SidebarFooter,
34 SidebarGroup,
35 SidebarMenu,
36 SidebarMenuButton,
37 SidebarMenuItem,
38 useSidebar,
39} from "../ui/sidebar";
40import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
41import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";
42import { scrollToSettingsTarget } from "./settingsLayout";
43import {
44 searchSettings,
45 SETTINGS_SEARCH_ITEMS,
46 SETTINGS_SECTION_LABELS,
47 type SettingsPath,
48 type SettingsSearchItem,
49} from "./settingsSearch";
50​
51const SETTINGS_SECTION_ICONS: Readonly<
52 Record<SettingsPath, ComponentType<{ className?: string }>>
53> = {
54 "/settings/general": Settings2Icon,
55 "/settings/appearance": PaletteIcon,
56 "/settings/keybindings": KeyboardIcon,
57 "/settings/providers": BotIcon,
58 "/settings/integrations": BlocksIcon,
59 "/settings/source-control": GitBranchIcon,
60 "/settings/connections": Link2Icon,
61 "/settings/archived": ArchiveIcon,
62};
63​
64export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
65 label: string;
66 to: SettingsPath;
67 icon: ComponentType<{ className?: string }>;
68}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[]).map((to) => ({
69 to,
70 label: SETTINGS_SECTION_LABELS[to],
71 icon: SETTINGS_SECTION_ICONS[to],
72}));
73​
74function SettingsSectionIcon({ to }: { to: SettingsPath }) {
75 const Icon = SETTINGS_SECTION_ICONS[to];
76 return <Icon className="mt-0.5 size-3.5 shrink-0 text-sidebar-muted-foreground/60" />;
78​
79export function SettingsSidebarNav({ pathname }: { pathname: string }) {
80 const navigate = useNavigate();
81 const currentHash = useLocation({ select: (location) => location.hash });
82 const { isMobile, setOpenMobile, open, setOpen } = useSidebar();
83 const searchInputRef = useRef<HTMLInputElement>(null);
84 const [query, setQuery] = useState("");
85 const [activeResultIndex, setActiveResultIndex] = useState(0);
86 const desktopWsl = useEnvironmentQuery(isElectron ? desktopWslStateAtom : null);
87 const searchableItems = useMemo(() => {
88 const wslState = desktopWsl.data;
89 const rowRenders = isWslSettingsRowVisible({
90 state: wslState,
91 error: desktopWsl.error,
92 });
93 if (rowRenders) {
94 return SETTINGS_SEARCH_ITEMS;
95 }
96 return SETTINGS_SEARCH_ITEMS.filter((item) => item.id !== "wsl-backend");
97 }, [desktopWsl.data, desktopWsl.error]);
98 const results = useMemo(() => searchSettings(query, searchableItems), [query, searchableItems]);
99 const isSearching = query.trim().length > 0;
100 const hasResults = results.length > 0;
101​
102 useEffect(() => {
103 setActiveResultIndex((index) => Math.min(index, Math.max(results.length - 1, 0)));
104 }, [results.length]);
105​
106 useEffect(() => {
107 const result = results[activeResultIndex];
108 if (!result) return;
109 document
110 .getElementById(`settings-search-result-${result.id}`)
111 ?.scrollIntoView({ block: "nearest" });
112 }, [activeResultIndex, results]);
113​
114 useEffect(() => {
115 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
116 if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
117​
118 const target = event.target;
119 if (
120 target instanceof HTMLElement &&
121 (target.tagName === "INPUT" ||
122 target.tagName === "TEXTAREA" ||
123 target.isContentEditable ||
124 // Keep focus inside open dialogs and popups instead of escaping
125 // their focus trap into the sidebar search.
126 target.closest('[role="dialog"], [aria-modal="true"], [data-slot$="popup"]') !== null)
127 ) {
128 return;
129 }
130​
131 event.preventDefault();
132 if (isMobile) {
133 setOpenMobile(true);
134 } else if (!open) {
135 setOpen(true);
136 }
137 requestAnimationFrame(() => {
138 searchInputRef.current?.focus();
139 searchInputRef.current?.select();
140 });
141 };
142 window.addEventListener("keydown", handleKeyDown);
143 return () => window.removeEventListener("keydown", handleKeyDown);
144 }, [isMobile, open, setOpen, setOpenMobile]);
145​
146 const handleSectionClick = useCallback(
147 (to: SettingsPath) => {
148 if (isMobile) {
149 setOpenMobile(false);
150 }
151 void navigate({ to, hash: "", replace: true, hashScrollIntoView: false });
152 },
153 [isMobile, navigate, setOpenMobile],
154 );
155 const clearSearch = useCallback(() => {
156 setQuery("");
157 setActiveResultIndex(0);
158 }, []);
159 const handleSearchResultClick = useCallback(
160 (item: SettingsSearchItem) => {
161 clearSearch();
162 if (isMobile) {
163 setOpenMobile(false);
164 }
165 const targetId = item.targetId ?? item.id;
166 if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
167 scrollToSettingsTarget(targetId);
168 return;
169 }
170 void navigate({ to: item.to, hash: targetId, replace: true, hashScrollIntoView: false });
171 },
172 [clearSearch, currentHash, isMobile, navigate, pathname, setOpenMobile],
173 );
174 const handleSearchKeyDown = useCallback(
175 (event: KeyboardEvent<HTMLInputElement>) => {
176 if (event.key === "Escape" && isSearching) {
177 event.preventDefault();
178 event.stopPropagation();
179 clearSearch();
180 return;
181 }
182 if (results.length === 0) return;
183 if (event.key === "ArrowDown") {
184 event.preventDefault();
185 setActiveResultIndex((index) => (index + 1) % results.length);
186 return;
187 }
188 if (event.key === "ArrowUp") {
189 event.preventDefault();
190 setActiveResultIndex((index) => (index - 1 + results.length) % results.length);
191 return;
192 }
193 if (event.key === "Enter") {
194 event.preventDefault();
195 const result = results[activeResultIndex];
196 if (result) handleSearchResultClick(result);
197 }
198 },
199 [activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],
200 );
201 return (
202 <>
203 <SidebarContent className="overflow-x-hidden">
204 <SidebarGroup className="gap-2 p-[var(--sidebar-content-inset)]">
205 <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">
206 <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
207 <Input
208 ref={searchInputRef}
209 nativeInput
210 unstyled
211 type="search"
212 value={query}
213 onChange={(event) => {
214 setQuery(event.currentTarget.value);
215 setActiveResultIndex(0);
216 }}
217 onKeyDown={handleSearchKeyDown}
218 placeholder="Search"
219 aria-label="Search settings"
220 role="combobox"
221 aria-autocomplete="list"
222 aria-expanded={isSearching && hasResults}
223 aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
224 aria-activedescendant={
225 isSearching && results[activeResultIndex]
226 ? `settings-search-result-${results[activeResultIndex].id}`
227 : undefined
228 }
229 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"
230 />
231 {isSearching ? (
232 <Button
233 type="button"
234 size="icon-micro"
235 variant="ghost"
236 className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
237 aria-label="Clear settings search"
238 onClick={() => {
239 clearSearch();
240 searchInputRef.current?.focus();
241 }}
242 >
243 <XIcon className="size-3" />
244 </Button>
245 ) : (
246 <Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">/</Kbd>
247 )}
248 </div>
249 {isSearching && results.length === 0 ? (
250 <p
251 role="status"
252 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
253 >
254 No settings found
255 </p>
256 ) : null}
257 <SidebarMenu
258 className="ps-px"
259 id={isSearching && hasResults ? "settings-search-results" : undefined}
260 role={isSearching && hasResults ? "listbox" : undefined}
261 aria-label={isSearching && hasResults ? "Settings search results" : undefined}
262 >
263 {isSearching
264 ? results.map((item, index) => (
265 <SidebarMenuItem key={item.id} role="presentation">
266 <SidebarMenuButton
267 id={`settings-search-result-${item.id}`}
268 role="option"
269 aria-selected={index === activeResultIndex}
270 tabIndex={-1}
271 size="sm"
272 isActive={index === activeResultIndex}
273 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"
274 onMouseMove={() => setActiveResultIndex(index)}
275 onClick={() => handleSearchResultClick(item)}
276 >
277 <SettingsSectionIcon to={item.to} />
278 <span className="min-w-0 flex-1">
279 <span className="block truncate text-sm font-medium text-sidebar-foreground">
280 {item.title}
281 </span>
282 <span className="block truncate text-[11px] text-sidebar-muted-foreground/75">
283 {SETTINGS_SECTION_LABELS[item.to]}
284 </span>
285 </span>
286 </SidebarMenuButton>
287 </SidebarMenuItem>
288 ))
289 : SETTINGS_NAV_ITEMS.map((item) => {
290 const Icon = item.icon;
291 const isActive = pathname === item.to || pathname.startsWith(`${item.to}/`);
292 return (
293 <SidebarMenuItem key={item.to}>
294 <SidebarMenuButton
295 isActive={isActive}
296 onClick={() => handleSectionClick(item.to)}
297 >
298 <Icon />
299 <span className="truncate">{item.label}</span>
300 </SidebarMenuButton>
301 </SidebarMenuItem>
302 );
303 })}
304 </SidebarMenu>
305 </SidebarGroup>
306 </SidebarContent>
307 <SidebarFooter className="p-[var(--sidebar-content-inset)]">
308 <T3ConnectSidebarSignIn />
309 <div className="flex items-center gap-1">
310 <div className="min-w-0 flex-1">
311 <SidebarUtilityMenu />
312 </div>
313 <T3ConnectSidebarAvatar />
314 </div>
315 </SidebarFooter>
316 </>
317 );