"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InsertCursor = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
// eslint-disable-next-line import/no-extraneous-dependencies
const dom_1 = require("@floating-ui/dom");
const uikit_1 = require("@gravity-ui/uikit");
const react_use_1 = require("react-use");
const react_utils_1 = require("../../../../../../../react-utils/index.js");
const placementByType = {
    row: 'bottom-start',
    column: 'right-start',
};
const InsertCursor = function YfmTableInsertCursor({ type, anchor: referenceEl, }) {
    const [floatingEl, setFloatingEl] = (0, react_utils_1.useElementState)();
    const { width, height, updateRect } = useSize(type, () => referenceEl.getBoundingClientRect());
    const widhtRef = (0, react_use_1.useLatest)(width);
    const [floatingStyles, setFloatingStyles] = (0, react_1.useState)({ top: -9999, left: -9999 });
    (0, react_1.useEffect)(() => {
        if (referenceEl && floatingEl) {
            return (0, dom_1.autoUpdate)(referenceEl, floatingEl, () => {
                updateRect(referenceEl.getBoundingClientRect());
                (0, dom_1.computePosition)(referenceEl, floatingEl, {
                    placement: placementByType[type],
                }).then(({ x, y }) => {
                    if (type === 'row')
                        setFloatingStyles({ left: x, top: y - 1 });
                    else
                        setFloatingStyles({ left: x - 1, top: y });
                });
            });
        }
        return undefined;
    }, [referenceEl, floatingEl, widhtRef, type, updateRect]);
    return ((0, jsx_runtime_1.jsx)(uikit_1.Portal, { children: (0, jsx_runtime_1.jsx)("div", { ref: setFloatingEl, style: {
                position: 'absolute',
                zIndex: 1005,
                width,
                height,
                pointerEvents: 'auto',
                outline: 'none',
                backgroundColor: 'var(--g-color-line-brand)',
                ...floatingStyles,
            } }) }));
};
exports.InsertCursor = InsertCursor;
function useSize(type, getRect) {
    const [size, setSize] = (0, react_1.useState)(() => getSize(type, getRect()));
    const sizeRef = (0, react_use_1.useLatest)(size);
    return {
        width: size.width,
        height: size.height,
        updateRect: (0, react_1.useCallback)((rect) => {
            const newSize = getSize(type, rect);
            if (type === 'row' && newSize.width !== sizeRef.current.width)
                setSize(newSize);
            if (type === 'column' && newSize.height !== sizeRef.current.height)
                setSize(newSize);
        }, [sizeRef, type]),
    };
}
function getSize(type, rect) {
    if (type === 'row')
        return { height: 2, width: rect.width };
    return { width: 2, height: rect.height };
}
//# sourceMappingURL=InsertCursor.js.map
