mergecellcommand.js 9.6 KB

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