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 p from 'prefix-classname';
import { useDragDropManager } from 'react-dnd';
import { Spin } from 'antd';
import { useLocalStorageStateSync } from '@rcp/use.syncstorage/dist/es/src/storage';
import { CLS_PREFIX, overingNodeSubject, selectedNodeSubject, useLocationAction, locationActionSubject, iframeWindowsSubject } from '../../../config/const';
import { addModules } from '../../utils/externals-modules';
import { useSharedMap, useSharedUpdateMap, useShared } from '@rcp/use.shared';
import { Resizable } from 're-resizable';
const cn = p('');
const c = p(`${CLS_PREFIX}-stage`);
import './style.scss';
import { headerStatusSubject, useHeaderStatus } from '../header';
import { register, addRemoteGlobalThis, removeRemoteGlobalThis, setId } from '../../../../shared/pipe';
import LocationWidget from '../location-widget';
import ResizeWidget, { defaultValue } from '../resize-widget';
import { symbol } from '../../utils/utils';
import usePersistFn from '@rcp/use.persistfn';
import ResizeHandler from '../resize-handler';
import { setEditorHandler } from '../../utils/error-overlay';
setId(`main`);
const DndManager = React.lazy(() => import('../../../render-floating').then((x) => ({ default: x.DndLayoutManager })));
const _ResizeContainerAs = React.forwardRef((_a, ref) => {
    var { isMobileMode } = _a, props = __rest(_a, ["isMobileMode"]);
    return (React.createElement("div", Object.assign({ ref: ref }, props, { style: isMobileMode ? props.style : {} }), props.children));
});
const ResizeContainer = React.memo(({ children, isMobileMode, resizeValues, setResizeValues }) => {
    return (React.createElement(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.createElement(ResizeHandler, { right: true }),
            bottom: React.createElement(ResizeHandler, { bottom: true }),
            left: React.createElement(ResizeHandler, { left: true }),
            bottomRight: React.createElement(ResizeHandler, { 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.memo(({ className, externalModules, bundlerURL }) => {
    React.useLayoutEffect(() => {
        if (externalModules) {
            return addModules(externalModules);
        }
    }, [externalModules]);
    const iframeRef = React.useRef(null);
    React.useEffect(() => {
        var _a;
        if ((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow) {
            addRemoteGlobalThis(iframeRef.current.contentWindow);
            return () => {
                var _a;
                removeRemoteGlobalThis((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow);
            };
        }
    }, [iframeRef]);
    const [action, setAction] = useLocationAction();
    React.useLayoutEffect(() => {
        setAction({ action: 'PUSH', url: bundlerURL, outer: true });
    }, [bundlerURL]);
    const [iframeSrc, setIframeSrc] = React.useState(bundlerURL);
    React.useLayoutEffect(() => {
        if (!action) {
            return;
        }
        if (action.url.includes('#')) {
            setIframeSrc(action.url);
            return;
        }
        if (action.outer) {
            setIframeSrc(action.url);
        }
    }, [action]);
    const [{ isMobileMode, showLocation }] = useHeaderStatus();
    const [api] = useShared('api');
    React.useLayoutEffect(() => {
        setEditorHandler((loc) => {
            // @ts-ignore
            api.openEditor(loc);
        });
    }, [api]);
    const ddManager = useDragDropManager();
    const _sharedMap = useSharedMap();
    const _sharedUpdateMap = useSharedUpdateMap();
    const shared = React.useMemo(() => ({
        api,
        iframeWindowsSubject,
        overingNodeSubject,
        selectedNodeSubject,
        headerStatusSubject,
        locationActionSubject,
        ddManager,
        _sharedMap,
        _sharedUpdateMap
    }), [ddManager, _sharedMap, _sharedUpdateMap, api]);
    React.useLayoutEffect(() => register('shared', shared), [shared]);
    const [resizeValues, setResizeValues] = useLocalStorageStateSync(symbol('resize-widget'), defaultValue);
    const paddingSize = 20;
    const [playground, setPlayground] = React.useState(null);
    const getSize = usePersistFn((playground) => {
        return {
            height: playground.clientHeight - paddingSize * 2,
            width: playground.clientWidth - paddingSize * 2
        };
    });
    return (React.createElement("div", { className: cn(c(), className) },
        !!showLocation && React.createElement(LocationWidget, { iframeRef: iframeRef }),
        !!isMobileMode && (React.createElement(ResizeWidget, { container: playground, getContainerSize: getSize, value: resizeValues, onChange: setResizeValues })),
        React.createElement("div", { ref: (dom) => {
                setPlayground(dom);
            }, style: {
                backgroundColor: '#e2e5ec',
                flex: 1,
                display: 'flex',
                justifyContent: 'center',
                padding: paddingSize,
                height: 0,
                overflow: 'auto'
            } },
            React.createElement(ResizeContainer, { isMobileMode: isMobileMode, resizeValues: resizeValues, setResizeValues: setResizeValues },
                React.createElement("div", { className: c('__iframe-mask') },
                    React.createElement(Spin, { style: { flex: 1 }, tip: '渲染中...' })),
                React.createElement("iframe", { ref: iframeRef, src: iframeSrc, className: c('__iframe') }),
                React.createElement("div", { className: c('__iframe-floating-container') },
                    React.createElement(DndManager, null))))));
});
const Stage = (props) => {
    return (React.createElement(React.Suspense, { fallback: React.createElement(Spin, { className: c('__spin'), tip: '加载中...' }) },
        React.createElement(StageContent, Object.assign({}, props))));
};
Stage.defaultProps = {
    bundlerURL: '/bundler.html'
};
export default Stage;
//# sourceMappingURL=index.js.map