aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/ui/Header.js
blob: 2d042bfe6cf3ca59fb77b77c7d54639853b12b38 (plain) (blame)
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
import React, { useEffect, useCallback, useRef } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

const elClassHidden = 'header--hidden';

const header = document.getElementById('header');

export default function Header({ children }) {
    let dHeight = useRef(0);
    let wHeight = useRef(0);
    let wScrollCurrent = useRef(0);
    let wScrollBefore = useRef(0);
    let wScrollDiff = useRef(0);

    /**
     * @param {number} delay
     * @param {{ (): void; apply?: any; }} fn
     */
    let throttle = (delay, fn) => {
        var last, deferTimer;
        return function () {
            var context = this, args = arguments, now = +new Date;
            if (last && now < last + delay) {
                clearTimeout(deferTimer);
                deferTimer = setTimeout(
                    function () {
                        last = now;
                        fn.apply(context, args);
                    },
                    delay);
            } else {
                last = now;
                fn.apply(context, args);
            }
        };
    };
    let updateHeader = useCallback(() => {
        dHeight.current = document.body.offsetHeight;
        wHeight.current = window.innerHeight;
        wScrollCurrent.current = window.pageYOffset;
        wScrollDiff.current = wScrollBefore.current - wScrollCurrent.current;

        if (wScrollCurrent.current <= 0) {
            // scrolled to the very top; element sticks to the top
            header.classList.remove(elClassHidden);
        } else if (wScrollDiff.current > 0 && header.classList.contains(elClassHidden)) {
            // scrolled up; element slides in
            header.classList.remove(elClassHidden);
        } else if (wScrollDiff.current < 0) {
            // scrolled down
            if (wScrollCurrent.current + wHeight.current >= dHeight.current && header.classList.contains(elClassHidden)) {
                // scrolled to the very bottom; element slides in
                header.classList.remove(elClassHidden);
            } else {
                // scrolled down; element slides out
                header.classList.add(elClassHidden);
            }
        }
        wScrollBefore.current = wScrollCurrent.current;
    }, []);

    useEffect(() => {
        window.addEventListener('scroll', () => (!window.requestAnimationFrame)
            ? throttle(250, updateHeader)
            : window.requestAnimationFrame(updateHeader), false);
    }, [updateHeader]);
    return ReactDOM.createPortal(children, header);
}

Header.propTypes = {
    children: PropTypes.node
};