refactor(v2): extract scroll position detection into separate hook (#2627)

This commit is contained in:
Alexey Pyltsyn 2020-04-22 08:56:04 +03:00 committed by GitHub
parent 41b3c66f5e
commit 4367197c77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 73 additions and 37 deletions

View file

@ -8,6 +8,7 @@
import {useState, useCallback, useEffect} from 'react';
import {useLocation} from '@docusaurus/router';
import useLocationHash from '@theme/hooks/useLocationHash';
import useScrollPosition from '@theme/hooks/useScrollPosition';
const useHideableNavbar = (hideOnScroll) => {
const [isNavbarVisible, setIsNavbarVisible] = useState(true);
@ -22,8 +23,11 @@ const useHideableNavbar = (hideOnScroll) => {
const location = useLocation();
const [hash, setHash] = useLocationHash(location.hash);
const handleScroll = () => {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
useScrollPosition(
({scrollY: scrollTop}) => {
if (!hideOnScroll) {
return;
}
if (scrollTop === 0) {
setIsNavbarVisible(true);
@ -40,7 +44,8 @@ const useHideableNavbar = (hideOnScroll) => {
return;
}
const documentHeight = document.documentElement.scrollHeight - navbarHeight;
const documentHeight =
document.documentElement.scrollHeight - navbarHeight;
const windowHeight = window.innerHeight;
if (lastScrollTop && scrollTop >= lastScrollTop) {
@ -50,19 +55,9 @@ const useHideableNavbar = (hideOnScroll) => {
}
setLastScrollTop(scrollTop);
};
useEffect(() => {
if (!hideOnScroll) {
return undefined;
}
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [lastScrollTop, navbarHeight]);
},
[lastScrollTop, navbarHeight],
);
useEffect(() => {
if (!hideOnScroll) {

View file

@ -0,0 +1,41 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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';
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
const getScrollPosition = () => ({
scrollX: ExecutionEnvironment.canUseDOM ? window.pageXOffset : 0,
scrollY: ExecutionEnvironment.canUseDOM ? window.pageYOffset : 0,
});
const useScrollPosition = (effect, deps = []) => {
const [scrollPosition, setScrollPosition] = useState(getScrollPosition());
const handleScroll = () => {
const currentScrollPosition = getScrollPosition();
setScrollPosition(currentScrollPosition);
if (effect) {
effect(currentScrollPosition);
}
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () =>
window.removeEventListener('scroll', handleScroll, {
passive: true,
});
}, deps);
return scrollPosition;
};
export default useScrollPosition;