All files / src/value/scroll utils.ts

17.65% Statements 3/17
0% Branches 0/4
0% Functions 0/4
23.08% Lines 3/13

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 5330x                                         30x                         30x                                    
import { motionValue, MotionValue } from "../"
 
/**
 * @public
 */
export interface ScrollMotionValues {
    scrollX: MotionValue<number>
    scrollY: MotionValue<number>
    scrollXProgress: MotionValue<number>
    scrollYProgress: MotionValue<number>
}
 
export interface ScrollOffsets {
    xOffset: number
    yOffset: number
    xMaxOffset: number
    yMaxOffset: number
}
 
export type GetScrollOffsets = () => ScrollOffsets
 
export function createScrollMotionValues(): ScrollMotionValues {
    return {
        scrollX: motionValue(0),
        scrollY: motionValue(0),
        scrollXProgress: motionValue(0),
        scrollYProgress: motionValue(0),
    }
}
 
function setProgress(offset: number, maxOffset: number, value: MotionValue) {
    value.set(!offset || !maxOffset ? 0 : offset / maxOffset)
}
 
export function createScrollUpdater(
    values: ScrollMotionValues,
    getOffsets: GetScrollOffsets
) {
    const update = () => {
        const { xOffset, yOffset, xMaxOffset, yMaxOffset } = getOffsets()
        // Set absolute positions
        values.scrollX.set(xOffset)
        values.scrollY.set(yOffset)
        // Set 0-1 progress
        setProgress(xOffset, xMaxOffset, values.scrollXProgress)
        setProgress(yOffset, yMaxOffset, values.scrollYProgress)
    }
 
    update()
 
    return update
}