All files / src/render/utils animation-state.ts

99.15% Statements 116/117
96.88% Branches 93/96
94.12% Functions 16/17
99.07% Lines 107/108

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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 43736x 36x     36x   36x         36x 36x                                               36x                   36x 36x     240x 214x 217x 217x         36x     240x 240x 240x 240x           240x       599x   599x 1130x 565x     599x                       39x                                 592x 592x           592x           592x             592x           592x               4144x 4144x 4144x 4144x 4144x             4144x   4144x                 4144x         4144x         2x             4144x     4144x                                 595x           595x                         595x           595x         595x                     595x 595x       595x 292x 292x 292x     595x 607x 607x     607x         519x         315x 7x 3x           4x   308x   281x     27x   204x         8x           196x               595x 595x         595x 572x     595x 3x               595x 242x 245x               592x             592x 19x 19x 19x 19x 19x       19x     592x   592x         16x     592x 592x                       109x     81x 9x     81x   81x     240x         277x       36x 598x 220x 378x 15x     363x                     3120x 1680x                 240x                    
import { isAnimationControls } from "../../animation/utils/is-animation-controls"
import { isKeyframesTarget } from "../../animation/utils/is-keyframes-target"
import { VariantLabels } from "../../motion/types"
import { TargetAndTransition } from "../../types"
import { shallowCompare } from "../../utils/shallow-compare"
import { VisualElement } from "../types"
import {
    animateVisualElement,
    AnimationDefinition,
    AnimationOptions,
} from "./animation"
import { AnimationType } from "./types"
import { isVariantLabel, isVariantLabels, resolveVariant } from "./variants"
 
export interface AnimationState {
    animateChanges: (
        options?: AnimationOptions,
        type?: AnimationType
    ) => Promise<any>
    setActive: (
        type: AnimationType,
        isActive: boolean,
        options?: AnimationOptions
    ) => Promise<any>
    setAnimateFunction: (fn: any) => void
    isAnimated(key: string): boolean
    getState: () => { [key: string]: AnimationTypeState }
}
 
interface DefinitionAndOptions {
    animation: AnimationDefinition
    options?: AnimationOptions
}
 
export type AnimationList = string[] | TargetAndTransition[]
 
export const variantPriorityOrder = [
    AnimationType.Animate,
    AnimationType.InView,
    AnimationType.Focus,
    AnimationType.Hover,
    AnimationType.Tap,
    AnimationType.Drag,
    AnimationType.Exit,
]
 
const reversePriorityOrder = [...variantPriorityOrder].reverse()
const numAnimationTypes = variantPriorityOrder.length
 
function animateList(visualElement: VisualElement) {
    return (animations: DefinitionAndOptions[]) =>
        Promise.all(
            animations.map(({ animation, options }) =>
                animateVisualElement(visualElement, animation, options)
            )
        )
}
 
export function createAnimationState(
    visualElement: VisualElement
): AnimationState {
    let animate = animateList(visualElement)
    const state = createState()
    let allAnimatedKeys = {}
    let isInitialRender = true
 
    /**
     * This function will be used to reduce the animation definitions for
     * each active animation type into an object of resolved values for it.
     */
    const buildResolvedTypeValues = (
        acc: { [key: string]: any },
        definition: string | TargetAndTransition | undefined
    ) => {
        const resolved = resolveVariant(visualElement, definition)
 
        if (resolved) {
            const { transition, transitionEnd, ...target } = resolved
            acc = { ...acc, ...target, ...transitionEnd }
        }
 
        return acc
    }
 
    function isAnimated(key: string) {
        return allAnimatedKeys[key] !== undefined
    }
 
    /**
     * This just allows us to inject mocked animation functions
     * @internal
     */
    function setAnimateFunction(makeAnimator: typeof animateList) {
        animate = makeAnimator(visualElement)
    }
 
    /**
     * When we receive new props, we need to:
     * 1. Create a list of protected keys for each type. This is a directory of
     *    value keys that are currently being "handled" by types of a higher priority
     *    so that whenever an animation is played of a given type, these values are
     *    protected from being animated.
     * 2. Determine if an animation type needs animating.
     * 3. Determine if any values have been removed from a type and figure out
     *    what to animate those to.
     */
    function animateChanges(
        options?: AnimationOptions,
        changedActiveType?: AnimationType
    ) {
        const props = visualElement.getProps()
        const context = visualElement.getVariantContext(true) || {}
 
        /**
         * A list of animations that we'll build into as we iterate through the animation
         * types. This will get executed at the end of the function.
         */
        const animations: DefinitionAndOptions[] = []
 
        /**
         * Keep track of which values have been removed. Then, as we hit lower priority
         * animation types, we can check if they contain removed values and animate to that.
         */
        const removedKeys = new Set<string>()
 
        /**
         * A dictionary of all encountered keys. This is an object to let us build into and
         * copy it without iteration. Each time we hit an animation type we set its protected
         * keys - the keys its not allowed to animate - to the latest version of this object.
         */
        let encounteredKeys = {}
 
        /**
         * If a variant has been removed at a given index, and this component is controlling
         * variant animations, we want to ensure lower-priority variants are forced to animate.
         */
        let removedVariantIndex = Infinity
 
        /**
         * Iterate through all animation types in reverse priority order. For each, we want to
         * detect which values it's handling and whether or not they've changed (and therefore
         * need to be animated). If any values have been removed, we want to detect those in
         * lower priority props and flag for animation.
         */
        for (let i = 0; i < numAnimationTypes; i++) {
            const type = reversePriorityOrder[i]
            const typeState = state[type]
            const prop = props[type] ?? context[type]
            const propIsVariant = isVariantLabel(prop)
 
            /**
             * If this type has *just* changed isActive status, set activeDelta
             * to that status. Otherwise set to null.
             */
            const activeDelta =
                type === changedActiveType ? typeState.isActive : null
 
            if (activeDelta === false) removedVariantIndex = i
 
            /**
             * If this prop is an inherited variant, rather than been set directly on the
             * component itself, we want to make sure we allow the parent to trigger animations.
             *
             * TODO: Can probably change this to a !isControllingVariants check
             */
            let isInherited =
                prop === context[type] && prop !== props[type] && propIsVariant
 
            /**
             *
             */
            if (
                isInherited &&
                isInitialRender &&
                visualElement.manuallyAnimateOnMount
            ) {
                isInherited = false
            }
 
            /**
             * Set all encountered keys so far as the protected keys for this type. This will
             * be any key that has been animated or otherwise handled by active, higher-priortiy types.
             */
            typeState.protectedKeys = { ...encounteredKeys }
 
            // Check if we can skip analysing this prop early
            if (
                // If it isn't active and hasn't *just* been set as inactive
                (!typeState.isActive && activeDelta === null) ||
                // If we didn't and don't have any defined prop for this animation type
                (!prop && !typeState.prevProp) ||
                // Or if the prop doesn't define an animation
                isAnimationControls(prop) ||
                typeof prop === "boolean"
            ) {
                continue
            }
 
            /**
             * As we go look through the values defined on this type, if we detect
             * a changed value or a value that was removed in a higher priority, we set
             * this to true and add this prop to the animation list.
             */
            const variantDidChange = checkVariantsDidChange(
                typeState.prevProp,
                prop
            )
 
            let shouldAnimateType =
                variantDidChange ||
                // If we're making this variant active, we want to always make it active
                (type === changedActiveType &&
                    typeState.isActive &&
                    !isInherited &&
                    propIsVariant) ||
                // If we removed a higher-priority variant (i is in reverse order)
                (i > removedVariantIndex && propIsVariant)
 
            /**
             * As animations can be set as variant lists, variants or target objects, we
             * coerce everything to an array if it isn't one already
             */
            const definitionList = Array.isArray(prop) ? prop : [prop]
 
            /**
             * Build an object of all the resolved values. We'll use this in the subsequent
             * animateChanges calls to determine whether a value has changed.
             */
            let resolvedValues = definitionList.reduce(
                buildResolvedTypeValues,
                {}
            )
 
            if (activeDelta === false) resolvedValues = {}
 
            /**
             * Now we need to loop through all the keys in the prev prop and this prop,
             * and decide:
             * 1. If the value has changed, and needs animating
             * 2. If it has been removed, and needs adding to the removedKeys set
             * 3. If it has been removed in a higher priority type and needs animating
             * 4. If it hasn't been removed in a higher priority but hasn't changed, and
             *    needs adding to the type's protectedKeys list.
             */
            const { prevResolvedValues = {} } = typeState
            const allKeys = {
                ...prevResolvedValues,
                ...resolvedValues,
            }
            const markToAnimate = (key: string) => {
                shouldAnimateType = true
                removedKeys.delete(key)
                typeState.needsAnimating[key] = true
            }
 
            for (const key in allKeys) {
                const next = resolvedValues[key]
                const prev = prevResolvedValues[key]
 
                // If we've already handled this we can just skip ahead
                if (encounteredKeys.hasOwnProperty(key)) continue
 
                /**
                 * If the value has changed, we probably want to animate it.
                 */
                if (next !== prev) {
                    /**
                     * If both values are keyframes, we need to shallow compare them to
                     * detect whether any value has changed. If it has, we animate it.
                     */
                    if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
                        if (!shallowCompare(next, prev) || variantDidChange) {
                            markToAnimate(key)
                        } else {
                            /**
                             * If it hasn't changed, we want to ensure it doesn't animate by
                             * adding it to the list of protected keys.
                             */
                            typeState.protectedKeys[key] = true
                        }
                    } else if (next !== undefined) {
                        // If next is defined and doesn't equal prev, it needs animating
                        markToAnimate(key)
                    } else {
                        // If it's undefined, it's been removed.
                        removedKeys.add(key)
                    }
                } else if (next !== undefined && removedKeys.has(key)) {
                    /**
                     * If next hasn't changed and it isn't undefined, we want to check if it's
                     * been removed by a higher priority
                     */
                    markToAnimate(key)
                } else {
                    /**
                     * If it hasn't changed, we add it to the list of protected values
                     * to ensure it doesn't get animated.
                     */
                    typeState.protectedKeys[key] = true
                }
            }
 
            /**
             * Update the typeState so next time animateChanges is called we can compare the
             * latest prop and resolvedValues to these.
             */
            typeState.prevProp = prop
            typeState.prevResolvedValues = resolvedValues
 
            /**
             *
             */
            if (typeState.isActive) {
                encounteredKeys = { ...encounteredKeys, ...resolvedValues }
            }
 
            if (isInitialRender && visualElement.blockInitialAnimation) {
                shouldAnimateType = false
            }
 
            /**
             * If this is an inherited prop we want to hard-block animations
             * TODO: Test as this should probably still handle animations triggered
             * by removed values?
             */
            if (shouldAnimateType && !isInherited) {
                animations.push(
                    ...definitionList.map((animation) => ({
                        animation: animation as AnimationDefinition,
                        options: { type, ...options },
                    }))
                )
            }
        }
 
        allAnimatedKeys = { ...encounteredKeys }
 
        /**
         * If there are some removed value that haven't been dealt with,
         * we need to create a new animation that falls back either to the value
         * defined in the style prop, or the last read value.
         */
        if (removedKeys.size) {
            const fallbackAnimation = {}
            removedKeys.forEach((key) => {
                const fallbackTarget = visualElement.getBaseTarget(key)
                Eif (fallbackTarget !== undefined) {
                    fallbackAnimation[key] = fallbackTarget
                }
            })
 
            animations.push({ animation: fallbackAnimation })
        }
 
        let shouldAnimate = Boolean(animations.length)
 
        if (
            isInitialRender &&
            props.initial === false &&
            !visualElement.manuallyAnimateOnMount
        ) {
            shouldAnimate = false
        }
 
        isInitialRender = false
        return shouldAnimate ? animate(animations) : Promise.resolve()
    }
 
    /**
     * Change whether a certain animation type is active.
     */
    function setActive(
        type: AnimationType,
        isActive: boolean,
        options?: AnimationOptions
    ) {
        // If the active state hasn't changed, we can safely do nothing here
        if (state[type].isActive === isActive) return Promise.resolve()
 
        // Propagate active change to children
        visualElement.variantChildren?.forEach((child) =>
            child.animationState?.setActive(type, isActive)
        )
 
        state[type].isActive = isActive
 
        return animateChanges(options, type)
    }
 
    return {
        isAnimated,
        animateChanges,
        setActive,
        setAnimateFunction,
        getState: () => state,
    }
}
 
export function checkVariantsDidChange(prev: any, next: any) {
    if (typeof next === "string") {
        return next !== prev
    } else if (isVariantLabels(next)) {
        return !shallowCompare(next, prev)
    }
 
    return false
}
 
export interface AnimationTypeState {
    isActive: boolean
    protectedKeys: { [key: string]: true }
    needsAnimating: { [key: string]: boolean }
    prevResolvedValues: { [key: string]: any }
    prevProp?: VariantLabels | TargetAndTransition
}
 
function createTypeState(isActive = false): AnimationTypeState {
    return {
        isActive,
        protectedKeys: {},
        needsAnimating: {},
        prevResolvedValues: {},
    }
}
 
function createState() {
    return {
        [AnimationType.Animate]: createTypeState(true),
        [AnimationType.InView]: createTypeState(),
        [AnimationType.Hover]: createTypeState(),
        [AnimationType.Tap]: createTypeState(),
        [AnimationType.Drag]: createTypeState(),
        [AnimationType.Focus]: createTypeState(),
        [AnimationType.Exit]: createTypeState(),
    }
}