All files / src/render/utils animation.ts

100% Statements 85/85
91.43% Branches 64/70
100% Functions 19/19
100% Lines 73/73

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 23438x                       38x 38x                                                     38x     254x   239x     239x 3x 6x   3x 236x 74x     162x     162x     239x 178x             122x   122x 122x 122x   122x 3x               122x 103x 19x           122x 65x   35x     105x   35x                 87x           122x 122x 3x         3x   119x                   265x     265x 265x 265x 265x   265x   265x     265x   265x 287x 287x   287x           1x     286x         286x     265x 203x             35x 66x 69x     35x     35x     35x 38x 4x   35x     42x       38x       35x     38x 18x     38x 8x                   251x       251x   251x 251x    
import { startAnimation } from "../../animation/utils/transitions"
import { VariantLabels } from "../../motion/types"
import {
    Target,
    TargetAndTransition,
    TargetResolver,
    TargetWithKeyframes,
    Transition,
} from "../../types"
import { VisualElement } from "../types"
import { AnimationTypeState } from "./animation-state"
import { AnimationType } from "./types"
import { setTarget } from "./setters"
import { resolveVariant } from "./variants"
 
export type AnimationDefinition =
    | VariantLabels
    | TargetAndTransition
    | TargetResolver
 
export type AnimationOptions = {
    delay?: number
    transitionOverride?: Transition
    custom?: any
    type?: AnimationType
}
 
export type MakeTargetAnimatable = (
    visualElement: VisualElement,
    target: TargetWithKeyframes,
    origin?: Target,
    transitionEnd?: Target
) => {
    target: TargetWithKeyframes
    transitionEnd?: Target
}
 
/**
 * @internal
 */
export function animateVisualElement(
    visualElement: VisualElement,
    definition: AnimationDefinition,
    options: AnimationOptions = {}
) {
    visualElement.notifyAnimationStart(definition)
    let animation: Promise<any>
 
    if (Array.isArray(definition)) {
        const animations = definition.map((variant) =>
            animateVariant(visualElement, variant, options)
        )
        animation = Promise.all(animations)
    } else if (typeof definition === "string") {
        animation = animateVariant(visualElement, definition, options)
    } else {
        const resolvedDefinition =
            typeof definition === "function"
                ? resolveVariant(visualElement, definition, options.custom)
                : definition
        animation = animateTarget(visualElement, resolvedDefinition, options)
    }
 
    return animation.then(() =>
        visualElement.notifyAnimationComplete(definition)
    )
}
 
function animateVariant(
    visualElement: VisualElement,
    variant: string,
    Ioptions: AnimationOptions = {}
) {
    const resolved = resolveVariant(visualElement, variant, options.custom)
    let { transition = visualElement.getDefaultTransition() || {} } =
        resolved || {}
 
    if (options.transitionOverride) {
        transition = options.transitionOverride
    }
 
    /**
     * If we have a variant, create a callback that runs it as an animation.
     * Otherwise, we resolve a Promise immediately for a composable no-op.
     */
 
    const getAnimation = resolved
        ? () => animateTarget(visualElement, resolved, options)
        : () => Promise.resolve()
 
    /**
     * If we have children, create a callback that runs all their animations.
     * Otherwise, we resolve a Promise immediately for a composable no-op.
     */
    const getChildAnimations = visualElement.variantChildren?.size
        ? (forwardDelay = 0) => {
              const {
                  delayChildren = 0,
                  staggerChildren,
                  staggerDirection,
              } = transition
 
              return animateChildren(
                  visualElement,
                  variant,
                  delayChildren + forwardDelay,
                  staggerChildren,
                  staggerDirection,
                  options
              )
          }
        : () => Promise.resolve()
 
    /**
     * If the transition explicitly defines a "when" option, we need to resolve either
     * this animation or all children animations before playing the other.
     */
    const { when } = transition
    if (when) {
        const [first, last] =
            when === "beforeChildren"
                ? [getAnimation, getChildAnimations]
                : [getChildAnimations, getAnimation]
 
        return first().then(last)
    } else {
        return Promise.all([getAnimation(), getChildAnimations(options.delay)])
    }
}
 
/**
 * @internal
 */
function animateTarget(
    visualElement: VisualElement,
    definition: TargetAndTransition,
    { delay = 0, transitionOverride, type }: AnimationOptions = {}
): Promise<any> {
    let {
        transition = visualElement.getDefaultTransition(),
        transitionEnd,
        ...target
    } = visualElement.makeTargetAnimatable(definition)
 
    if (transitionOverride) transition = transitionOverride
 
    const animations: Promise<any>[] = []
 
    const animationTypeState =
        type && visualElement.animationState?.getState()[type]
 
    for (const key in target) {
        const value = visualElement.getValue(key)
        const valueTarget = target[key]
 
        if (
            !value ||
            valueTarget === undefined ||
            (animationTypeState &&
                shouldBlockAnimation(animationTypeState, key))
        ) {
            continue
        }
 
        const animation = startAnimation(key, value, valueTarget, {
            delay,
            ...transition,
        })
 
        animations.push(animation)
    }
 
    return Promise.all(animations).then(() => {
        transitionEnd && setTarget(visualElement, transitionEnd)
    })
}
 
function animateChildren(
    visualElement: VisualElement,
    variant: string,
    IdelayChildren = 0,
    staggerChildren = 0,
    staggerDirection = 1,
    options: AnimationOptions
) {
    const animations: Promise<any>[] = []
 
    const maxStaggerDuration =
        (visualElement.variantChildren!.size - 1) * staggerChildren
 
    const generateStaggerDuration =
        staggerDirection === 1
            ? (Ii = 0) => i * staggerChildren
            : (Ii = 0) => maxStaggerDuration - i * staggerChildren
 
    Array.from(visualElement.variantChildren!)
        .sort(sortByTreeOrder)
        .forEach((child, i) => {
            animations.push(
                animateVariant(child, variant, {
                    ...options,
                    delay: delayChildren + generateStaggerDuration(i),
                }).then(() => child.notifyAnimationComplete(variant))
            )
        })
 
    return Promise.all(animations)
}
 
export function stopAnimation(visualElement: VisualElement) {
    visualElement.forEachValue((value) => value.stop())
}
 
export function sortByTreeOrder(a: VisualElement, b: VisualElement) {
    return a.sortNodePosition(b)
}
 
/**
 * Decide whether we should block this animation. Previously, we achieved this
 * just by checking whether the key was listed in protectedKeys, but this
 * posed problems if an animation was triggered by afterChildren and protectedKeys
 * had been set to true in the meantime.
 */
function shouldBlockAnimation(
    { protectedKeys, needsAnimating }: AnimationTypeState,
    key: string
) {
    const shouldBlock =
        protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true
 
    needsAnimating[key] = false
    return shouldBlock
}