utils.js 12 KB

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