8
0

utils.js 1.6 KB

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