"use strict";
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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OveringFloat = exports.FloatingUi = void 0;
const react_1 = __importDefault(require("react"));
const classnames_1 = __importDefault(require("classnames"));
const lodash_es_1 = require("lodash-es");
const dom_1 = require("@floating-ui/dom");
const icons_1 = require("@ant-design/icons");
const emotion_css_1 = require("../utils/emotion-css");
const use_persistfn_1 = __importDefault(require("@rcp/use.persistfn"));
const antd_1 = require("antd");
const dom_api_1 = require("./dom-api");
const c_preventfastop_1 = require("@rcp/c.preventfastop");
const more_button_1 = __importDefault(require("./components/more-button"));
const react_dnd_1 = require("react-dnd");
const get_from_main_1 = require("../utils/get-from-main");
const { api } = (0, get_from_main_1.getSharedFromMain)();
function usePosition(dom) {
    const [data, setData] = react_1.default.useState({ isReady: false, rect: { width: 0, height: 0, x: 0, y: 0 } });
    const [shouldHide, setShouldHide] = react_1.default.useState(false);
    react_1.default.useEffect(() => {
        if (!dom) {
            return;
        }
        const updatePos = () => {
            const rect = dom.getBoundingClientRect();
            setData({ rect, isReady: true });
        };
        updatePos();
        const parents = (0, dom_1.getScrollParents)(dom);
        const reset = (0, lodash_es_1.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);
}
exports.FloatingUi = react_1.default.forwardRef(function FloatingUi(_a, ref) {
    var { centerBottomElement, centerTopElement, rightTopElement, rightBottomElement, leftTopElement, children, dom } = _a, props = __rest(_a, ["centerBottomElement", "centerTopElement", "rightTopElement", "rightBottomElement", "leftTopElement", "children", "dom"]);
    const { isReady, shouldHide, rect } = usePosition(dom);
    const handlerKeys = react_1.default.useMemo(() => {
        return Object.keys(props).filter((n) => /^on[A-Z]/.test(n));
    }, [props]);
    const events = react_1.default.useMemo(() => (0, lodash_es_1.pick)(props, handlerKeys), [handlerKeys, props]);
    (0, dom_api_1.useProxyEvents)(dom, events);
    return (!!isReady && (react_1.default.createElement("div", Object.assign({ ref: ref, style: {
            position: 'absolute',
            left: rect.x,
            top: rect.y,
            width: rect.width,
            minHeight: rect.height,
            display: shouldHide ? 'none' : ''
        } }, (0, lodash_es_1.omit)(props, handlerKeys)),
        children,
        !!leftTopElement && (react_1.default.createElement("div", { className: (0, emotion_css_1.css) `
              display: flex;
              transform: translateY(-100%);
              position: absolute;
              top: 0px;
              left: -1px;
            ` }, leftTopElement)),
        !!rightTopElement && (react_1.default.createElement("div", { className: (0, emotion_css_1.css) `
              display: flex;
              transform: translateY(-100%);
              position: absolute;
              top: 0px;
              right: -1px;
            ` }, rightTopElement)),
        !!rightBottomElement && (react_1.default.createElement("div", { className: (0, emotion_css_1.css) `
              display: flex;
              transform: translateY(100%);
              position: absolute;
              bottom: 0;
              right: -1px;
            ` }, rightBottomElement)),
        !!centerTopElement && (react_1.default.createElement("div", { className: (0, emotion_css_1.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_1.default.createElement("div", { className: (0, emotion_css_1.css) `
              display: flex;
              transform: translate(-50%, 100%);
              position: absolute;
              bottom: 0px;
              left: 50%;
              display: flex;
              width: 100%;
              align-items: center;
              justify-content: center;
            ` }, centerBottomElement)))));
});
exports.OveringFloat = react_1.default.forwardRef(function OveringFloat(_a, ref) {
    var _b;
    var { isOverCurrent, isSelected, onDeselect, onSelect, dom } = _a, props = __rest(_a, ["isOverCurrent", "isSelected", "onDeselect", "onSelect", "dom"]);
    react_1.default.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] = (0, react_dnd_1.useDrag)(() => ({
        type: 'dom',
        item: dom,
        end: (item, monitor) => { },
        collect: (monitor) => JSON.stringify({
            isDragging: monitor.isDragging()
        })
    }), [dom]);
    const { isDragging } = react_1.default.useMemo(() => JSON.parse(dataStr), [dataStr]);
    const onClickFn = (0, use_persistfn_1.default)((evt) => {
        // eslint-disable-next-line no-unused-expressions
        onSelect === null || onSelect === void 0 ? void 0 : onSelect();
    });
    const color = isSelected ? '#5185EC' : '#6F97E7';
    const commonCss = (0, emotion_css_1.css) `
    display: flex;
    align-items: center;
    color: #fff;
    background-color: ${color};
    height: 21px;
    padding: 0 4px;
    font-size: 12px;
    pointer-events: auto;
    border-radius: 3px 3px 0 0;
  `;
    const btnCss = (0, emotion_css_1.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 = (0, use_persistfn_1.default)((opType) => __awaiter(this, void 0, void 0, function* () {
        return api.handleViewOp(opType, dom);
    }));
    const { rect } = usePosition(dom);
    if (!dom || !data) {
        return null;
    }
    const commonOverCls = (0, emotion_css_1.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_1.default.createElement("div", { ref: preview, className: (0, classnames_1.default)(commonCss), title: data.text },
        !!data.container && '*',
        data.name || 'Unknown'));
    const opElement = (react_1.default.createElement(react_1.default.Fragment, null,
        !!data.previousSibling && (react_1.default.createElement(antd_1.Tooltip, { title: '上移' },
            react_1.default.createElement(c_preventfastop_1.PreventFastClick, { className: (0, classnames_1.default)(btnCss), onClick: () => opHandler('up') },
                react_1.default.createElement(antd_1.Button, { type: 'text', size: 'small', icon: react_1.default.createElement(icons_1.ArrowUpOutlined, null) })))),
        !!data.nextSibling && (react_1.default.createElement(antd_1.Tooltip, { title: '下移' },
            react_1.default.createElement(c_preventfastop_1.PreventFastClick, { className: (0, classnames_1.default)(btnCss), onClick: () => opHandler('down') },
                react_1.default.createElement(antd_1.Button, { type: 'text', size: 'small', icon: react_1.default.createElement(icons_1.ArrowDownOutlined, null) })))),
        react_1.default.createElement(antd_1.Tooltip, { title: '删除' },
            react_1.default.createElement(c_preventfastop_1.PreventFastClick, { className: (0, classnames_1.default)(btnCss), onClick: () => opHandler('del') },
                react_1.default.createElement(antd_1.Button, { type: 'text', size: 'small', icon: react_1.default.createElement(icons_1.DeleteOutlined, { title: '删除' }) })))));
    const dragElem = (react_1.default.createElement(antd_1.Tooltip, { title: '按住并拖动来进行移动；暂时只允许同名文件内移动' },
        react_1.default.createElement(c_preventfastop_1.PreventFastClick, { className: (0, classnames_1.default)(btnCss), onClick: () => opHandler('moving') },
            react_1.default.createElement(antd_1.Button, { ref: drag, type: 'text', size: 'small', icon: react_1.default.createElement(icons_1.DragOutlined, null), title: '' }))));
    const isSimple = rect.width < 230;
    const shouldShowOp = !isDragging && isSelected && !isOverCurrent;
    return (react_1.default.createElement(exports.FloatingUi, { ref: ref, leftTopElement: !isDragging && flagElem, rightBottomElement: isSimple &&
            shouldShowOp && (react_1.default.createElement("div", { className: (0, classnames_1.default)(commonCss, (0, emotion_css_1.css) `
                border-radius: 0 0 3px 3px;
              `) },
            dragElem,
            react_1.default.createElement(more_button_1.default, { className: btnCss, dom: dom, menu: react_1.default.createElement(react_1.default.Fragment, null,
                    !!data.previousSibling && react_1.default.createElement(antd_1.Menu.Item, { onClick: () => opHandler('up') }, "\u4E0A\u79FB"),
                    !!data.nextSibling && react_1.default.createElement(antd_1.Menu.Item, { onClick: () => opHandler('down') }, "\u4E0B\u79FB"),
                    react_1.default.createElement(antd_1.Menu.Item, { danger: true, onClick: () => opHandler('del') }, "\u5220\u9664")) }))), rightTopElement: !isSimple &&
            shouldShowOp && (react_1.default.createElement("div", { className: (0, classnames_1.default)(commonCss) },
            dragElem,
            opElement,
            react_1.default.createElement(more_button_1.default, { className: btnCss, dom: dom }))), dom: dom, className: (0, classnames_1.default)((0, emotion_css_1.css) `
        pointer-events: none; !important;
        display: flex;
        flex-direction: ${widthGte ? 'row' : 'column'};
      `, isDragging &&
            (0, emotion_css_1.css) `
            background-color: rgba(96, 125, 217, 0.3);
          `, !isOverCurrent && (0, emotion_css_1.css) `outline: ${isSelected ? '1px solid ' + color : '1px dashed ' + color}; !important;`), onClick: onClickFn }, !!isOverCurrent && (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { "data-pos": 'up', className: (0, classnames_1.default)(commonOverCls, (0, emotion_css_1.css) `
                background-color: rgba(95, 217, 129, 0.3);
                flex: 2;
              `) }, "\u653E\u7F6E\u5728\u4E0A"),
        !data.selfClosed && (react_1.default.createElement("div", { "data-pos": 'child', className: (0, classnames_1.default)(commonOverCls, (0, emotion_css_1.css) `
                  flex: 3;
                `, widthGte
                ? (0, emotion_css_1.css) `
                      border-left: none !important;
                      border-right: none !important;
                    `
                : (0, emotion_css_1.css) `
                      border-top: none !important;
                      border-bottom: none !important;
                    `) }, "\u653E\u7F6E\u5728\u8FD9")),
        react_1.default.createElement("div", { "data-pos": 'down', className: (0, classnames_1.default)(commonOverCls, (0, emotion_css_1.css) `
                background-color: rgba(89, 214, 219, 0.3);
                flex: 2;
              `) }, "\u653E\u7F6E\u5728\u4E0B")))));
});
//# sourceMappingURL=floating-ui.js.map