-
Notifications
You must be signed in to change notification settings - Fork 34
/
Algolia.tsx
174 lines (151 loc) · 4.72 KB
/
Algolia.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
import React, { useState, useRef, useCallback } from 'react'
import { AnchorHTMLAttributes } from 'react'
import { createPortal } from 'react-dom'
import { useRouter } from 'next/navigation.js'
import Link from 'next/link.js'
import { useDocSearchKeyboardEvents } from '@docsearch/react'
import type { LinkProps } from 'next/link'
import type {
DocSearchModal as DocSearchModalType,
DocSearchProps,
DocSearchModalProps,
} from '@docsearch/react'
import type { InternalDocSearchHit, StoredDocSearchHit } from '@docsearch/react/dist/esm/types'
export type AlgoliaSearchProps = {
algoliaConfig: DocSearchProps
}
export interface AlgoliaConfig {
provider: 'algolia'
algoliaConfig: DocSearchProps
}
export interface AlgoliaSearchQuery {
setSearch: (search: string) => void
toggle: () => void
}
export interface AlgoliaSearchContext {
query: AlgoliaSearchQuery
}
let DocSearchModal: typeof DocSearchModalType | null = null
const CustomLink = ({ href, ...rest }: LinkProps & AnchorHTMLAttributes<HTMLAnchorElement>) => {
const isInternalLink = href && href.startsWith('/')
const isAnchorLink = href && href.startsWith('#')
if (isInternalLink) {
return <Link href={href} {...rest} />
}
if (isAnchorLink) {
return <a href={href} {...rest} />
}
return <a target="_blank" rel="noopener noreferrer" href={href} {...rest} />
}
function Hit({
hit,
children,
}: {
hit: InternalDocSearchHit | StoredDocSearchHit
children: React.ReactNode
}) {
return <CustomLink href={hit.url}>{children}</CustomLink>
}
export const AlgoliaSearchContext = React.createContext<AlgoliaSearchContext>(
{} as AlgoliaSearchContext
)
/**
* Command palette like search component for algolia - `ctrl-k` to open the palette.
* To toggle the modal or search from child components, use the search context:
* ```
* import { AlgoliaSearchContext } from 'pliny/search/algolia'
* const { query } = useContext(AlgoliaSearchContext)
* ```
*
*/
export const AlgoliaSearchProvider: React.FC<React.PropsWithChildren<AlgoliaSearchProps>> = (
props
) => {
const { algoliaConfig } = props
const router = useRouter()
const [isOpen, setIsOpen] = useState(false)
const [initialQuery, setInitialQuery] = useState<string | undefined>(undefined)
const importDocSearchModalIfNeeded = useCallback(() => {
if (DocSearchModal) {
return Promise.resolve()
}
return Promise.all([import('@docsearch/react')]).then(([{ DocSearchModal: Modal }]) => {
DocSearchModal = Modal
})
}, [])
const onOpen = useCallback(() => {
importDocSearchModalIfNeeded().then(() => {
setIsOpen(true)
})
}, [importDocSearchModalIfNeeded, setIsOpen])
const onClose = useCallback(() => {
setIsOpen(false)
}, [setIsOpen])
const onInput = useCallback(
(event: KeyboardEvent) => {
importDocSearchModalIfNeeded().then(() => {
setIsOpen(true)
setInitialQuery(event.key)
})
},
[importDocSearchModalIfNeeded, setIsOpen, setInitialQuery]
)
const navigator = useRef({
navigate({ itemUrl }: { itemUrl?: string }) {
// Algolia results could contain URL's from other domains which cannot
// be served through history and should navigate with window.location
const isInternalLink = itemUrl.startsWith('/')
const isAnchorLink = itemUrl.startsWith('#')
if (!isInternalLink && !isAnchorLink) {
window.open(itemUrl, '_blank')
} else {
router.push(itemUrl)
}
},
}).current
const transformItems = useRef<DocSearchModalProps['transformItems']>((items) =>
items.map((item) => {
// If Algolia contains a external domain, we should navigate without
// relative URL
const isInternalLink = item.url.startsWith('/')
const isAnchorLink = item.url.startsWith('#')
if (!isInternalLink && !isAnchorLink) {
return item
}
// We transform the absolute URL into a relative URL.
const url = new URL(item.url)
return {
...item,
// url: withBaseUrl(`${url.pathname}${url.hash}`),
url: `${url.pathname}${url.hash}`,
}
})
).current
useDocSearchKeyboardEvents({
isOpen,
onOpen,
onClose,
onInput,
})
return (
<AlgoliaSearchContext.Provider
value={{ query: { setSearch: setInitialQuery, toggle: onOpen } }}
>
{props.children}
{isOpen &&
DocSearchModal &&
createPortal(
<DocSearchModal
onClose={onClose}
initialScrollY={window.scrollY}
initialQuery={initialQuery}
navigator={navigator}
transformItems={transformItems}
hitComponent={Hit}
{...algoliaConfig}
/>,
document.body
)}
</AlgoliaSearchContext.Provider>
)
}