"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactRenderStorage = exports.ReactRendererExtension = exports.ReactRendererComponent = void 0;
exports.getReactRendererFromState = getReactRendererFromState;
const prosemirror_state_1 = require("prosemirror-state");
const event_emitter_1 = require("../../../utils/event-emitter.js");
var react_1 = require("./react.js");
Object.defineProperty(exports, "ReactRendererComponent", { enumerable: true, get: function () { return react_1.Renderer; } });
const key = new prosemirror_state_1.PluginKey('reactrenderer');
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;
}
const ReactRendererExtension = (builder, renderer) => {
    builder.context.set('reactrenderer', renderer);
    builder.addPlugin(() => new prosemirror_state_1.Plugin({
        key,
        state: {
            init: () => renderer,
            apply: () => renderer,
        },
    }), builder.Priority.Highest);
};
exports.ReactRendererExtension = ReactRendererExtension;
class ReactRenderStorage extends event_emitter_1.EventEmitter {
    static Item = class Item extends event_emitter_1.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);
    }
}
exports.ReactRenderStorage = ReactRenderStorage;
//# sourceMappingURL=index.js.map
