import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2007-2026 GoodData Corporation
import { Children, Component, cloneElement, createRef, } from "react";
import cx from "classnames";
import { pickBy, throttle } from "lodash-es";
import { elementRegion } from "../utils/domUtilities.js";
/**
 * @internal
 */
export class FlexDimensions extends Component {
    static defaultProps = {
        children: false,
        className: "",
        measureWidth: true,
        measureHeight: true,
    };
    wrapperRef = createRef();
    throttledUpdateSize;
    resizeObserver;
    constructor(props) {
        super(props);
        this.state = {
            width: 0,
            height: 0,
        };
        this.throttledUpdateSize = throttle(this.updateSize, 250, { leading: false });
        this.resizeObserver = new ResizeObserver(this.throttledUpdateSize);
    }
    componentDidMount() {
        if (this.wrapperRef.current) {
            this.resizeObserver.observe(this.wrapperRef.current);
        }
        this.throttledUpdateSize();
    }
    componentWillUnmount() {
        this.throttledUpdateSize.cancel();
        this.resizeObserver.disconnect();
    }
    getChildrenDimensions() {
        return pickBy(this.state, (_, key) => {
            const setWidth = this.props.measureWidth && key === "width";
            const setHeight = this.props.measureHeight && key === "height";
            return setWidth || setHeight;
        });
    }
    updateSize = () => {
        if (!this.wrapperRef.current) {
            return;
        }
        const { width, height } = elementRegion(this.wrapperRef.current);
        this.setState({
            width,
            height,
        });
    };
    renderChildren() {
        const child = Children.only(this.props.children);
        return cloneElement(child, this.getChildrenDimensions());
    }
    render() {
        const classNames = cx(this.props.className);
        return (_jsx("div", { ref: this.wrapperRef, className: classNames, children: this.renderChildren() }));
    }
}
