All files / animations/generators decay.ts

100% Statements 22/22
100% Branches 18/18
66.67% Functions 2/3
100% Lines 16/16

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      11x 11x 11x 11x 11x 11x           11x   11x 11x   11x           11x   11x   255x 255x 255x 255x          
import { Animation, AnimationState, DecayOptions } from "../types"
 
export function decay({
    velocity = 0,
    from = 0,
    power = 0.8,
    timeConstant = 350,
    restDelta = 0.5,
    modifyTarget,
}: DecayOptions): Animation<number> {
    /**
     * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
     * to reduce GC during animation.
     */
    const state: AnimationState<number> = { done: false, value: from }
 
    let amplitude = power * velocity
    const ideal = from + amplitude
 
    const target = modifyTarget === undefined ? ideal : modifyTarget(ideal)
 
    /**
     * If the target has changed we need to re-calculate the amplitude, otherwise
     * the animation will start from the wrong position.
     */
    if (target !== ideal) amplitude = target - from
 
    return {
        next: (t: number) => {
            const delta = -amplitude * Math.exp(-t / timeConstant)
            state.done = !(delta > restDelta || delta < -restDelta)
            state.value = state.done ? target : target + delta
            return state
        },
        flipTarget: () => {},
    }
}