Appending one block to another, preserving cursor position

I am trying to join 2 ProseMirror docs, one of which is focused and contains a cursor:

<doc-1> Hello… </doc-1>

<doc-2> Ther<CURSOR>e… </doc-2>

(we can assume that we already know which doc is focused)

I would like to append doc-2 to doc-1, and have the cursor remain exactly where it is. Is there a straightforward way to think about doing this? I haven’t yet wrapped my head around all the different kinds of selections and positions.

I’ve tried reading the cursor’s coordinates on the screen, and then mapping that back to the newly-joined doc, but was getting inconsistent results, and this also wouldn’t work if the two docs were not exactly next to each other. I would rather have some way of using the offset/position precisely, just not sure how to do that when joining two documents.

If the docs can be cleanly joined, without introducing intermediate wrapper nodes, you can just add the size of the first doc to the cursor position and create a new selection from that, i.e. something like TextSelection.create(joinedDoc, oldSelection.anchor + doc1.content.size). A cleaner and more general way is to create a mapping that moves all positions forward, and map the selection through that — oldSelection.map(joineDoc, StepMap.offset(doc1.content.size)) (though StepMap.offset isn’t in the latest release yet, where you’d do something like new StepMap([0, 0, doc1.content.size]) instead.

Thanks, that’s very helpful.