"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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 });
const react_1 = __importDefault(require("react"));
const prefix_classname_1 = __importDefault(require("prefix-classname"));
const react_dnd_1 = require("react-dnd");
const antd_1 = require("antd");
const storage_1 = require("@rcp/use.syncstorage/dist/es/src/storage");
const const_1 = require("../../../config/const");
const externals_modules_1 = require("../../utils/externals-modules");
const use_shared_1 = require("@rcp/use.shared");
const re_resizable_1 = require("re-resizable");
const cn = (0, prefix_classname_1.default)('');
const c = (0, prefix_classname_1.default)(`${const_1.CLS_PREFIX}-stage`);
require("./style.scss");
const header_1 = require("../header");
const pipe_1 = require("../../../../shared/pipe");
const location_widget_1 = __importDefault(require("../location-widget"));
const resize_widget_1 = __importStar(require("../resize-widget"));
const utils_1 = require("../../utils/utils");
const use_persistfn_1 = __importDefault(require("@rcp/use.persistfn"));
const resize_handler_1 = __importDefault(require("../resize-handler"));
const error_overlay_1 = require("../../utils/error-overlay");
(0, pipe_1.setId)(`main`);
const DndManager = react_1.default.lazy(() => Promise.resolve().then(() => __importStar(require('../../../render-floating'))).then((x) => ({ default: x.DndLayoutManager })));
const _ResizeContainerAs = react_1.default.forwardRef((_a, ref) => {
    var { isMobileMode } = _a, props = __rest(_a, ["isMobileMode"]);
    return (react_1.default.createElement("div", Object.assign({ ref: ref }, props, { style: isMobileMode ? props.style : {} }), props.children));
});
const ResizeContainer = react_1.default.memo(({ children, isMobileMode, resizeValues, setResizeValues }) => {
    return (react_1.default.createElement(re_resizable_1.Resizable
    // @ts-ignore
    , { 
        // @ts-ignore
        isMobileMode: isMobileMode, as: _ResizeContainerAs, enable: !isMobileMode || resizeValues.type !== 'custom'
            ? {}
            : {
                top: false,
                right: true,
                bottom: true,
                left: true,
                topRight: false,
                bottomRight: true,
                bottomLeft: false,
                topLeft: false
            }, handleWrapperStyle: { zIndex: 300 }, handleStyles: {
            right: {
                width: 'auto',
                right: 0,
                transform: 'translateX(100%)'
            },
            left: {
                width: 'auto',
                left: 0,
                transform: 'translateX(-100%)'
            },
            bottom: {
                height: 'auto',
                bottom: 0,
                transform: 'translateY(100%)'
            },
            bottomRight: {
                right: 0,
                bottom: 0,
                transform: 'translate(100%, 100%)'
            }
        }, handleComponent: {
            right: react_1.default.createElement(resize_handler_1.default, { right: true }),
            bottom: react_1.default.createElement(resize_handler_1.default, { bottom: true }),
            left: react_1.default.createElement(resize_handler_1.default, { left: true }),
            bottomRight: react_1.default.createElement(resize_handler_1.default, { bottomRight: true })
        }, resizeRatio: 2, minHeight: 100, minWidth: 100, className: c('__iframe-wrapper'), size: {
            width: resizeValues.width,
            height: resizeValues.height
        }, onResizeStop: (evt, direction, elem, delta) => {
            setResizeValues(Object.assign(Object.assign({}, resizeValues), { width: resizeValues.width + delta.width, height: resizeValues.height + delta.height }));
        }, style: {
            transform: resizeValues.rate ? `scale(${resizeValues.rate})` : '',
            transformOrigin: `50% 0`
        } }, children));
});
const StageContent = react_1.default.memo(({ className, externalModules, bundlerURL }) => {
    react_1.default.useLayoutEffect(() => {
        if (externalModules) {
            return (0, externals_modules_1.addModules)(externalModules);
        }
    }, [externalModules]);
    const iframeRef = react_1.default.useRef(null);
    react_1.default.useEffect(() => {
        var _a;
        if ((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow) {
            (0, pipe_1.addRemoteGlobalThis)(iframeRef.current.contentWindow);
            return () => {
                var _a;
                (0, pipe_1.removeRemoteGlobalThis)((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow);
            };
        }
    }, [iframeRef]);
    const [action, setAction] = (0, const_1.useLocationAction)();
    react_1.default.useLayoutEffect(() => {
        setAction({ action: 'PUSH', url: bundlerURL, outer: true });
    }, [bundlerURL]);
    const [iframeSrc, setIframeSrc] = react_1.default.useState(bundlerURL);
    react_1.default.useLayoutEffect(() => {
        if (!action) {
            return;
        }
        if (action.url.includes('#')) {
            setIframeSrc(action.url);
            return;
        }
        if (action.outer) {
            setIframeSrc(action.url);
        }
    }, [action]);
    const [{ isMobileMode, showLocation }] = (0, header_1.useHeaderStatus)();
    const [api] = (0, use_shared_1.useShared)('api');
    react_1.default.useLayoutEffect(() => {
        (0, error_overlay_1.setEditorHandler)((loc) => {
            // @ts-ignore
            api.openEditor(loc);
        });
    }, [api]);
    const ddManager = (0, react_dnd_1.useDragDropManager)();
    const _sharedMap = (0, use_shared_1.useSharedMap)();
    const _sharedUpdateMap = (0, use_shared_1.useSharedUpdateMap)();
    const shared = react_1.default.useMemo(() => ({
        api,
        iframeWindowsSubject: const_1.iframeWindowsSubject,
        overingNodeSubject: const_1.overingNodeSubject,
        selectedNodeSubject: const_1.selectedNodeSubject,
        headerStatusSubject: header_1.headerStatusSubject,
        locationActionSubject: const_1.locationActionSubject,
        ddManager,
        _sharedMap,
        _sharedUpdateMap
    }), [ddManager, _sharedMap, _sharedUpdateMap, api]);
    react_1.default.useLayoutEffect(() => (0, pipe_1.register)('shared', shared), [shared]);
    const [resizeValues, setResizeValues] = (0, storage_1.useLocalStorageStateSync)((0, utils_1.symbol)('resize-widget'), resize_widget_1.defaultValue);
    const paddingSize = 20;
    const [playground, setPlayground] = react_1.default.useState(null);
    const getSize = (0, use_persistfn_1.default)((playground) => {
        return {
            height: playground.clientHeight - paddingSize * 2,
            width: playground.clientWidth - paddingSize * 2
        };
    });
    return (react_1.default.createElement("div", { className: cn(c(), className) },
        !!showLocation && react_1.default.createElement(location_widget_1.default, { iframeRef: iframeRef }),
        !!isMobileMode && (react_1.default.createElement(resize_widget_1.default, { container: playground, getContainerSize: getSize, value: resizeValues, onChange: setResizeValues })),
        react_1.default.createElement("div", { ref: (dom) => {
                setPlayground(dom);
            }, style: {
                backgroundColor: '#e2e5ec',
                flex: 1,
                display: 'flex',
                justifyContent: 'center',
                padding: paddingSize,
                height: 0,
                overflow: 'auto'
            } },
            react_1.default.createElement(ResizeContainer, { isMobileMode: isMobileMode, resizeValues: resizeValues, setResizeValues: setResizeValues },
                react_1.default.createElement("div", { className: c('__iframe-mask') },
                    react_1.default.createElement(antd_1.Spin, { style: { flex: 1 }, tip: '渲染中...' })),
                react_1.default.createElement("iframe", { ref: iframeRef, src: iframeSrc, className: c('__iframe') }),
                react_1.default.createElement("div", { className: c('__iframe-floating-container') },
                    react_1.default.createElement(DndManager, null))))));
});
const Stage = (props) => {
    return (react_1.default.createElement(react_1.default.Suspense, { fallback: react_1.default.createElement(antd_1.Spin, { className: c('__spin'), tip: '加载中...' }) },
        react_1.default.createElement(StageContent, Object.assign({}, props))));
};
Stage.defaultProps = {
    bundlerURL: '/bundler.html'
};
exports.default = Stage;
//# sourceMappingURL=index.js.map