Nodeview.setSelection() selection is out of bounds for underlying CodeMirror

I’ve got a nodeview which uses a CodeMirror view. My implementation closely follows the example provided in the examples in the ProseMirror docs, and it seems to mostly work. I’ve recently run into a problem with setSelection(), however, and I’m not sure what to make of it.

My setSelection() implementation is actually exactly what’s in the example:

setSelection(anchor: number, head: number, root: Document) {
    this.updating = true;
    this.cmView.dispatch({ selection: { anchor, head } });
    this.updating = false;

But what I’m seeing is that occasionally the cmView.dispatch complains that “Selection points outside of document”, i.e. I’ve asked for a selection that’s not in the CM doc’s bounds. Even more strange, this seems to happen when I click on the ‘panel’ section of the nodeview; I get anchor and head values which are 10 positions beyond the last position in the CM doc. I’ve also seen problems when I click just slightly above the CM editor, though I can’t make this happen as consistently.

I can of course add guards in my setSelection which return when the arguments are outside the CM doc bounds, but I’m not sure if that’s the right thing to do, or just a patch around a deeper problem.

So, should I ever expect the anchor and/or head arguments to be outside my CM doc’s bounds, assuming that everything else is implemented correctly? If I should not be seeing that condition, where might I have gone wrong?

That depends on how your code block node corresponds to your CodeMirror content. If its text content corresponds to the code editor content, and the two have been synced, then the selection range passed to setSelection should fit in the CodeMirror document.