mergecellcommand.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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/commands/mergecellcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import TableWalker from '../tablewalker';
  10. import { findAncestor, updateNumericAttribute } from './utils';
  11. /**
  12. * The merge cell command.
  13. *
  14. * The command is registered by {@link module:table/tableediting~TableEditing} as the `'mergeTableCellRight'`, `'mergeTableCellLeft'`,
  15. * `'mergeTableCellUp'` and `'mergeTableCellDown'` editor commands.
  16. *
  17. * To merge a table cell at the current selection with another cell, execute the command corresponding with the preferred direction.
  18. *
  19. * For example, to merge with a cell to the right:
  20. *
  21. * editor.execute( 'mergeTableCellRight' );
  22. *
  23. * **Note**: If a table cell has a different [`rowspan`](https://www.w3.org/TR/html50/tabular-data.html#attr-tdth-rowspan)
  24. * (for `'mergeTableCellRight'` and `'mergeTableCellLeft'`) or [`colspan`](https://www.w3.org/TR/html50/tabular-data.html#attr-tdth-colspan)
  25. * (for `'mergeTableCellUp'` and `'mergeTableCellDown'`), the command will be disabled.
  26. *
  27. * @extends module:core/command~Command
  28. */
  29. export default class MergeCellCommand extends Command {
  30. /**
  31. * Creates a new `MergeCellCommand` instance.
  32. *
  33. * @param {module:core/editor/editor~Editor} editor The editor on which this command will be used.
  34. * @param {Object} options
  35. * @param {String} options.direction Indicates which cell to merge with the currently selected one.
  36. * Possible values are: `'left'`, `'right'`, `'up'` and `'down'`.
  37. */
  38. constructor( editor, options ) {
  39. super( editor );
  40. /**
  41. * The direction that indicates which cell will be merged with the currently selected one.
  42. *
  43. * @readonly
  44. * @member {String} #direction
  45. */
  46. this.direction = options.direction;
  47. /**
  48. * Whether the merge is horizontal (left/right) or vertical (up/down).
  49. *
  50. * @readonly
  51. * @member {Boolean} #isHorizontal
  52. */
  53. this.isHorizontal = this.direction == 'right' || this.direction == 'left';
  54. }
  55. /**
  56. * @inheritDoc
  57. */
  58. refresh() {
  59. const cellToMerge = this._getMergeableCell();
  60. this.value = cellToMerge;
  61. this.isEnabled = !!cellToMerge;
  62. }
  63. /**
  64. * Executes the command.
  65. *
  66. * Depending on the command's {@link #direction} value, it will merge the cell that is to the `'left'`, `'right'`, `'up'` or `'down'`.
  67. *
  68. * @fires execute
  69. */
  70. execute() {
  71. const model = this.editor.model;
  72. const doc = model.document;
  73. const tableCell = findAncestor( 'tableCell', doc.selection.getFirstPosition() );
  74. const cellToMerge = this.value;
  75. const direction = this.direction;
  76. model.change( writer => {
  77. const isMergeNext = direction == 'right' || direction == 'down';
  78. // The merge mechanism is always the same so sort cells to be merged.
  79. const cellToExpand = isMergeNext ? tableCell : cellToMerge;
  80. const cellToRemove = isMergeNext ? cellToMerge : tableCell;
  81. // Cache the parent of cell to remove for later check.
  82. const removedTableCellRow = cellToRemove.parent;
  83. mergeTableCells( cellToRemove, cellToExpand, writer );
  84. const spanAttribute = this.isHorizontal ? 'colspan' : 'rowspan';
  85. const cellSpan = parseInt( tableCell.getAttribute( spanAttribute ) || 1 );
  86. const cellToMergeSpan = parseInt( cellToMerge.getAttribute( spanAttribute ) || 1 );
  87. // Update table cell span attribute and merge set selection on merged contents.
  88. writer.setAttribute( spanAttribute, cellSpan + cellToMergeSpan, cellToExpand );
  89. writer.setSelection( writer.createRangeIn( cellToExpand ) );
  90. // Remove empty row after merging.
  91. if ( !removedTableCellRow.childCount ) {
  92. removeEmptyRow( removedTableCellRow, writer );
  93. }
  94. } );
  95. }
  96. /**
  97. * Returns a cell that can be merged with the current cell depending on the command's direction.
  98. *
  99. * @returns {module:engine/model/element~Element|undefined}
  100. * @private
  101. */
  102. _getMergeableCell() {
  103. const model = this.editor.model;
  104. const doc = model.document;
  105. const tableCell = findAncestor( 'tableCell', doc.selection.getFirstPosition() );
  106. if ( !tableCell ) {
  107. return;
  108. }
  109. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  110. // First get the cell on proper direction.
  111. const cellToMerge = this.isHorizontal ?
  112. getHorizontalCell( tableCell, this.direction, tableUtils ) :
  113. getVerticalCell( tableCell, this.direction );
  114. if ( !cellToMerge ) {
  115. return;
  116. }
  117. // If found check if the span perpendicular to merge direction is equal on both cells.
  118. const spanAttribute = this.isHorizontal ? 'rowspan' : 'colspan';
  119. const span = parseInt( tableCell.getAttribute( spanAttribute ) || 1 );
  120. const cellToMergeSpan = parseInt( cellToMerge.getAttribute( spanAttribute ) || 1 );
  121. if ( cellToMergeSpan === span ) {
  122. return cellToMerge;
  123. }
  124. }
  125. }
  126. // Returns the cell that can be merged horizontally.
  127. //
  128. // @param {module:engine/model/element~Element} tableCell
  129. // @param {String} direction
  130. // @returns {module:engine/model/node~Node|null}
  131. function getHorizontalCell( tableCell, direction, tableUtils ) {
  132. const tableRow = tableCell.parent;
  133. const table = tableRow.parent;
  134. const horizontalCell = direction == 'right' ? tableCell.nextSibling : tableCell.previousSibling;
  135. const headingColumns = table.getAttribute( 'headingColumns' ) || 0;
  136. if ( !horizontalCell ) {
  137. return;
  138. }
  139. // Sort cells:
  140. const cellOnLeft = direction == 'right' ? tableCell : horizontalCell;
  141. const cellOnRight = direction == 'right' ? horizontalCell : tableCell;
  142. // Get their column indexes:
  143. const { column: leftCellColumn } = tableUtils.getCellLocation( cellOnLeft );
  144. const { column: rightCellColumn } = tableUtils.getCellLocation( cellOnRight );
  145. const leftCellSpan = parseInt( cellOnLeft.getAttribute( 'colspan' ) || 1 );
  146. const rightCellSpan = parseInt( cellOnRight.getAttribute( 'colspan' ) || 1 );
  147. // We cannot merge cells if the result will extend over heading section.
  148. const isMergeWithBodyCell = direction == 'right' && ( rightCellColumn + rightCellSpan > headingColumns );
  149. const isMergeWithHeadCell = direction == 'left' && ( leftCellColumn + leftCellSpan > headingColumns - 1 );
  150. if ( headingColumns && ( isMergeWithBodyCell || isMergeWithHeadCell ) ) {
  151. return;
  152. }
  153. // The cell on the right must have index that is distant to the cell on the left by the left cell's width (colspan).
  154. const cellsAreTouching = leftCellColumn + leftCellSpan === rightCellColumn;
  155. // If the right cell's column index is different it means that there are rowspanned cells between them.
  156. return cellsAreTouching ? horizontalCell : undefined;
  157. }
  158. // Returns the cell that can be merged vertically.
  159. //
  160. // @param {module:engine/model/element~Element} tableCell
  161. // @param {String} direction
  162. // @returns {module:engine/model/node~Node|null}
  163. function getVerticalCell( tableCell, direction ) {
  164. const tableRow = tableCell.parent;
  165. const table = tableRow.parent;
  166. const rowIndex = table.getChildIndex( tableRow );
  167. // Don't search for mergeable cell if direction points out of the table.
  168. if ( ( direction == 'down' && rowIndex === table.childCount - 1 ) || ( direction == 'up' && rowIndex === 0 ) ) {
  169. return;
  170. }
  171. const rowspan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  172. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  173. const isMergeWithBodyCell = direction == 'down' && ( rowIndex + rowspan ) === headingRows;
  174. const isMergeWithHeadCell = direction == 'up' && rowIndex === headingRows;
  175. // Don't search for mergeable cell if direction points out of the current table section.
  176. if ( headingRows && ( isMergeWithBodyCell || isMergeWithHeadCell ) ) {
  177. return;
  178. }
  179. const currentCellRowSpan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  180. const rowOfCellToMerge = direction == 'down' ? rowIndex + currentCellRowSpan : rowIndex;
  181. const tableMap = [ ...new TableWalker( table, { endRow: rowOfCellToMerge } ) ];
  182. const currentCellData = tableMap.find( value => value.cell === tableCell );
  183. const mergeColumn = currentCellData.column;
  184. const cellToMergeData = tableMap.find( ( { row, rowspan, column } ) => {
  185. if ( column !== mergeColumn ) {
  186. return false;
  187. }
  188. if ( direction == 'down' ) {
  189. // If merging a cell below the mergeRow is already calculated.
  190. return row === rowOfCellToMerge;
  191. } else {
  192. // If merging a cell above calculate if it spans to mergeRow.
  193. return rowOfCellToMerge === row + rowspan;
  194. }
  195. } );
  196. return cellToMergeData && cellToMergeData.cell;
  197. }
  198. // Properly removes an empty row from a table. It will update the `rowspan` attribute of cells that overlap the removed row.
  199. //
  200. // @param {module:engine/model/element~Element} removedTableCellRow
  201. // @param {module:engine/model/writer~Writer} writer
  202. function removeEmptyRow( removedTableCellRow, writer ) {
  203. const table = removedTableCellRow.parent;
  204. const removedRowIndex = table.getChildIndex( removedTableCellRow );
  205. for ( const { cell, row, rowspan } of new TableWalker( table, { endRow: removedRowIndex } ) ) {
  206. const overlapsRemovedRow = row + rowspan - 1 >= removedRowIndex;
  207. if ( overlapsRemovedRow ) {
  208. updateNumericAttribute( 'rowspan', rowspan - 1, cell, writer );
  209. }
  210. }
  211. writer.remove( removedTableCellRow );
  212. }
  213. // Merges two table cells. It will ensure that after merging cells with an empty paragraph, the resulting table cell will only have one
  214. // paragraph. If one of the merged table cell is empty, the merged table cell will have the contents of the non-empty table cell.
  215. // If both are empty, the merged table cell will have only one empty paragraph.
  216. //
  217. // @param {module:engine/model/element~Element} cellToRemove
  218. // @param {module:engine/model/element~Element} cellToExpand
  219. // @param {module:engine/model/writer~Writer} writer
  220. function mergeTableCells( cellToRemove, cellToExpand, writer ) {
  221. if ( !isEmpty( cellToRemove ) ) {
  222. if ( isEmpty( cellToExpand ) ) {
  223. writer.remove( writer.createRangeIn( cellToExpand ) );
  224. }
  225. writer.move( writer.createRangeIn( cellToRemove ), writer.createPositionAt( cellToExpand, 'end' ) );
  226. }
  227. // Remove merged table cell.
  228. writer.remove( cellToRemove );
  229. }
  230. // Checks if the passed table cell contains an empty paragraph.
  231. //
  232. // @param {module:engine/model/element~Element} tableCell
  233. // @returns {Boolean}
  234. function isEmpty( tableCell ) {
  235. return tableCell.childCount == 1 && tableCell.getChild( 0 ).is( 'paragraph' ) && tableCell.getChild( 0 ).isEmpty;
  236. }