8
0

mergecellcommand.js 9.6 KB

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