/
useHideableNavbar.ts
81 lines (69 loc) · 2.41 KB
/
useHideableNavbar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 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, useCallback, useRef} from 'react';
import {useLocationChange} from '../utils/useLocationChange';
import {useScrollPosition} from '../utils/scrollUtils';
/**
* Wires the imperative logic of a hideable navbar.
* @param hideOnScroll If `false`, this hook is basically a no-op.
*/
export function useHideableNavbar(hideOnScroll: boolean): {
/** A ref to the navbar component. Plug this into the actual element. */
readonly navbarRef: (node: HTMLElement | null) => void;
/** If `false`, the navbar component should not be rendered. */
readonly isNavbarVisible: boolean;
} {
const [isNavbarVisible, setIsNavbarVisible] = useState(hideOnScroll);
const isFocusedAnchor = useRef(false);
const navbarHeight = useRef(0);
const navbarRef = useCallback((node: HTMLElement | null) => {
if (node !== null) {
navbarHeight.current = node.getBoundingClientRect().height;
}
}, []);
useScrollPosition(({scrollY: scrollTop}, lastPosition) => {
if (!hideOnScroll) {
return;
}
// Needed mostly for handling rubber band scrolling.
// See https://github.com/facebook/docusaurus/pull/5721
if (scrollTop < navbarHeight.current) {
setIsNavbarVisible(true);
return;
}
if (isFocusedAnchor.current) {
isFocusedAnchor.current = false;
return;
}
const lastScrollTop = lastPosition?.scrollY;
const documentHeight =
document.documentElement.scrollHeight - navbarHeight.current;
const windowHeight = window.innerHeight;
if (lastScrollTop && scrollTop >= lastScrollTop) {
setIsNavbarVisible(false);
} else if (scrollTop + windowHeight < documentHeight) {
setIsNavbarVisible(true);
}
});
useLocationChange((locationChangeEvent) => {
if (!hideOnScroll) {
return;
}
// See https://github.com/facebook/docusaurus/pull/8059#issuecomment-1239639480
const currentHash = locationChangeEvent.location.hash;
const currentHashAnchor = currentHash
? document.getElementById(currentHash.substring(1))
: undefined;
if (currentHashAnchor) {
isFocusedAnchor.current = true;
setIsNavbarVisible(false);
return;
}
setIsNavbarVisible(true);
});
return {navbarRef, isNavbarVisible};
}