Open History to see the last commit
1import React from 'react'
2import { createPortal } from 'react-dom'
3import Router from 'next/router'
4import Head from 'next/head'
5import Link from 'next/link'
6import { useDocSearchKeyboardEvents } from '@docsearch/react'
7import { siteConfig } from 'siteConfig'
8β
9const SearchContext = React.createContext()
10let DocSearchModal = null
11β
12export const useSearch = () => React.useContext(SearchContext)
13β
14export function SearchProvider({
15 children,
16 searchParameters = {
17 hitsPerPage: 5,
18 },
19}) {
20 const [isShowing, setIsShowing] = React.useState(false)
21β
22 const onOpen = React.useCallback(function onOpen() {
23 function importDocSearchModalIfNeeded() {
24 if (DocSearchModal) {
25 return Promise.resolve()
26 }
27β
28 return import('@docsearch/react/modal').then(
29 ({ DocSearchModal: Modal }) => (DocSearchModal = Modal)
30 )
31 }
32β
33 importDocSearchModalIfNeeded().then(() => {
34 setIsShowing(true)
35 })
36 }, [])
37β
38 const onClose = React.useCallback(() => setIsShowing(false), [])
39β
40 useDocSearchKeyboardEvents({
41 isOpen: isShowing,
42 onOpen,
43 onClose,
44 })
45β
46 const options = {
47 appId: siteConfig.algolia.appId,
48 apiKey: siteConfig.algolia.apiKey,
49 indexName: siteConfig.algolia.indexName,
50 renderModal: true,
51 }
52β
53 return (
54 <>
55 <Head>
56 <link
57 key="algolia"
58 rel="preconnect"
59 href={`https://${options.appId}-dsn.algolia.net`}
60 crossOrigin="true"
61 />
62 </Head>
63β
64 <SearchContext.Provider value={{ DocSearchModal, onOpen }}>
65 {children}
66 </SearchContext.Provider>
67β
68 {isShowing &&
69 createPortal(
70 <DocSearchModal
71 {...options}
72 searchParameters={searchParameters}
73 onClose={onClose}
74 navigator={{
75 navigate({ suggestionUrl }) {
76 Router.push(suggestionUrl)
77 },
78 }}
79 transformItems={items => {
80 return items.map(item => {
81 const url = new URL(item.url)
82 return {
83 ...item,
84 url: item.url
85 .replace(url.origin, '')
86 .replace('#__next', '')
87 .replace('/docs/#', '/docs/overview#'),
88 }
89 })
90 }}
91 hitComponent={Hit}
92 />,
93 document.body
94 )}
95 </>
96 )
97}
98β
99function Hit({ hit, children }) {
100 return (
101 <Link href={hit.url.replace()}>
102 <a>{children}</a>
103 </Link>
104 )
105}