8
0

utils.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @param {Number} columns
  7. * @param {Array.<String>} tableData
  8. * @param {Object} [attributes]
  9. *
  10. * @returns {String}
  11. */
  12. export function modelTable( columns, tableData, attributes ) {
  13. const tableRows = tableData
  14. .map( cellData => `<tableCell>${ cellData }</tableCell>` )
  15. .reduce( ( table, tableCell, index ) => {
  16. if ( index % columns === 0 ) {
  17. table += '<tableRow>';
  18. }
  19. table += tableCell;
  20. if ( index % columns === columns - 1 ) {
  21. table += '</tableRow>';
  22. }
  23. return table;
  24. }, '' );
  25. let attributesString = '';
  26. if ( attributes ) {
  27. const entries = Object.entries( attributes );
  28. attributesString = ' ' + entries.map( entry => `${ entry[ 0 ] }="${ entry[ 1 ] }"` ).join( ' ' );
  29. }
  30. return `<table${ attributesString }>${ tableRows }</table>`;
  31. }
  32. export function formatModelTable( tableString ) {
  33. return tableString
  34. .replace( /<tableRow>/g, '\n<tableRow>\n ' )
  35. .replace( /<\/tableRow>/g, '\n</tableRow>' )
  36. .replace( /<\/table>/g, '\n</table>' );
  37. }
  38. export function formattedModelTable( columns, tableData, attributes ) {
  39. const tableString = modelTable( columns, tableData, attributes );
  40. return formatModelTable( tableString );
  41. }