Set property of all table cells

Hi

In our work, we have started to implement the prosemirror editor. In it, we added support for tables, and have made use of cell attributes, example from schema

cellAttributes: {
    background: {
        default: null,
        getFromDOM(dom) {
            return (dom.dataset && dom.dataset.cellBackground) || null;
        },
        setDOMAttr(value, attrs) {
            if (value){
                attrs["data-cell-background"] = value
            }
        }
    }
}

We have also implemented our own menubar. From the menu bar, we do the following to update background colour of table cells:

        const cmd = setCellAttr("background", colour)
        cmd(this.state, this.dispatch)

This works great. However, I’m having some problems figuring out how to

  1. On click on a button
  2. Iterate all table cells
  3. clear background attribute on iterated table cell

i.e. walk through all table cells, and call setCellAttr("background", null)

This is something we need when we want to “remove all styling” from the editor.

Thanks in advance

You could use use state.doc.descendants, check whether each node is a table cell with attributes to clear, and if so, use setNodeMarkup to build up a transaction that clears the attribute.

Thank you so much for the quick reply

Is there a straightforward way of getting the position of each cell, i.e. for the first argument to setNodeMarkup

this.doc.descendants((node) => {
    if (node.type.name === "table_cell" && node.attrs.background) {
        // const pos =
        this.state.tr.setNodeMarkup(pos, null, setAttr(node.attrs, "background", null))
    }
})

Yes, it’s the second argument to the callback you pass to descendants.

Fantastic :slight_smile:

This works:

this.doc.descendants((node, pos) => {
    if (node.type.name === "table_cell" && node.attrs.background) {
        tr.setNodeMarkup(pos, null, setAttr(node.attrs, "background", null))
    }
})