Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

Search.tsx 7.8 KB

You have to be logged in to leave a comment. Sign In
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
  1. import { useState, useEffect, useRef, Children, ReactNode } from 'react'
  2. import cx from 'classnames'
  3. import { useRouter } from 'next/router'
  4. import debounce from 'lodash/debounce'
  5. import { useTranslation } from 'components/hooks/useTranslation'
  6. import { sendEvent } from '../javascripts/events'
  7. import { useMainContext } from './context/MainContext'
  8. import { useVersion } from 'components/hooks/useVersion'
  9. type SearchResult = {
  10. url: string
  11. breadcrumbs: string
  12. heading: string
  13. title: string
  14. content: string
  15. }
  16. type Props = {
  17. isStandalone?: boolean
  18. updateSearchParams?: boolean
  19. children?: (props: { SearchInput: ReactNode; SearchResults: ReactNode }) => ReactNode
  20. }
  21. // Homepage and 404 should be `isStandalone`, all others not
  22. // `updateSearchParams` should be false on the GraphQL explorer page
  23. export function Search({ isStandalone = false, updateSearchParams = true, children }: Props) {
  24. const [query, setQuery] = useState('')
  25. const [results, setResults] = useState<Array<SearchResult>>([])
  26. const [activeHit, setActiveHit] = useState(0)
  27. const inputRef = useRef<HTMLInputElement>(null)
  28. const { t } = useTranslation('search')
  29. const { currentVersion } = useVersion()
  30. // Figure out language and version for index
  31. const { expose } = useMainContext()
  32. const {
  33. searchOptions: { languages, versions, nonEnterpriseDefaultVersion },
  34. } = JSON.parse(expose)
  35. const router = useRouter()
  36. // fall back to the non-enterprise default version (FPT currently) on the homepage, 404 page, etc.
  37. const version = versions[currentVersion] || versions[nonEnterpriseDefaultVersion]
  38. const language = (languages.includes(router.locale) && router.locale) || 'en'
  39. // If the user shows up with a query in the URL, go ahead and search for it
  40. useEffect(() => {
  41. const params = new URLSearchParams(location.search)
  42. if (params.has('query')) {
  43. const xquery = params.get('query')?.trim() || ''
  44. setQuery(xquery)
  45. /* await */ fetchSearchResults(xquery)
  46. }
  47. }, [])
  48. // Search with your keyboard
  49. useEffect(() => {
  50. document.addEventListener('keydown', searchWithYourKeyboard)
  51. return () => document.removeEventListener('keydown', searchWithYourKeyboard)
  52. }, [results, activeHit])
  53. function searchWithYourKeyboard(event: KeyboardEvent) {
  54. switch (event.key) {
  55. case '/':
  56. // when the input is focused, `/` should have no special behavior
  57. if ((event.target as HTMLInputElement)?.type === 'search') break
  58. event.preventDefault() // prevent slash from being typed into input
  59. inputRef.current?.focus()
  60. break
  61. case 'Escape':
  62. closeSearch()
  63. break
  64. case 'ArrowDown':
  65. if (!results.length) break
  66. event.preventDefault() // prevent window scrolling
  67. if (activeHit >= results.length) break
  68. setActiveHit(activeHit + 1)
  69. break
  70. case 'ArrowUp':
  71. if (!results.length) break
  72. event.preventDefault() // prevent window scrolling
  73. if (activeHit === 0) break
  74. setActiveHit(activeHit - 1)
  75. break
  76. case 'Enter':
  77. // look for a link in the given hit, then visit it
  78. if (activeHit === 0 || !results.length) break
  79. window.location.href = results[activeHit - 1]?.url
  80. break
  81. }
  82. }
  83. // When the user finishes typing, update the results
  84. async function onSearch(e: React.ChangeEvent<HTMLInputElement>) {
  85. const xquery = e.target?.value?.trim()
  86. setQuery(xquery)
  87. // Update the URL with the search parameters in the query string
  88. if (updateSearchParams) {
  89. const pushUrl = new URL(location.toString())
  90. pushUrl.searchParams.set('query', xquery)
  91. history.pushState({}, '', pushUrl.toString())
  92. }
  93. // deactivate any active hit when typing in search box
  94. setActiveHit(0)
  95. return await fetchSearchResults(xquery)
  96. }
  97. // If there's a query, call the endpoint
  98. // Otherwise, there's no results by default
  99. async function fetchSearchResults(xquery: string) {
  100. if (xquery) {
  101. const endpointUrl = new URL(location.origin)
  102. endpointUrl.pathname = '/search'
  103. const endpointParams: Record<string, string> = {
  104. language,
  105. version,
  106. query: xquery,
  107. }
  108. endpointUrl.search = new URLSearchParams(endpointParams).toString()
  109. const response = await fetch(endpointUrl.toString(), {
  110. method: 'GET',
  111. headers: { 'Content-Type': 'application/json' },
  112. })
  113. setResults(response.ok ? await response.json() : [])
  114. } else {
  115. setResults([])
  116. }
  117. // Analytics tracking
  118. if (xquery) {
  119. sendEvent({
  120. type: 'search',
  121. search_query: xquery,
  122. // search_context
  123. })
  124. }
  125. }
  126. // Close panel if overlay is clicked
  127. function closeSearch() {
  128. setQuery('')
  129. setResults([])
  130. }
  131. // Prevent the page from refreshing when you "submit" the form
  132. function preventRefresh(evt: React.FormEvent) {
  133. evt.preventDefault()
  134. }
  135. const SearchResults = (
  136. <>
  137. <div id="search-results-container" className={results.length ? 'js-open' : ''}>
  138. {Boolean(results.length) && (
  139. <div className="ais-Hits d-block">
  140. <ol className="ais-Hits-list">
  141. {results.map(({ url, breadcrumbs, heading, title, content }, index) => (
  142. <li
  143. key={url}
  144. className={'ais-Hits-item' + (index + 1 === activeHit ? ' active' : '')}
  145. >
  146. <div className="search-result border-top color-border-secondary py-3 px-2">
  147. <a className="no-underline" href={url}>
  148. {/* Breadcrumbs in search records don't include the page title. These fields may contain <mark> elements that we need to render */}
  149. <div
  150. className="search-result-breadcrumbs d-block color-text-primary opacity-60 text-small pb-1"
  151. dangerouslySetInnerHTML={{ __html: breadcrumbs }}
  152. />
  153. <div
  154. className="search-result-title d-block h4-mktg color-text-primary"
  155. dangerouslySetInnerHTML={{
  156. __html: heading ? `${title}: ${heading}` : title,
  157. }}
  158. />
  159. <div
  160. className="search-result-content d-block color-text-secondary"
  161. dangerouslySetInnerHTML={{ __html: content }}
  162. />
  163. </a>
  164. </div>
  165. </li>
  166. ))}
  167. </ol>
  168. </div>
  169. )}
  170. </div>
  171. <div
  172. className={'search-overlay-desktop' + (!isStandalone && query ? ' js-open' : '')}
  173. onClick={closeSearch}
  174. ></div>
  175. </>
  176. )
  177. const SearchInput = (
  178. <div id="search-input-container" aria-hidden="true">
  179. <div className="ais-SearchBox">
  180. <form role="search" className="ais-SearchBox-form" noValidate onSubmit={preventRefresh}>
  181. <input
  182. ref={inputRef}
  183. className={'ais-SearchBox-input' + (isStandalone || query ? ' js-open' : '')}
  184. type="search"
  185. placeholder={t`placeholder`}
  186. autoFocus={isStandalone}
  187. autoComplete="off"
  188. autoCorrect="off"
  189. autoCapitalize="off"
  190. spellCheck="false"
  191. maxLength={512}
  192. onChange={debounce(onSearch, 200)}
  193. defaultValue={query}
  194. />
  195. <button
  196. className="ais-SearchBox-submit"
  197. type="submit"
  198. title="Submit the search query."
  199. hidden
  200. />
  201. </form>
  202. </div>
  203. </div>
  204. )
  205. return (
  206. <>
  207. {typeof children === 'function' ? (
  208. children({ SearchInput, SearchResults })
  209. ) : (
  210. <>
  211. {SearchInput}
  212. {SearchResults}
  213. </>
  214. )}
  215. </>
  216. )
  217. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...