import { Fragment, jsx } from "react/jsx-runtime";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { Popover } from "antd";
const getContentWidth = (element)=>{
    if (element) {
        const range = document.createRange();
        range.selectNodeContents(element);
        const contentWidth = range.getBoundingClientRect().width;
        return contentWidth;
    }
};
const ellipsisDefaultStyle = {
    overflow: 'hidden',
    overflowWrap: 'break-word',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    wordBreak: 'break-all'
};
const EllipsisWithTooltip = /*#__PURE__*/ forwardRef((props, ref)=>{
    const [ellipsis, setEllipsis] = useState(false);
    const [visible, setVisible] = useState(false);
    const elRef = useRef();
    useImperativeHandle(ref, ()=>({
            setPopoverVisible: setVisible
        }));
    if (!props.ellipsis) return /*#__PURE__*/ jsx(Fragment, {
        children: props.children
    });
    const { popoverContent } = props;
    const isOverflowTooltip = ()=>{
        var _elRef_current;
        const contentWidth = getContentWidth(elRef.current);
        const offsetWidth = null == (_elRef_current = elRef.current) ? void 0 : _elRef_current.offsetWidth;
        return contentWidth > offsetWidth;
    };
    return /*#__PURE__*/ jsx(Popover, {
        open: ellipsis && visible,
        onOpenChange: (visible)=>{
            setVisible(ellipsis && visible);
        },
        content: /*#__PURE__*/ jsx("div", {
            style: {
                width: 300,
                overflow: 'auto',
                maxHeight: 400
            },
            children: popoverContent || props.children
        }),
        children: /*#__PURE__*/ jsx("div", {
            ref: elRef,
            style: {
                ...ellipsisDefaultStyle
            },
            onMouseEnter: (e)=>{
                const el = e.target;
                const isShowTooltips = isOverflowTooltip();
                if (isShowTooltips) setEllipsis(el.scrollWidth >= el.clientWidth);
            },
            children: props.children
        })
    });
});
EllipsisWithTooltip.displayName = 'EllipsisWithTooltip';
export { EllipsisWithTooltip };
