import { jsx as _jsx } from "react/jsx-runtime";
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useEffectOnce } from 'react-use';
import { useRafThrottle } from "../../hooks/use-raf-throttle.js";
import { FloatingPlusButton, } from "../FloatingPlusButton/index.js";
export const FloatingPlusControl = memo(function YfmTableRowFloatingPlusControl({ type, index, cellElem, tableElem, onClick }) {
    const anchor = useMemo(() => ({
        contextElement: tableElem,
        getBoundingClientRect() {
            const cellRect = cellElem.getBoundingClientRect();
            const tableRect = tableElem.getBoundingClientRect();
            return type === 'row'
                ? {
                    x: tableRect.x,
                    y: cellRect.y,
                    width: tableRect.width,
                    height: cellRect.height,
                    top: cellRect.top,
                    left: tableRect.left,
                    right: tableRect.right,
                    bottom: cellRect.top,
                }
                : {
                    x: cellRect.x,
                    y: tableRect.y,
                    width: cellRect.width,
                    height: tableRect.height,
                    top: tableRect.top,
                    left: cellRect.left,
                    right: cellRect.right,
                    bottom: tableRect.top,
                };
        },
    }), [cellElem, tableElem, type]);
    const [visible, setVisible] = useState(() => shouldBeVisible(type, cellElem, tableElem));
    const buttonRef = useRef(null);
    const updateVisibility = () => {
        const newVisible = shouldBeVisible(type, cellElem, tableElem);
        if (visible !== newVisible)
            setVisible(newVisible);
    };
    const onChange = useRafThrottle(() => {
        buttonRef.current?.forceUpdate();
        updateVisibility();
    });
    // Update after first render
    useEffectOnce(updateVisibility);
    useEffect(() => {
        if (type !== 'column')
            return undefined;
        const observer = new ResizeObserver(onChange);
        observer.observe(tableElem);
        tableElem.addEventListener('scroll', onChange);
        return () => {
            observer.unobserve(tableElem);
            tableElem.removeEventListener('scroll', onChange);
        };
    }, [tableElem, onChange, type]);
    return (_jsx(FloatingPlusButton, { ref: buttonRef, anchor: anchor, type: type, onClick: () => onClick(index), floatingStyles: visible ? undefined : { display: 'none' } }));
});
function shouldBeVisible(type, cellElem, tableElem) {
    if (type !== 'column')
        return true;
    const THRESHOLD = 4; // px
    const cellRect = cellElem.getBoundingClientRect();
    const tableRect = tableElem.getBoundingClientRect();
    return (tableRect.left - cellRect.right <= THRESHOLD &&
        cellRect.right - tableRect.right <= THRESHOLD);
}
//# sourceMappingURL=FloatingPlusControl.js.map
