utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. import {
  6. downcastInsertCell,
  7. downcastInsertRow,
  8. downcastInsertTable,
  9. downcastRemoveRow,
  10. downcastTableHeadingColumnsChange,
  11. downcastTableHeadingRowsChange
  12. } from '../../src/converters/downcast';
  13. import upcastTable, { upcastTableCell } from '../../src/converters/upcasttable';
  14. import { assertEqualMarkup } from '@ckeditor/ckeditor5-utils/tests/_utils/utils';
  15. const WIDGET_TABLE_CELL_CLASS = 'ck-editor__editable ck-editor__nested-editable';
  16. /**
  17. * Returns a model representation of a table shorthand notation:
  18. *
  19. * modelTable( [
  20. * [ '00' ] // first row
  21. * [ '10' ] // second row
  22. * ] );
  23. *
  24. * will output:
  25. *
  26. * '<table><tableRow><tableCell>00</tableCell></tableRow><tableRow><tableCell>10</tableCell></tableRow></table>'
  27. *
  28. * Each table row passed in `tableData` array is represented as an array of strings or objects. A string defines text contents of a cell.
  29. *
  30. * Passing an object allows to pass additional table cell attributes:
  31. *
  32. * const tableCellData = {
  33. * colspan: 2,
  34. * rowspan: 4,
  35. * contents: 'foo' // text contents of a cell
  36. * };
  37. *
  38. * @param {Array.<Array.<String>|Object>} tableData
  39. * @param {Object} [attributes] Optional table attributes: `headingRows` and `headingColumns`.
  40. *
  41. * @returns {String}
  42. */
  43. export function modelTable( tableData, attributes ) {
  44. const tableRows = makeRows( tableData, {
  45. cellElement: 'tableCell',
  46. rowElement: 'tableRow',
  47. headingElement: 'tableCell',
  48. wrappingElement: 'paragraph',
  49. enforceWrapping: true
  50. } );
  51. return `<table${ formatAttributes( attributes ) }>${ tableRows }</table>`;
  52. }
  53. /**
  54. * Returns a view representation of a table shorthand notation:
  55. *
  56. * viewTable( [
  57. * [ '00', '01' ] // first row
  58. * [ '10', '11' ] // second row
  59. * ] );
  60. *
  61. * will output:
  62. *
  63. * '<table><tbody><tr><td>00</td><td>01<td></tr><tr><td>10</td><td>11<td></tr></tbody></table>'
  64. *
  65. * Each table row passed in `tableData` array is represented as an array of strings or objects. A string defines text contents of a cell.
  66. *
  67. * Passing an object allows to pass additional table cell attributes:
  68. *
  69. * const tableCellData = {
  70. * colspan: 2,
  71. * rowspan: 4,
  72. * isHeading: true, // will render table cell as `<th>` element
  73. * contents: 'foo' // text contents of a cell
  74. * };
  75. *
  76. * @param {Array.<Array.<String|Object>>} tableData The table data array.
  77. * @param {Object} [attributes] Optional table attributes: `headingRows` and `headingColumns` - passing them will properly render rows
  78. * in `<tbody>` or `<thead>` sections.
  79. *
  80. * @returns {String}
  81. */
  82. export function viewTable( tableData, attributes = {} ) {
  83. const headingRows = attributes.headingRows || 0;
  84. const asWidget = !!attributes.asWidget;
  85. const thead = headingRows > 0 ? `<thead>${ makeRows( tableData.slice( 0, headingRows ), {
  86. cellElement: 'th',
  87. rowElement: 'tr',
  88. headingElement: 'th',
  89. wrappingElement: asWidget ? 'span' : 'p',
  90. enforceWrapping: asWidget,
  91. asWidget
  92. } ) }</thead>` : '';
  93. const tbody = tableData.length > headingRows ?
  94. `<tbody>${ makeRows( tableData.slice( headingRows ), {
  95. cellElement: 'td',
  96. rowElement: 'tr',
  97. headingElement: 'th',
  98. wrappingElement: asWidget ? 'span' : 'p',
  99. enforceWrapping: asWidget,
  100. asWidget
  101. } ) }</tbody>` : '';
  102. const figureAttributes = asWidget ?
  103. 'class="ck-widget ck-widget_with-selection-handle table" contenteditable="false"' : 'class="table"';
  104. const widgetHandler = '<div class="ck ck-widget__selection-handle"></div>';
  105. return `<figure ${ figureAttributes }>${ asWidget ? widgetHandler : '' }<table>${ thead }${ tbody }</table></figure>`;
  106. }
  107. /**
  108. * Formats model or view table - useful for chai assertions debugging.
  109. *
  110. * @param {String} tableString
  111. * @returns {String}
  112. */
  113. export function formatTable( tableString ) {
  114. return tableString
  115. .replace( /<tableRow>/g, '\n<tableRow>\n ' )
  116. .replace( /<thead>/g, '\n<thead>\n ' )
  117. .replace( /<tbody>/g, '\n<tbody>\n ' )
  118. .replace( /<tr>/g, '\n<tr>\n ' )
  119. .replace( /<\/tableRow>/g, '\n</tableRow>' )
  120. .replace( /<\/thead>/g, '\n</thead>' )
  121. .replace( /<\/tbody>/g, '\n</tbody>' )
  122. .replace( /<\/tr>/g, '\n</tr>' )
  123. .replace( /<\/table>/g, '\n</table>' )
  124. .replace( /<\/figure>/g, '\n</figure>' );
  125. }
  126. /**
  127. * Returns formatted model table string.
  128. *
  129. * @param {Array.<String>} tableData
  130. * @param {Object} [attributes]
  131. * @returns {String}
  132. */
  133. export function formattedModelTable( tableData, attributes ) {
  134. const tableString = modelTable( tableData, attributes );
  135. return formatTable( tableString );
  136. }
  137. /**
  138. * Returns formatted view table string.
  139. *
  140. * @param {Array.<String>} tableData
  141. * @param {Object} [attributes]
  142. * @returns {String}
  143. */
  144. export function formattedViewTable( tableData, attributes ) {
  145. return formatTable( viewTable( tableData, attributes ) );
  146. }
  147. export function defaultSchema( schema, registerParagraph = true ) {
  148. schema.register( 'table', {
  149. allowWhere: '$block',
  150. allowAttributes: [ 'headingRows', 'headingColumns' ],
  151. isLimit: true,
  152. isObject: true,
  153. isBlock: true
  154. } );
  155. schema.register( 'tableRow', {
  156. allowIn: 'table',
  157. isLimit: true
  158. } );
  159. schema.register( 'tableCell', {
  160. allowIn: 'tableRow',
  161. allowAttributes: [ 'colspan', 'rowspan' ],
  162. isLimit: true
  163. } );
  164. // Allow all $block content inside table cell.
  165. schema.extend( '$block', { allowIn: 'tableCell' } );
  166. // Disallow table in table.
  167. schema.addChildCheck( ( context, childDefinition ) => {
  168. if ( childDefinition.name == 'table' && Array.from( context.getNames() ).includes( 'table' ) ) {
  169. return false;
  170. }
  171. } );
  172. if ( registerParagraph ) {
  173. schema.register( 'paragraph', { inheritAllFrom: '$block' } );
  174. }
  175. // Styles
  176. schema.extend( 'tableCell', {
  177. allowAttributes: [ 'border' ]
  178. } );
  179. }
  180. export function defaultConversion( conversion, asWidget = false ) {
  181. conversion.elementToElement( { model: 'paragraph', view: 'p' } );
  182. // Table conversion.
  183. conversion.for( 'upcast' ).add( upcastTable() );
  184. conversion.for( 'downcast' ).add( downcastInsertTable( { asWidget } ) );
  185. // Table row conversion.
  186. conversion.for( 'upcast' ).elementToElement( { model: 'tableRow', view: 'tr' } );
  187. conversion.for( 'downcast' ).add( downcastInsertRow( { asWidget } ) );
  188. conversion.for( 'downcast' ).add( downcastRemoveRow( { asWidget } ) );
  189. // Table cell conversion.
  190. conversion.for( 'upcast' ).add( upcastTableCell( 'td' ) );
  191. conversion.for( 'upcast' ).add( upcastTableCell( 'th' ) );
  192. conversion.for( 'downcast' ).add( downcastInsertCell( { asWidget } ) );
  193. // Table attributes conversion.
  194. conversion.attributeToAttribute( { model: 'colspan', view: 'colspan' } );
  195. conversion.attributeToAttribute( { model: 'rowspan', view: 'rowspan' } );
  196. conversion.for( 'downcast' ).add( downcastTableHeadingColumnsChange( { asWidget } ) );
  197. conversion.for( 'downcast' ).add( downcastTableHeadingRowsChange( { asWidget } ) );
  198. // Styles
  199. conversion.for( 'upcast' ).attributeToAttribute( {
  200. view: {
  201. name: 'td',
  202. styles: {
  203. border: /[\s\S]+/
  204. }
  205. },
  206. model: {
  207. key: 'border',
  208. value: viewElement => viewElement.getStyle( 'border' )
  209. }
  210. } );
  211. }
  212. /**
  213. * Assertion helper for top-right-bottom-left attribute object.
  214. *
  215. * @param {module:engine/model/node~Node} element
  216. * @param {String} key Attribute key
  217. * @param {String} top Top value. Pass null to omit value in attributes object.
  218. * @param {String} [right=top] Right value - defaults to top if not provided.
  219. * Pass null to omit value in attributes object.
  220. * @param {String} [bottom=top] Bottom value - defaults to top (right value must be defined).
  221. * Pass null to omit value in attributes object.
  222. * @param {String} [left=right] Left value - defaults to right (bottom and right values must be defined).
  223. * Pass null to omit value in attributes object.
  224. */
  225. export function assertTRBLAttribute( element, key, top, right = top, bottom = top, left = right ) {
  226. const styleObject = {};
  227. if ( top ) {
  228. styleObject.top = top;
  229. }
  230. if ( right ) {
  231. styleObject.right = right;
  232. }
  233. if ( bottom ) {
  234. styleObject.bottom = bottom;
  235. }
  236. if ( left ) {
  237. styleObject.left = left;
  238. }
  239. expect( element.getAttribute( key ) ).to.deep.equal( styleObject );
  240. }
  241. /**
  242. * Assertion helper for testing <table> style attribute.
  243. *
  244. * @param {module:core/editor/editor~Editor} editor
  245. * @param {String} tableStyle A style to assert on table.
  246. */
  247. export function assertTableStyle( editor, tableStyle ) {
  248. assertEqualMarkup( editor.getData(),
  249. `<figure class="table"><table style="${ tableStyle }"><tbody><tr><td>foo</td></tr></tbody></table></figure>`
  250. );
  251. }
  252. /**
  253. * Assertion helper for testing <td> style attribute.
  254. *
  255. * @param {module:core/editor/editor~Editor} editor
  256. * @param {String} tableCellStyle A style to assert on td.
  257. */
  258. export function assertTableCellStyle( editor, tableCellStyle ) {
  259. assertEqualMarkup( editor.getData(),
  260. `<figure class="table"><table><tbody><tr><td style="${ tableCellStyle }">foo</td></tr></tbody></table></figure>`
  261. );
  262. }
  263. // Formats table cell attributes
  264. //
  265. // @param {Object} attributes Attributes of a cell.
  266. function formatAttributes( attributes ) {
  267. let attributesString = '';
  268. if ( attributes ) {
  269. const entries = Object.entries( attributes );
  270. if ( entries.length ) {
  271. attributesString = ' ' + entries.map( entry => `${ entry[ 0 ] }="${ entry[ 1 ] }"` ).join( ' ' );
  272. }
  273. }
  274. return attributesString;
  275. }
  276. // Formats passed table data to a set of table rows.
  277. function makeRows( tableData, options ) {
  278. const { cellElement, rowElement, headingElement, wrappingElement, enforceWrapping, asWidget } = options;
  279. return tableData
  280. .reduce( ( previousRowsString, tableRow ) => {
  281. const tableRowString = tableRow.reduce( ( tableRowString, tableCellData ) => {
  282. const isObject = typeof tableCellData === 'object';
  283. let contents = isObject ? tableCellData.contents : tableCellData;
  284. let resultingCellElement = cellElement;
  285. if ( isObject ) {
  286. if ( tableCellData.isHeading ) {
  287. resultingCellElement = headingElement;
  288. }
  289. delete tableCellData.contents;
  290. delete tableCellData.isHeading;
  291. }
  292. const attributes = isObject ? tableCellData : {};
  293. if ( asWidget ) {
  294. attributes.class = WIDGET_TABLE_CELL_CLASS + ( attributes.class ? ` ${ attributes.class }` : '' );
  295. attributes.contenteditable = 'true';
  296. }
  297. if ( !( contents.replace( '[', '' ).replace( ']', '' ).startsWith( '<' ) ) && enforceWrapping ) {
  298. contents = `<${ wrappingElement }>${ contents }</${ wrappingElement }>`;
  299. }
  300. const formattedAttributes = formatAttributes( attributes );
  301. tableRowString += `<${ resultingCellElement }${ formattedAttributes }>${ contents }</${ resultingCellElement }>`;
  302. return tableRowString;
  303. }, '' );
  304. return `${ previousRowsString }<${ rowElement }>${ tableRowString }</${ rowElement }>`;
  305. }, '' );
  306. }