tableutils.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module table/tableutils
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import Position from '@ckeditor/ckeditor5-engine/src/model/position';
  10. import TableWalker from './tablewalker';
  11. import { createEmptyTableCell, updateNumericAttribute } from './commands/utils';
  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, { startRow: rowIndex, endRow: 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 at a given position.
  64. *
  65. * @param {module:engine/model/position~Position} position The position where the table will be inserted.
  66. * @param {Number} rows The number of rows to create.
  67. * @param {Number} columns The number of columns to create.
  68. * @returns {module:engine/model/element~Element} The created table element.
  69. */
  70. createTable( position, rows, columns ) {
  71. const model = this.editor.model;
  72. return model.change( writer => {
  73. const table = writer.createElement( 'table' );
  74. writer.insert( table, position );
  75. createEmptyRows( writer, table, 0, rows, columns );
  76. return table;
  77. } );
  78. }
  79. /**
  80. * Inserts rows into a table.
  81. *
  82. * editor.plugins.get( 'TableUtils' ).insertRows( table, { at: 1, rows: 2 } );
  83. *
  84. * Assuming the table on the left, the above code will transform it to the table on the right:
  85. *
  86. * row index
  87. * 0 +---+---+---+ `at` = 1, +---+---+---+ 0
  88. * | a | b | c | `rows` = 2, | a | b | c |
  89. * 1 + +---+---+ <-- insert here + +---+---+ 1
  90. * | | d | e | | | | |
  91. * 2 + +---+---+ will give: + +---+---+ 2
  92. * | | f | g | | | | |
  93. * 3 +---+---+---+ + +---+---+ 3
  94. * | | d | e |
  95. * +---+---+---+ 4
  96. * + + f | g |
  97. * +---+---+---+ 5
  98. *
  99. * @param {module:engine/model/element~Element} table The table model element where the rows will be inserted.
  100. * @param {Object} options
  101. * @param {Number} [options.at=0] Row index at which the rows will be inserted.
  102. * @param {Number} [options.rows=1] The number of rows to insert.
  103. */
  104. insertRows( table, options = {} ) {
  105. const model = this.editor.model;
  106. const insertAt = options.at || 0;
  107. const rowsToInsert = options.rows || 1;
  108. model.change( writer => {
  109. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  110. // Inserting rows inside heading section requires to update `headingRows` attribute as the heading section will grow.
  111. if ( headingRows > insertAt ) {
  112. writer.setAttribute( 'headingRows', headingRows + rowsToInsert, table );
  113. }
  114. // Inserting at the end and at the beginning of a table doesn't require to calculate anything special.
  115. if ( insertAt === 0 || insertAt === table.childCount ) {
  116. createEmptyRows( writer, table, insertAt, rowsToInsert, this.getColumns( table ) );
  117. return;
  118. }
  119. // Iterate over all rows above inserted rows in order to check for rowspanned cells.
  120. const tableIterator = new TableWalker( table, { endRow: insertAt } );
  121. // Will hold number of cells needed to insert in created rows.
  122. // The number might be different then table cell width when there are rowspanned cells.
  123. let cellsToInsert = 0;
  124. for ( const { row, rowspan, colspan, cell } of tableIterator ) {
  125. const isBeforeInsertedRow = row < insertAt;
  126. const overlapsInsertedRow = row + rowspan > insertAt;
  127. if ( isBeforeInsertedRow && overlapsInsertedRow ) {
  128. // This cell overlaps inserted rows so we need to expand it further.
  129. writer.setAttribute( 'rowspan', rowspan + rowsToInsert, cell );
  130. }
  131. // Calculate how many cells to insert based on the width of cells in a row at insert position.
  132. // It might be lower then table width as some cells might overlaps inserted row.
  133. // In the table above the cell 'a' overlaps inserted row so only two empty cells are need to be created.
  134. if ( row === insertAt ) {
  135. cellsToInsert += colspan;
  136. }
  137. }
  138. createEmptyRows( writer, table, insertAt, rowsToInsert, cellsToInsert );
  139. } );
  140. }
  141. /**
  142. * Inserts columns into a table.
  143. *
  144. * editor.plugins.get( 'TableUtils' ).insertColumns( table, { at: 1, columns: 2 } );
  145. *
  146. * Assuming the table on the left, the above code will transform it to the table on the right:
  147. *
  148. * 0 1 2 3 0 1 2 3 4 5
  149. * +---+---+---+ +---+---+---+---+---+
  150. * | a | b | | a | b |
  151. * + +---+ + +---+
  152. * | | c | | | c |
  153. * +---+---+---+ will give: +---+---+---+---+---+
  154. * | d | e | f | | d | | | e | f |
  155. * +---+ +---+ +---+---+---+ +---+
  156. * | g | | h | | g | | | | h |
  157. * +---+---+---+ +---+---+---+---+---+
  158. * | i | | i |
  159. * +---+---+---+ +---+---+---+---+---+
  160. * ^---- insert here, `at` = 1, `columns` = 2
  161. *
  162. * @param {module:engine/model/element~Element} table The table model element where the columns will be inserted.
  163. * @param {Object} options
  164. * @param {Number} [options.at=0] Column index at which the columns will be inserted.
  165. * @param {Number} [options.columns=1] The number of columns to insert.
  166. */
  167. insertColumns( table, options = {} ) {
  168. const model = this.editor.model;
  169. const insertAt = options.at || 0;
  170. const columnsToInsert = options.columns || 1;
  171. model.change( writer => {
  172. const headingColumns = table.getAttribute( 'headingColumns' );
  173. // Inserting columns inside heading section requires to update `headingColumns` attribute as the heading section will grow.
  174. if ( insertAt < headingColumns ) {
  175. writer.setAttribute( 'headingColumns', headingColumns + columnsToInsert, table );
  176. }
  177. const tableColumns = this.getColumns( table );
  178. // Inserting at the end and at the beginning of a table doesn't require to calculate anything special.
  179. if ( insertAt === 0 || tableColumns === insertAt ) {
  180. for ( const tableRow of table.getChildren() ) {
  181. createCells( columnsToInsert, writer, Position.createAt( tableRow, insertAt ? 'end' : 0 ) );
  182. }
  183. return;
  184. }
  185. const tableWalker = new TableWalker( table, { column: insertAt, includeSpanned: true } );
  186. for ( const { row, column, cell, colspan, rowspan, cellIndex } of tableWalker ) {
  187. // When iterating over column the table walker outputs either:
  188. // - cells at given column index (cell "e" from method docs),
  189. // - spanned columns (spanned cell from row between cells "g" and "h" - spanned by "e", only if `includeSpanned: true`),
  190. // - or a cell from the same row which spans over this column (cell "a").
  191. if ( column !== insertAt ) {
  192. // If column is different than `insertAt`, it is a cell that spans over an inserted column (cell "a" & "i").
  193. // For such cells expand them by a number of columns inserted.
  194. writer.setAttribute( 'colspan', colspan + columnsToInsert, cell );
  195. // The `includeSpanned` option will output the "empty"/spanned column so skip this row already.
  196. tableWalker.skipRow( row );
  197. // This cell will overlap cells in rows below so skip them also (because of `includeSpanned` option) - (cell "a")
  198. if ( rowspan > 1 ) {
  199. for ( let i = row + 1; i < row + rowspan; i++ ) {
  200. tableWalker.skipRow( i );
  201. }
  202. }
  203. } else {
  204. // It's either cell at this column index or spanned cell by a rowspanned cell from row above.
  205. // In table above it's cell "e" and a spanned position from row below (empty cell between cells "g" and "h")
  206. const insertPosition = Position.createFromParentAndOffset( table.getChild( row ), cellIndex );
  207. createCells( columnsToInsert, writer, insertPosition );
  208. }
  209. }
  210. } );
  211. }
  212. /**
  213. * Divides a table cell vertically into several ones.
  214. *
  215. * The cell will be visually split into more cells by updating colspans of other cells in a column
  216. * and inserting cells (columns) after that cell.
  217. *
  218. * In the table below, if cell "a" is split to 3 cells:
  219. *
  220. * +---+---+---+
  221. * | a | b | c |
  222. * +---+---+---+
  223. * | d | e | f |
  224. * +---+---+---+
  225. *
  226. * it will result in the table below:
  227. *
  228. * +---+---+---+---+---+
  229. * | a | | | b | c |
  230. * +---+---+---+---+---+
  231. * | d | e | f |
  232. * +---+---+---+---+---+
  233. *
  234. * So cell "d" will get its `colspan` updated to `3` and 2 cells will be added (2 columns will be created).
  235. *
  236. * Splitting a cell that already has a `colspan` attribute set will distribute the cell `colspan` evenly and the remainder
  237. * will be left to the original cell:
  238. *
  239. * +---+---+---+
  240. * | a |
  241. * +---+---+---+
  242. * | b | c | d |
  243. * +---+---+---+
  244. *
  245. * Splitting cell "a" with `colspan=3` to 2 cells will create 1 cell with a `colspan=a` and cell "a" that will have `colspan=2`:
  246. *
  247. * +---+---+---+
  248. * | a | |
  249. * +---+---+---+
  250. * | b | c | d |
  251. * +---+---+---+
  252. *
  253. * @param {module:engine/model/element~Element} tableCell
  254. * @param {Number} numberOfCells
  255. */
  256. splitCellVertically( tableCell, numberOfCells = 2 ) {
  257. const model = this.editor.model;
  258. const tableRow = tableCell.parent;
  259. const table = tableRow.parent;
  260. const rowspan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  261. const colspan = parseInt( tableCell.getAttribute( 'colspan' ) || 1 );
  262. model.change( writer => {
  263. // First check - the cell spans over multiple rows so before doing anything else just split this cell.
  264. if ( colspan > 1 ) {
  265. // Get spans of new (inserted) cells and span to update of split cell.
  266. const { newCellsSpan, updatedSpan } = breakSpanEvenly( colspan, numberOfCells );
  267. updateNumericAttribute( 'colspan', updatedSpan, tableCell, writer );
  268. // Each inserted cell will have the same attributes:
  269. const newCellsAttributes = {};
  270. // Do not store default value in the model.
  271. if ( newCellsSpan > 1 ) {
  272. newCellsAttributes.colspan = newCellsSpan;
  273. }
  274. // Copy rowspan of split cell.
  275. if ( rowspan > 1 ) {
  276. newCellsAttributes.rowspan = rowspan;
  277. }
  278. const cellsToInsert = colspan > numberOfCells ? numberOfCells - 1 : colspan - 1;
  279. createCells( cellsToInsert, writer, Position.createAfter( tableCell ), newCellsAttributes );
  280. }
  281. // Second check - the cell has colspan of 1 or we need to create more cells then the currently one spans over.
  282. if ( colspan < numberOfCells ) {
  283. const cellsToInsert = numberOfCells - colspan;
  284. // First step: expand cells on the same column as split cell.
  285. const tableMap = [ ...new TableWalker( table ) ];
  286. // Get the column index of split cell.
  287. const { column: splitCellColumn } = tableMap.find( ( { cell } ) => cell === tableCell );
  288. // Find cells which needs to be expanded vertically - those on the same column or those that spans over split cell's column.
  289. const cellsToUpdate = tableMap.filter( ( { cell, colspan, column } ) => {
  290. const isOnSameColumn = cell !== tableCell && column === splitCellColumn;
  291. const spansOverColumn = ( column < splitCellColumn && column + colspan > splitCellColumn );
  292. return isOnSameColumn || spansOverColumn;
  293. } );
  294. // Expand cells vertically.
  295. for ( const { cell, colspan } of cellsToUpdate ) {
  296. writer.setAttribute( 'colspan', colspan + cellsToInsert, cell );
  297. }
  298. // Second step: create columns after split cell.
  299. // Each inserted cell will have the same attributes:
  300. const newCellsAttributes = {};
  301. // Do not store default value in the model.
  302. // Copy rowspan of split cell.
  303. if ( rowspan > 1 ) {
  304. newCellsAttributes.rowspan = rowspan;
  305. }
  306. createCells( cellsToInsert, writer, Position.createAfter( tableCell ), newCellsAttributes );
  307. const headingColumns = table.getAttribute( 'headingColumns' ) || 0;
  308. // Update heading section if split cell is in heading section.
  309. if ( headingColumns > splitCellColumn ) {
  310. updateNumericAttribute( 'headingColumns', headingColumns + cellsToInsert, table, writer );
  311. }
  312. }
  313. } );
  314. }
  315. /**
  316. * Divides a table cell horizontally into several ones.
  317. *
  318. * 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
  319. * below.
  320. *
  321. * If in the table below cell "b" is split to 3 cells:
  322. *
  323. * +---+---+---+
  324. * | a | b | c |
  325. * +---+---+---+
  326. * | d | e | f |
  327. * +---+---+---+
  328. *
  329. * It will result in the table below:
  330. *
  331. * +---+---+---+
  332. * | a | b | c |
  333. * + +---+ +
  334. * | | | |
  335. * + +---+ +
  336. * | | | |
  337. * +---+---+---+
  338. * | d | e | f |
  339. * +---+---+---+
  340. *
  341. * So cells "a" and "b" will get their `rowspan` updated to `3` and 2 rows with a single cell will be added.
  342. *
  343. * Splitting a cell that already has a `rowspan` attribute set will distribute the cell `rowspan` evenly and the remainder
  344. * will be left to the original cell:
  345. *
  346. * +---+---+---+
  347. * | a | b | c |
  348. * + +---+---+
  349. * | | d | e |
  350. * + +---+---+
  351. * | | f | g |
  352. * + +---+---+
  353. * | | h | i |
  354. * +---+---+---+
  355. *
  356. * Splitting cell "a" with `rowspan=4` to 3 cells will create 2 cells with a `rowspan=1` and cell "a" will have `rowspan=2`:
  357. *
  358. * +---+---+---+
  359. * | a | b | c |
  360. * + +---+---+
  361. * | | d | e |
  362. * +---+---+---+
  363. * | | f | g |
  364. * +---+---+---+
  365. * | | h | i |
  366. * +---+---+---+
  367. *
  368. * @param {module:engine/model/element~Element} tableCell
  369. * @param {Number} numberOfCells
  370. */
  371. splitCellHorizontally( tableCell, numberOfCells = 2 ) {
  372. const model = this.editor.model;
  373. const tableRow = tableCell.parent;
  374. const table = tableRow.parent;
  375. const splitCellRow = table.getChildIndex( tableRow );
  376. const rowspan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  377. const colspan = parseInt( tableCell.getAttribute( 'colspan' ) || 1 );
  378. model.change( writer => {
  379. // First check - the cell spans over multiple rows so before doing anything else just split this cell.
  380. if ( rowspan > 1 ) {
  381. // Cache table map before updating table.
  382. const tableMap = [ ...new TableWalker( table, {
  383. startRow: splitCellRow,
  384. endRow: splitCellRow + rowspan - 1,
  385. includeSpanned: true
  386. } ) ];
  387. // Get spans of new (inserted) cells and span to update of split cell.
  388. const { newCellsSpan, updatedSpan } = breakSpanEvenly( rowspan, numberOfCells );
  389. updateNumericAttribute( 'rowspan', updatedSpan, tableCell, writer );
  390. const { column: cellColumn } = tableMap.find( ( { cell } ) => cell === tableCell );
  391. // Each inserted cell will have the same attributes:
  392. const newCellsAttributes = {};
  393. // Do not store default value in the model.
  394. if ( newCellsSpan > 1 ) {
  395. newCellsAttributes.rowspan = newCellsSpan;
  396. }
  397. // Copy colspan of split cell.
  398. if ( colspan > 1 ) {
  399. newCellsAttributes.colspan = colspan;
  400. }
  401. for ( const { column, row, cellIndex } of tableMap ) {
  402. // As both newly created cells and the split cell might have rowspan,
  403. // the insertion of new cells must go to appropriate rows:
  404. //
  405. // 1. It's a row after split cell + it's height.
  406. const isAfterSplitCell = row >= splitCellRow + updatedSpan;
  407. // 2. Is on the same column.
  408. const isOnSameColumn = column === cellColumn;
  409. // 3. And it's row index is after previous cell height.
  410. const isInEvenlySplitRow = ( row + splitCellRow + updatedSpan ) % newCellsSpan === 0;
  411. if ( isAfterSplitCell && isOnSameColumn && isInEvenlySplitRow ) {
  412. const position = Position.createFromParentAndOffset( table.getChild( row ), cellIndex );
  413. createCells( 1, writer, position, newCellsAttributes );
  414. }
  415. }
  416. }
  417. // Second check - the cell has rowspan of 1 or we need to create more cells than the current cell spans over.
  418. if ( rowspan < numberOfCells ) {
  419. // We already split the cell in check one so here we split to the remaining number of cells only.
  420. const cellsToInsert = numberOfCells - rowspan;
  421. // This check is needed since we need to check if there are any cells from previous rows than spans over this cell's row.
  422. const tableMap = [ ...new TableWalker( table, { startRow: 0, endRow: splitCellRow } ) ];
  423. // First step: expand cells.
  424. for ( const { cell, rowspan, row } of tableMap ) {
  425. // Expand rowspan of cells that are either:
  426. // - on the same row as current cell,
  427. // - or are below split cell row and overlaps that row.
  428. if ( cell !== tableCell && row + rowspan > splitCellRow ) {
  429. const rowspanToSet = rowspan + cellsToInsert;
  430. writer.setAttribute( 'rowspan', rowspanToSet, cell );
  431. }
  432. }
  433. // Second step: create rows with single cell below split cell.
  434. const newCellsAttributes = {};
  435. // Copy colspan of split cell.
  436. if ( colspan > 1 ) {
  437. newCellsAttributes.colspan = colspan;
  438. }
  439. createEmptyRows( writer, table, splitCellRow + 1, cellsToInsert, 1, newCellsAttributes );
  440. // Update heading section if split cell is in heading section.
  441. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  442. if ( headingRows > splitCellRow ) {
  443. updateNumericAttribute( 'headingRows', headingRows + cellsToInsert, table, writer );
  444. }
  445. }
  446. } );
  447. }
  448. /**
  449. * Returns the number of columns for a given table.
  450. *
  451. * editor.plugins.get( 'TableUtils' ).getColumns( table );
  452. *
  453. * @param {module:engine/model/element~Element} table The table to analyze.
  454. * @returns {Number}
  455. */
  456. getColumns( table ) {
  457. // Analyze first row only as all the rows should have the same width.
  458. const row = table.getChild( 0 );
  459. return [ ...row.getChildren() ].reduce( ( columns, row ) => {
  460. const columnWidth = parseInt( row.getAttribute( 'colspan' ) || 1 );
  461. return columns + columnWidth;
  462. }, 0 );
  463. }
  464. }
  465. // Creates empty rows at the given index in an existing table.
  466. //
  467. // @param {module:engine/model/writer~Writer} writer
  468. // @param {module:engine/model/element~Element} table
  469. // @param {Number} insertAt Row index of row insertion.
  470. // @param {Number} rows Number of rows to create.
  471. // @param {Number} tableCellToInsert Number of cells to insert in each row.
  472. function createEmptyRows( writer, table, insertAt, rows, tableCellToInsert, attributes = {} ) {
  473. for ( let i = 0; i < rows; i++ ) {
  474. const tableRow = writer.createElement( 'tableRow' );
  475. writer.insert( tableRow, table, insertAt );
  476. createCells( tableCellToInsert, writer, Position.createAt( tableRow, 'end' ), attributes );
  477. }
  478. }
  479. // Creates cells at a given position.
  480. //
  481. // @param {Number} columns Number of columns to create
  482. // @param {module:engine/model/writer~Writer} writer
  483. // @param {module:engine/model/position~Position} insertPosition
  484. function createCells( cells, writer, insertPosition, attributes = {} ) {
  485. for ( let i = 0; i < cells; i++ ) {
  486. createEmptyTableCell( writer, insertPosition, attributes );
  487. }
  488. }
  489. // Evenly distributes the span of a cell to a number of provided cells.
  490. // The resulting spans will always be integer values.
  491. //
  492. // For instance breaking a span of 7 into 3 cells will return:
  493. //
  494. // { newCellsSpan: 2, updatedSpan: 3 }
  495. //
  496. // as two cells will have a span of 2 and the remainder will go the first cell so its span will change to 3.
  497. //
  498. // @param {Number} span Span value do break.
  499. // @param {Number} numberOfCells Number of resulting spans.
  500. // @returns {{newCellsSpan: Number, updatedSpan: Number}}
  501. function breakSpanEvenly( span, numberOfCells ) {
  502. if ( span < numberOfCells ) {
  503. return { newCellsSpan: 1, updatedSpan: 1 };
  504. }
  505. const newCellsSpan = Math.floor( span / numberOfCells );
  506. const updatedSpan = ( span - newCellsSpan * numberOfCells ) + newCellsSpan;
  507. return { newCellsSpan, updatedSpan };
  508. }