"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToolbarUpdateOnRerender = ToolbarUpdateOnRerender;
exports.ToolbarWrapToContext = ToolbarWrapToContext;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_use_1 = require("react-use");
const utils_1 = require("../utils/index.js");
const context_1 = require("./context.js");
/**
 Rerender the content when an update event is received in the event bus from the context.
 @internal
 */
// TODO [major]: Always expect the toolbar to be wrapped in context; remove this component as unnecessary.
function ToolbarUpdateOnRerender({ content }) {
    const rerender = (0, react_use_1.useUpdate)();
    const context = (0, context_1.useToolbarContext)();
    (0, react_1.useEffect)(() => {
        if (!context)
            return undefined;
        context.eventBus.on('update', rerender);
        return () => {
            context.eventBus.off('update', rerender);
        };
    }, [context, rerender]);
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: content() });
}
/**
 If there is no external context, wraps the content in the toolbar context
 and emits an update event on each component re-render.
 @internal
 */
// TODO [major]: Always expect the toolbar to be wrapped in context; remove this component as unnecessary.
function ToolbarWrapToContext({ editor, children }) {
    const outerContext = (0, context_1.useToolbarContext)();
    const innerContext = (0, react_1.useMemo)(() => {
        if (outerContext)
            return undefined;
        const eventBus = new utils_1.EventEmitter();
        return { editor, eventBus };
    }, [editor, outerContext]);
    (0, react_1.useEffect)(() => {
        innerContext?.eventBus.emit('update', null);
    });
    // wrapping in inner context only if there is no outer context
    return innerContext ? ((0, jsx_runtime_1.jsx)(context_1.ToolbarProvider, { value: innerContext, children: children })) : ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children }));
}
//# sourceMappingURL=ToolbarRerender.js.map
