Control cursor/caret position on focus

By default, when a user focuses/clicks on the editor, the editor sets the cursor/caret as near as possible to where the click happened.

If the click happens below the last line of content ( but still inside the editor ), the cursor is added to the last digit of the content.

In these cases I’d like for a new paragraph to be added to after the current content and for the cursor to be moved to that paragraph.

I’ve been able to do so by adding the following function as a click event listener

const handleEditorClick = (event: MouseEvent): void => {
    const { state, dispatch } = editorView;
    const { tr, doc } = state;
    const lastChildElement = editorView.dom.lastChild as HTMLElement | null;
   
    if (lastChildElement && event.clientY > lastChildElement.getBoundingClientRect().bottom) {
        tr.insert(tr.selection.to, state.schema.nodes.p.create());
        const newSelection = TextSelection.create(tr.doc, doc.content.size+1, doc.content.size+1);
        tr.setSelection(newSelection);
        dispatch(tr);
    }
};

However this function runs after the cursor as already been placed in the last digit of the content. This means that there is a glitch where the cursor appears on the last digit of the content and then moves to the paragraph that was just created

So ideally I would run a function similar to what I presented before the cursor position is set or I would add this logic alongside the logic that sets the cursor position. How can I do it?

You could use a mousedown handler, but that has the disadvantage that a drag selection from below the bottom of the document no longer works, when you prevent the default behavior of mousedown. By the time the click even is fired, the browser’s native cursor setting behavior has already happened, and there’s not much a script can do about that.

Thanks!

I ended up creating a plugin and added a handler for the selectstart event on handleDOMEvents