All files / owid-grapher/grapher/controls VerticalScrollContainer.tsx

95.63% Statements 175/183
81.25% Branches 13/16
83.33% Functions 5/6
95.63% Lines 175/183

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 2561x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x           4x 4x 4x                                                                                                                                                      
import React, { useEffect, useState } from "react"
import classnames from "classnames"
 
type VerticalScrollContainerProps = React.DetailedHTMLProps<
    React.HTMLAttributes<HTMLDivElement>,
    HTMLDivElement
> & {
    scrollingShadows?: boolean
    scrollLock?: boolean
    contentsId?: string
}
 
type ReactRef<T> =
    | ((instance: T | null) => void)
    | React.MutableRefObject<T | null>
    | null
 
function useCombinedRefs<T>(...refs: ReactRef<T>[]): React.RefObject<T> {
    const targetRef = React.useRef<T>(null)
 
    React.useEffect(() => {
        refs.forEach((ref) => {
            if (!ref) return
            if (typeof ref === "function") {
                ref(targetRef.current || null)
            } else {
                ref.current = targetRef.current || null
            }
        })
    }, [refs])
 
    return targetRef
}
 
export const VerticalScrollContainer = React.forwardRef(
    (props: VerticalScrollContainerProps, ref: ReactRef<HTMLDivElement>) => {
        let {
            scrollingShadows,
            scrollLock,
            className,
            children,
            contentsId,
            style,
            ...rest
        } = props
 
        scrollingShadows = scrollingShadows ?? true
        scrollLock = scrollLock ?? true
 
        const scrollContainerRef = useCombinedRefs<HTMLDivElement>(ref)
        const [scrollTop, scrollBottom] = useScrollBounds(
            scrollContainerRef,
            contentsId
        )
 
        if (scrollLock) {
            useScrollLock(scrollContainerRef, { doNotLockIfNoScroll: true })
        }
 
        return (
            <div
                className="VerticalScrollContainerShadows"
                style={{
                    position: "relative",
                    height: "100%",
                }}
            >
                {scrollingShadows && (
                    <ScrollingShadow
                        direction="down"
                        size={10}
                        opacity={getShadowOpacity(0.15, 80, scrollTop)}
                    />
                )}
                <div
                    className={classnames(className, "VerticalScrollContainer")}
                    style={{
                        overflowY: "auto",
                        position: "absolute",
                        top: 0,
                        right: 0,
                        bottom: 0,
                        left: 0,
                        ...style,
                    }}
                    ref={scrollContainerRef}
                    {...rest}
                >
                    {children}
                </div>
                {scrollingShadows && (
                    <ScrollingShadow
                        direction="up"
                        size={10}
                        opacity={getShadowOpacity(0.15, 80, scrollBottom)}
                    />
                )}
            </div>
        )
    }
)
 
function getShadowOpacity(
    maxOpacity: number,
    maxDistance: number,
    scrollDistance: number | undefined
): number {
    const distance =
        scrollDistance !== undefined ? Math.min(scrollDistance, maxDistance) : 0
    return (distance / maxDistance) * maxOpacity
}
 
const ScrollingShadow = (props: {
    direction: "up" | "down"
    size: number
    opacity: number
}): JSX.Element => {
    // "Eased" gradient
    // https://larsenwork.com/easing-gradients/
    const background = `linear-gradient(
        to ${props.direction === "up" ? "bottom" : "top"},
        hsla(0, 0%, 0%, 0) 0%,
        hsla(0, 0%, 0%, 0.104) 25.8%,
        hsla(0, 0%, 0%, 0.45) 60.9%,
        hsla(0, 0%, 0%, 0.825) 88.7%,
        hsl(0, 0%, 0%) 100%
    )`
    return (
        <div
            style={{
                position: "absolute",
                left: 0,
                right: 0,
                [props.direction === "up" ? "bottom" : "top"]: 0,
                height: `${props.size}px`,
                background: background,
                opacity: props.opacity,
                pointerEvents: "none",
                zIndex: 10,
            }}
        />
    )
}
 
/**
 * A throttled function that returns the available scrollTop and scrollBottom
 * @param ref
 * @param contentsId when this string changes, it's a signal that the contents have re-rendered and
 * the height has likely changed.
 */
function useScrollBounds<ElementType extends HTMLElement>(
    ref: React.RefObject<ElementType>,
    contentsId?: string
): [number | undefined, number | undefined] {
    const [scrollTop, onScrollTop] = useState<number | undefined>(undefined)
    const [scrollBottom, onScrollBottom] = useState<number | undefined>(
        undefined
    )
 
    useEffect(() => {
        const el = ref.current!
        if (el) {
            let pendingUpdate = false
 
            function onScroll(): void {
                const { scrollTop, scrollHeight, offsetHeight } = el
                onScrollTop(scrollTop)
                onScrollBottom(scrollHeight - offsetHeight - scrollTop)
                pendingUpdate = false
            }
            onScroll() // execute for first time to setState
 
            const onScrollThrottled = (): void => {
                if (!pendingUpdate) {
                    window.requestAnimationFrame(onScroll)
                    pendingUpdate = true
                }
            }
 
            el.addEventListener("scroll", onScrollThrottled)
            return (): void => {
                el.removeEventListener("scroll", onScrollThrottled)
            }
        }
        return
    }, [contentsId])
 
    return [scrollTop, scrollBottom]
}
 
interface ScrollLockOptions {
    doNotLockIfNoScroll: boolean
}
 
/**
 * React hook to prevent scroll events propagating to parent element.
 * @param ref the ReactRef of the scrolling container
 */
function useScrollLock<ElementType extends HTMLElement>(
    ref: React.RefObject<ElementType>,
    opts?: Partial<ScrollLockOptions>
): void {
    useEffect(() => {
        const el = ref.current
        const options: ScrollLockOptions = {
            doNotLockIfNoScroll: false,
            ...opts,
        }
        if (el) {
            function onWheel(ev: WheelEvent): void {
                const el = ref.current
                if (el) {
                    const delta = ev.deltaY
                    const up = delta < 0
                    const { scrollTop, scrollHeight, offsetHeight } = el
 
                    if (
                        options.doNotLockIfNoScroll &&
                        scrollHeight <= offsetHeight
                    ) {
                        return
                    }
 
                    function prevent(): void {
                        ev.stopPropagation()
                        ev.preventDefault()
                    }
 
                    if (
                        !up &&
                        delta > scrollHeight - offsetHeight - scrollTop
                    ) {
                        // Scrolling down, but this will take us past the bottom.
                        el.scrollTop = scrollHeight
                        return prevent()
                    } else if (up && -delta > scrollTop) {
                        // Scrolling up, but this will take us past the top.
                        el.scrollTop = 0
                        return prevent()
                    }
                }
            }
            el.addEventListener("wheel", onWheel as any, {
                // We need to be in non-passive mode to be able to cancel the event
                passive: false,
            })
            return (): void => {
                if (el) {
                    el.removeEventListener("wheel", onWheel as any)
                }
            }
        }
        return
    }, [])
}