Skip to content

Commit

Permalink
feat(v2): algolia search result no longer cause full page refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
endiliey committed Dec 3, 2019
1 parent cc2201e commit ea54588
Showing 1 changed file with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -22,6 +23,7 @@ const Search = props => {
const {
themeConfig: {algolia},
} = siteConfig;
const history = useHistory();

const initAlgolia = () => {
if (!initialized.current) {
Expand All @@ -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;
}
Expand Down

0 comments on commit ea54588

Please sign in to comment.