import { createBlock } from '@wordpress/blocks'; import type { BlockConfiguration } from '@wordpress/blocks'; import { normalizeRowColSpan } from './utils'; import type { TableCell, TableCellTag, TablePasteSchemaArgs, TableRow, TableSectionName, } from './types'; const tableContentPasteSchema = ( { phrasingContentSchema, }: TablePasteSchemaArgs ) => ( { tr: { allowEmpty: true, children: { th: { allowEmpty: true, children: phrasingContentSchema, attributes: [ 'scope', 'colspan', 'rowspan', 'style' ], }, td: { allowEmpty: true, children: phrasingContentSchema, attributes: [ 'colspan', 'rowspan', 'style' ], }, }, }, } ); const tablePasteSchema = ( args: TablePasteSchemaArgs ) => ( { table: { children: { thead: { allowEmpty: true, children: tableContentPasteSchema( args ), }, tfoot: { allowEmpty: true, children: tableContentPasteSchema( args ), }, tbody: { allowEmpty: true, children: tableContentPasteSchema( args ), }, }, }, } ); const transforms: BlockConfiguration[ 'transforms' ] = { from: [ { type: 'raw', selector: 'table', schema: tablePasteSchema, transform: ( node ) => { const attributes = Array.from( node.children ).reduce( ( sectionAcc, section ) => { if ( ! section.children.length ) { return sectionAcc; } const sectionName = section.nodeName .toLowerCase() .slice( 1 ) as TableSectionName; const sectionAttributes = Array.from( section.children ).reduce( ( rowAcc, row ) => { if ( ! row.children.length ) { return rowAcc; } const rowAttributes = Array.from( row.children ).reduce( ( colAcc, col ) => { const rowspan = normalizeRowColSpan( col.getAttribute( 'rowspan' ) ); const colspan = normalizeRowColSpan( col.getAttribute( 'colspan' ) ); const { textAlign } = ( col as HTMLElement ).style || {}; let align: string | undefined; if ( textAlign === 'left' || textAlign === 'center' || textAlign === 'right' ) { align = textAlign; } colAcc.push( { tag: col.nodeName.toLowerCase() as TableCellTag, content: col.innerHTML, rowspan, colspan, align, } ); return colAcc; }, [] as TableCell[] ); rowAcc.push( { cells: rowAttributes, } ); return rowAcc; }, [] as TableRow[] ); sectionAcc[ sectionName ] = sectionAttributes; return sectionAcc; }, {} as Partial< Record< TableSectionName, TableRow[] > > ); return createBlock( 'core/table', attributes ); }, }, ], }; export default transforms;