Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(v2): adjust correct behavior of navbar when active anchor #2248

Merged
merged 1 commit into from
Jan 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;