RangeError after setting the initial selection via dispatch

I’m setting the initial caret position like this:

    selection: { anchor: caretPosition },
        { type: {}, value: 'my.initialSelection' }
    scrollIntoView: true

The reason I’m using dispatch() rather than providing the initial selection straight in the view: I use the custom annotation my.initialSelection to scroll the selection into the middle of the view (and not the bottom).

The initial selection gets applied correctly. However, the first time i’m typing something, it results in an error of type RangeError: Selection points outside of document and ignores/undos the first key.

If I continue typing, there is no more error and everything works normal. If I set the caret position manually by clicking, there is no error on the first key press either. Only if it’s applied by the dispatch() above. Any ideas, what could cause this?

The new centerOn effect should make scrolling something into the middle of the view easier.

If you can distill the error down to a small, simple script, I’ll gladly debug it. Right now, this post doesn’t really provide enough information to reproduce the problem.

1 Like

Okay, I just found out, the problems also occurs, if I set the selection property of EditorState directly.

let editor = new EditorView({
    state: EditorState.create({
        doc: content,
        selection: EditorSelection.single(caretPosition),
        extensions: [],
    parent: parent,

I’ve deactivated all extensions and the issue still occurs.

centerOn looks very promising. Could you perhaps provide an example how to combine this with editor.dispatch({ selection })?

What’s the value of caretPosition and content?

editor.dispatch({effects: EditorView.centerOn.of(selection.main), selection}) should work.

1 Like

Phew, I finally found the cause of the issue.

caretPosition is being fetched from local storage and used to be a string, not an integer. That made it break. After I converted it to int, it’s working perfectly.

EditorSelection.single() allows a string as anchor and places the caret correctly. However, typing afterwards fails.

PS: The centerOn works like a charm. Allowed me to remove an entire extension. Keep up the great work!