-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathSearchMenu.tsx
More file actions
334 lines (297 loc) · 11.9 KB
/
Copy pathSearchMenu.tsx
File metadata and controls
334 lines (297 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
'use client';
import {ActionButton, SearchField} from '@react-spectrum/s2';
import {Autocomplete, Dialog, Key, OverlayTriggerStateContext, Provider} from 'react-aria-components';
import Close from '@react-spectrum/s2/icons/Close';
import {ComponentCardView} from './ComponentCardView';
import {
type ComponentItem,
createSearchOptions,
filterAndSortSearchItems,
getOrderedLibraries,
getPageTitle,
getResourceTags,
SearchEmptyState,
sortItemsForDisplay,
sortSearchItems,
useFilteredIcons,
useSearchTagSelection,
useSectionTagsForDisplay
} from './searchUtils';
import {getLibraryFromPage, getLibraryFromUrl} from './library';
import {IconSearchSkeleton, useIconFilter} from './IconSearchView';
import {type Library, TAB_DEFS} from './constants';
// @ts-ignore
import {Page} from '@parcel/rsc';
import React, {CSSProperties, lazy, Suspense, useEffect, useMemo, useRef, useState} from 'react';
import {SearchTagGroups} from './SearchTagGroups';
import {style} from '@react-spectrum/s2/style' with { type: 'macro' };
import {Tab, TabList, TabPanel, Tabs} from './Tabs';
import {TextFieldRef} from '@react-types/textfield';
export function stripMarkdown(description: string | undefined) {
return (description || '').replace(/\[(.*?)\]\(.*?\)/g, '$1');
}
export const divider = style({
marginY: 8,
marginStart: -8,
marginEnd: 0,
alignSelf: 'stretch',
backgroundColor: {
default: 'gray-400',
forcedColors: 'ButtonBorder'
},
borderStyle: 'none',
borderRadius: 'full',
flexGrow: 0,
flexShrink: 0,
width: '[3px]'
});
const IconSearchView = lazy(() => import('./IconSearchView').then(({IconSearchView}) => ({default: IconSearchView})));
interface SearchMenuProps {
pages: Page[],
currentPage: Page,
onClose: () => void,
overlayId?: string,
initialSearchValue: string,
isSearchOpen: boolean
}
function CloseButton({onClose}: {onClose: () => void}) {
return (
<div style={{position: 'absolute', top: 8, right: 8}}>
<Provider values={[[OverlayTriggerStateContext, null]]}>
<ActionButton isQuiet onPress={onClose}>
<Close />
</ActionButton>
</Provider>
</div>
);
}
export function SearchMenu(props: SearchMenuProps) {
let {pages, currentPage, onClose, overlayId, isSearchOpen} = props;
const currentLibrary = getLibraryFromPage(currentPage);
let [selectedLibrary, setSelectedLibrary] = useState<Library>(currentLibrary);
let [searchValue, setSearchValue] = useState(props.initialSearchValue);
const orderedTabs = useMemo(() => getOrderedLibraries(currentPage), [currentPage]);
const searchRef = useRef<TextFieldRef<HTMLInputElement> | null>(null);
// Auto-focus search field when menu opens
// We don't put autoFocus on the SearchField because it will cause a flicker when switching tabs
useEffect(() => {
const timer = setTimeout(() => {
searchRef.current?.focus();
}, 0);
return () => clearTimeout(timer);
}, []);
// Transform pages data into component data structure
const transformedComponents = useMemo(() => {
if (!pages || !Array.isArray(pages)) {
return [];
}
const components = pages
.filter(page => page.url && page.url.endsWith('.html') && getLibraryFromUrl(page.url) === selectedLibrary && !page.exports?.hideFromSearch)
.map(page => {
const name = page.url.replace(/^\//, '').replace(/\.html$/, '');
const title = getPageTitle(page);
const section: string = (page.exports?.section as string) || 'Components';
const tags: string[] = (page.exports?.tags || page.exports?.keywords as string[]) || [];
const description: string = stripMarkdown(page.exports?.description);
const date: string | undefined = page.exports?.date;
return {
id: name,
name: title,
href: page.url,
section,
tags,
description,
date
};
});
return components;
}, [pages, selectedLibrary]);
// Build sections for the selected library
const sections = useMemo(() => {
const sectionNames = Array.from(new Set(transformedComponents.map(c => c.section || 'Components')));
return sectionNames.map(sectionName => ({
id: sectionName.toLowerCase(),
name: sectionName,
children: transformedComponents.filter(c => (c.section || 'Components') === sectionName)
})).sort((a, b) => {
if (a.id === 'components') {
return -1;
}
if (b.id === 'components') {
return 1;
}
return 0;
});
}, [transformedComponents]);
const sectionTags = useMemo(() => sections.map(s => ({id: s.id, name: s.name})), [sections]);
const resourceTags = useMemo(() => getResourceTags(selectedLibrary), [selectedLibrary]);
const [selectedTagId, setSelectedTagId] = useSearchTagSelection(
searchValue,
sectionTags,
resourceTags,
currentPage.exports?.section?.toLowerCase() || 'components'
);
const filteredIcons = useFilteredIcons(searchValue);
const iconFilter = useIconFilter();
let filteredComponents = useMemo(() => {
if (!searchValue) {
return sections;
}
const allItems = sections.flatMap(section => section.children);
const sortedItems = filterAndSortSearchItems(allItems, searchValue, createSearchOptions<ComponentItem>());
const resultsBySection = new Map<string, typeof transformedComponents>();
sortedItems.forEach(item => {
const section = item.section || 'Components';
if (!resultsBySection.has(section)) {
resultsBySection.set(section, []);
}
resultsBySection.get(section)!.push(item);
});
return sections
.map(section => ({
...section,
children: resultsBySection.get(section.name) || []
}))
.filter(section => section.children.length > 0);
}, [sections, searchValue]);
const sectionTagsForDisplay = useSectionTagsForDisplay(
sections,
searchValue,
selectedTagId,
resourceTags.map(t => t.id)
);
const handleTabSelectionChange = React.useCallback((key: Key) => {
setSelectedLibrary(key as typeof selectedLibrary);
// Focus main search field of the newly selected tab
setTimeout(() => {
const lib = key as Library;
const expectedLabel = `Search ${TAB_DEFS[lib].label}`;
if (searchRef.current && searchRef.current.getInputElement()?.getAttribute('aria-label') === expectedLabel) {
searchRef.current.focus();
}
}, 10);
}, []);
const handleSectionSelectionChange = React.useCallback((keys: Iterable<Key>) => {
const firstKey = Array.from(keys)[0] as string;
if (firstKey) {
setSelectedTagId(firstKey);
}
}, [setSelectedTagId]);
const handleIconSelectionChange = React.useCallback((keys: Iterable<Key>) => {
const firstKey = Array.from(keys)[0] as string;
if (firstKey) {
setSelectedTagId(firstKey);
}
}, [setSelectedTagId]);
const selectedItems = useMemo(() => {
let items: typeof transformedComponents = [];
if (searchValue.trim().length > 0 && selectedTagId === 'all') {
items = filteredComponents.flatMap(s => s.children) || [];
items = sortSearchItems(items, searchValue, createSearchOptions<ComponentItem>());
} else {
items = (filteredComponents.find(s => s.id === selectedTagId)?.children) || [];
items = sortItemsForDisplay(items, searchValue);
}
return items;
}, [filteredComponents, selectedTagId, searchValue]);
const selectedSectionName = useMemo(() => {
if (searchValue.trim().length > 0 && selectedTagId === 'all') {
return 'All';
}
return (filteredComponents.find(s => s.id === selectedTagId)?.name)
|| (sections.find(s => s.id === selectedTagId)?.name)
|| 'Items';
}, [filteredComponents, sections, selectedTagId, searchValue]);
useEffect(() => {
const handleNavigationStart = () => {
setSearchValue('');
onClose();
};
window.addEventListener('rsc-navigation-start', handleNavigationStart);
return () => {
window.removeEventListener('rsc-navigation-start', handleNavigationStart);
};
}, [onClose]);
return (
<Dialog id={overlayId} className={style({height: 'full'})} aria-label="Search menu">
<Tabs
aria-label="Libraries"
keyboardActivation="manual"
orientation="vertical"
selectedKey={selectedLibrary}
onSelectionChange={handleTabSelectionChange}>
<TabList aria-label="Library">
{orderedTabs.map((tab, i) => (
<Tab key={tab.id} id={tab.id}>
<div className={style({display: 'flex', gap: 12, marginTop: 4})}>
<div style={{viewTransitionName: (i === 0 && isSearchOpen) ? 'search-menu-icon' : 'none'} as CSSProperties}>
{tab.icon}
</div>
<div>
<span style={{viewTransitionName: (i === 0 && isSearchOpen) ? 'search-menu-label' : 'none'} as CSSProperties} className={style({font: 'ui-2xl'})}>
{tab.label}
</span>
<div className={style({fontSize: 'ui-sm'})}>{tab.description}</div>
</div>
</div>
</Tab>
))}
</TabList>
{orderedTabs.map((tab, i) => {
const tabResourceTags = getResourceTags(tab.id);
const selectedResourceTag = tabResourceTags.find(tag => tag.id === selectedTagId);
const placeholderText = selectedResourceTag
? `Search ${selectedResourceTag.name}`
: `Search ${tab.label}`;
return (
<TabPanel key={tab.id} id={tab.id}>
<Autocomplete filter={selectedTagId === 'icons' ? iconFilter : undefined}>
<div className={style({display: 'flex', flexDirection: 'column', height: 'full'})}>
<div className={style({flexShrink: 0, marginStart: 16, marginEnd: 64})}>
<SearchField
value={searchValue}
onChange={setSearchValue}
ref={searchRef}
size="L"
aria-label={`Search ${tab.label}`}
placeholder={placeholderText}
UNSAFE_style={{marginInlineEnd: 296, viewTransitionName: (i === 0 && isSearchOpen) ? 'search-menu-search-field' : 'none'} as CSSProperties}
styles={style({width: 500})} />
</div>
<CloseButton onClose={onClose} />
<SearchTagGroups
sectionTags={sectionTagsForDisplay}
resourceTags={tabResourceTags}
selectedTagId={selectedTagId}
onSectionSelectionChange={handleSectionSelectionChange}
onResourceSelectionChange={handleIconSelectionChange} />
{selectedTagId === 'icons' ? (
<div className={style({flexGrow: 1, overflow: 'auto', display: 'flex', flexDirection: 'column'})}>
<Suspense fallback={<IconSearchSkeleton />}>
<IconSearchView
filteredItems={filteredIcons}
listBoxClassName={style({flexGrow: 1, overflow: 'auto', width: '100%', scrollPaddingY: 4})} />
</Suspense>
</div>
) : (
<ComponentCardView
onAction={onClose}
items={selectedItems.map(item => ({
id: item.id,
name: item.name,
href: item.href ?? `/${tab.id}/${item.name}.html`,
description: item.description
}))}
ariaLabel={selectedSectionName}
renderEmptyState={() => <SearchEmptyState searchValue={searchValue} libraryLabel={tab.label} />} />
)}
</div>
</Autocomplete>
</TabPanel>
);
})}
</Tabs>
</Dialog>
);
}
export {MobileSearchMenu} from './MobileSearchMenu';