tableutils.js 20 KB

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