8
0

mergecellcommand.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 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 `'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.isEnabled = !!cellToMerge;
  61. // In order to check if currently selected cell can be merged with one defined by #direction some computation are done beforehand.
  62. // As such we can cache it as a command's value.
  63. this.value = 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 = findAncestor( 'tableCell', doc.selection.getFirstPosition() );
  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. // Remove empty row after merging.
  93. if ( !removedTableCellRow.childCount ) {
  94. removeEmptyRow( removedTableCellRow, writer );
  95. }
  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|undefined}
  102. * @private
  103. */
  104. _getMergeableCell() {
  105. const model = this.editor.model;
  106. const doc = model.document;
  107. const tableCell = findAncestor( 'tableCell', doc.selection.getFirstPosition() );
  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 horizontalCell = direction == 'right' ? tableCell.nextSibling : tableCell.previousSibling;
  135. if ( !horizontalCell ) {
  136. return;
  137. }
  138. // Sort cells:
  139. const cellOnLeft = direction == 'right' ? tableCell : horizontalCell;
  140. const cellOnRight = direction == 'right' ? horizontalCell : tableCell;
  141. // Get their column indexes:
  142. const { column: leftCellColumn } = tableUtils.getCellLocation( cellOnLeft );
  143. const { column: rightCellColumn } = tableUtils.getCellLocation( cellOnRight );
  144. const leftCellSpan = parseInt( cellOnLeft.getAttribute( 'colspan' ) || 1 );
  145. // The cell on the right must have index that is distant to the cell on the left by the left cell's width (colspan).
  146. const cellsAreTouching = leftCellColumn + leftCellSpan === rightCellColumn;
  147. // If the right cell's column index is different it means that there are rowspanned cells between them.
  148. return cellsAreTouching ? horizontalCell : undefined;
  149. }
  150. // Returns the cell that can be merged vertically.
  151. //
  152. // @param {module:engine/model/element~Element} tableCell
  153. // @param {String} direction
  154. // @returns {module:engine/model/node~Node|null}
  155. function getVerticalCell( tableCell, direction ) {
  156. const tableRow = tableCell.parent;
  157. const table = tableRow.parent;
  158. const rowIndex = table.getChildIndex( tableRow );
  159. // Don't search for mergeable cell if direction points out of the table.
  160. if ( ( direction == 'down' && rowIndex === table.childCount - 1 ) || ( direction == 'up' && rowIndex === 0 ) ) {
  161. return;
  162. }
  163. const rowspan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  164. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  165. const isMergeWithBodyCell = direction == 'down' && ( rowIndex + rowspan ) === headingRows;
  166. const isMergeWithHeadCell = direction == 'up' && rowIndex === headingRows;
  167. // Don't search for mergeable cell if direction points out of the current table section.
  168. if ( headingRows && ( isMergeWithBodyCell || isMergeWithHeadCell ) ) {
  169. return;
  170. }
  171. const currentCellRowSpan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  172. const rowOfCellToMerge = direction == 'down' ? rowIndex + currentCellRowSpan : rowIndex;
  173. const tableMap = [ ...new TableWalker( table, { endRow: rowOfCellToMerge } ) ];
  174. const currentCellData = tableMap.find( value => value.cell === tableCell );
  175. const mergeColumn = currentCellData.column;
  176. const cellToMergeData = tableMap.find( ( { row, rowspan, column } ) => {
  177. if ( column !== mergeColumn ) {
  178. return false;
  179. }
  180. if ( direction == 'down' ) {
  181. // If merging a cell below the mergeRow is already calculated.
  182. return row === rowOfCellToMerge;
  183. } else {
  184. // If merging a cell above calculate if it spans to mergeRow.
  185. return rowOfCellToMerge === row + rowspan;
  186. }
  187. } );
  188. return cellToMergeData && cellToMergeData.cell;
  189. }
  190. // Properly removes empty row from a table. Will update `rowspan` attribute of cells that overlaps removed row.
  191. //
  192. // @param {module:engine/model/element~Element} removedTableCellRow
  193. // @param {module:engine/model/writer~Writer} writer
  194. function removeEmptyRow( removedTableCellRow, writer ) {
  195. const table = removedTableCellRow.parent;
  196. const removedRowIndex = table.getChildIndex( removedTableCellRow );
  197. for ( const { cell, row, rowspan } of new TableWalker( table, { endRow: removedRowIndex } ) ) {
  198. const overlapsRemovedRow = row + rowspan - 1 >= removedRowIndex;
  199. if ( overlapsRemovedRow ) {
  200. updateNumericAttribute( 'rowspan', rowspan - 1, cell, writer );
  201. }
  202. }
  203. writer.remove( removedTableCellRow );
  204. }
  205. // Merges two table cells - will ensure that after merging cells with empty paragraph the result table cell will only have one paragraph.
  206. // If one of the merged table cell is empty the merged table cell will have contents of the non-empty table cell.
  207. // If both are empty the merged table cell will have only one empty paragraph.
  208. //
  209. // @param {module:engine/model/element~Element} cellToRemove
  210. // @param {module:engine/model/element~Element} cellToExpand
  211. // @param {module:engine/model/writer~Writer} writer
  212. function mergeTableCells( cellToRemove, cellToExpand, writer ) {
  213. if ( !isEmpty( cellToRemove ) ) {
  214. if ( isEmpty( cellToExpand ) ) {
  215. writer.remove( writer.createRangeIn( cellToExpand ) );
  216. }
  217. writer.move( writer.createRangeIn( cellToRemove ), writer.createPositionAt( cellToExpand, 'end' ) );
  218. }
  219. // Remove merged table cell.
  220. writer.remove( cellToRemove );
  221. }
  222. // Checks if passed table cell contains empty paragraph.
  223. //
  224. // @param {module:engine/model/element~Element} tableCell
  225. // @returns {Boolean}
  226. function isEmpty( tableCell ) {
  227. return tableCell.childCount == 1 && tableCell.getChild( 0 ).is( 'paragraph' ) && tableCell.getChild( 0 ).isEmpty;
  228. }