All files / src/motion/utils use-motion-ref.ts

100% Statements 12/12
93.75% Branches 15/16
100% Functions 2/2
100% Lines 12/12

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  33x   33x             33x         1410x   694x   694x 662x         694x 30x 2x 28x 28x                        
import * as React from "react"
import { useCallback } from "react"
import { VisualElement } from "../../render/types"
import { isRefObject } from "../../utils/is-ref-object"
import { VisualState } from "./use-visual-state"
 
/**
 * Creates a ref function that, when called, hydrates the provided
 * external ref and VisualElement.
 */
export function useMotionRef<Instance, RenderState>(
    visualState: VisualState<Instance, RenderState>,
    visualElement?: VisualElement<Instance> | null,
    externalRef?: React.Ref<Instance>
): React.Ref<Instance> {
    return useCallback(
        (instance: Instance) => {
            instance && visualState.mount?.(instance)
 
            if (visualElement) {
                instance
                    ? visualElement.mount(instance)
                    : visualElement.unmount()
            }
 
            if (externalRef) {
                if (typeof externalRef === "function") {
                    externalRef(instance)
                } else Eif (isRefObject(externalRef)) {
                    ;(externalRef as any).current = instance
                }
            }
        },
        /**
         * Only pass a new ref callback to React if we've received a visual element
         * factory. Otherwise we'll be mounting/remounting every time externalRef
         * or other dependencies change.
         */
        [visualElement]
    )
}