I'm attempting to mount a ProseMirror view, set the cursor position based on known coordinates, and then focus it.
In the browsers I've tried (Chrome 59.0.3071.115 and 60.0.3112.78, Safari, and Firefox), using prosemirror-view 0.22.0 (I also tried prosemirror-view master from github), when I dispatch a setSelection command and .focus() the view (either immediately before or after), the cursor is set to position zero instead of the position given to the setSelection command.
Example:
// immediately after ProseMirror has mounted;
// switching the order of these two lines doesn't seem to make a difference
pmView.dispatch(tr.setSelection(selection))
pmView.focus()
// Desired behaviour: cursor moves to the given position
// Actual behaviour: cursor moves to position 0
The closest I can get to the desired behaviour is setting a timeout on the dispatching of the setSelection transaction, in which case the cursor first jumps to 0, then to where I set the selection:
pmView.focus()
setTimeout(function(){pmView.dispatch(tr.setSelection(selection))}, 10)
// cursor visibly jumps to 0 and then to the correct position
Setting the timeout to 0 does not work reliably, so I wondered if there is something asynchronous going on, but I couldn't find anything in the docs.
Not sure if it is relevant, but this is being applied to a 'fresh' ProseMirror view which has not previously had focus.
Adding a handler like this to a demo seems to reliably focus the editor and put the cursor at position 10:
document.onmousedown = function(e) {
e.preventDefault()
view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(10))))
view.focus()
}
Is there anything you're doing differently?
Hmm. The only thing I can think of, is that I was trying to setSelection+focus _immediately_ after mounting the Prosemirror instance. When I try to do the same thing later (after any timeOut at all), it works as expected.
I'm not seeing the issue directly after creating the view either, so I'm going to close this until more information comes in.
Most helpful comment
Adding a handler like this to a demo seems to reliably focus the editor and put the cursor at position 10:
Is there anything you're doing differently?