I get very confused by the “pos” values that are used throughout the docs.
In an appendTransaction
, I check if the number of paragraphs has grown. If it has, I grab the marks from the selection position of the old state, and then try to store them in the new state:
new Plugin({
appendTransaction(transactions, oldState, newState) {
const oldParagraphCount = oldState.doc.content.content.length;
const newParagraphCount = newState.doc.content.content.length;
if (newParagraphCount > oldParagraphCount) {
const transaction = newState.tr;
const oldMarks = oldState.storedMarks || oldState.selection.$head.marks();
const markObj = oldMarks.reduce((all, current) => {
const markName = current.type.name;
const markValue = current.attrs[markName];
all[markName] = markValue;
return all;
}, {});
transaction.setStoredMarks(oldMarks);
transaction.setNodeMarkup(
newState.selection.$head.pos - 1,
null,
{ marks: markObj }
);
return transaction;
}
}
})
Here, I found that I have to subtract one from the resolved position of the selection head. This works as long as I am pressing enter while at the end of the last paragraph. If, however, I am in any paragraph before the last one, the setNodeMarkup
doesn’t target the node I expect.
I really expected to be able to do this:
transaction.setNodeMarkup(
newState.selection.$head.pos,
null,
{ marks: markObj }
);
This raises RangeError: No node at given position
.
I am missing something fundamental in my understanding of the positions, but I don’t know what it is. Can anyone help me to bridge the gap in my understanding?
Thank you!