import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useMemo } from 'react';
import { useUpdate } from 'react-use';
import { EventEmitter } from "../utils/index.js";
import { ToolbarProvider, useToolbarContext, } from "./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.
export function ToolbarUpdateOnRerender({ content }) {
    const rerender = useUpdate();
    const context = useToolbarContext();
    useEffect(() => {
        if (!context)
            return undefined;
        context.eventBus.on('update', rerender);
        return () => {
            context.eventBus.off('update', rerender);
        };
    }, [context, rerender]);
    return _jsx(_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.
export function ToolbarWrapToContext({ editor, children }) {
    const outerContext = useToolbarContext();
    const innerContext = useMemo(() => {
        if (outerContext)
            return undefined;
        const eventBus = new EventEmitter();
        return { editor, eventBus };
    }, [editor, outerContext]);
    useEffect(() => {
        innerContext?.eventBus.emit('update', null);
    });
    // wrapping in inner context only if there is no outer context
    return innerContext ? (_jsx(ToolbarProvider, { value: innerContext, children: children })) : (_jsx(_Fragment, { children: children }));
}
//# sourceMappingURL=ToolbarRerender.js.map
