import { Plugin, PluginKey } from 'prosemirror-state';
import { Decoration, DecorationSet } from 'prosemirror-view';
export const widgetDecorationPluginKey = new PluginKey();
export const WidgetDecorationPlugin = () => {
    return new Plugin({
        key: widgetDecorationPluginKey,
        props: {
            decorations(state) {
                return widgetDecorationPluginKey.getState(state) ?? null;
            },
        },
        state: {
            init() {
                return 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(widgetDecorationPluginKey);
                if (meta?.type === 'add') {
                    const { descriptor } = meta;
                    const spec = {
                        id: descriptor.id,
                        pos: descriptor.initPos,
                        descriptor,
                    };
                    const deco = 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;
            },
        },
    });
};
//# sourceMappingURL=plugin.js.map
