How to set initial focus of document

Hey there,

I want set the initial cursor in the document at the end of the first paragraph. Here’s my code so far:

	const doc = schema.nodeFromJSON({ type: "doc", content: [{ type: "paragraph" }] })
	const state = EditorState.create({/* ... */})
	const view = new EditorView<EditorSchema>(node, {/* ... */})

	// Focus
	node.childNodes[0].focus()

	// Error: Selection passed to setSelection must point at the current document
	view.dispatch(
		view.state.tr.setSelection(
			TextSelection.atEnd(view.state.tr.doc.firstChild)
		)
	)

I’m seeing a weird error having to do with the doc being used for the selection is not the same on for the transaction? It’s a bit unclear to me what I’m supposed to do differently though.

Any thoughts?

Thanks

Does your state initialization set the state’s doc to doc? In any case, you’ll probably want to pass the new selection right away when creating the state, and call view.focus() instead of just the DOM focus method.

Ah, I get it now.

Calling node.childNodes[0].focus() changes the selection of the view which means that the state has changed by the time I call setSelection.

This appears to work without that error.

const state = EditorState.create({
    selection: TextSelection.atEnd(doc.firstChild!),
    /* ... */
})
view.focus()

However, I think I may have found a bug… This code places the cursor at one character before the end :thinking:

This is the code I have:

const doc = schema.nodeFromJSON(initialDocJson)

const state = EditorState.create({
	selection: TextSelection.atEnd(doc.firstChild!),
	schema: schema,
	doc: doc,
	plugins: [
		history(),
		keymap({ "Mod-z": undo, "Mod-y": redo }),
		keymap({ "Mod-b": toggleMark(schema.marks.bold) }),
	],
})

And here is the result: ProseMirror Examples

You can repro yourself as well:

git clone git@github.com:ccorcos/prosemirror-examples.git
cd prosemirror-examples
npm install
npm start
open http://localhost:8080/#/focus

atEnd expects the entire document, not any node (it creates a selection relative to the document it was given, which as you found doesn’t work if it only uses a given node).

Ah, that makes sense. Thanks