summaryrefslogtreecommitdiff
path: root/shared/components/src/actions/updateScrollAndWindowDependentVisuals.ts
blob: b934e37bb71a1852d6e2deb48a1c6f977bc56982 (plain)
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
import { debounce } from '@amp/web-app-components/src/utils/debounce';
import { throttle } from '@amp/web-app-components/src/utils/throttle';
/**
 * Dynamically change header and bottom gradient style when scrolling within a modal, and on window resize
 */
export function updateScrollAndWindowDependentVisuals(node) {
    let animationRequest;
    const handleScroll = () => {
        // Get scroll details
        const { scrollHeight, scrollTop, offsetHeight } = node;
        const maxScroll = scrollHeight - offsetHeight;

        // Calculate whether content is scrolled
        const contentIsScrolling = scrollTop > 1;

        // Calculate if bottom gradient should be hidden
        const scrollingNotPossible = maxScroll === 0;
        const pastMaxScroll = scrollTop >= maxScroll;
        const hideGradient = scrollingNotPossible || pastMaxScroll;

        if (animationRequest) {
            window.cancelAnimationFrame(animationRequest);
        }

        animationRequest = window.requestAnimationFrame(() =>
            node.dispatchEvent(
                new CustomEvent('scrollStatus', {
                    detail: { contentIsScrolling, hideGradient },
                }),
            ),
        );
    };

    const onResize = throttle(handleScroll, 250);
    const onScroll = debounce(handleScroll, 50);
    node.addEventListener('scroll', onScroll, { capture: true, passive: true });
    window.addEventListener('resize', onResize);

    return {
        destroy() {
            node.removeEventListener('scroll', onScroll, { capture: true });
            window.removeEventListener('resize', onResize);
            if (animationRequest) {
                window.cancelAnimationFrame(animationRequest);
            }
        },
    };
}