feat(v2): algolia search result no longer cause full page refresh (#2079)

This commit is contained in:
Endi 2019-12-04 12:40:31 +07:00 committed by Yangshun Tay
parent 718b1e11b5
commit dd6b10da30

View file

@ -9,6 +9,7 @@ import React, {useRef, useCallback} from 'react';
import classnames from 'classnames';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import {useHistory} from '@docusaurus/router';
import './styles.css';
@ -22,6 +23,7 @@ const Search = props => {
const {
themeConfig: {algolia},
} = siteConfig;
const history = useHistory();
const initAlgolia = () => {
if (!initialized.current) {
@ -31,6 +33,22 @@ const Search = props => {
indexName: algolia.indexName,
inputSelector: '#search_input_react',
algoliaOptions: algolia.algoliaOptions,
// Override algolia's default selection event, allowing us to do client-side
// navigation and avoiding a full page refresh.
handleSelected: (_input, _event, suggestion) => {
// Use an anchor tag to parse the absolute url into a relative url
// Alternatively, we can use new URL(suggestion.url) but its not supported in IE
const a = document.createElement('a');
a.href = suggestion.url;
// Algolia use closest parent element id #__docusaurus when a h1 page title does not have an id
// So, we can safely remove it. See https://github.com/facebook/docusaurus/issues/1828 for more details.
const routePath =
`#__docusaurus` === a.hash
? `${a.pathname}`
: `${a.pathname}${a.hash}`;
history.push(routePath);
},
});
initialized.current = true;
}