I’ve set up the schema and a plugin to assign a unique ID to each paragraph. The schema includes this attribute blockId
:
paragraph: {
attrs: { blockId: { default: null } },
content: 'inline*',
group: 'block',
parseDOM: [
{
tag: 'p',
getAttrs(dom) {
const p = dom as HTMLParagraphElement;
return {
blockId: p.getAttribute('data-block-id'),
};
},
},
],
toDOM(node: ProsemirrorNode) {
const domAttrs = {
'data-block-id': node.attrs.blockId,
};
return ['p', domAttrs, 0];
},
},
and it gets assigned by this plugin:
export const blockIdPlugin = new Plugin({
appendTransaction: (transactions, _prevState, nextState) => {
const tr = nextState.tr;
let modified = false;
if (transactions.some((transaction) => transaction.docChanged)) {
nextState.doc.descendants((node, pos) => {
if ('blockId' in node.attrs && node.attrs.blockId == null) {
tr.setNodeMarkup(pos, undefined, { ...node.attrs, blockId: nanoid() });
modified = true;
}
});
}
return modified ? tr : null;
},
});
However, when I create new empty paragraphs in the editor (press Enter a few times), only the first paragraph gets assigned a unique ID and the subsequent paragraphs reuse the same attribute values. Does ProseMirror automatically copy attribute values to new nodes? Is there a way to control this behaviour?