All files / src/render/dom/utils unit-conversion.ts

81.76% Statements 121/148
72.94% Branches 62/85
75% Functions 18/24
87.3% Lines 110/126

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 30835x   35x 35x   35x   35x     35x                   386x 35x 249x     35x     12x 12x     35x 23x   35x 35x 35x 35x 35x 35x 35x               35x       35x 70x 2x   2x   2x     2x 2x     2x         35x 35x 700x         4x   4x   68x 68x             4x   4x     35x     6x 6x 8x 8x                         35x         4x 4x 4x 4x 4x       4x                   4x 6x       4x   4x   4x     6x   6x 6x     4x     35x     109x 214x   109x 109x   109x       109x 109x   109x   109x 118x     118x   118x 118x 118x             118x 5x 5x 5x 5x   5x 11x 5x   5x           6x             113x     118x     14x 4x 4x 4x   4x   4x     10x             4x 4x             6x 4x   4x     6x 6x         6x         109x 4x             4x             4x   4x   105x                     35x           249x                  
import { number, px, ValueType } from "style-value-types"
import { Target, TargetWithKeyframes } from "../../../types"
import { isKeyframesTarget } from "../../../animation/utils/is-keyframes-target"
import { invariant } from "hey-listen"
import { MotionValue } from "../../../value"
import { transformProps } from "../../html/utils/transform"
import { ResolvedValues, VisualElement } from "../../types"
import { findDimensionValueType } from "../value-types/dimensions"
import { Box } from "../../../projection/geometry/types"
 
const positionalKeys = new Set([
    "width",
    "height",
    "top",
    "left",
    "right",
    "bottom",
    "x",
    "y",
])
const isPositionalKey = (key: string) => positionalKeys.has(key)
const hasPositionalKey = (target: TargetWithKeyframes) => {
    return Object.keys(target).some(isPositionalKey)
}
 
const setAndResetVelocity = (value: MotionValue, to: string | number) => {
    // Looks odd but setting it twice doesn't render, it'll just
    // set both prev and current to the latest value
    value.set(to, false)
    value.set(to)
}
 
const isNumOrPxType = (v?: ValueType): v is ValueType =>
    v === number || v === px
 
export enum BoundingBoxDimension {
    width = "width",
    height = "height",
    left = "left",
    right = "right",
    top = "top",
    bottom = "bottom",
}
 
type GetActualMeasurementInPixels = (
    bbox: Box,
    computedStyle: Partial<CSSStyleDeclaration>
) => number
 
const getPosFromMatrix = (matrix: string, pos: number) =>
    parseFloat(matrix.split(", ")[pos])
 
const getTranslateFromMatrix =
    (pos2: number, pos3: number): GetActualMeasurementInPixels =>
    (_bbox, { transform }) => {
        Iif (transform === "none" || !transform) return 0
 
        const matrix3d = transform.match(/^matrix3d\((.+)\)$/)
 
        Iif (matrix3d) {
            return getPosFromMatrix(matrix3d[1], pos3)
        } else {
            const matrix = transform.match(/^matrix\((.+)\)$/) as string[]
            Iif (matrix) {
                return getPosFromMatrix(matrix[1], pos2)
            } else {
                return 0
            }
        }
    }
 
const transformKeys = new Set(["x", "y", "z"])
const nonTranslationalTransformKeys = transformProps.filter(
    (key) => !transformKeys.has(key)
)
 
type RemovedTransforms = [string, string | number][]
function removeNonTranslationalTransform(visualElement: VisualElement) {
    const removedTransforms: RemovedTransforms = []
 
    nonTranslationalTransformKeys.forEach((key) => {
        const value: MotionValue<string | number> | undefined =
            visualElement.getValue(key)
        Iif (value !== undefined) {
            removedTransforms.push([key, value.get()])
            value.set(key.startsWith("scale") ? 1 : 0)
        }
    })
 
    // Apply changes to element before measurement
    Iif (removedTransforms.length) visualElement.syncRender()
 
    return removedTransforms
}
 
export const positionalValues: { [key: string]: GetActualMeasurementInPixels } =
    {
        // Dimensions
        width: ({ x }, { paddingLeft = "0", paddingRight = "0" }) =>
            x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight),
        height: ({ y }, { paddingTop = "0", paddingBottom = "0" }) =>
            y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom),
 
        top: (_bbox, { top }) => parseFloat(top as string),
        left: (_bbox, { left }) => parseFloat(left as string),
        bottom: ({ y }, { top }) => parseFloat(top as string) + (y.max - y.min),
        right: ({ x }, { left }) =>
            parseFloat(left as string) + (x.max - x.min),
 
        // Transform
        x: getTranslateFromMatrix(4, 13),
        y: getTranslateFromMatrix(5, 14),
    }
 
const convertChangedValueTypes = (
    target: TargetWithKeyframes,
    visualElement: VisualElement,
    changedKeys: string[]
) => {
    const originBbox = visualElement.measureViewportBox()
    const element = visualElement.getInstance()
    const elementComputedStyle = getComputedStyle(element)
    const { display } = elementComputedStyle
    const origin: ResolvedValues = {}
 
    // If the element is currently set to display: "none", make it visible before
    // measuring the target bounding box
    Iif (display === "none") {
        visualElement.setStaticValue(
            "display",
            (target.display as string) || "block"
        )
    }
 
    /**
     * Record origins before we render and update styles
     */
    changedKeys.forEach((key) => {
        origin[key] = positionalValues[key](originBbox, elementComputedStyle)
    })
 
    // Apply the latest values (as set in checkAndConvertChangedValueTypes)
    visualElement.syncRender()
 
    const targetBbox = visualElement.measureViewportBox()
 
    changedKeys.forEach((key) => {
        // Restore styles to their **calculated computed style**, not their actual
        // originally set style. This allows us to animate between equivalent pixel units.
        const value = visualElement.getValue(key) as MotionValue
 
        setAndResetVelocity(value, origin[key])
        target[key] = positionalValues[key](targetBbox, elementComputedStyle)
    })
 
    return target
}
 
const checkAndConvertChangedValueTypes = (
    visualElement: VisualElement,
    target: TargetWithKeyframes,
    Iorigin: Target = {},
    transitionEnd: Target = {}
): { target: TargetWithKeyframes; transitionEnd: Target } => {
    target = { ...target }
    transitionEnd = { ...transitionEnd }
 
    const targetPositionalKeys = Object.keys(target).filter(isPositionalKey)
 
    // We want to remove any transform values that could affect the element's bounding box before
    // it's measured. We'll reapply these later.
    let removedTransformValues: RemovedTransforms = []
    let hasAttemptedToRemoveTransformValues = false
 
    const changedValueTypeKeys: string[] = []
 
    targetPositionalKeys.forEach((key) => {
        const value = visualElement.getValue(key) as MotionValue<
            number | string
        >
        Iif (!visualElement.hasValue(key)) return
 
        let from = origin[key]
        let fromType = findDimensionValueType(from)
        const to = target[key]
        let toType
 
        // TODO: The current implementation of this basically throws an error
        // if you try and do value conversion via keyframes. There's probably
        // a way of doing this but the performance implications would need greater scrutiny,
        // as it'd be doing multiple resize-remeasure operations.
        if (isKeyframesTarget(to)) {
            const numKeyframes = to.length
            const fromIndex = to[0] === null ? 1 : 0
            from = to[fromIndex]
            fromType = findDimensionValueType(from)
 
            for (let i = fromIndex; i < numKeyframes; i++) {
                if (!toType) {
                    toType = findDimensionValueType(to[i])
 
                    invariant(
                        toType === fromType ||
                            (isNumOrPxType(fromType) && isNumOrPxType(toType)),
                        "Keyframes must be of the same dimension as the current value"
                    )
                } else {
                    invariant(
                        findDimensionValueType(to[i]) === toType,
                        "All keyframes must be of the same type"
                    )
                }
            }
        } else {
            toType = findDimensionValueType(to)
        }
 
        if (fromType !== toType) {
            // If they're both just number or px, convert them both to numbers rather than
            // relying on resize/remeasure to convert (which is wasteful in this situation)
            if (isNumOrPxType(fromType) && isNumOrPxType(toType)) {
                const current = value.get()
                Eif (typeof current === "string") {
                    value.set(parseFloat(current))
                }
                Iif (typeof to === "string") {
                    target[key] = parseFloat(to)
                } else Iif (Array.isArray(to) && toType === px) {
                    target[key] = to.map(parseFloat)
                }
            } else if (
                fromType?.transform &&
                toType?.transform &&
                (from === 0 || to === 0)
            ) {
                // If one or the other value is 0, it's safe to coerce it to the
                // type of the other without measurement
                Eif (from === 0) {
                    value.set((toType as any).transform(from))
                } else {
                    target[key] = (fromType as any).transform(to)
                }
            } else {
                // If we're going to do value conversion via DOM measurements, we first
                // need to remove non-positional transform values that could affect the bbox measurements.
                if (!hasAttemptedToRemoveTransformValues) {
                    removedTransformValues =
                        removeNonTranslationalTransform(visualElement)
                    hasAttemptedToRemoveTransformValues = true
                }
 
                changedValueTypeKeys.push(key)
                transitionEnd[key] =
                    transitionEnd[key] !== undefined
                        ? transitionEnd[key]
                        : target[key]
 
                setAndResetVelocity(value, to)
            }
        }
    })
 
    if (changedValueTypeKeys.length) {
        const convertedTarget = convertChangedValueTypes(
            target,
            visualElement,
            changedValueTypeKeys
        )
 
        // If we removed transform values, reapply them before the next render
        Iif (removedTransformValues.length) {
            removedTransformValues.forEach(([key, value]) => {
                visualElement.getValue(key)!.set(value)
            })
        }
 
        // Reapply original values
        visualElement.syncRender()
 
        return { target: convertedTarget, transitionEnd }
    } else {
        return { target, transitionEnd }
    }
}
 
/**
 * Convert value types for x/y/width/height/top/left/bottom/right
 *
 * Allows animation between `'auto'` -> `'100%'` or `0` -> `'calc(50% - 10vw)'`
 *
 * @internal
 */
export function unitConversion(
    visualElement: VisualElement,
    target: TargetWithKeyframes,
    origin?: Target,
    transitionEnd?: Target
): { target: TargetWithKeyframes; transitionEnd?: Target } {
    return hasPositionalKey(target)
        ? checkAndConvertChangedValueTypes(
              visualElement,
              target,
              origin,
              transitionEnd
          )
        : { target, transitionEnd }
}