Can I reuse Compartments for multiple editor instances?

Hi, I have found the following code on Stack Overflow:

import { history, historyKeymap } from '@codemirror/commands';

let undoRedo = new Compartment;
let editor = new EditorView({
    state: EditorState.create({
        extensions: [
            basicSetup,
            //...
            undoRedo.of([history()]),
            keymap.of([
                ...historyKeymap,
            ])
        ]
    }),
    parent: document.getElementById("txtInput")
});

function resetUndoRedo() {
    editor.dispatch({
        effects: undoRedo.reconfigure([]) //first remove history() to clear it!!
    });
    editor.dispatch({
        effects: undoRedo.reconfigure([history()])
    });
}

//a typical usage:
function setEditorText(text) {
    let transaction = editor.state.update({ changes: { 
                from: 0, 
                to: editor.state.doc.length, 
                insert: text} 
    });
    editor.update([transaction]);
    resetUndoRedo();
}

In my case I have multiple instances of editors in a Map<string, EditorView>.

General question: Do I need a new Compartment instance per EditorView instance or can I reuse a single Compartment instance without having the different editors affect each other in some way?

In case that I need a new Compartment instance per EditorView instance: Is there a way to get the Compartment instance from an EditorView or do I have to manage and store them separately by myself (e.g. in the Map)?

No. The compartments themselves are immutable values that are just used to tag part of a concrete editor implementation. They can be shared without issue.

1 Like