utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. * Returns a view representation of a table shorthand notation:
  85. *
  86. * viewTable( [
  87. * [ '00', '01' ] // first row
  88. * [ '10', '11' ] // second row
  89. * ] );
  90. *
  91. * will output:
  92. *
  93. * '<table><tbody><tr><td>00</td><td>01<td></tr><tr><td>10</td><td>11<td></tr></tbody></table>'
  94. *
  95. * Each table row passed in `tableData` array is represented as an array of strings or objects. A string defines text contents of a cell.
  96. *
  97. * Passing an object allows to pass additional table cell attributes:
  98. *
  99. * const tableCellData = {
  100. * colspan: 2,
  101. * rowspan: 4,
  102. * isHeading: true, // will render table cell as `<th>` element
  103. * contents: 'foo' // text contents of a cell
  104. * };
  105. *
  106. * @param {Array.<Array.<String|Object>>} tableData The table data array.
  107. * @param {Object} [attributes] Optional table attributes: `headingRows` and `headingColumns` - passing them will properly render rows
  108. * in `<tbody>` or `<thead>` sections.
  109. *
  110. * @returns {String}
  111. */
  112. export function viewTable( tableData, attributes = {} ) {
  113. const headingRows = attributes.headingRows || 0;
  114. const asWidget = !!attributes.asWidget;
  115. const thead = headingRows > 0 ? `<thead>${ makeRows( tableData.slice( 0, headingRows ), {
  116. cellElement: 'th',
  117. rowElement: 'tr',
  118. headingElement: 'th',
  119. wrappingElement: asWidget ? 'span' : 'p',
  120. enforceWrapping: asWidget,
  121. asWidget
  122. } ) }</thead>` : '';
  123. const tbody = tableData.length > headingRows ?
  124. `<tbody>${ makeRows( tableData.slice( headingRows ), {
  125. cellElement: 'td',
  126. rowElement: 'tr',
  127. headingElement: 'th',
  128. wrappingElement: asWidget ? 'span' : 'p',
  129. enforceWrapping: asWidget,
  130. asWidget
  131. } ) }</tbody>` : '';
  132. const figureAttributes = asWidget ?
  133. 'class="ck-widget ck-widget_with-selection-handle table" contenteditable="false"' : 'class="table"';
  134. const widgetHandler = '<div class="ck ck-widget__selection-handle"></div>';
  135. return `<figure ${ figureAttributes }>${ asWidget ? widgetHandler : '' }<table>${ thead }${ tbody }</table></figure>`;
  136. }
  137. export function defaultSchema( schema, registerParagraph = true ) {
  138. schema.register( 'table', {
  139. allowWhere: '$block',
  140. allowAttributes: [ 'headingRows', 'headingColumns' ],
  141. isLimit: true,
  142. isObject: true,
  143. isBlock: true
  144. } );
  145. schema.register( 'tableRow', {
  146. allowIn: 'table',
  147. isLimit: true
  148. } );
  149. schema.register( 'tableCell', {
  150. allowIn: 'tableRow',
  151. allowAttributes: [ 'colspan', 'rowspan' ],
  152. isLimit: true
  153. } );
  154. // Allow all $block content inside table cell.
  155. schema.extend( '$block', { allowIn: 'tableCell' } );
  156. // Disallow table in table.
  157. schema.addChildCheck( ( context, childDefinition ) => {
  158. if ( childDefinition.name == 'table' && Array.from( context.getNames() ).includes( 'table' ) ) {
  159. return false;
  160. }
  161. } );
  162. if ( registerParagraph ) {
  163. schema.register( 'paragraph', { inheritAllFrom: '$block' } );
  164. }
  165. // Styles
  166. schema.extend( 'tableCell', {
  167. allowAttributes: [ 'border' ]
  168. } );
  169. }
  170. export function defaultConversion( conversion, asWidget = false ) {
  171. conversion.elementToElement( { model: 'paragraph', view: 'p' } );
  172. // Table conversion.
  173. conversion.for( 'upcast' ).add( upcastTable() );
  174. conversion.for( 'downcast' ).add( downcastInsertTable( { asWidget } ) );
  175. // Table row conversion.
  176. conversion.for( 'upcast' ).elementToElement( { model: 'tableRow', view: 'tr' } );
  177. conversion.for( 'downcast' ).add( downcastInsertRow( { asWidget } ) );
  178. conversion.for( 'downcast' ).add( downcastRemoveRow( { asWidget } ) );
  179. // Table cell conversion.
  180. conversion.for( 'upcast' ).add( upcastTableCell( 'td' ) );
  181. conversion.for( 'upcast' ).add( upcastTableCell( 'th' ) );
  182. conversion.for( 'downcast' ).add( downcastInsertCell( { asWidget } ) );
  183. // Table attributes conversion.
  184. conversion.attributeToAttribute( { model: 'colspan', view: 'colspan' } );
  185. conversion.attributeToAttribute( { model: 'rowspan', view: 'rowspan' } );
  186. conversion.for( 'downcast' ).add( downcastTableHeadingColumnsChange( { asWidget } ) );
  187. conversion.for( 'downcast' ).add( downcastTableHeadingRowsChange( { asWidget } ) );
  188. // Styles
  189. conversion.for( 'upcast' ).attributeToAttribute( {
  190. view: {
  191. name: 'td',
  192. styles: {
  193. border: /[\s\S]+/
  194. }
  195. },
  196. model: {
  197. key: 'border',
  198. value: viewElement => viewElement.getStyle( 'border' )
  199. }
  200. } );
  201. }
  202. /**
  203. * Assertion helper for top-right-bottom-left attribute object.
  204. *
  205. * @param {module:engine/model/node~Node} element
  206. * @param {String} key Attribute key
  207. * @param {String} top Top value. Pass null to omit value in attributes object.
  208. * @param {String} [right=top] Right value - defaults to top if not provided.
  209. * Pass null to omit value in attributes object.
  210. * @param {String} [bottom=top] Bottom value - defaults to top (right value must be defined).
  211. * Pass null to omit value in attributes object.
  212. * @param {String} [left=right] Left value - defaults to right (bottom and right values must be defined).
  213. * Pass null to omit value in attributes object.
  214. */
  215. export function assertTRBLAttribute( element, key, top, right = top, bottom = top, left = right ) {
  216. const styleObject = {};
  217. if ( top ) {
  218. styleObject.top = top;
  219. }
  220. if ( right ) {
  221. styleObject.right = right;
  222. }
  223. if ( bottom ) {
  224. styleObject.bottom = bottom;
  225. }
  226. if ( left ) {
  227. styleObject.left = left;
  228. }
  229. expect( element.getAttribute( key ) ).to.deep.equal( styleObject );
  230. }
  231. /**
  232. * Assertion helper for testing <table> style attribute.
  233. *
  234. * @param {module:core/editor/editor~Editor} editor
  235. * @param {String} tableStyle A style to assert on table.
  236. */
  237. export function assertTableStyle( editor, tableStyle ) {
  238. const styleEntry = tableStyle ? ` style="${ tableStyle }"` : '';
  239. assertEqualMarkup( editor.getData(),
  240. `<figure class="table"><table${ styleEntry }><tbody><tr><td>foo</td></tr></tbody></table></figure>`
  241. );
  242. }
  243. /**
  244. * Assertion helper for testing <td> style attribute.
  245. *
  246. * @param {module:core/editor/editor~Editor} editor
  247. * @param {String} tableCellStyle A style to assert on td.
  248. */
  249. export function assertTableCellStyle( editor, tableCellStyle ) {
  250. assertEqualMarkup( editor.getData(),
  251. '<figure class="table"><table><tbody><tr>' +
  252. `<td${ tableCellStyle ? ` style="${ tableCellStyle }"` : '' }>foo</td>` +
  253. '</tr></tbody></table></figure>'
  254. );
  255. }
  256. // Formats table cell attributes
  257. //
  258. // @param {Object} attributes Attributes of a cell.
  259. function formatAttributes( attributes ) {
  260. let attributesString = '';
  261. if ( attributes ) {
  262. const entries = Object.entries( attributes );
  263. if ( entries.length ) {
  264. attributesString = ' ' + entries.map( entry => `${ entry[ 0 ] }="${ entry[ 1 ] }"` ).join( ' ' );
  265. }
  266. }
  267. return attributesString;
  268. }
  269. // Formats passed table data to a set of table rows.
  270. function makeRows( tableData, options ) {
  271. const { cellElement, rowElement, headingElement, wrappingElement, enforceWrapping, asWidget } = options;
  272. return tableData
  273. .reduce( ( previousRowsString, tableRow ) => {
  274. const tableRowString = tableRow.reduce( ( tableRowString, tableCellData ) => {
  275. const isObject = typeof tableCellData === 'object';
  276. let contents = isObject ? tableCellData.contents : tableCellData;
  277. let resultingCellElement = cellElement;
  278. if ( isObject ) {
  279. if ( tableCellData.isHeading ) {
  280. resultingCellElement = headingElement;
  281. }
  282. delete tableCellData.contents;
  283. delete tableCellData.isHeading;
  284. }
  285. const attributes = isObject ? tableCellData : {};
  286. if ( asWidget ) {
  287. attributes.class = WIDGET_TABLE_CELL_CLASS + ( attributes.class ? ` ${ attributes.class }` : '' );
  288. attributes.contenteditable = 'true';
  289. }
  290. if ( !( contents.replace( '[', '' ).replace( ']', '' ).startsWith( '<' ) ) && enforceWrapping ) {
  291. contents = `<${ wrappingElement }>${ contents }</${ wrappingElement }>`;
  292. }
  293. const formattedAttributes = formatAttributes( attributes );
  294. tableRowString += `<${ resultingCellElement }${ formattedAttributes }>${ contents }</${ resultingCellElement }>`;
  295. return tableRowString;
  296. }, '' );
  297. return `${ previousRowsString }<${ rowElement }>${ tableRowString }</${ rowElement }>`;
  298. }, '' );
  299. }