doc.silverstripe.org/src/components/SearchBox.tsx

56 lines
1.6 KiB
TypeScript
Raw Normal View History

2019-11-08 03:40:20 +01:00
import React from 'react'
import { StatelessComponent, ReactElement, useEffect } from 'react';
import { navigateTo } from "gatsby-link"
2019-11-13 00:43:22 +01:00
import { getCurrentVersion } from '../utils/nodes';
2019-11-08 03:40:20 +01:00
interface SearchBoxProps {
identifier: string;
}
const autocompleteSelected = (e) => {
e.stopPropagation()
// Use an anchor tag to parse the absolute url (from autocomplete.js) into a relative url
// eslint-disable-next-line no-undef
const a = document.createElement(`a`)
a.href = e._args[0].url
navigateTo(`${a.pathname}${a.hash}`)
};
const SearchBox: StatelessComponent<SearchBoxProps> = ({ identifier }): ReactElement|null => {
useEffect(() => {
if (typeof window === 'undefined') return;
2019-12-17 02:04:09 +01:00
if (!process.env.GATSBY_DOCSEARCH_API_KEY) {
return;
}
2019-11-08 03:40:20 +01:00
window.addEventListener(
`autocomplete:selected`,
autocompleteSelected,
true
);
if(window.docsearch){
window.docsearch({
2019-11-13 00:43:22 +01:00
algoliaOptions: {
facetFilters: [`version:${getCurrentVersion()}`],
hitsPerPage: 5,
},
2019-11-08 03:40:20 +01:00
apiKey: process.env.GATSBY_DOCSEARCH_API_KEY,
2019-11-13 00:43:22 +01:00
debug: true,
2019-11-08 03:40:20 +01:00
indexName: process.env.GATSBY_DOCSEARCH_INDEX,
inputSelector: `#${identifier}`,
});
}
}, []);
return (
<input
id={identifier}
type="search"
placeholder="Search the docs..."
className="form-control search-input"
/>
)
};
export default SearchBox;