-
-
Notifications
You must be signed in to change notification settings - Fork 896
/
Copy pathAlgoliaSearch.tsx
333 lines (295 loc) · 9.49 KB
/
AlgoliaSearch.tsx
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
/* eslint-disable no-underscore-dangle */
import { DocSearchModal } from '@docsearch/react';
import type { DocSearchHit, InternalDocSearchHit, StoredDocSearchHit } from '@docsearch/react/dist/esm/types';
import clsx from 'clsx';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
export const INDEX_NAME = 'asyncapi';
export const DOCS_INDEX_NAME = 'asyncapi-docs';
const APP_ID = 'Z621OGRI9Y';
const API_KEY = '5a4122ae46ce865146d23d3530595d38';
interface ISearchContext {
isOpen: boolean;
onOpen: (indexName?: string) => void;
onClose: () => void;
onInput?: (e: React.KeyboardEvent) => void;
}
const SearchContext = createContext<ISearchContext>({} as ISearchContext);
interface IHitProps {
hit: (StoredDocSearchHit | InternalDocSearchHit) & {
__is_result?: () => boolean;
__is_parent?: () => boolean;
__is_child?: () => boolean;
__is_first?: () => boolean;
__is_last?: () => boolean;
};
children: React.ReactNode;
}
interface AlgoliaModalProps {
onClose: (event?: React.MouseEvent) => void;
initialQuery: string;
indexName: string;
}
interface IUseDocSearchKeyboardEvents {
isOpen: boolean;
onOpen: (indexName?: string) => void;
onClose: () => void;
onInput?: (e: React.KeyboardEvent) => void;
}
type ISearchButtonProps = Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'children'> & {
children?: React.ReactNode | (({ actionKey }: { actionKey: { shortKey: string; key: string } }) => React.ReactNode);
indexName?: string;
};
/**
*
* @description The function used to transform the items
* @param {StoredDocSearchHit[]} items - The items to be transformed
*/
function transformItems(items: DocSearchHit[]) {
return items.map((item, index) => {
// We transform the absolute URL into a relative URL to
// leverage Next's preloading.
const a = document.createElement('a');
a.href = item.url;
const hash = a.hash === '#content-wrapper' || a.hash === '#header' ? '' : a.hash;
if (item.hierarchy?.lvl0) {
// eslint-disable-next-line no-param-reassign
item.hierarchy.lvl0 = item.hierarchy.lvl0.replace(/&/g, '&');
}
return {
...item,
url: `${a.pathname}${hash}`,
__is_result: () => true,
__is_parent: () => item.type === 'lvl1' && items.length > 1 && index === 0,
__is_child: () => item.type !== 'lvl1' && items.length > 1 && items[0].type === 'lvl1' && index !== 0,
__is_first: () => index === 1,
__is_last: () => index === items.length - 1 && index !== 0
};
});
}
/**
*
* @description The hit component used for the Algolia search
* @param {IHitProps} props - The props of the hit
*/
function Hit({ hit, children }: IHitProps) {
return (
<Link
href={hit.url}
className={clsx({
'DocSearch-Hit--Result': hit.__is_result?.(),
'DocSearch-Hit--Parent': hit.__is_parent?.(),
'DocSearch-Hit--FirstChild': hit.__is_first?.(),
'DocSearch-Hit--LastChild': hit.__is_last?.(),
'DocSearch-Hit--Child': hit.__is_child?.()
})}
>
{children}
</Link>
);
}
/**
*
* @description The Algolia modal used for searching the website
* @param {IAlgoliaModalProps} props - The props of the Algolia modal
*/
function AlgoliaModal({ onClose, initialQuery, indexName }: AlgoliaModalProps) {
const router = useRouter();
return createPortal(
<DocSearchModal
initialQuery={initialQuery}
initialScrollY={window.scrollY}
searchParameters={{
distinct: 1
}}
placeholder={indexName === DOCS_INDEX_NAME ? 'Search documentation' : 'Search resources'}
onClose={onClose}
indexName={indexName}
apiKey={API_KEY}
appId={APP_ID}
navigator={{
navigate({ itemUrl }) {
onClose();
router.push(itemUrl);
}
}}
hitComponent={Hit}
transformItems={transformItems}
getMissingResultsUrl={({ query }) => {
return `https://github.com/asyncapi/website/issues/new?title=Cannot%20search%20given%20query:%20${query}`;
}}
/>,
document.body
);
}
/**
* @description The function used to check if the content is being edited
* @param {KeyboardEvent} event - The keyboard event
* @returns {boolean} - Whether the content is being edited
*/
function isEditingContent(event: KeyboardEvent) {
const element = event.target;
const { tagName } = element as HTMLElement;
return (
(element as HTMLElement).isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA'
);
}
/**
* @description The function used to get the action key
* @returns {Object} - The action key
*/
function getActionKey() {
if (typeof navigator !== 'undefined') {
if (/(Mac|iPhone|iPod|iPad)/i.test(navigator.userAgent || navigator.platform)) {
return {
shortKey: '⌘',
key: 'Command'
};
}
return {
shortKey: 'Ctrl',
key: 'Control'
};
}
return {
shortKey: 'Ctrl',
key: 'Control'
};
}
/**
*
* @description The hook used for the Algolia search keyboard events
* @param {IUseDocSearchKeyboardEvents} props - The props of the useDocSearchKeyboardEvents hook
*/
function useDocSearchKeyboardEvents({ isOpen, onOpen, onClose }: IUseDocSearchKeyboardEvents) {
useEffect(() => {
/**
* @description The function used to handle the keyboard event.
* @description It opens the search modal when the '/' key is pressed
* @description It closes the search modal when the 'Escape' key is pressed
* @description It opens the search modal when the 'k' key is pressed with the 'Command' or 'Control' key
* @param {KeyboardEvent} event - The keyboard event
* @returns {void}
*/
function onKeyDown(event: KeyboardEvent): void {
if (
(event.key === 'Escape' && isOpen) ||
(event.key === 'k' && (event.metaKey || event.ctrlKey)) ||
(!isEditingContent(event) && event.key === '/' && !isOpen)
) {
event.preventDefault();
if (isOpen) {
onClose();
} else if (!document.body.classList.contains('DocSearch--active')) {
let indexName = INDEX_NAME;
if (typeof document !== 'undefined') {
const loc = document.location;
indexName = loc.pathname.startsWith('/docs') ? DOCS_INDEX_NAME : INDEX_NAME;
}
onOpen(indexName);
}
}
}
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('keydown', onKeyDown);
};
}, [isOpen, onOpen, onClose]);
}
/**
*
* @description The Algolia search component used for searching the website
* @param {React.ReactNode} children - The content of the page
*/
export default function AlgoliaSearch({ children }: { children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(false);
const [indexName, setIndexName] = useState<string>(INDEX_NAME);
const [initialQuery, setInitialQuery] = useState<string>();
const onOpen = useCallback(
(_indexName?: string) => {
if (_indexName) {
setIndexName(_indexName);
}
setIsOpen(true);
},
[setIsOpen, setIndexName]
);
const onClose = useCallback(() => {
setIsOpen(false);
}, [setIsOpen]);
const onInput = useCallback(
(e: React.KeyboardEvent) => {
setIsOpen(true);
setInitialQuery(e.key);
},
[setIsOpen, setInitialQuery]
);
useDocSearchKeyboardEvents({
isOpen,
onOpen,
onClose,
onInput
});
return (
<>
<Head>
<link rel='preconnect' href={`https://${APP_ID}-dsn.algolia.net`} crossOrigin='anonymous' />
</Head>
<SearchContext.Provider value={{ isOpen, onOpen, onClose, onInput }}>{children}</SearchContext.Provider>
{isOpen && <AlgoliaModal initialQuery={initialQuery ?? ''} onClose={onClose} indexName={indexName} />}
</>
);
}
/**
*
* @description The search button component used for opening the Algolia search
* @param {ISearchButtonProps} props - The props of the search button
*/
export function SearchButton({ children, indexName = INDEX_NAME, ...props }: ISearchButtonProps) {
const { onOpen, onInput } = useContext(SearchContext);
const [Children, setChildren] = useState<string | React.ReactNode>('');
const searchButtonRef = useRef<HTMLButtonElement>(null);
const actionKey = getActionKey();
useEffect(() => {
/**
* @description It triggers the onInput event when a key is pressed and the search button is focused
* @description It starts search with the key pressed
* @param {KeyboardEvent} event - The keyboard event
* @returns {void}
*/
function onKeyDown(event: KeyboardEvent) {
if (searchButtonRef && searchButtonRef.current === document.activeElement && onInput) {
if (/[a-zA-Z0-9]/.test(event.key)) {
onInput(event as unknown as React.KeyboardEvent);
}
}
}
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('keydown', onKeyDown);
};
}, [onInput, searchButtonRef]);
useEffect(() => {
if (typeof children === 'function') {
setChildren(children({ actionKey }));
} else {
setChildren(children);
}
}, []);
return (
<button
type='button'
ref={searchButtonRef}
onClick={() => {
onOpen(indexName);
}}
{...props}
data-testid='Search-Button'
>
{Children}
</button>
);
}