4

I'm trying to allow users to paste (relatively) simple tables into Gutenberg. The editor converts the raw HTML fine but strips out any attributes/classes. For the most part this is good - I want to ensure the markup is clean - but it strips out the colspan and rowspan attributes too.

Looking into the table block in the Gutenberg repo on GitHub and block filters in the Guenberg Handbook on wordpress.org, I've put together the following:

const { getPhrasingContentSchema } = wp.blocks;

// Partially defines what's allowed in a table when pasted.
// Copied from the core table block file in the Gutenberg repo.
const tableContentPasteSchema = {
    tr: {
        children: {
            th: {
                children: getPhrasingContentSchema(),
            },
            td: {
                children: getPhrasingContentSchema(),

                // This is the only new part in the schema
                attributes: [ 'colspan', 'rowspan'],
            },
        },
    },
};

// Partially defines what's allowed in a table when pasted.
// Copied from the core table block file in the Gutenberg repo.
const tablePasteSchema = {
    table: {
        children: {
            thead: {
                children: tableContentPasteSchema,
            },
            tfoot: {
                children: tableContentPasteSchema,
            },
            tbody: {
                children: tableContentPasteSchema,
            },
        },
    },
};

// Overloads the table block transforms setting
function addTableBlockSpanAttributes( settings, name ) {
    if ( name !== 'core/table' ) {
        return settings;
    }

    return lodash.assign({}, settings, {
        transforms: {
            from: [
                {
                    type: 'raw',
                    selector: 'table',
                    schema: tableSchema,
                },
            ],
        },
    });
}

wp.hooks.addFilter(
    'blocks.registerBlockType',
    'my-plugin/transforms/table-block',
    addTableBlockSpanAttributes
);

(Code based on example here: https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-registerblocktype)

This all seems to be correct as far as I can tell, but any colspan/rowspans are stripped when pasted in. In addition, manually editing the block in the post HTML causes a block error which can only be resolved by removing the colspan/rowspan attribute.

It's worth noting that if I use the same code but allow colspan on a <span> inside the <td> that works absolutely fine (despite <span colspan="2"> not being valid HTML).

What am I doing wrong? Is there another approach to overloading the core/table block's allowed attributes? Is there something else in core that's prohibiting <td> attributes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.