All files / src/animation/utils transitions.ts

90.35% Statements 103/114
81.82% Branches 99/121
100% Functions 19/19
90% Lines 99/110

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 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296          43x 43x 43x   43x 43x 43x 43x 43x 43x                 43x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x   163x     43x       43x 161x 161x 161x 161x 161x 161x   161x   161x         161x 115x 161x 2x         161x 31x               161x         161x                                         161x   161x           43x 343x 343x     43x 158x 6x 6x     158x     43x         156x 13x     156x         156x 59x           156x                               338x 338x   338x   338x           338x 7x 331x               338x   338x           195x         2730x     195x                   1352x 1352x     88x 88x           136x 136x 136x 136x 136x 136x     338x             43x 667x               43x     13x         43x 681x                 43x       338x   338x 6x     338x     338x             338x   338x   338x 15x   323x     338x 60x 60x        
import {
    Transition,
    PermissiveTransitionDefinition,
    ResolvedValueTarget,
} from "../../types"
import { AnimationOptions, animate, inertia } from "popmotion"
import { secondsToMilliseconds } from "../../utils/time-conversion"
import { isEasingArray, easingDefinitionToFunction } from "./easing"
import { MotionValue } from "../../value"
import { isAnimatable } from "./is-animatable"
import { getDefaultTransition } from "./default-transitions"
import { warning } from "hey-listen"
import { getAnimatableNone } from "../../render/dom/value-types/animatable-none"
import { instantAnimationState } from "../../utils/use-instant-transition-state"
import { resolveFinalValueInKeyframes } from "../../utils/resolve-value"
 
type StopAnimation = { stop: () => void }
 
/**
 * Decide whether a transition is defined on a given Transition.
 * This filters out orchestration options and returns true
 * if any options are left.
 */
export function isTransitionDefined({
    when,
    delay,
    delayChildren,
    staggerChildren,
    staggerDirection,
    repeat,
    repeatType,
    repeatDelay,
    from,
    ...transition
}: Transition) {
    return !!Object.keys(transition).length
}
 
let legacyRepeatWarning = false
/**
 * Convert Framer Motion's Transition type into Popmotion-compatible options.
 */
export function convertTransitionToAnimationOptions<T>({
    ease,
    times,
    yoyo,
    flip,
    loop,
    ...transition
}: PermissiveTransitionDefinition): AnimationOptions<T> {
    const options: AnimationOptions<T> = { ...transition }
 
    if (times) options["offset"] = times
 
    /**
     * Convert any existing durations from seconds to milliseconds
     */
    if (transition.duration)
        options["duration"] = secondsToMilliseconds(transition.duration)
    if (transition.repeatDelay)
        options.repeatDelay = secondsToMilliseconds(transition.repeatDelay)
 
    /**
     * Map easing names to Popmotion's easing functions
     */
    if (ease) {
        options["ease"] = isEasingArray(ease)
            ? ease.map(easingDefinitionToFunction)
            : easingDefinitionToFunction(ease)
    }
 
    /**
     * Support legacy transition API
     */
    if (transition.type === "tween") options.type = "keyframes"
 
    /**
     * TODO: These options are officially removed from the API.
     */
    Iif (yoyo || loop || flip) {
        warning(
            !legacyRepeatWarning,
            "yoyo, loop and flip have been removed from the API. Replace with repeat and repeatType options."
        )
        legacyRepeatWarning = true
        if (yoyo) {
            options.repeatType = "reverse"
        } else if (loop) {
            options.repeatType = "loop"
        } else if (flip) {
            options.repeatType = "mirror"
        }
        options.repeat = loop || yoyo || flip || transition.repeat
    }
 
    /**
     * TODO: Popmotion 9 has the ability to automatically detect whether to use
     * a keyframes or spring animation, but does so by detecting velocity and other spring options.
     * It'd be good to introduce a similar thing here.
     */
    if (transition.type !== "spring") options.type = "keyframes"
 
    return options
}
 
/**
 * Get the delay for a value by checking Transition with decreasing specificity.
 */
export function getDelayFromTransition(transition: Transition, key: string) {
    const valueTransition = getValueTransition(transition, key) || {}
    return valueTransition.delay ?? transition.delay ?? 0
}
 
export function hydrateKeyframes(options: PermissiveTransitionDefinition) {
    if (Array.isArray(options.to) && options.to[0] === null) {
        options.to = [...options.to]
        options.to[0] = options.from
    }
 
    return options
}
 
export function getPopmotionAnimationOptions(
    transition: PermissiveTransitionDefinition,
    options: any,
    key: string
) {
    if (Array.isArray(options.to)) {
        transition.duration ??= 0.8
    }
 
    hydrateKeyframes(options)
 
    /**
     * Get a default transition if none is determined to be defined.
     */
    if (!isTransitionDefined(transition)) {
        transition = {
            ...transition,
            ...getDefaultTransition(key, options.to),
        }
    }
 
    return {
        ...options,
        ...convertTransitionToAnimationOptions(transition),
    }
}
 
/**
 *
 */
function getAnimation(
    key: string,
    value: MotionValue,
    target: ResolvedValueTarget,
    transition: PermissiveTransitionDefinition,
    onComplete: () => void
) {
    const valueTransition = getValueTransition(transition, key)
    let origin = valueTransition.from ?? value.get()
 
    const isTargetAnimatable = isAnimatable(key, target)
 
    Iif (origin === "none" && isTargetAnimatable && typeof target === "string") {
        /**
         * If we're trying to animate from "none", try and get an animatable version
         * of the target. This could be improved to work both ways.
         */
        origin = getAnimatableNone(key, target)
    } else if (isZero(origin) && typeof target === "string") {
        origin = getZeroUnit(target)
    } else Iif (
        !Array.isArray(target) &&
        isZero(target) &&
        typeof origin === "string"
    ) {
        target = getZeroUnit(origin)
    }
 
    const isOriginAnimatable = isAnimatable(key, origin)
 
    warning(
        isOriginAnimatable === isTargetAnimatable,
        `You are trying to animate ${key} from "${origin}" to "${target}". ${origin} is not an animatable value - to enable this animation set ${origin} to a value animatable to ${target} via the \`style\` property.`
    )
 
    function start(): StopAnimation {
        const options = {
            from: origin,
            to: target,
            velocity: value.getVelocity(),
            onComplete,
            onUpdate: (v: Animatable) => value.set(v),
        }
 
        return valueTransition.type === "inertia" ||
            valueTransition.type === "decay"
            ? inertia({ ...options, ...valueTransition })
            : animate({
                  ...getPopmotionAnimationOptions(
                      valueTransition,
                      options,
                      key
                  ),
                  onUpdate: (v: any) => {
                      options.onUpdate(v)
                      valueTransition.onUpdate?.(v)
                  },
                  onComplete: () => {
                      options.onComplete()
                      valueTransition.onComplete?.()
                  },
              })
    }
 
    function set(): StopAnimation {
        const finalTarget = resolveFinalValueInKeyframes(target)
        value.set(finalTarget)
        onComplete()
        valueTransition?.onUpdate?.(finalTarget)
        valueTransition?.onComplete?.()
        return { stop: () => {} }
    }
 
    return !isOriginAnimatable ||
        !isTargetAnimatable ||
        valueTransition.type === false
        ? set
        : start
}
 
export function isZero(value: string | number) {
    return (
        value === 0 ||
        (typeof value === "string" &&
            parseFloat(value) === 0 &&
            value.indexOf(" ") === -1)
    )
}
 
export function getZeroUnit(
    potentialUnitType: string | number
): string | number {
    return typeof potentialUnitType === "number"
        ? 0
        : getAnimatableNone("", potentialUnitType)
}
 
export function getValueTransition(transition: Transition, key: string) {
    return transition[key] || transition["default"] || transition
}
 
/**
 * Start animation on a MotionValue. This function is an interface between
 * Framer Motion and Popmotion
 *
 * @internal
 */
export function startAnimation(
    key: string,
    value: MotionValue,
    target: ResolvedValueTarget,
    Itransition: Transition = {}
) {
    if (instantAnimationState.current) {
        transition = { type: false }
    }
 
    return value.start((onComplete) => {
        let delayTimer: number
        let controls: StopAnimation
        const animation = getAnimation(
            key,
            value,
            target,
            transition,
            onComplete
        )
        const delay = getDelayFromTransition(transition, key)
 
        const start = () => (controls = animation())
 
        if (delay) {
            delayTimer = window.setTimeout(start, secondsToMilliseconds(delay))
        } else {
            start()
        }
 
        return () => {
            clearTimeout(delayTimer)
            controls?.stop()
        }
    })
}