"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MainEditorStoreProvider = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const constants_1 = require("../../../common/constants.js");
const utils_1 = require("../../../common/utils.js");
const store_1 = require("../../store.js");
const iframeContext_1 = require("../iframeContext/index.js");
const MainEditorStoreContext_1 = require("./MainEditorStoreContext.js");
const MainEditorStoreProvider = ({ children }) => {
    const { iframeElement } = React.useContext(iframeContext_1.IframeContext);
    const storeRef = React.useRef();
    const sendPostMessage = React.useCallback((data) => {
        const message = {
            state: data,
            source: constants_1.POST_MESSAGE_SOURCE,
        };
        if (iframeElement && iframeElement.contentWindow) {
            iframeElement.contentWindow.postMessage(message, '*');
        }
    }, [iframeElement]);
    if (!storeRef.current) {
        storeRef.current = (0, store_1.createEditorStore)();
    }
    React.useEffect(() => {
        storeRef.current?.subscribe((state) => {
            const { historyPast: _historyPast, historyFuture: _historyFuture, ...syncable } = state;
            sendPostMessage((0, utils_1.removeFn)({ ...syncable, historyPast: [], historyFuture: [] }));
        });
    }, [sendPostMessage]);
    return ((0, jsx_runtime_1.jsx)(MainEditorStoreContext_1.MainEditorStoreContext.Provider, { value: {
            state: storeRef.current,
        }, children: children }));
};
exports.MainEditorStoreProvider = MainEditorStoreProvider;
//# sourceMappingURL=MainEditorStoreProvider.js.map
