var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React from 'react';
import { createPortal } from 'react-dom';
import c from 'classnames';
import { debounce, pick } from 'lodash-es';
import { getScrollParents } from '@floating-ui/dom';
import { ArrowUpOutlined, ArrowDownOutlined, DragOutlined, DeleteOutlined } from '@ant-design/icons';
import { css } from '../utils/emotion-css';
import usePersistFn from '@rcp/use.persistfn';
import { Button } from 'antd';
import { useProxyEvents } from './dom-api';
import { PreventFastClick } from '@rcp/c.preventfastop';
import MoreButton from './components/more-button';
import { useDrag } from 'react-dnd';
import { getSharedFromMain } from '../utils/get-from-main';
import { globalGetContainer } from '../config/backlist-dom';
const { api } = getSharedFromMain();
function usePosition(dom) {
    const [data, setData] = React.useState({ isReady: false, rect: { width: 0, height: 0, x: 0, y: 0 } });
    const [shouldHide, setShouldHide] = React.useState(false);
    React.useEffect(() => {
        if (!dom) {
            return;
        }
        const updatePos = () => {
            const rect = dom.getBoundingClientRect();
            setData({ rect, isReady: true });
        };
        updatePos();
        const parents = getScrollParents(dom);
        const reset = debounce(() => {
            setShouldHide(false);
            updatePos();
        }, 500);
        const debouncedUpdate = () => {
            setShouldHide(true);
            reset();
        };
        parents.forEach((par) => {
            par.addEventListener('resize', debouncedUpdate);
            par.addEventListener('scroll', debouncedUpdate);
        });
        return () => {
            parents.forEach((par) => {
                par.removeEventListener('resize', debouncedUpdate);
                par.removeEventListener('scroll', debouncedUpdate);
            });
        };
    }, [dom]);
    return Object.assign({ shouldHide }, data);
}
export const FloatingUi = React.forwardRef(function FloatingUi(_a, ref) {
    var { centerBottomElement, centerTopElement, rightTopElement, leftTopElement, children, dom, getContainer = globalGetContainer } = _a, props = __rest(_a, ["centerBottomElement", "centerTopElement", "rightTopElement", "leftTopElement", "children", "dom", "getContainer"]);
    const { isReady, shouldHide, rect } = usePosition(dom);
    const handlerKeys = React.useMemo(() => {
        return Object.keys(props).filter((n) => /^on[A-Z]/.test(n));
    }, [props]);
    const events = React.useMemo(() => pick(props, handlerKeys), [handlerKeys, props]);
    useProxyEvents(dom, events);
    return (!!isReady &&
        createPortal(React.createElement("div", Object.assign({ ref: ref, style: {
                position: 'absolute',
                left: rect.x,
                top: rect.y,
                width: rect.width,
                minHeight: rect.height,
                display: shouldHide ? 'none' : ''
            } }, props),
            children,
            !!leftTopElement && (React.createElement("div", { className: css `
              display: flex;
              transform: translateY(-100%);
              position: absolute;
              top: 0px;
              left: -1px;
            ` }, leftTopElement)),
            !!rightTopElement && (React.createElement("div", { className: css `
              display: flex;
              transform: translateY(-100%);
              position: absolute;
              top: 0px;
              right: -1px;
            ` }, rightTopElement)),
            !!centerTopElement && (React.createElement("div", { className: css `
              display: flex;
              transform: translate(-50%, -100%);
              position: absolute;
              top: 0px;
              left: 50%;
              display: flex;
              width: 100%;
              align-items: center;
              justify-content: center;
            ` }, centerTopElement)),
            !!centerBottomElement && (React.createElement("div", { className: css `
              display: flex;
              transform: translate(-50%, 100%);
              position: absolute;
              bottom: 0px;
              left: 50%;
              display: flex;
              width: 100%;
              align-items: center;
              justify-content: center;
            ` }, centerBottomElement))), getContainer()));
});
function delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
export const OveringFloat = React.forwardRef(function OveringFloat(_a, ref) {
    var _b;
    var { isOverCurrent, isSelected, onDeselect, onSelect, dom, getContainer } = _a, props = __rest(_a, ["isOverCurrent", "isSelected", "onDeselect", "onSelect", "dom", "getContainer"]);
    React.useEffect(() => {
        dom.__mometa.preventEvent = false;
        return () => {
            if (dom === null || dom === void 0 ? void 0 : dom.__mometa) {
                dom.__mometa.preventEvent = true;
            }
        };
    }, [dom]);
    const data = (_b = dom.__mometa) === null || _b === void 0 ? void 0 : _b.getMometaData();
    const [dataStr, drag, preview] = useDrag(() => ({
        type: 'dom',
        item: dom,
        end: (item, monitor) => { },
        collect: (monitor) => JSON.stringify({
            isDragging: monitor.isDragging()
        })
    }), [dom]);
    const { isDragging } = React.useMemo(() => JSON.parse(dataStr), [dataStr]);
    // React.useLayoutEffect(() => {
    //   const cls = css`
    //     background-color: #fff !important;
    //   `
    //   if (isDragging && dom) {
    //     dom.classList.add(cls)
    //     return () => {
    //       dom?.classList?.remove(cls)
    //     }
    //   }
    // }, [dom, isDragging])
    const onClickFn = usePersistFn(() => {
        // eslint-disable-next-line no-unused-expressions
        onSelect === null || onSelect === void 0 ? void 0 : onSelect();
    });
    const color = isSelected ? '#5185EC' : '#6F97E7';
    const commonCss = css `
    display: flex;
    color: #fff;
    background-color: ${color};
    padding: 2px 4px;
    font-size: 12px;
    pointer-events: auto;
    border-radius: 3px 3px 0 0;
  `;
    const btnCss = css `
    display: inline-flex;
    cursor: pointer;
    margin-left: 2px;
    margin-right: 2px;
    width: 15px !important;
    height: 17px !important;
    line-height: 1 !important;

    &::before {
      background: transparent !important;
    }
    .anticon {
      color: #fff !important;
    }
  `;
    const opHandler = usePersistFn((opType) => __awaiter(this, void 0, void 0, function* () {
        return api.handleViewOp(opType, dom);
    }));
    if (!dom || !data) {
        return null;
    }
    const commonOverCls = css `
    min-height: 25px;
    color: rgb(161, 160, 160);
    font-style: italic;

    display: flex;
    justify-content: center;
    align-items: center;

    background-color: rgba(96, 125, 217, 0.3);
    border: 1px dashed rgba(47, 84, 235, 0.8);

    margin-left: -1px;
    margin-right: -1px;
    width: calc(100% + 2px);
  `;
    const widthGte = true; //rect.width >= rect.height
    const flagElem = (React.createElement("div", { ref: preview, className: c(commonCss), title: data.text },
        !!data.container && '*',
        data.name || 'Unknown'));
    return (React.createElement(FloatingUi, { ref: ref, leftTopElement: !isDragging && flagElem, rightTopElement: !isDragging &&
            isSelected &&
            !isOverCurrent && (React.createElement("div", { className: c(commonCss) },
            React.createElement(PreventFastClick, { onClick: () => opHandler('moving') },
                React.createElement(Button, { ref: drag, className: c(btnCss), type: 'text', size: 'small', icon: React.createElement(DragOutlined, null), title: '按住并拖动来进行移动；只允许同名文件内移动' })),
            !!data.previousSibling && (React.createElement(PreventFastClick, { onClick: () => opHandler('up') },
                React.createElement(Button, { className: c(btnCss), type: 'text', size: 'small', title: '上移', icon: React.createElement(ArrowUpOutlined, null) }))),
            !!data.nextSibling && (React.createElement(PreventFastClick, { onClick: () => opHandler('down') },
                React.createElement(Button, { className: c(btnCss), type: 'text', size: 'small', title: '下移', icon: React.createElement(ArrowDownOutlined, null) }))),
            React.createElement(PreventFastClick, { onClick: () => opHandler('del') },
                React.createElement(Button, { className: c(btnCss), type: 'text', size: 'small', title: '删除', icon: React.createElement(DeleteOutlined, { title: '删除' }) })),
            React.createElement(MoreButton, { className: btnCss, dom: dom }))), dom: dom, getContainer: getContainer, className: c(css `
        pointer-events: none; !important;
        display: flex;
        flex-direction: ${widthGte ? 'row' : 'column'};
      `, isDragging &&
            css `
            background-color: rgba(96, 125, 217, 0.3);
          `, !isOverCurrent && css `outline: ${isSelected ? '1px solid ' + color : '1px dashed ' + color}; !important;`), onClick: onClickFn }, !!isOverCurrent && (React.createElement(React.Fragment, null,
        React.createElement("div", { "data-pos": 'up', className: c(commonOverCls, css `
                background-color: rgba(95, 217, 129, 0.3);
                flex: 2;
              `) }, "\u653E\u7F6E\u5728\u4E0A"),
        !data.selfClosed && (React.createElement("div", { "data-pos": 'child', className: c(commonOverCls, css `
                  flex: 3;
                `, widthGte
                ? css `
                      border-left: none !important;
                      border-right: none !important;
                    `
                : css `
                      border-top: none !important;
                      border-bottom: none !important;
                    `) }, "\u653E\u7F6E\u5728\u8FD9")),
        React.createElement("div", { "data-pos": 'down', className: c(commonOverCls, css `
                background-color: rgba(89, 214, 219, 0.3);
                flex: 2;
              `) }, "\u653E\u7F6E\u5728\u4E0B")))));
});
//# sourceMappingURL=floating-ui.js.map