tableutils.js 33 KB

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