utils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. import { assertEqualMarkup } from '@ckeditor/ckeditor5-utils/tests/_utils/utils';
  6. import { setData } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
  7. import TableWalker from '../../src/tablewalker';
  8. const WIDGET_TABLE_CELL_CLASS = 'ck-editor__editable ck-editor__nested-editable';
  9. /**
  10. * Returns a model representation of a table shorthand notation:
  11. *
  12. * modelTable( [
  13. * [ '00' ] // first row
  14. * [ '10' ] // second row
  15. * ] );
  16. *
  17. * will output:
  18. *
  19. * '<table><tableRow><tableCell>00</tableCell></tableRow><tableRow><tableCell>10</tableCell></tableRow></table>'
  20. *
  21. * Each table row passed in `tableData` array is represented as an array of strings or objects. A string defines text contents of a cell.
  22. *
  23. * Passing an object allows to pass additional table cell attributes:
  24. *
  25. * const tableCellData = {
  26. * colspan: 2,
  27. * rowspan: 4,
  28. * contents: 'foo' // text contents of a cell
  29. * };
  30. *
  31. * @param {Array.<Array.<String>|Object>} tableData
  32. * @param {Object} [attributes] Optional table attributes: `headingRows` and `headingColumns`.
  33. *
  34. * @returns {String}
  35. */
  36. export function modelTable( tableData, attributes ) {
  37. const tableRows = makeRows( tableData, {
  38. cellElement: 'tableCell',
  39. rowElement: 'tableRow',
  40. headingElement: 'tableCell',
  41. wrappingElement: 'paragraph',
  42. enforceWrapping: true
  43. } );
  44. return `<table${ formatAttributes( attributes ) }>${ tableRows }</table>`;
  45. }
  46. /**
  47. * A helper method for creating a test table with a single table cell of which attributes are defined as objects.
  48. *
  49. * setTableCellWithObjectAttributes(
  50. * model,
  51. * {
  52. * margin: { top: '1px', left: '2px' },
  53. * borderColor: { top: '#f00', left: '#ba2' }
  54. * backgroundColor: '#f00'
  55. * },
  56. * 'fo[o]'
  57. * );
  58. *
  59. * This will create a model table with one table cell with a "foo" text.
  60. * The selection will be set on the last "o" and a table cell will have three attributes.
  61. *
  62. * @param {module:engine/model/model~Model} model
  63. * @param {Object} attributes
  64. * @param {String} cellContent
  65. */
  66. export function setTableCellWithObjectAttributes( model, attributes, cellContent ) {
  67. setData( model, modelTable( [ [ { contents: cellContent } ] ] ) );
  68. const tableCell = model.document.getRoot().getNodeByPath( [ 0, 0, 0 ] );
  69. model.change( writer => {
  70. for ( const [ key, value ] of Object.entries( attributes ) ) {
  71. writer.setAttribute( key, value, tableCell );
  72. }
  73. } );
  74. }
  75. /**
  76. * A helper method for creating a test table, with a single table cell. Table attributes are defined as objects.
  77. *
  78. * setTableWithObjectAttributes(
  79. * model,
  80. * {
  81. * borderColor: { top: '#f00', left: '#ba2' }
  82. * backgroundColor: '#f00'
  83. * },
  84. * 'fo[o]'
  85. * );
  86. *
  87. * This will create a model table with one table cell with a "foo" text.
  88. * The selection will be set on last "o" and a table will have three attributes.
  89. *
  90. * @param {module:engine/model/model~Model} model
  91. * @param {Object} attributes
  92. * @param {String} cellContent
  93. */
  94. export function setTableWithObjectAttributes( model, attributes, cellContent ) {
  95. setData( model, modelTable( [ [ { contents: cellContent } ] ] ) );
  96. const table = model.document.getRoot().getChild( 0 );
  97. model.change( writer => {
  98. for ( const [ key, value ] of Object.entries( attributes ) ) {
  99. writer.setAttribute( key, value, table );
  100. }
  101. } );
  102. }
  103. /**
  104. * Returns a view representation of a table shorthand notation:
  105. *
  106. * viewTable( [
  107. * [ '00', '01' ] // first row
  108. * [ '10', '11' ] // second row
  109. * ] );
  110. *
  111. * will output:
  112. *
  113. * '<table><tbody><tr><td>00</td><td>01<td></tr><tr><td>10</td><td>11<td></tr></tbody></table>'
  114. *
  115. * Each table row passed in `tableData` array is represented as an array of strings or objects. A string defines text contents of a cell.
  116. *
  117. * Passing an object allows to pass additional table cell attributes:
  118. *
  119. * const tableCellData = {
  120. * colspan: 2,
  121. * rowspan: 4,
  122. * isHeading: true, // will render table cell as `<th>` element
  123. * contents: 'foo' // text contents of a cell
  124. * };
  125. *
  126. * @param {Array.<Array.<String|Object>>} tableData The table data array.
  127. * @param {Object} [attributes] Optional table attributes: `headingRows` and `headingColumns` - passing them will properly render rows
  128. * in `<tbody>` or `<thead>` sections.
  129. *
  130. * @returns {String}
  131. */
  132. export function viewTable( tableData, attributes = {} ) {
  133. const headingRows = attributes.headingRows || 0;
  134. const asWidget = !!attributes.asWidget;
  135. const thead = headingRows > 0 ? `<thead>${ makeRows( tableData.slice( 0, headingRows ), {
  136. cellElement: 'th',
  137. rowElement: 'tr',
  138. headingElement: 'th',
  139. wrappingElement: asWidget ? 'span' : 'p',
  140. enforceWrapping: asWidget,
  141. asWidget
  142. } ) }</thead>` : '';
  143. const tbody = tableData.length > headingRows ?
  144. `<tbody>${ makeRows( tableData.slice( headingRows ), {
  145. cellElement: 'td',
  146. rowElement: 'tr',
  147. headingElement: 'th',
  148. wrappingElement: asWidget ? 'span' : 'p',
  149. enforceWrapping: asWidget,
  150. asWidget
  151. } ) }</tbody>` : '';
  152. const figureAttributes = asWidget ?
  153. 'class="ck-widget ck-widget_with-selection-handle table" contenteditable="false"' : 'class="table"';
  154. const widgetHandler = '<div class="ck ck-widget__selection-handle"></div>';
  155. return `<figure ${ figureAttributes }>${ asWidget ? widgetHandler : '' }<table>${ thead }${ tbody }</table></figure>`;
  156. }
  157. /**
  158. * An assertion helper for top-right-bottom-left attribute object.
  159. *
  160. * @param {module:engine/model/node~Node} element
  161. * @param {String} key Attribute key
  162. * @param {String} top Top value. Pass `null` to omit the value in the attributes object.
  163. * @param {String} [right=top] Right value - defaults to top if not provided.
  164. * Pass `null` to omit the value in the attributes object.
  165. * @param {String} [bottom=top] Bottom value - defaults to top (right value must be defined).
  166. * Pass `null` to omit the value in the attributes object.
  167. * @param {String} [left=right] Left value - defaults to right (bottom and right values must be defined).
  168. * Pass `null` to omit the value in the attributes object.
  169. */
  170. export function assertTRBLAttribute( element, key, top, right = top, bottom = top, left = right ) {
  171. const styleObject = {};
  172. if ( top ) {
  173. styleObject.top = top;
  174. }
  175. if ( right ) {
  176. styleObject.right = right;
  177. }
  178. if ( bottom ) {
  179. styleObject.bottom = bottom;
  180. }
  181. if ( left ) {
  182. styleObject.left = left;
  183. }
  184. expect( element.getAttribute( key ) ).to.deep.equal( styleObject );
  185. }
  186. /**
  187. * An assertion helper for testing the `<table>` style attribute.
  188. *
  189. * @param {module:core/editor/editor~Editor} editor
  190. * @param {String} [tableStyle=''] A style to assert on <table>.
  191. * @param {String} [figureStyle=''] A style to assert on <figure>.
  192. */
  193. export function assertTableStyle( editor, tableStyle, figureStyle ) {
  194. const tableStyleEntry = tableStyle ? ` style="${ tableStyle }"` : '';
  195. const figureStyleEntry = figureStyle ? ` style="${ figureStyle }"` : '';
  196. assertEqualMarkup( editor.getData(),
  197. `<figure class="table"${ figureStyleEntry }>` +
  198. `<table${ tableStyleEntry }>` +
  199. '<tbody><tr><td>foo</td></tr></tbody>' +
  200. '</table>' +
  201. '</figure>'
  202. );
  203. }
  204. /**
  205. * An assertion helper for testing the `<td>` style attribute.
  206. *
  207. * @param {module:core/editor/editor~Editor} editor
  208. * @param {String} [tableCellStyle=''] A style to assert on td.
  209. */
  210. export function assertTableCellStyle( editor, tableCellStyle ) {
  211. assertEqualMarkup( editor.getData(),
  212. '<figure class="table"><table><tbody><tr>' +
  213. `<td${ tableCellStyle ? ` style="${ tableCellStyle }"` : '' }>foo</td>` +
  214. '</tr></tbody></table></figure>'
  215. );
  216. }
  217. /**
  218. * A helper method for asserting selected table cells.
  219. *
  220. * To check if a table has expected cells selected pass two dimensional array of truthy and falsy values:
  221. *
  222. * assertSelectedCells( model, [
  223. * [ 0, 1 ],
  224. * [ 0, 1 ]
  225. * ] );
  226. *
  227. * The above call will check if table has second column selected (assuming no spans).
  228. *
  229. * **Note**: This function operates on child indexes - not rows/columns.
  230. *
  231. * Examples:
  232. *
  233. * +----+----+----+----+
  234. * | 00 | 01 | 02 | 03 |
  235. * +----+ +----+----+
  236. * |[10]| |[12]|[13]|
  237. * +----+----+----+----+
  238. * | 20 | 21 | 22 | 23 |
  239. * +----+----+----+----+
  240. * | 30 | 31 | 33 |
  241. * +----+----+----+----+
  242. *
  243. * assertSelectedCells( model, [
  244. * [ 0, 0, 0, 0 ],
  245. * [ 1, 1, 1 ],
  246. * [ 0, 0, 0, 0 ],
  247. * [ 0, 0, 0 ]
  248. * ] );
  249. *
  250. * +----+----+----+----+
  251. * | 00 |[01]| 02 | 03 |
  252. * +----+ +----+----+
  253. * | 10 | | 12 | 13 |
  254. * +----+----+----+----+
  255. * | 20 |[21]| 22 | 23 |
  256. * +----+----+----+----+
  257. * | 30 |[31] | 33 |
  258. * +----+----+----+----+
  259. *
  260. * assertSelectedCells( model, [
  261. * [ 0, 1, 0, 0 ],
  262. * [ 0, 0, 0 ],
  263. * [ 0, 1, 0, 0 ],
  264. * [ 0, 1, 0 ]
  265. * ] );
  266. *
  267. */
  268. export function assertSelectedCells( model, tableMap ) {
  269. const tableIndex = 0;
  270. for ( let rowIndex = 0; rowIndex < tableMap.length; rowIndex++ ) {
  271. const row = tableMap[ rowIndex ];
  272. for ( let cellIndex = 0; cellIndex < row.length; cellIndex++ ) {
  273. const expectSelected = row[ cellIndex ];
  274. if ( expectSelected ) {
  275. assertNodeIsSelected( model, [ tableIndex, rowIndex, cellIndex ] );
  276. } else {
  277. assertNodeIsNotSelected( model, [ tableIndex, rowIndex, cellIndex ] );
  278. }
  279. }
  280. }
  281. }
  282. function assertNodeIsSelected( model, path ) {
  283. const modelRoot = model.document.getRoot();
  284. const node = modelRoot.getNodeByPath( path );
  285. const selectionRanges = Array.from( model.document.selection.getRanges() );
  286. expect( selectionRanges.some( range => range.containsItem( node ) ), `Expected node [${ path }] to be selected` ).to.be.true;
  287. }
  288. function assertNodeIsNotSelected( model, path ) {
  289. const modelRoot = model.document.getRoot();
  290. const node = modelRoot.getNodeByPath( path );
  291. const selectionRanges = Array.from( model.document.selection.getRanges() );
  292. expect( selectionRanges.every( range => !range.containsItem( node ) ), `Expected node [${ path }] to be not selected` ).to.be.true;
  293. }
  294. // Formats table cell attributes
  295. //
  296. // @param {Object} attributes Attributes of a cell.
  297. function formatAttributes( attributes ) {
  298. let attributesString = '';
  299. if ( attributes ) {
  300. const sortedKeys = Object.keys( attributes ).sort();
  301. if ( sortedKeys.length ) {
  302. attributesString = ' ' + sortedKeys.map( key => `${ key }="${ attributes[ key ] }"` ).join( ' ' );
  303. }
  304. }
  305. return attributesString;
  306. }
  307. // Formats passed table data to a set of table rows.
  308. function makeRows( tableData, options ) {
  309. const { cellElement, rowElement, headingElement, wrappingElement, enforceWrapping, asWidget } = options;
  310. return tableData
  311. .reduce( ( previousRowsString, tableRow ) => {
  312. const tableRowString = tableRow.reduce( ( tableRowString, tableCellData ) => {
  313. const isObject = typeof tableCellData === 'object';
  314. let contents = isObject ? tableCellData.contents : tableCellData;
  315. let resultingCellElement = cellElement;
  316. let isSelected = false;
  317. if ( isObject ) {
  318. if ( tableCellData.isHeading ) {
  319. resultingCellElement = headingElement;
  320. }
  321. isSelected = !!tableCellData.isSelected;
  322. delete tableCellData.contents;
  323. delete tableCellData.isHeading;
  324. delete tableCellData.isSelected;
  325. }
  326. let attributes = {};
  327. if ( asWidget ) {
  328. attributes.class = getClassToSet( attributes );
  329. attributes.contenteditable = 'true';
  330. }
  331. if ( isObject ) {
  332. attributes = {
  333. ...attributes,
  334. ...tableCellData
  335. };
  336. }
  337. if ( !( contents.replace( '[', '' ).replace( ']', '' ).startsWith( '<' ) ) && enforceWrapping ) {
  338. contents =
  339. `<${ wrappingElement == 'span' ? 'span style="display:inline-block"' : wrappingElement }>` +
  340. contents +
  341. `</${ wrappingElement }>`;
  342. }
  343. const formattedAttributes = formatAttributes( attributes );
  344. const tableCell = `<${ resultingCellElement }${ formattedAttributes }>${ contents }</${ resultingCellElement }>`;
  345. tableRowString += isSelected ? `[${ tableCell }]` : tableCell;
  346. return tableRowString;
  347. }, '' );
  348. return `${ previousRowsString }<${ rowElement }>${ tableRowString }</${ rowElement }>`;
  349. }, '' );
  350. }
  351. // Properly handles passed CSS class - editor do sort them.
  352. function getClassToSet( attributes ) {
  353. return ( WIDGET_TABLE_CELL_CLASS + ( attributes.class ? ` ${ attributes.class }` : '' ) )
  354. .split( ' ' )
  355. .sort()
  356. .join( ' ' );
  357. }
  358. /**
  359. * Returns ascii-art visualization of the table.
  360. *
  361. * @param {module:engine/model/model~Model} model The editor model.
  362. * @param {module:engine/model/element~Element} table The table model element.
  363. * @returns {String}
  364. */
  365. export function createTableAsciiArt( model, table ) {
  366. const tableMap = [ ...new TableWalker( table, { includeAllSlots: true } ) ];
  367. if ( !tableMap.length ) {
  368. return '';
  369. }
  370. const { row: lastRow, column: lastColumn } = tableMap[ tableMap.length - 1 ];
  371. const columns = lastColumn + 1;
  372. const headingRows = parseInt( table.getAttribute( 'headingRows' ) ) || 0;
  373. const headingColumns = parseInt( table.getAttribute( 'headingColumns' ) ) || 0;
  374. let result = '';
  375. for ( let row = 0; row <= lastRow; row++ ) {
  376. let gridLine = '';
  377. let contentLine = '';
  378. for ( let column = 0; column <= lastColumn; column++ ) {
  379. const cellInfo = tableMap[ row * columns + column ];
  380. const isColSpan = cellInfo.cellAnchorColumn != cellInfo.column;
  381. const isRowSpan = cellInfo.cellAnchorRow != cellInfo.row;
  382. gridLine += !isColSpan || !isRowSpan ? '+' : ' ';
  383. gridLine += !isRowSpan ? '----' : ' ';
  384. let contents = getElementPlainText( model, cellInfo.cell ).substring( 0, 2 );
  385. contents += ' '.repeat( 2 - contents.length );
  386. contentLine += !isColSpan ? '|' : ' ';
  387. contentLine += !isColSpan && !isRowSpan ? ` ${ contents } ` : ' ';
  388. if ( column == lastColumn ) {
  389. gridLine += '+';
  390. contentLine += '|';
  391. if ( headingRows && row == headingRows ) {
  392. gridLine += ' <-- heading rows';
  393. }
  394. }
  395. }
  396. result += gridLine + '\n';
  397. result += contentLine + '\n';
  398. if ( row == lastRow ) {
  399. result += `+${ '----+'.repeat( columns ) }`;
  400. if ( headingRows && row == headingRows - 1 ) {
  401. result += ' <-- heading rows';
  402. }
  403. if ( headingColumns > 0 ) {
  404. result += `\n${ ' '.repeat( headingColumns ) }^-- heading columns`;
  405. }
  406. }
  407. }
  408. return result;
  409. }
  410. /**
  411. * Generates input data for `modelTable` helper method.
  412. *
  413. * @param {module:engine/model/model~Model} model The editor model.
  414. * @param {module:engine/model/element~Element} table The table model element.
  415. * @returns {Array.<Array.<String|Object>>}
  416. */
  417. export function prepareModelTableInput( model, table ) {
  418. const result = [];
  419. let row = [];
  420. for ( const cellInfo of new TableWalker( table, { includeAllSlots: true } ) ) {
  421. if ( cellInfo.column == 0 && cellInfo.row > 0 ) {
  422. result.push( row );
  423. row = [];
  424. }
  425. if ( !cellInfo.isAnchor ) {
  426. continue;
  427. }
  428. const contents = getElementPlainText( model, cellInfo.cell );
  429. if ( cellInfo.cellWidth > 1 || cellInfo.cellHeight > 1 ) {
  430. row.push( {
  431. contents,
  432. ...( cellInfo.cellWidth > 1 ? { colspan: cellInfo.cellWidth } : null ),
  433. ...( cellInfo.cellHeight > 1 ? { rowspan: cellInfo.cellHeight } : null )
  434. } );
  435. } else {
  436. row.push( contents );
  437. }
  438. }
  439. result.push( row );
  440. return result;
  441. }
  442. /**
  443. * Pretty formats `modelTable` input data.
  444. *
  445. * @param {Array.<Array.<String|Object>>} data
  446. * @returns {String}
  447. */
  448. export function prettyFormatModelTableInput( data ) {
  449. const rowsStringified = data.map( row => {
  450. const cellsStringified = row.map( cell => {
  451. if ( typeof cell == 'string' ) {
  452. return `'${ cell }'`;
  453. }
  454. const fieldsStringified = Object.entries( cell ).map( ( [ key, value ] ) => {
  455. return `${ key }: ${ typeof value == 'string' ? `'${ value }'` : value }`;
  456. } );
  457. return `{ ${ fieldsStringified.join( ', ' ) } }`;
  458. } );
  459. return '\t[ ' + cellsStringified.join( ', ' ) + ' ]';
  460. } );
  461. return `[\n${ rowsStringified.join( ',\n' ) }\n]`;
  462. }
  463. // Returns all the text content from element.
  464. function getElementPlainText( model, element ) {
  465. return [ ...model.createRangeIn( element ).getWalker() ]
  466. .filter( ( { type } ) => type == 'text' )
  467. .map( ( { item: { data } } ) => data )
  468. .join( '' );
  469. }