utils.js 15 KB

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