8
0

utils.js 18 KB

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