Skip to content

Commit

Permalink
fix(v2): adjust correct behavior of navbar when active anchor (#2248)
Browse files Browse the repository at this point in the history
  • Loading branch information
lex111 authored and yangshun committed Jan 28, 2020
1 parent 78c1fe8 commit 4b5ef84
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@

import {useState, useCallback, useEffect} from 'react';
import {useLocation} from '@docusaurus/router';
import useLocationHash from '@theme/hooks/useLocationHash';

const useHideableNavbar = hideOnScroll => {
const [isNavbarVisible, setIsNavbarVisible] = useState(true);
const [isFocusedAnchor, setIsFocusedAnchor] = useState(false);
const [lastScrollTop, setLastScrollTop] = useState(0);
const [navbarHeight, setNavbarHeight] = useState(0);
const navbarRef = useCallback(node => {
Expand All @@ -18,6 +20,7 @@ const useHideableNavbar = hideOnScroll => {
}
}, []);
const location = useLocation();
const [hash, setHash] = useLocationHash(location.hash);

const handleScroll = () => {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
Expand All @@ -26,11 +29,10 @@ const useHideableNavbar = hideOnScroll => {
return;
}

const focusedElement = document.activeElement;

if (focusedElement && /^#/.test(window.location.hash)) {
if (isFocusedAnchor) {
setIsFocusedAnchor(false);
setIsNavbarVisible(false);
focusedElement.blur();
setLastScrollTop(scrollTop);
return;
}

Expand Down Expand Up @@ -59,9 +61,26 @@ const useHideableNavbar = hideOnScroll => {
}, [lastScrollTop, navbarHeight]);

useEffect(() => {
if (!hideOnScroll) {
return;
}

setIsNavbarVisible(true);
setHash(location.hash);
}, [location]);

useEffect(() => {
if (!hideOnScroll) {
return;
}

if (!hash) {
return;
}

setIsFocusedAnchor(true);
}, [hash]);

return {
navbarRef,
isNavbarVisible,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {useState, useEffect} from 'react';

function useLocationHash(initialHash) {
const [hash, setHash] = useState(initialHash);

useEffect(() => {
const handleHashChange = () => setHash(window.location.hash);

window.addEventListener('hashchange', handleHashChange);

return () => window.removeEventListener('hashchange', handleHashChange);
}, []);

return [hash, setHash];
}

export default useLocationHash;

0 comments on commit 4b5ef84

Please sign in to comment.