All files / src/components/AnimatePresence index.tsx

95.45% Statements 84/88
82.98% Branches 39/47
100% Functions 14/14
97.47% Lines 77/79

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 26331x                   31x   31x 31x 31x         666x               224x   224x 150x   150x 150x           150x     150x         224x     224x 224x     224x                                                                       31x 226x 224x 224x 224x 224x 224x       224x 224x 224x   224x   224x 224x 27x 24x           224x       224x     224x         224x   224x       224x 54x   54x   54x                             170x       170x 170x     170x 170x 180x 180x 102x     78x           170x 12x         170x   102x   102x 102x   102x   102x 23x 23x     23x 23x   23x     23x 21x 21x 4x   17x 17x       102x                                 170x 186x 186x                         170x   170x                   170x       60x        
import {
    useEffect,
    useRef,
    isValidElement,
    cloneElement,
    Children,
    ReactElement,
    ReactNode,
    useContext,
} from "react"
import * as React from "react"
import { AnimatePresenceProps } from "./types"
import { useForceUpdate } from "../../utils/use-force-update"
import { PresenceChild } from "./PresenceChild"
import { LayoutGroupContext } from "../../context/LayoutGroupContext"
 
type ComponentKey = string | number
 
function getChildKey(child: ReactElement<any>): ComponentKey {
    return child.key || ""
}
 
function updateChildLookup(
    children: ReactElement<any>[],
    allChildren: Map<ComponentKey, ReactElement<any>>
) {
    const seenChildren =
        process.env.NODE_ENV !== "production" ? new Set<ComponentKey>() : null
 
    children.forEach((child) => {
        const key = getChildKey(child)
 
        Eif (process.env.NODE_ENV !== "production" && seenChildren) {
            Iif (seenChildren.has(key)) {
                console.warn(
                    `Children of AnimatePresence require unique keys. "${key}" is a duplicate.`
                )
            }
 
            seenChildren.add(key)
        }
 
        allChildren.set(key, child)
    })
}
 
function onlyElements(children: ReactNode): ReactElement<any>[] {
    const filtered: ReactElement<any>[] = []
 
    // We use forEach here instead of map as map mutates the component key by preprending `.$`
    Children.forEach(children, (child) => {
        if (isValidElement(child)) filtered.push(child)
    })
 
    return filtered
}
 
/**
 * `AnimatePresence` enables the animation of components that have been removed from the tree.
 *
 * When adding/removing more than a single child, every child **must** be given a unique `key` prop.
 *
 * Any `motion` components that have an `exit` property defined will animate out when removed from
 * the tree.
 *
 * ```jsx
 * import { motion, AnimatePresence } from 'framer-motion'
 *
 * export const Items = ({ items }) => (
 *   <AnimatePresence>
 *     {items.map(item => (
 *       <motion.div
 *         key={item.id}
 *         initial={{ opacity: 0 }}
 *         animate={{ opacity: 1 }}
 *         exit={{ opacity: 0 }}
 *       />
 *     ))}
 *   </AnimatePresence>
 * )
 * ```
 *
 * You can sequence exit animations throughout a tree using variants.
 *
 * If a child contains multiple `motion` components with `exit` props, it will only unmount the child
 * once all `motion` components have finished animating out. Likewise, any components using
 * `usePresence` all need to call `safeToRemove`.
 *
 * @public
 */
export const AnimatePresence: React.FunctionComponent<AnimatePresenceProps> = ({
    children,
    custom,
    initial = true,
    onExitComplete,
    exitBeforeEnter,
    presenceAffectsLayout = true,
}) => {
    // We want to force a re-render once all exiting animations have finished. We
    // either use a local forceRender function, or one from a parent context if it exists.
    let [forceRender] = useForceUpdate()
    const forceRenderLayoutGroup = useContext(LayoutGroupContext).forceRender
    if (forceRenderLayoutGroup) forceRender = forceRenderLayoutGroup
 
    const isInitialRender = useRef(true)
 
    const isMounted = useRef(true)
    useEffect(
        () => () => {
            isMounted.current = false
        },
        []
    )
 
    // Filter out any children that aren't ReactElements. We can only track ReactElements with a props.key
    const filteredChildren = onlyElements(children)
 
    // Keep a living record of the children we're actually rendering so we
    // can diff to figure out which are entering and exiting
    const presentChildren = useRef(filteredChildren)
 
    // A lookup table to quickly reference components by key
    const allChildren = useRef(
        new Map<ComponentKey, ReactElement<any>>()
    ).current
 
    // A living record of all currently exiting components.
    const exiting = useRef(new Set<ComponentKey>()).current
 
    updateChildLookup(filteredChildren, allChildren)
 
    // If this is the initial component render, just deal with logic surrounding whether
    // we play onMount animations or not.
    if (isInitialRender.current) {
        isInitialRender.current = false
 
        return (
            <>
                {filteredChildren.map((child) => (
                    <PresenceChild
                        key={getChildKey(child)}
                        isPresent
                        initial={initial ? undefined : false}
                        presenceAffectsLayout={presenceAffectsLayout}
                    >
                        {child}
                    </PresenceChild>
                ))}
            </>
        )
    }
 
    // If this is a subsequent render, deal with entering and exiting children
    let childrenToRender = [...filteredChildren]
 
    // Diff the keys of the currently-present and target children to update our
    // exiting list.
    const presentKeys = presentChildren.current.map(getChildKey)
    const targetKeys = filteredChildren.map(getChildKey)
 
    // Diff the present children with our target children and mark those that are exiting
    const numPresent = presentKeys.length
    for (let i = 0; i < numPresent; i++) {
        const key = presentKeys[i]
        if (targetKeys.indexOf(key) === -1) {
            exiting.add(key)
        } else {
            // In case this key has re-entered, remove from the exiting list
            exiting.delete(key)
        }
    }
 
    // If we currently have exiting children, and we're deferring rendering incoming children
    // until after all current children have exiting, empty the childrenToRender array
    if (exitBeforeEnter && exiting.size) {
        childrenToRender = []
    }
 
    // Loop through all currently exiting components and clone them to overwrite `animate`
    // with any `exit` prop they might have defined.
    exiting.forEach((key) => {
        // If this component is actually entering again, early return
        Iif (targetKeys.indexOf(key) !== -1) return
 
        const child = allChildren.get(key)
        Iif (!child) return
 
        const insertionIndex = presentKeys.indexOf(key)
 
        const onExit = () => {
            allChildren.delete(key)
            exiting.delete(key)
 
            // Remove this child from the present children
            const removeIndex = presentChildren.current.findIndex(
                (presentChild) => presentChild.key === key
            )
            presentChildren.current.splice(removeIndex, 1)
 
            // Defer re-rendering until all exiting children have indeed left
            if (!exiting.size) {
                presentChildren.current = filteredChildren
                if (isMounted.current === false) {
                    return
                }
                forceRender()
                onExitComplete && onExitComplete()
            }
        }
 
        childrenToRender.splice(
            insertionIndex,
            0,
            <PresenceChild
                key={getChildKey(child)}
                isPresent={false}
                onExitComplete={onExit}
                custom={custom}
                presenceAffectsLayout={presenceAffectsLayout}
            >
                {child}
            </PresenceChild>
        )
    })
 
    // Add `MotionContext` even to children that don't need it to ensure we're rendering
    // the same tree between renders
    childrenToRender = childrenToRender.map((child) => {
        const key = child.key as string | number
        return exiting.has(key) ? (
            child
        ) : (
            <PresenceChild
                key={getChildKey(child)}
                isPresent
                presenceAffectsLayout={presenceAffectsLayout}
            >
                {child}
            </PresenceChild>
        )
    })
 
    presentChildren.current = childrenToRender
 
    Iif (
        process.env.NODE_ENV !== "production" &&
        exitBeforeEnter &&
        childrenToRender.length > 1
    ) {
        console.warn(
            `You're attempting to animate multiple children within AnimatePresence, but its exitBeforeEnter prop is set to true. This will lead to odd visual behaviour.`
        )
    }
 
    return (
        <>
            {exiting.size
                ? childrenToRender
                : childrenToRender.map((child) => cloneElement(child))}
        </>
    )
}