mirror of
https://github.com/facebook/docusaurus.git
synced 2025-05-08 14:47:12 +02:00
fix(v2): adjust correct behavior of navbar when active anchor (#2248)
This commit is contained in:
parent
78c1fe86db
commit
4b5ef84d0f
2 changed files with 47 additions and 4 deletions
|
@ -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 => {
|
||||
|
@ -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;
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
|
@ -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,
|
||||
|
|
|
@ -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;
|
Loading…
Add table
Reference in a new issue