diff --git a/packages/docusaurus-theme-search-algolia/src/theme/SearchBar/index.js b/packages/docusaurus-theme-search-algolia/src/theme/SearchBar/index.js index 6ef3809b01..a219cf11ee 100644 --- a/packages/docusaurus-theme-search-algolia/src/theme/SearchBar/index.js +++ b/packages/docusaurus-theme-search-algolia/src/theme/SearchBar/index.js @@ -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; }