/** * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md. */ function formatAttributes( attributes ) { let attributesString = ''; if ( attributes ) { const entries = Object.entries( attributes ); if ( entries.length ) { attributesString = ' ' + entries.map( entry => `${ entry[ 0 ] }="${ entry[ 1 ] }"` ).join( ' ' ); } } return attributesString; } function makeRows( tableData, cellElement, rowElement, headingElement = 'th' ) { const tableRows = tableData .reduce( ( previousRowsString, tableRow ) => { const tableRowString = tableRow.reduce( ( tableRowString, tableCellData ) => { let tableCell = tableCellData; const isObject = typeof tableCellData === 'object'; let resultingCellElement = cellElement; if ( isObject ) { tableCell = tableCellData.contents; if ( tableCellData.isHeading ) { resultingCellElement = headingElement; } delete tableCellData.contents; delete tableCellData.isHeading; } const formattedAttributes = formatAttributes( isObject ? tableCellData : '' ); tableRowString += `<${ resultingCellElement }${ formattedAttributes }>${ tableCell }`; return tableRowString; }, '' ); return `${ previousRowsString }<${ rowElement }>${ tableRowString }`; }, '' ); return tableRows; } /** * @param {Number} columns * @param {Array.} tableData * @param {Object} [attributes] * * @returns {String} */ export function modelTable( tableData, attributes ) { const tableRows = makeRows( tableData, 'tableCell', 'tableRow' ); return `${ tableRows }`; } /** * @param {Number} columns * @param {Array.} tableData * @param {Object} [attributes] * * @returns {String} */ export function viewTable( tableData, attributes = {} ) { const headingRows = attributes.headingRows || 0; const thead = headingRows > 0 ? `${ makeRows( tableData.slice( 0, headingRows ), 'th', 'tr' ) }` : ''; const tbody = tableData.length > headingRows ? `${ makeRows( tableData.slice( headingRows ), 'td', 'tr' ) }` : ''; return `${ thead }${ tbody }
`; } export function formatModelTable( tableString ) { return tableString .replace( //g, '\n\n ' ) .replace( /<\/tableRow>/g, '\n' ) .replace( /<\/table>/g, '\n' ); } export function formattedModelTable( tableData, attributes ) { const tableString = modelTable( tableData, attributes ); return formatModelTable( tableString ); }