import { Plugin, PluginKey } from 'prosemirror-state';
import { EventEmitter } from "../../../utils/event-emitter.js";
export { Renderer as ReactRendererComponent } from "./react.js";
const key = new PluginKey('reactrenderer');
export function getReactRendererFromState(state) {
    const renderer = key.getState(state);
    if (!renderer) {
        throw new Error('ReactRenderer is missing in the editor state. Probably, you forgot to use ReactRendererExtension');
    }
    return renderer;
}
export const ReactRendererExtension = (builder, renderer) => {
    builder.context.set('reactrenderer', renderer);
    builder.addPlugin(() => new Plugin({
        key,
        state: {
            init: () => renderer,
            apply: () => renderer,
        },
    }), builder.Priority.Highest);
};
export class ReactRenderStorage extends EventEmitter {
    static Item = class Item extends EventEmitter {
        static GlobalId = 0;
        static getNextId() {
            return this.GlobalId++;
        }
        id;
        renderFn;
        removeFn;
        constructor(idPrefix, renderFn, removeFn) {
            super();
            this.id = idPrefix + Item.getNextId();
            this.renderFn = renderFn;
            this.removeFn = removeFn;
        }
        render() {
            return this.renderFn();
        }
        remove() {
            this.removeFn(this);
        }
        rerender() {
            this.emit('rerender', null);
        }
    };
    #items = [];
    getItems() {
        return this.#items;
    }
    createItem(idPrefix, render) {
        const item = new ReactRenderStorage.Item(idPrefix, render, this.removeItem.bind(this));
        this.#items.push(item);
        this.emit('update', null);
        return item;
    }
    removeItem(itemOrId) {
        if (typeof itemOrId === 'string') {
            this.#items = this.#items.filter((item) => item.id !== itemOrId);
        }
        else {
            this.#items = this.#items.filter((item) => item !== itemOrId);
        }
        this.emit('update', null);
    }
}
//# sourceMappingURL=index.js.map
