"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pluginSpec = exports.pluginKey = void 0;
const state_1 = require("../../../pm/state.js");
const event_emitter_1 = require("../../../utils/event-emitter.js");
/** @internal */
exports.pluginKey = new state_1.PluginKey('shared-state');
exports.pluginSpec = {
    key: exports.pluginKey,
    state: {
        init() {
            return {
                map: new Map(),
                changedKeys: null,
                notifyBus: new event_emitter_1.EventEmitter(),
            };
        },
        apply(tr, { map, notifyBus }) {
            const meta = tr.getMeta(exports.pluginKey);
            if (!meta || !meta.actions.length)
                return { changedKeys: null, map, notifyBus };
            const changedKeys = new Set();
            for (const action of meta.actions) {
                switch (action.type) {
                    case 'delete': {
                        map.delete(action.key);
                        break;
                    }
                    case 'update': {
                        let value = map.get(action.key);
                        value = { ...value, ...action.data };
                        map.set(action.key, value);
                        break;
                    }
                    case 'set': {
                        map.set(action.key, action.data);
                        break;
                    }
                    default: {
                        continue;
                    }
                }
                changedKeys.add(action.key);
            }
            return { changedKeys, map, notifyBus };
        },
    },
    view: () => {
        return {
            update(view) {
                const state = exports.pluginKey.getState(view.state);
                if (!state || !state.changedKeys || !state.changedKeys.size)
                    return;
                for (const key of state.changedKeys) {
                    const value = state.map.get(key);
                    state.notifyBus.emit(key, value);
                }
            },
        };
    },
};
//# sourceMappingURL=plugin.js.map
