Update parent node's attrs when child node's attrs change

This seems to work, though I’m not sure whether it has any problems:

  • Define an attr on the parent node (chunk) (here I’m just using numChildren which will hold childCount, which is something that changes on join operations I care about)
  • In a plugin, recompute and update this attr for every parent node affected.

I understand from Identifying the changed nodes for a given transaction - #2 by marijn that the latter may require more care to get the positions right, but for typical cases / light editing, this seems to work:

function updateChunkAttrPlugin() {
    return new Plugin({
        appendTransaction(transactions, oldState, newState) {
            let transactionToAppend: Transaction | null = null;
            transactions.forEach(tx => {
                tx.steps.forEach((step) => {
                    step.getMap().forEach((oldStart, oldEnd, newStart, newEnd) => {
                        newState.doc.nodesBetween(newStart, newEnd, (node, pos) => {
                            if (node.type.name === "chunk") {
                                const newAttrValue = node.childCount;
                                if (node.attrs.numChildren !== newAttrValue) {
                                    if (!transactionToAppend) transactionToAppend = newState.tr;
                                    transactionToAppend.setNodeAttribute(pos, 'numChildren', newAttrValue);
                                }
                            }
                        });
                    });
                });
            });
            return transactionToAppend;
        }
    });
}