mergecellcommand.js 8.7 KB

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