getTransformHandleFun

PHOTO EMBED

Mon Sep 02 2024 11:25:47 GMT+0000 (Coordinated Universal Time)

Saved by @vasttininess #javascript

function getTransformHandleFun(ele) {
    if (!(ele instanceof HTMLElement || ele instanceof Node)) throw new Error("Note element or node");
    const clamp = (value, min, max) => {
        if (typeof min === "number" && typeof max === "number") {
            return Math.min(Math.max(value, min), max);
        } else if (typeof min === "number" && typeof max !== "number") {
            return Math.max(value, min)
        } else if (typeof min !== "number" && typeof max === "number") {
            return Math.min(value, max)
        }
        return value
    }

    const setTranslate = (options) => {
        if (typeof options === "function") options = options();
        const { isDeff = true } = options;
        const o = { value: 0 }, _ = isDeff ? o : { value: 1 };
        const { dA = _, dB = o, dC = o, dD = _, dTx = o, dTy = o } = options;
        console.log(dA, dB);

        const style = getComputedStyle(ele);
        let transform = style.transform || style.webkitTransform || style.mozTransform;
        if (transform === 'none') transform = "matrix(1, 0, 0, 1, 0, 0)";

        if (transform) {
            const matrixValues = transform.match(/^matrix.*\((.+)\)$/);
            if (!matrixValues) return "matrix(1, 0, 0, 1, 0, 0)";
            const vals = matrixValues[1].split(', ').map(Number);
            const arr = [dA, dB, dC, dD, dTx, dTy];
            while (vals.length < 6) vals.push(0);
            let getVal = isDeff ? (i) => +arr[i].value + vals[i] : (i) => +arr[i].value;
            for (let i = 0; i < vals.length; i++) {
                vals.splice(i, 1, clamp(getVal(i), arr[i].min, arr[i].max))
            }
            transform = `matrix(${vals})`;
        }

        return transform;
    }

    return (options) => {
        ele.style.transform = setTranslate(options);
        return ele;
    }
};
content_copyCOPY