"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CSSNumericVariableWatch = exports.useCSSVariableWatch = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const ResizeObserver_1 = require("../ResizeObserver");
const WRAPPER_STYLE = {
    position: 'absolute',
    pointerEvents: 'none',
    width: 0,
    height: 0,
    lineHeight: 0,
    fontSize: 0,
    overflow: 'hidden',
};
const useCSSVariableWatch = (params) => {
    const lastValueRef = (0, react_1.useRef)(0);
    const onResize = React.useCallback(({ height }) => {
        if (height != null && height !== lastValueRef.current) {
            lastValueRef.current = height;
            params.onChange(height);
        }
    }, [params.onChange]);
    (0, ResizeObserver_1.useResizeObserver)(params.ref, onResize, { earlyAttach: true });
    React.useLayoutEffect(() => {
        const value = params.ref.current.getBoundingClientRect().height;
        if (value != null) {
            lastValueRef.current = value;
            return params.onChange(value);
        }
        else {
            console.warn(`Specified variable ${params.varName} not found or does not have a numeric value.`);
        }
    }, []);
};
exports.useCSSVariableWatch = useCSSVariableWatch;
const CSSNumericVariableWatch = (props) => {
    const domRef = (0, react_1.useRef)(null);
    (0, exports.useCSSVariableWatch)({
        ...props,
        ref: domRef,
    });
    const height = props.varName.startsWith('var(') ? props.varName : `var(${props.varName})`;
    const { allowInts = false } = props;
    return (React.createElement("div", { "data-name": "css-variable-watcher", "data-var": props.varName, style: WRAPPER_STYLE },
        React.createElement("div", { ref: domRef, style: {
                height: allowInts ? `calc(1px * ${height})` : height, // we do multiplication in order to support integer (without px) values as well
            } })));
};
exports.CSSNumericVariableWatch = CSSNumericVariableWatch;
