Hi everyone i’m new to prosemirror and I’m trying to figure it out the best solution to add a node from the menu into the doc but after a specific node position . So for example I have this editor that can have sections, and each section has a header and a content.
<section contenteditable="true">
<div class="section-heading">
<h1>TEXT</h1>
<span class="section-heading-line"></span>
</div>
<div class="section-content">
<h2>H2 Heading</h2></div>
<blockquote>
<p style="text-align: left">A block quote</p><p style="text-align: left">With some text</p>.
</blockquote>
</section>
<section contenteditable="true">
<div class="section-heading">
<h1>TEXT2</h1>
<span class="section-heading-line"></span>
</div>
<div class="section-content">
<p>Something</p>
</div>
</section>
<section contenteditable="true">...</section>
.
.
.
In the menu i have a function that allows me to add a new section, and the desired behaviour is to add that new <section>
AFTER the current one. Considering that i need to find the parent i’m in, i’m going through all the parents from current node till i find a nodeType section.
export function getMainParentPosition(state: EditorState, parentType: NodeType) {
const selectionStart: ResolvedPos = state.selection.$from;
let { depth } = selectionStart;
let parent;
console.log('selection start', selectionStart);
console.log('state', state)
do {
parent = selectionStart.node(depth);
if (parent) {
if (parent.type === parentType) {
console.log('NOW WE GOT the Section Parent from our selection ',parent.content.size);
// HERE i would like to return the position where the next node will be inserted
// From the examples i saw people return the size of the parent, but in this case is not the correct answer.
return parent.content.size;
}
depth--;
}
} while (depth > 0 && parent);
}
But now that i have the parent from that selection i just can’t seem to find from where to take the position at the end of this parent ? I thought the size would do, but if i am in the second section trying to ad a 3rd, i will get the size of that section only and its not the correct position in the doc.
const node = state.schema.nodes.section.create(null, [sectionHeader, content]);
const parentPosition = getMainParentPosition(state, state.schema.nodes.section);
let newSectionPosition =
transaction.doc.content.size > 1 && parentPosition ? parentPosition + 1 : transaction.doc.content.size;
console.log('position', newSectionPosition, node, checkParent);
if (dispatch) {
dispatch(
transaction
.insert(newSectionPosition, node)
.scrollIntoView()
.setSelection(TextSelection.near(transaction.doc.resolve(newSectionPosition))),
);
}
inserting it like this, only works when i want to add a new section FROM ANYWHERE inside the first section because then the size is actually the position of that node.
I appreciate your help on this thank you.