2021-09-08 05:26:31 -04:00
|
|
|
import _ from 'lodash'
|
2021-09-15 10:06:32 -04:00
|
|
|
import { formatWikiHit, searchWiki } from '../algolia-search/search-wiki'
|
2021-09-08 05:26:31 -04:00
|
|
|
import { sendMB } from '../../infrastructure/event-tracking'
|
|
|
|
|
|
|
|
export function setupSearch(formEl) {
|
|
|
|
const inputEl = formEl.querySelector('[name="subject"]')
|
|
|
|
const resultsEl = formEl.querySelector('[data-ol-search-results]')
|
|
|
|
const wrapperEl = formEl.querySelector('[data-ol-search-results-wrapper]')
|
|
|
|
|
|
|
|
let lastValue = ''
|
|
|
|
function hideResults() {
|
|
|
|
wrapperEl.setAttribute('hidden', '')
|
|
|
|
}
|
|
|
|
function showResults() {
|
|
|
|
wrapperEl.removeAttribute('hidden')
|
|
|
|
}
|
|
|
|
|
|
|
|
async function handleChange() {
|
|
|
|
const value = inputEl.value
|
|
|
|
if (value === lastValue) return
|
|
|
|
lastValue = value
|
|
|
|
if (value.length < 3) {
|
|
|
|
hideResults()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const { hits, nbHits } = await searchWiki(value, {
|
|
|
|
hitsPerPage: 3,
|
|
|
|
typoTolerance: 'strict',
|
|
|
|
})
|
|
|
|
resultsEl.innerText = ''
|
|
|
|
|
|
|
|
for (const hit of hits) {
|
2021-09-15 10:06:32 -04:00
|
|
|
const { url, pageName } = formatWikiHit(hit)
|
2021-09-08 05:26:31 -04:00
|
|
|
const liEl = document.createElement('li')
|
|
|
|
|
|
|
|
const linkEl = document.createElement('a')
|
|
|
|
linkEl.className = 'contact-suggestion-list-item'
|
|
|
|
linkEl.href = url
|
|
|
|
linkEl.target = '_blank'
|
|
|
|
liEl.append(linkEl)
|
|
|
|
|
|
|
|
const contentEl = document.createElement('span')
|
|
|
|
contentEl.innerHTML = pageName
|
|
|
|
linkEl.append(contentEl)
|
|
|
|
|
|
|
|
const iconEl = document.createElement('i')
|
|
|
|
iconEl.className = 'fa fa-angle-right'
|
|
|
|
iconEl.setAttribute('aria-hidden', 'true')
|
2024-08-13 07:37:15 -04:00
|
|
|
linkEl.append(iconEl)
|
2021-09-08 05:26:31 -04:00
|
|
|
|
|
|
|
resultsEl.append(liEl)
|
|
|
|
}
|
|
|
|
if (nbHits > 0) {
|
|
|
|
showResults()
|
|
|
|
sendMB('contact-form-suggestions-shown')
|
|
|
|
} else {
|
|
|
|
hideResults()
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
hideResults()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
inputEl.addEventListener('input', _.debounce(handleChange, 350))
|
|
|
|
|
|
|
|
// display initial results
|
|
|
|
handleChange()
|
|
|
|
}
|