tableutils.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. /**
  6. * @module table/tableutils
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import TableWalker from './tablewalker';
  10. import { createEmptyTableCell, updateNumericAttribute } from './utils/common';
  11. /**
  12. * The table utilities plugin.
  13. *
  14. * @extends module:core/plugin~Plugin
  15. */
  16. export default class TableUtils extends Plugin {
  17. /**
  18. * @inheritDoc
  19. */
  20. static get pluginName() {
  21. return 'TableUtils';
  22. }
  23. /**
  24. * Returns the table cell location as an object with table row and table column indexes.
  25. *
  26. * For instance, in the table below:
  27. *
  28. * 0 1 2 3
  29. * +---+---+---+---+
  30. * 0 | a | b | c |
  31. * + + +---+
  32. * 1 | | | d |
  33. * +---+---+ +---+
  34. * 2 | e | | f |
  35. * +---+---+---+---+
  36. *
  37. * the method will return:
  38. *
  39. * const cellA = table.getNodeByPath( [ 0, 0 ] );
  40. * editor.plugins.get( 'TableUtils' ).getCellLocation( cellA );
  41. * // will return { row: 0, column: 0 }
  42. *
  43. * const cellD = table.getNodeByPath( [ 1, 0 ] );
  44. * editor.plugins.get( 'TableUtils' ).getCellLocation( cellD );
  45. * // will return { row: 1, column: 3 }
  46. *
  47. * @param {module:engine/model/element~Element} tableCell
  48. * @returns {Object} Returns a `{row, column}` object.
  49. */
  50. getCellLocation( tableCell ) {
  51. const tableRow = tableCell.parent;
  52. const table = tableRow.parent;
  53. const rowIndex = table.getChildIndex( tableRow );
  54. const tableWalker = new TableWalker( table, { startRow: rowIndex, endRow: rowIndex } );
  55. for ( const { cell, row, column } of tableWalker ) {
  56. if ( cell === tableCell ) {
  57. return { row, column };
  58. }
  59. }
  60. }
  61. /**
  62. * Creates an empty table with a proper structure. The table needs to be inserted into the model,
  63. * for example, by using the {@link module:engine/model/model~Model#insertContent} function.
  64. *
  65. * model.change( ( writer ) => {
  66. * // Create a table of 2 rows and 7 columns:
  67. * const table = tableUtils.createTable( writer, 2, 7);
  68. *
  69. * // Insert a table to the model at the best position taking the current selection:
  70. * model.insertContent( table );
  71. * }
  72. *
  73. * @param {module:engine/model/writer~Writer} writer The model writer.
  74. * @param {Number} rows The number of rows to create.
  75. * @param {Number} columns The number of columns to create.
  76. * @returns {module:engine/model/element~Element} The created table element.
  77. */
  78. createTable( writer, rows, columns ) {
  79. const table = writer.createElement( 'table' );
  80. createEmptyRows( writer, table, 0, rows, columns );
  81. return table;
  82. }
  83. /**
  84. * Inserts rows into a table.
  85. *
  86. * editor.plugins.get( 'TableUtils' ).insertRows( table, { at: 1, rows: 2 } );
  87. *
  88. * Assuming the table on the left, the above code will transform it to the table on the right:
  89. *
  90. * row index
  91. * 0 +---+---+---+ `at` = 1, +---+---+---+ 0
  92. * | a | b | c | `rows` = 2, | a | b | c |
  93. * 1 + +---+---+ <-- insert here + +---+---+ 1
  94. * | | d | e | | | | |
  95. * 2 + +---+---+ will give: + +---+---+ 2
  96. * | | f | g | | | | |
  97. * 3 +---+---+---+ + +---+---+ 3
  98. * | | d | e |
  99. * + +---+---+ 4
  100. * + + f | g |
  101. * +---+---+---+ 5
  102. *
  103. * @param {module:engine/model/element~Element} table The table model element where the rows will be inserted.
  104. * @param {Object} options
  105. * @param {Number} [options.at=0] The row index at which the rows will be inserted.
  106. * @param {Number} [options.rows=1] The number of rows to insert.
  107. * @param {Boolean|undefined} [options.copyStructureFromAbove] The flag for copying row structure. Note that
  108. * the row structure will not be copied if this option is not provided.
  109. */
  110. insertRows( table, options = {} ) {
  111. const model = this.editor.model;
  112. const insertAt = options.at || 0;
  113. const rowsToInsert = options.rows || 1;
  114. const isCopyStructure = options.copyStructureFromAbove !== undefined;
  115. const copyStructureFrom = options.copyStructureFromAbove ? insertAt - 1 : insertAt;
  116. const rows = this.getRows( table );
  117. const columns = this.getColumns( table );
  118. model.change( writer => {
  119. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  120. // Inserting rows inside heading section requires to update `headingRows` attribute as the heading section will grow.
  121. if ( headingRows > insertAt ) {
  122. writer.setAttribute( 'headingRows', headingRows + rowsToInsert, table );
  123. }
  124. // Inserting at the end or at the beginning of a table doesn't require to calculate anything special.
  125. if ( !isCopyStructure && ( insertAt === 0 || insertAt === rows ) ) {
  126. createEmptyRows( writer, table, insertAt, rowsToInsert, columns );
  127. return;
  128. }
  129. // Iterate over all the rows above the inserted rows in order to check for the row-spanned cells.
  130. const walkerEndRow = isCopyStructure ? Math.max( insertAt, copyStructureFrom ) : insertAt;
  131. const tableIterator = new TableWalker( table, { endRow: walkerEndRow } );
  132. // Store spans of the reference row to reproduce it's structure. This array is column number indexed.
  133. const rowColSpansMap = new Array( columns ).fill( 1 );
  134. for ( const { row, column, rowspan, colspan, cell } of tableIterator ) {
  135. const lastCellRow = row + rowspan - 1;
  136. const isOverlappingInsertedRow = row < insertAt && insertAt <= lastCellRow;
  137. const isReferenceRow = row <= copyStructureFrom && copyStructureFrom <= lastCellRow;
  138. // If the cell is row-spanned and overlaps the inserted row, then reserve space for it in the row map.
  139. if ( isOverlappingInsertedRow ) {
  140. // This cell overlaps the inserted rows so we need to expand it further.
  141. writer.setAttribute( 'rowspan', rowspan + rowsToInsert, cell );
  142. // Mark this cell with negative number to indicate how many cells should be skipped when adding the new cells.
  143. rowColSpansMap[ column ] = -colspan;
  144. }
  145. // Store the colspan from reference row.
  146. else if ( isCopyStructure && isReferenceRow ) {
  147. rowColSpansMap[ column ] = colspan;
  148. }
  149. }
  150. for ( let rowIndex = 0; rowIndex < rowsToInsert; rowIndex++ ) {
  151. const tableRow = writer.createElement( 'tableRow' );
  152. writer.insert( tableRow, table, insertAt );
  153. for ( let cellIndex = 0; cellIndex < rowColSpansMap.length; cellIndex++ ) {
  154. const colspan = rowColSpansMap[ cellIndex ];
  155. const insertPosition = writer.createPositionAt( tableRow, 'end' );
  156. // Insert the empty cell only if this slot is not row-spanned from any other cell.
  157. if ( colspan > 0 ) {
  158. createEmptyTableCell( writer, insertPosition, colspan > 1 ? { colspan } : null );
  159. }
  160. // Skip the col-spanned slots, there won't be any cells.
  161. cellIndex += Math.abs( colspan ) - 1;
  162. }
  163. }
  164. } );
  165. }
  166. /**
  167. * Inserts columns into a table.
  168. *
  169. * editor.plugins.get( 'TableUtils' ).insertColumns( table, { at: 1, columns: 2 } );
  170. *
  171. * Assuming the table on the left, the above code will transform it to the table on the right:
  172. *
  173. * 0 1 2 3 0 1 2 3 4 5
  174. * +---+---+---+ +---+---+---+---+---+
  175. * | a | b | | a | b |
  176. * + +---+ + +---+
  177. * | | c | | | c |
  178. * +---+---+---+ will give: +---+---+---+---+---+
  179. * | d | e | f | | d | | | e | f |
  180. * +---+ +---+ +---+---+---+ +---+
  181. * | g | | h | | g | | | | h |
  182. * +---+---+---+ +---+---+---+---+---+
  183. * | i | | i |
  184. * +---+---+---+ +---+---+---+---+---+
  185. * ^---- insert here, `at` = 1, `columns` = 2
  186. *
  187. * @param {module:engine/model/element~Element} table The table model element where the columns will be inserted.
  188. * @param {Object} options
  189. * @param {Number} [options.at=0] The column index at which the columns will be inserted.
  190. * @param {Number} [options.columns=1] The number of columns to insert.
  191. */
  192. insertColumns( table, options = {} ) {
  193. const model = this.editor.model;
  194. const insertAt = options.at || 0;
  195. const columnsToInsert = options.columns || 1;
  196. model.change( writer => {
  197. const headingColumns = table.getAttribute( 'headingColumns' );
  198. // Inserting columns inside heading section requires to update `headingColumns` attribute as the heading section will grow.
  199. if ( insertAt < headingColumns ) {
  200. writer.setAttribute( 'headingColumns', headingColumns + columnsToInsert, table );
  201. }
  202. const tableColumns = this.getColumns( table );
  203. // Inserting at the end and at the beginning of a table doesn't require to calculate anything special.
  204. if ( insertAt === 0 || tableColumns === insertAt ) {
  205. for ( const tableRow of table.getChildren() ) {
  206. createCells( columnsToInsert, writer, writer.createPositionAt( tableRow, insertAt ? 'end' : 0 ) );
  207. }
  208. return;
  209. }
  210. const tableWalker = new TableWalker( table, { column: insertAt, includeSpanned: true } );
  211. for ( const { row, cell, cellIndex } of tableWalker ) {
  212. // When iterating over column the table walker outputs either:
  213. // - cells at given column index (cell "e" from method docs),
  214. // - spanned columns (spanned cell from row between cells "g" and "h" - spanned by "e", only if `includeSpanned: true`),
  215. // - or a cell from the same row which spans over this column (cell "a").
  216. const rowspan = parseInt( cell.getAttribute( 'rowspan' ) || 1 );
  217. const colspan = parseInt( cell.getAttribute( 'colspan' ) || 1 );
  218. if ( cellIndex !== insertAt && colspan > 1 ) {
  219. // If column is different than `insertAt`, it is a cell that spans over an inserted column (cell "a" & "i").
  220. // For such cells expand them by a number of columns inserted.
  221. writer.setAttribute( 'colspan', colspan + columnsToInsert, cell );
  222. // The `includeSpanned` option will output the "empty"/spanned column so skip this row already.
  223. tableWalker.skipRow( row );
  224. // This cell will overlap cells in rows below so skip them also (because of `includeSpanned` option) - (cell "a")
  225. if ( rowspan > 1 ) {
  226. for ( let i = row + 1; i < row + rowspan; i++ ) {
  227. tableWalker.skipRow( i );
  228. }
  229. }
  230. } else {
  231. // It's either cell at this column index or spanned cell by a rowspanned cell from row above.
  232. // In table above it's cell "e" and a spanned position from row below (empty cell between cells "g" and "h")
  233. const insertPosition = writer.createPositionAt( table.getChild( row ), cellIndex );
  234. createCells( columnsToInsert, writer, insertPosition );
  235. }
  236. }
  237. } );
  238. }
  239. /**
  240. * Removes rows from the given `table`.
  241. *
  242. * This method re-calculates the table geometry including `rowspan` attribute of table cells overlapping removed rows
  243. * and table headings values.
  244. *
  245. * editor.plugins.get( 'TableUtils' ).removeRows( table, { at: 1, rows: 2 } );
  246. *
  247. * Executing the above code in the context of the table on the left will transform its structure as presented on the right:
  248. *
  249. * row index
  250. * ┌───┬───┬───┐ `at` = 1 ┌───┬───┬───┐
  251. * 0 │ a │ b │ c │ `rows` = 2 │ a │ b │ c │ 0
  252. * │ ├───┼───┤ │ ├───┼───┤
  253. * 1 │ │ d │ e │ <-- remove from here │ │ d │ g │ 1
  254. * │ │ ├───┤ will give: ├───┼───┼───┤
  255. * 2 │ │ │ f │ │ h │ i │ j │ 2
  256. * │ │ ├───┤ └───┴───┴───┘
  257. * 3 │ │ │ g │
  258. * ├───┼───┼───┤
  259. * 4 │ h │ i │ j │
  260. * └───┴───┴───┘
  261. *
  262. * @param {module:engine/model/element~Element} table
  263. * @param {Object} options
  264. * @param {Number} options.at The row index at which the removing rows will start.
  265. * @param {Number} [options.rows=1] The number of rows to remove.
  266. */
  267. removeRows( table, options ) {
  268. const model = this.editor.model;
  269. const rowsToRemove = options.rows || 1;
  270. const first = options.at;
  271. const last = first + rowsToRemove - 1;
  272. const batch = options.batch || 'default';
  273. model.enqueueChange( batch, writer => {
  274. // Removing rows from the table require that most calculations to be done prior to changing table structure.
  275. // Preparations must be done in the same enqueueChange callback to use the current table structure.
  276. // 1. Preparation - get row-spanned cells that have to be modified after removing rows.
  277. const { cellsToMove, cellsToTrim } = getCellsToMoveAndTrimOnRemoveRow( table, first, last );
  278. // 2. Execution
  279. // 2a. Move cells from removed rows that extends over a removed section - must be done before removing rows.
  280. // This will fill any gaps in a rows below that previously were empty because of row-spanned cells.
  281. if ( cellsToMove.size ) {
  282. const rowAfterRemovedSection = last + 1;
  283. moveCellsToRow( table, rowAfterRemovedSection, cellsToMove, writer );
  284. }
  285. // 2b. Remove all required rows.
  286. for ( let i = last; i >= first; i-- ) {
  287. writer.remove( table.getChild( i ) );
  288. }
  289. // 2c. Update cells from rows above that overlap removed section. Similar to step 2 but does not involve moving cells.
  290. for ( const { rowspan, cell } of cellsToTrim ) {
  291. updateNumericAttribute( 'rowspan', rowspan, cell, writer );
  292. }
  293. // 2d. Adjust heading rows if removed rows were in a heading section.
  294. updateHeadingRows( table, first, last, model, batch );
  295. } );
  296. }
  297. /**
  298. * Removes columns from the given `table`.
  299. *
  300. * This method re-calculates the table geometry including the `colspan` attribute of table cells overlapping removed columns
  301. * and table headings values.
  302. *
  303. * editor.plugins.get( 'TableUtils' ).removeColumns( table, { at: 1, columns: 2 } );
  304. *
  305. * Executing the above code in the context of the table on the left will transform its structure as presented on the right:
  306. *
  307. * 0 1 2 3 4 0 1 2
  308. * ┌───────────────┬───┐ ┌───────┬───┐
  309. * │ a │ b │ │ a │ b │
  310. * │ ├───┤ │ ├───┤
  311. * │ │ c │ │ │ c │
  312. * ├───┬───┬───┬───┼───┤ will give: ├───┬───┼───┤
  313. * │ d │ e │ f │ g │ h │ │ d │ g │ h │
  314. * ├───┼───┼───┤ ├───┤ ├───┤ ├───┤
  315. * │ i │ j │ k │ │ l │ │ i │ │ l │
  316. * ├───┴───┴───┴───┴───┤ ├───┴───┴───┤
  317. * │ m │ │ m │
  318. * └───────────────────┘ └───────────┘
  319. * ^---- remove from here, `at` = 1, `columns` = 2
  320. *
  321. * @param {module:engine/model/element~Element} table
  322. * @param {Object} options
  323. * @param {Number} options.at The row index at which the removing columns will start.
  324. * @param {Number} [options.columns=1] The number of columns to remove.
  325. */
  326. removeColumns( table, options ) {
  327. const model = this.editor.model;
  328. const first = options.at;
  329. const columnsToRemove = options.columns || 1;
  330. const last = options.at + columnsToRemove - 1;
  331. model.change( writer => {
  332. adjustHeadingColumns( table, { first, last }, writer );
  333. const emptyRowsIndexes = [];
  334. for ( let removedColumnIndex = last; removedColumnIndex >= first; removedColumnIndex-- ) {
  335. for ( const { cell, column, colspan } of [ ...new TableWalker( table ) ] ) {
  336. // If colspaned cell overlaps removed column decrease its span.
  337. if ( column <= removedColumnIndex && colspan > 1 && column + colspan > removedColumnIndex ) {
  338. updateNumericAttribute( 'colspan', colspan - 1, cell, writer );
  339. } else if ( column === removedColumnIndex ) {
  340. const cellRow = cell.parent;
  341. // The cell in removed column has colspan of 1.
  342. writer.remove( cell );
  343. // If the cell was the last one in the row, get rid of the entire row.
  344. // https://github.com/ckeditor/ckeditor5/issues/6429
  345. if ( !cellRow.childCount ) {
  346. emptyRowsIndexes.push( cellRow.index );
  347. }
  348. }
  349. }
  350. }
  351. emptyRowsIndexes.reverse().forEach( row => this.removeRows( table, { at: row, batch: writer.batch } ) );
  352. } );
  353. }
  354. /**
  355. * Divides a table cell vertically into several ones.
  356. *
  357. * The cell will be visually split into more cells by updating colspans of other cells in a column
  358. * and inserting cells (columns) after that cell.
  359. *
  360. * In the table below, if cell "a" is split into 3 cells:
  361. *
  362. * +---+---+---+
  363. * | a | b | c |
  364. * +---+---+---+
  365. * | d | e | f |
  366. * +---+---+---+
  367. *
  368. * it will result in the table below:
  369. *
  370. * +---+---+---+---+---+
  371. * | a | | | b | c |
  372. * +---+---+---+---+---+
  373. * | d | e | f |
  374. * +---+---+---+---+---+
  375. *
  376. * So cell "d" will get its `colspan` updated to `3` and 2 cells will be added (2 columns will be created).
  377. *
  378. * Splitting a cell that already has a `colspan` attribute set will distribute the cell `colspan` evenly and the remainder
  379. * will be left to the original cell:
  380. *
  381. * +---+---+---+
  382. * | a |
  383. * +---+---+---+
  384. * | b | c | d |
  385. * +---+---+---+
  386. *
  387. * Splitting cell "a" with `colspan=3` into 2 cells will create 1 cell with a `colspan=a` and cell "a" that will have `colspan=2`:
  388. *
  389. * +---+---+---+
  390. * | a | |
  391. * +---+---+---+
  392. * | b | c | d |
  393. * +---+---+---+
  394. *
  395. * @param {module:engine/model/element~Element} tableCell
  396. * @param {Number} numberOfCells
  397. */
  398. splitCellVertically( tableCell, numberOfCells = 2 ) {
  399. const model = this.editor.model;
  400. const tableRow = tableCell.parent;
  401. const table = tableRow.parent;
  402. const rowspan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  403. const colspan = parseInt( tableCell.getAttribute( 'colspan' ) || 1 );
  404. model.change( writer => {
  405. // First check - the cell spans over multiple rows so before doing anything else just split this cell.
  406. if ( colspan > 1 ) {
  407. // Get spans of new (inserted) cells and span to update of split cell.
  408. const { newCellsSpan, updatedSpan } = breakSpanEvenly( colspan, numberOfCells );
  409. updateNumericAttribute( 'colspan', updatedSpan, tableCell, writer );
  410. // Each inserted cell will have the same attributes:
  411. const newCellsAttributes = {};
  412. // Do not store default value in the model.
  413. if ( newCellsSpan > 1 ) {
  414. newCellsAttributes.colspan = newCellsSpan;
  415. }
  416. // Copy rowspan of split cell.
  417. if ( rowspan > 1 ) {
  418. newCellsAttributes.rowspan = rowspan;
  419. }
  420. const cellsToInsert = colspan > numberOfCells ? numberOfCells - 1 : colspan - 1;
  421. createCells( cellsToInsert, writer, writer.createPositionAfter( tableCell ), newCellsAttributes );
  422. }
  423. // Second check - the cell has colspan of 1 or we need to create more cells then the currently one spans over.
  424. if ( colspan < numberOfCells ) {
  425. const cellsToInsert = numberOfCells - colspan;
  426. // First step: expand cells on the same column as split cell.
  427. const tableMap = [ ...new TableWalker( table ) ];
  428. // Get the column index of split cell.
  429. const { column: splitCellColumn } = tableMap.find( ( { cell } ) => cell === tableCell );
  430. // Find cells which needs to be expanded vertically - those on the same column or those that spans over split cell's column.
  431. const cellsToUpdate = tableMap.filter( ( { cell, colspan, column } ) => {
  432. const isOnSameColumn = cell !== tableCell && column === splitCellColumn;
  433. const spansOverColumn = ( column < splitCellColumn && column + colspan > splitCellColumn );
  434. return isOnSameColumn || spansOverColumn;
  435. } );
  436. // Expand cells vertically.
  437. for ( const { cell, colspan } of cellsToUpdate ) {
  438. writer.setAttribute( 'colspan', colspan + cellsToInsert, cell );
  439. }
  440. // Second step: create columns after split cell.
  441. // Each inserted cell will have the same attributes:
  442. const newCellsAttributes = {};
  443. // Do not store default value in the model.
  444. // Copy rowspan of split cell.
  445. if ( rowspan > 1 ) {
  446. newCellsAttributes.rowspan = rowspan;
  447. }
  448. createCells( cellsToInsert, writer, writer.createPositionAfter( tableCell ), newCellsAttributes );
  449. const headingColumns = table.getAttribute( 'headingColumns' ) || 0;
  450. // Update heading section if split cell is in heading section.
  451. if ( headingColumns > splitCellColumn ) {
  452. updateNumericAttribute( 'headingColumns', headingColumns + cellsToInsert, table, writer );
  453. }
  454. }
  455. } );
  456. }
  457. /**
  458. * Divides a table cell horizontally into several ones.
  459. *
  460. * The cell will be visually split into more cells by updating rowspans of other cells in the row and inserting rows with a single cell
  461. * below.
  462. *
  463. * If in the table below cell "b" is split into 3 cells:
  464. *
  465. * +---+---+---+
  466. * | a | b | c |
  467. * +---+---+---+
  468. * | d | e | f |
  469. * +---+---+---+
  470. *
  471. * It will result in the table below:
  472. *
  473. * +---+---+---+
  474. * | a | b | c |
  475. * + +---+ +
  476. * | | | |
  477. * + +---+ +
  478. * | | | |
  479. * +---+---+---+
  480. * | d | e | f |
  481. * +---+---+---+
  482. *
  483. * So cells "a" and "b" will get their `rowspan` updated to `3` and 2 rows with a single cell will be added.
  484. *
  485. * Splitting a cell that already has a `rowspan` attribute set will distribute the cell `rowspan` evenly and the remainder
  486. * will be left to the original cell:
  487. *
  488. * +---+---+---+
  489. * | a | b | c |
  490. * + +---+---+
  491. * | | d | e |
  492. * + +---+---+
  493. * | | f | g |
  494. * + +---+---+
  495. * | | h | i |
  496. * +---+---+---+
  497. *
  498. * Splitting cell "a" with `rowspan=4` into 3 cells will create 2 cells with a `rowspan=1` and cell "a" will have `rowspan=2`:
  499. *
  500. * +---+---+---+
  501. * | a | b | c |
  502. * + +---+---+
  503. * | | d | e |
  504. * +---+---+---+
  505. * | | f | g |
  506. * +---+---+---+
  507. * | | h | i |
  508. * +---+---+---+
  509. *
  510. * @param {module:engine/model/element~Element} tableCell
  511. * @param {Number} numberOfCells
  512. */
  513. splitCellHorizontally( tableCell, numberOfCells = 2 ) {
  514. const model = this.editor.model;
  515. const tableRow = tableCell.parent;
  516. const table = tableRow.parent;
  517. const splitCellRow = table.getChildIndex( tableRow );
  518. const rowspan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  519. const colspan = parseInt( tableCell.getAttribute( 'colspan' ) || 1 );
  520. model.change( writer => {
  521. // First check - the cell spans over multiple rows so before doing anything else just split this cell.
  522. if ( rowspan > 1 ) {
  523. // Cache table map before updating table.
  524. const tableMap = [ ...new TableWalker( table, {
  525. startRow: splitCellRow,
  526. endRow: splitCellRow + rowspan - 1,
  527. includeSpanned: true
  528. } ) ];
  529. // Get spans of new (inserted) cells and span to update of split cell.
  530. const { newCellsSpan, updatedSpan } = breakSpanEvenly( rowspan, numberOfCells );
  531. updateNumericAttribute( 'rowspan', updatedSpan, tableCell, writer );
  532. const { column: cellColumn } = tableMap.find( ( { cell } ) => cell === tableCell );
  533. // Each inserted cell will have the same attributes:
  534. const newCellsAttributes = {};
  535. // Do not store default value in the model.
  536. if ( newCellsSpan > 1 ) {
  537. newCellsAttributes.rowspan = newCellsSpan;
  538. }
  539. // Copy colspan of split cell.
  540. if ( colspan > 1 ) {
  541. newCellsAttributes.colspan = colspan;
  542. }
  543. for ( const { column, row, cellIndex } of tableMap ) {
  544. // As both newly created cells and the split cell might have rowspan,
  545. // the insertion of new cells must go to appropriate rows:
  546. //
  547. // 1. It's a row after split cell + it's height.
  548. const isAfterSplitCell = row >= splitCellRow + updatedSpan;
  549. // 2. Is on the same column.
  550. const isOnSameColumn = column === cellColumn;
  551. // 3. And it's row index is after previous cell height.
  552. const isInEvenlySplitRow = ( row + splitCellRow + updatedSpan ) % newCellsSpan === 0;
  553. if ( isAfterSplitCell && isOnSameColumn && isInEvenlySplitRow ) {
  554. const position = writer.createPositionAt( table.getChild( row ), cellIndex );
  555. createCells( 1, writer, position, newCellsAttributes );
  556. }
  557. }
  558. }
  559. // Second check - the cell has rowspan of 1 or we need to create more cells than the current cell spans over.
  560. if ( rowspan < numberOfCells ) {
  561. // We already split the cell in check one so here we split to the remaining number of cells only.
  562. const cellsToInsert = numberOfCells - rowspan;
  563. // This check is needed since we need to check if there are any cells from previous rows than spans over this cell's row.
  564. const tableMap = [ ...new TableWalker( table, { startRow: 0, endRow: splitCellRow } ) ];
  565. // First step: expand cells.
  566. for ( const { cell, rowspan, row } of tableMap ) {
  567. // Expand rowspan of cells that are either:
  568. // - on the same row as current cell,
  569. // - or are below split cell row and overlaps that row.
  570. if ( cell !== tableCell && row + rowspan > splitCellRow ) {
  571. const rowspanToSet = rowspan + cellsToInsert;
  572. writer.setAttribute( 'rowspan', rowspanToSet, cell );
  573. }
  574. }
  575. // Second step: create rows with single cell below split cell.
  576. const newCellsAttributes = {};
  577. // Copy colspan of split cell.
  578. if ( colspan > 1 ) {
  579. newCellsAttributes.colspan = colspan;
  580. }
  581. createEmptyRows( writer, table, splitCellRow + 1, cellsToInsert, 1, newCellsAttributes );
  582. // Update heading section if split cell is in heading section.
  583. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  584. if ( headingRows > splitCellRow ) {
  585. updateNumericAttribute( 'headingRows', headingRows + cellsToInsert, table, writer );
  586. }
  587. }
  588. } );
  589. }
  590. /**
  591. * Returns the number of columns for a given table.
  592. *
  593. * editor.plugins.get( 'TableUtils' ).getColumns( table );
  594. *
  595. * @param {module:engine/model/element~Element} table The table to analyze.
  596. * @returns {Number}
  597. */
  598. getColumns( table ) {
  599. // Analyze first row only as all the rows should have the same width.
  600. const row = table.getChild( 0 );
  601. return [ ...row.getChildren() ].reduce( ( columns, row ) => {
  602. const columnWidth = parseInt( row.getAttribute( 'colspan' ) || 1 );
  603. return columns + columnWidth;
  604. }, 0 );
  605. }
  606. /**
  607. * Returns the number of rows for a given table.
  608. *
  609. * editor.plugins.get( 'TableUtils' ).getRows( table );
  610. *
  611. * @param {module:engine/model/element~Element} table The table to analyze.
  612. * @returns {Number}
  613. */
  614. getRows( table ) {
  615. // Simple row counting, not including rowspan due to #6427.
  616. return table.childCount;
  617. }
  618. }
  619. // Creates empty rows at the given index in an existing table.
  620. //
  621. // @param {module:engine/model/writer~Writer} writer
  622. // @param {module:engine/model/element~Element} table
  623. // @param {Number} insertAt The row index of row insertion.
  624. // @param {Number} rows The number of rows to create.
  625. // @param {Number} tableCellToInsert The number of cells to insert in each row.
  626. function createEmptyRows( writer, table, insertAt, rows, tableCellToInsert, attributes = {} ) {
  627. for ( let i = 0; i < rows; i++ ) {
  628. const tableRow = writer.createElement( 'tableRow' );
  629. writer.insert( tableRow, table, insertAt );
  630. createCells( tableCellToInsert, writer, writer.createPositionAt( tableRow, 'end' ), attributes );
  631. }
  632. }
  633. // Creates cells at a given position.
  634. //
  635. // @param {Number} columns The number of columns to create
  636. // @param {module:engine/model/writer~Writer} writer
  637. // @param {module:engine/model/position~Position} insertPosition
  638. function createCells( cells, writer, insertPosition, attributes = {} ) {
  639. for ( let i = 0; i < cells; i++ ) {
  640. createEmptyTableCell( writer, insertPosition, attributes );
  641. }
  642. }
  643. // Evenly distributes the span of a cell to a number of provided cells.
  644. // The resulting spans will always be integer values.
  645. //
  646. // For instance breaking a span of 7 into 3 cells will return:
  647. //
  648. // { newCellsSpan: 2, updatedSpan: 3 }
  649. //
  650. // as two cells will have a span of 2 and the remainder will go the first cell so its span will change to 3.
  651. //
  652. // @param {Number} span The span value do break.
  653. // @param {Number} numberOfCells The number of resulting spans.
  654. // @returns {{newCellsSpan: Number, updatedSpan: Number}}
  655. function breakSpanEvenly( span, numberOfCells ) {
  656. if ( span < numberOfCells ) {
  657. return { newCellsSpan: 1, updatedSpan: 1 };
  658. }
  659. const newCellsSpan = Math.floor( span / numberOfCells );
  660. const updatedSpan = ( span - newCellsSpan * numberOfCells ) + newCellsSpan;
  661. return { newCellsSpan, updatedSpan };
  662. }
  663. // Updates heading columns attribute if removing a row from head section.
  664. function adjustHeadingColumns( table, removedColumnIndexes, writer ) {
  665. const headingColumns = table.getAttribute( 'headingColumns' ) || 0;
  666. if ( headingColumns && removedColumnIndexes.first < headingColumns ) {
  667. const headingsRemoved = Math.min( headingColumns - 1 /* Other numbers are 0-based */, removedColumnIndexes.last ) -
  668. removedColumnIndexes.first + 1;
  669. writer.setAttribute( 'headingColumns', headingColumns - headingsRemoved, table );
  670. }
  671. }
  672. // Calculates a new heading rows value for removing rows from heading section.
  673. function updateHeadingRows( table, first, last, model, batch ) {
  674. // Must be done after the changes in table structure (removing rows).
  675. // Otherwise the downcast converter for headingRows attribute will fail.
  676. // See https://github.com/ckeditor/ckeditor5/issues/6391.
  677. //
  678. // Must be completely wrapped in enqueueChange to get the current table state (after applying other enqueued changes).
  679. model.enqueueChange( batch, writer => {
  680. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  681. if ( first < headingRows ) {
  682. const newRows = last < headingRows ? headingRows - ( last - first + 1 ) : first;
  683. updateNumericAttribute( 'headingRows', newRows, table, writer, 0 );
  684. }
  685. } );
  686. }
  687. // Finds cells that will be:
  688. // - trimmed - Cells that are "above" removed rows sections and overlap the removed section - their rowspan must be trimmed.
  689. // - moved - Cells from removed rows section might stick out of. These cells are moved to the next row after a removed section.
  690. //
  691. // Sample table with overlapping & sticking out cells:
  692. //
  693. // +----+----+----+----+----+
  694. // | 00 | 01 | 02 | 03 | 04 |
  695. // +----+ + + + +
  696. // | 10 | | | | |
  697. // +----+----+ + + +
  698. // | 20 | 21 | | | | <-- removed row
  699. // + + +----+ + +
  700. // | | | 32 | | | <-- removed row
  701. // +----+ + +----+ +
  702. // | 40 | | | 43 | |
  703. // +----+----+----+----+----+
  704. //
  705. // In a table above:
  706. // - cells to trim: '02', '03' & '04'.
  707. // - cells to move: '21' & '32'.
  708. function getCellsToMoveAndTrimOnRemoveRow( table, first, last ) {
  709. const cellsToMove = new Map();
  710. const cellsToTrim = [];
  711. for ( const { row, column, rowspan, cell } of new TableWalker( table, { endRow: last } ) ) {
  712. const lastRowOfCell = row + rowspan - 1;
  713. const isCellStickingOutFromRemovedRows = row >= first && row <= last && lastRowOfCell > last;
  714. if ( isCellStickingOutFromRemovedRows ) {
  715. const rowspanInRemovedSection = last - row + 1;
  716. const rowSpanToSet = rowspan - rowspanInRemovedSection;
  717. cellsToMove.set( column, {
  718. cell,
  719. rowspan: rowSpanToSet
  720. } );
  721. }
  722. const isCellOverlappingRemovedRows = row < first && lastRowOfCell >= first;
  723. if ( isCellOverlappingRemovedRows ) {
  724. let rowspanAdjustment;
  725. // Cell fully covers removed section - trim it by removed rows count.
  726. if ( lastRowOfCell >= last ) {
  727. rowspanAdjustment = last - first + 1;
  728. }
  729. // Cell partially overlaps removed section - calculate cell's span that is in removed section.
  730. else {
  731. rowspanAdjustment = lastRowOfCell - first + 1;
  732. }
  733. cellsToTrim.push( {
  734. cell,
  735. rowspan: rowspan - rowspanAdjustment
  736. } );
  737. }
  738. }
  739. return { cellsToMove, cellsToTrim };
  740. }
  741. function moveCellsToRow( table, targetRowIndex, cellsToMove, writer ) {
  742. const tableWalker = new TableWalker( table, {
  743. includeSpanned: true,
  744. startRow: targetRowIndex,
  745. endRow: targetRowIndex
  746. } );
  747. const tableRowMap = [ ...tableWalker ];
  748. const row = table.getChild( targetRowIndex );
  749. let previousCell;
  750. for ( const { column, cell, isSpanned } of tableRowMap ) {
  751. if ( cellsToMove.has( column ) ) {
  752. const { cell: cellToMove, rowspan } = cellsToMove.get( column );
  753. const targetPosition = previousCell ?
  754. writer.createPositionAfter( previousCell ) :
  755. writer.createPositionAt( row, 0 );
  756. writer.move( writer.createRangeOn( cellToMove ), targetPosition );
  757. updateNumericAttribute( 'rowspan', rowspan, cellToMove, writer );
  758. previousCell = cellToMove;
  759. } else if ( !isSpanned ) {
  760. // If cell is spanned then `cell` holds reference to overlapping cell. See ckeditor/ckeditor5#6502.
  761. previousCell = cell;
  762. }
  763. }
  764. }