8
0

utils.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. function makeRows( tableData, cellElement, rowElement ) {
  14. const tableRows = tableData
  15. .reduce( ( previousRowsString, tableRow ) => {
  16. const tableRowString = tableRow.reduce( ( tableRowString, tableCellData ) => {
  17. let tableCell = tableCellData;
  18. const isObject = typeof tableCellData === 'object';
  19. if ( isObject ) {
  20. tableCell = tableCellData.contents;
  21. delete tableCellData.contents;
  22. }
  23. const formattedAttributes = formatAttributes( isObject ? tableCellData : '' );
  24. tableRowString += `<${ cellElement }${ formattedAttributes }>${ tableCell }</${ cellElement }>`;
  25. return tableRowString;
  26. }, '' );
  27. return `${ previousRowsString }<${ rowElement }>${ tableRowString }</${ rowElement }>`;
  28. }, '' );
  29. return tableRows;
  30. }
  31. /**
  32. * @param {Number} columns
  33. * @param {Array.<String>} tableData
  34. * @param {Object} [attributes]
  35. *
  36. * @returns {String}
  37. */
  38. export function modelTable( tableData, attributes ) {
  39. const tableRows = makeRows( tableData, 'tableCell', 'tableRow' );
  40. return `<table${ formatAttributes( attributes ) }>${ tableRows }</table>`;
  41. }
  42. /**
  43. * @param {Number} columns
  44. * @param {Array.<String>} tableData
  45. * @param {Object} [attributes]
  46. *
  47. * @returns {String}
  48. */
  49. export function viewTable( tableData, attributes ) {
  50. const tableRows = makeRows( tableData, 'td', 'tr' );
  51. return `<table${ formatAttributes( attributes ) }><tbody>${ tableRows }</tbody></table>`;
  52. }
  53. export function formatModelTable( tableString ) {
  54. return tableString
  55. .replace( /<tableRow>/g, '\n<tableRow>\n ' )
  56. .replace( /<\/tableRow>/g, '\n</tableRow>' )
  57. .replace( /<\/table>/g, '\n</table>' );
  58. }
  59. export function formattedModelTable( tableData, attributes ) {
  60. const tableString = modelTable( tableData, attributes );
  61. return formatModelTable( tableString );
  62. }