"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WidgetDecorationPlugin = exports.widgetDecorationPluginKey = void 0;
const prosemirror_state_1 = require("prosemirror-state");
const prosemirror_view_1 = require("prosemirror-view");
exports.widgetDecorationPluginKey = new prosemirror_state_1.PluginKey();
const WidgetDecorationPlugin = () => {
    return new prosemirror_state_1.Plugin({
        key: exports.widgetDecorationPluginKey,
        props: {
            decorations(state) {
                return exports.widgetDecorationPluginKey.getState(state) ?? null;
            },
        },
        state: {
            init() {
                return prosemirror_view_1.DecorationSet.empty;
            },
            apply(tr, oldSet) {
                // Adjust decoration positions to changes made by the transaction
                let set = oldSet.map(tr.mapping, tr.doc, {
                    onRemove(spec) {
                        const { descriptor } = spec;
                        descriptor.remove();
                    },
                });
                const meta = tr.getMeta(exports.widgetDecorationPluginKey);
                if (meta?.type === 'add') {
                    const { descriptor } = meta;
                    const spec = {
                        id: descriptor.id,
                        pos: descriptor.initPos,
                        descriptor,
                    };
                    const deco = prosemirror_view_1.Decoration.widget(descriptor.initPos, 
                    // @ts-expect-error
                    descriptor.render.bind(descriptor), spec);
                    set = set.add(tr.doc, [deco]);
                }
                if (meta?.type === 'remove') {
                    const decos = set.find(undefined, undefined, (spec) => spec.id === meta.id);
                    decos.forEach((deco) => deco.spec.descriptor.remove());
                    set = set.remove(decos);
                }
                return set;
            },
        },
    });
};
exports.WidgetDecorationPlugin = WidgetDecorationPlugin;
//# sourceMappingURL=plugin.js.map
