8
0

utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. isLimit: 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. // Formats table cell attributes
  292. //
  293. // @param {Object} attributes Attributes of a cell.
  294. function formatAttributes( attributes ) {
  295. let attributesString = '';
  296. if ( attributes ) {
  297. const entries = Object.entries( attributes );
  298. if ( entries.length ) {
  299. attributesString = ' ' + entries.map( entry => `${ entry[ 0 ] }="${ entry[ 1 ] }"` ).join( ' ' );
  300. }
  301. }
  302. return attributesString;
  303. }
  304. // Formats passed table data to a set of table rows.
  305. function makeRows( tableData, options ) {
  306. const { cellElement, rowElement, headingElement, wrappingElement, enforceWrapping, asWidget } = options;
  307. return tableData
  308. .reduce( ( previousRowsString, tableRow ) => {
  309. const tableRowString = tableRow.reduce( ( tableRowString, tableCellData ) => {
  310. const isObject = typeof tableCellData === 'object';
  311. let contents = isObject ? tableCellData.contents : tableCellData;
  312. let resultingCellElement = cellElement;
  313. if ( isObject ) {
  314. if ( tableCellData.isHeading ) {
  315. resultingCellElement = headingElement;
  316. }
  317. delete tableCellData.contents;
  318. delete tableCellData.isHeading;
  319. }
  320. const attributes = isObject ? tableCellData : {};
  321. if ( asWidget ) {
  322. attributes.class = WIDGET_TABLE_CELL_CLASS + ( attributes.class ? ` ${ attributes.class }` : '' );
  323. attributes.contenteditable = 'true';
  324. }
  325. if ( !( contents.replace( '[', '' ).replace( ']', '' ).startsWith( '<' ) ) && enforceWrapping ) {
  326. contents =
  327. `<${ wrappingElement == 'span' ? 'span style="display:inline-block"' : wrappingElement }>` +
  328. contents +
  329. `</${ wrappingElement }>`;
  330. }
  331. const formattedAttributes = formatAttributes( attributes );
  332. tableRowString += `<${ resultingCellElement }${ formattedAttributes }>${ contents }</${ resultingCellElement }>`;
  333. return tableRowString;
  334. }, '' );
  335. return `${ previousRowsString }<${ rowElement }>${ tableRowString }</${ rowElement }>`;
  336. }, '' );
  337. }