import { uniqueId } from "../../../lodash.js";
import { pluginKey } from "./plugin.js";
export class SharedStateKey {
    /**
     * Define a new key.
     * If you create two keys with the same name, they will refer to the same value from the state.
     * If name not passed, a unique one will be generated.
     */
    static define(spec = {}) {
        const key = spec.name ?? uniqueId('shared_state_key');
        return new this(key);
    }
    #key;
    /** Add metadata to transaction to change data in state */
    appendTransaction = Object.freeze({
        /** Set or replace data stored by current key */
        set: (tr, data) => {
            return this.appendTrMeta(tr, { type: 'set', data });
        },
        /** Update (patch) data stored by current key */
        update: (tr, data) => {
            return this.appendTrMeta(tr, { type: 'update', data });
        },
        /** Delete data stored by current key */
        delete: (tr) => {
            return this.appendTrMeta(tr, { type: 'delete' });
        },
    });
    constructor(key) {
        this.#key = key;
    }
    getNotifier(state) {
        const self = this;
        const notifyBus = pluginKey.getState(state)?.notifyBus;
        return {
            subscribe(fn) {
                notifyBus?.on(self.#key, fn);
                return () => {
                    this.unsubscribe(fn);
                };
            },
            unsubscribe(fn) {
                notifyBus?.off(self.#key, fn);
            },
        };
    }
    getValue(state) {
        return pluginKey.getState(state)?.map.get(this.#key);
    }
    appendTrMeta(tr, action) {
        const meta = tr.getMeta(pluginKey) || { actions: [] };
        meta.actions.push({ ...action, key: this.#key });
        return tr.setMeta(pluginKey, meta);
    }
}
//# sourceMappingURL=utils.js.map
