selection.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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/utils/selection
  7. */
  8. import TableWalker from '../tablewalker';
  9. import { findAncestor } from './common';
  10. /**
  11. * Returns all model table cells that are fully selected (from the outside)
  12. * within the provided model selection's ranges.
  13. *
  14. * To obtain the cells selected from the inside, use
  15. * {@link module:table/utils/selection~getTableCellsContainingSelection}.
  16. *
  17. * @param {module:engine/model/selection~Selection} selection
  18. * @returns {Array.<module:engine/model/element~Element>}
  19. */
  20. export function getSelectedTableCells( selection ) {
  21. const cells = [];
  22. for ( const range of sortRanges( selection.getRanges() ) ) {
  23. const element = range.getContainedElement();
  24. if ( element && element.is( 'tableCell' ) ) {
  25. cells.push( element );
  26. }
  27. }
  28. return cells;
  29. }
  30. /**
  31. * Returns all model table cells that the provided model selection's ranges
  32. * {@link module:engine/model/range~Range#start} inside.
  33. *
  34. * To obtain the cells selected from the outside, use
  35. * {@link module:table/utils/selection~getSelectedTableCells}.
  36. *
  37. * @param {module:engine/model/selection~Selection} selection
  38. * @returns {Array.<module:engine/model/element~Element>}
  39. */
  40. export function getTableCellsContainingSelection( selection ) {
  41. const cells = [];
  42. for ( const range of selection.getRanges() ) {
  43. const cellWithSelection = findAncestor( 'tableCell', range.start );
  44. if ( cellWithSelection ) {
  45. cells.push( cellWithSelection );
  46. }
  47. }
  48. return cells;
  49. }
  50. /**
  51. * Returns all model table cells that are either completely selected
  52. * by selection ranges or host selection range
  53. * {@link module:engine/model/range~Range#start start positions} inside them.
  54. *
  55. * Combines {@link module:table/utils/selection~getTableCellsContainingSelection} and
  56. * {@link module:table/utils/selection~getSelectedTableCells}.
  57. *
  58. * @param {module:engine/model/selection~Selection} selection
  59. * @returns {Array.<module:engine/model/element~Element>}
  60. */
  61. export function getSelectionAffectedTableCells( selection ) {
  62. const selectedCells = getSelectedTableCells( selection );
  63. if ( selectedCells.length ) {
  64. return selectedCells;
  65. }
  66. return getTableCellsContainingSelection( selection );
  67. }
  68. /**
  69. * Returns an object with the `first` and `last` row index contained in the given `tableCells`.
  70. *
  71. * const selectedTableCells = getSelectedTableCells( editor.model.document.selection );
  72. *
  73. * const { first, last } = getRowIndexes( selectedTableCells );
  74. *
  75. * console.log( `Selected rows: ${ first } to ${ last }` );
  76. *
  77. * @param {Array.<module:engine/model/element~Element>} tableCells
  78. * @returns {Object} Returns an object with the `first` and `last` table row indexes.
  79. */
  80. export function getRowIndexes( tableCells ) {
  81. const indexes = tableCells.map( cell => cell.parent.index );
  82. return getFirstLastIndexesObject( indexes );
  83. }
  84. /**
  85. * Returns an object with the `first` and `last` column index contained in the given `tableCells`.
  86. *
  87. * const selectedTableCells = getSelectedTableCells( editor.model.document.selection );
  88. *
  89. * const { first, last } = getColumnIndexes( selectedTableCells );
  90. *
  91. * console.log( `Selected columns: ${ first } to ${ last }` );
  92. *
  93. * @param {Array.<module:engine/model/element~Element>} tableCells
  94. * @returns {Object} Returns an object with the `first` and `last` table column indexes.
  95. */
  96. export function getColumnIndexes( tableCells ) {
  97. const table = findAncestor( 'table', tableCells[ 0 ] );
  98. const tableMap = [ ...new TableWalker( table ) ];
  99. const indexes = tableMap
  100. .filter( entry => tableCells.includes( entry.cell ) )
  101. .map( entry => entry.column );
  102. return getFirstLastIndexesObject( indexes );
  103. }
  104. /**
  105. * Checks if the selection contains cells that do not exceed rectangular selection.
  106. *
  107. * In a table below:
  108. *
  109. * ┌───┬───┬───┬───┐
  110. * │ a │ b │ c │ d │
  111. * ├───┴───┼───┤ │
  112. * │ e │ f │ │
  113. * │ ├───┼───┤
  114. * │ │ g │ h │
  115. * └───────┴───┴───┘
  116. *
  117. * Valid selections are these which create a solid rectangle (without gaps), such as:
  118. * - a, b (two horizontal cells)
  119. * - c, f (two vertical cells)
  120. * - a, b, e (cell "e" spans over four cells)
  121. * - c, d, f (cell d spans over a cell in the row below)
  122. *
  123. * While an invalid selection would be:
  124. * - a, c (the unselected cell "b" creates a gap)
  125. * - f, g, h (cell "d" spans over a cell from the row of "f" cell - thus creates a gap)
  126. *
  127. * @param {Array.<module:engine/model/element~Element>} selectedTableCells
  128. * @param {module:table/tableutils~TableUtils} tableUtils
  129. * @returns {Boolean}
  130. */
  131. export function isSelectionRectangular( selectedTableCells, tableUtils ) {
  132. if ( selectedTableCells.length < 2 || !areCellInTheSameTableSection( selectedTableCells ) ) {
  133. return false;
  134. }
  135. // A valid selection is a fully occupied rectangle composed of table cells.
  136. // Below we will calculate the area of a selected table cells and the area of valid selection.
  137. // The area of a valid selection is defined by top-left and bottom-right cells.
  138. const rows = new Set();
  139. const columns = new Set();
  140. let areaOfSelectedCells = 0;
  141. for ( const tableCell of selectedTableCells ) {
  142. const { row, column } = tableUtils.getCellLocation( tableCell );
  143. const rowspan = parseInt( tableCell.getAttribute( 'rowspan' ) || 1 );
  144. const colspan = parseInt( tableCell.getAttribute( 'colspan' ) || 1 );
  145. // Record row & column indexes of current cell.
  146. rows.add( row );
  147. columns.add( column );
  148. // For cells that spans over multiple rows add also the last row that this cell spans over.
  149. if ( rowspan > 1 ) {
  150. rows.add( row + rowspan - 1 );
  151. }
  152. // For cells that spans over multiple columns add also the last column that this cell spans over.
  153. if ( colspan > 1 ) {
  154. columns.add( column + colspan - 1 );
  155. }
  156. areaOfSelectedCells += ( rowspan * colspan );
  157. }
  158. // We can only merge table cells that are in adjacent rows...
  159. const areaOfValidSelection = getBiggestRectangleArea( rows, columns );
  160. return areaOfValidSelection == areaOfSelectedCells;
  161. }
  162. // Helper method to get an object with `first` and `last` indexes from an unsorted array of indexes.
  163. function getFirstLastIndexesObject( indexes ) {
  164. const allIndexesSorted = indexes.sort( ( indexA, indexB ) => indexA - indexB );
  165. const first = allIndexesSorted[ 0 ];
  166. const last = allIndexesSorted[ allIndexesSorted.length - 1 ];
  167. return { first, last };
  168. }
  169. function sortRanges( rangesIterator ) {
  170. return Array.from( rangesIterator ).sort( compareRangeOrder );
  171. }
  172. function compareRangeOrder( rangeA, rangeB ) {
  173. // Since table cell ranges are disjoint, it's enough to check their start positions.
  174. const posA = rangeA.start;
  175. const posB = rangeB.start;
  176. // Checking for equal position (returning 0) is not needed because this would be either:
  177. // a. Intersecting range (not allowed by model)
  178. // b. Collapsed range on the same position (allowed by model but should not happen).
  179. return posA.isBefore( posB ) ? -1 : 1;
  180. }
  181. // Calculates the area of a maximum rectangle that can span over the provided row & column indexes.
  182. //
  183. // @param {Array.<Number>} rows
  184. // @param {Array.<Number>} columns
  185. // @returns {Number}
  186. function getBiggestRectangleArea( rows, columns ) {
  187. const rowsIndexes = Array.from( rows.values() );
  188. const columnIndexes = Array.from( columns.values() );
  189. const lastRow = Math.max( ...rowsIndexes );
  190. const firstRow = Math.min( ...rowsIndexes );
  191. const lastColumn = Math.max( ...columnIndexes );
  192. const firstColumn = Math.min( ...columnIndexes );
  193. return ( lastRow - firstRow + 1 ) * ( lastColumn - firstColumn + 1 );
  194. }
  195. // Checks if the selection does not mix a header (column or row) with other cells.
  196. //
  197. // For instance, in the table below valid selections consist of cells with the same letter only.
  198. // So, a-a (same heading row and column) or d-d (body cells) are valid while c-d or a-b are not.
  199. //
  200. // header columns
  201. // ↓ ↓
  202. // ┌───┬───┬───┬───┐
  203. // │ a │ a │ b │ b │ ← header row
  204. // ├───┼───┼───┼───┤
  205. // │ c │ c │ d │ d │
  206. // ├───┼───┼───┼───┤
  207. // │ c │ c │ d │ d │
  208. // └───┴───┴───┴───┘
  209. function areCellInTheSameTableSection( tableCells ) {
  210. const table = findAncestor( 'table', tableCells[ 0 ] );
  211. const rowIndexes = getRowIndexes( tableCells );
  212. const headingRows = parseInt( table.getAttribute( 'headingRows' ) || 0 );
  213. // Calculating row indexes is a bit cheaper so if this check fails we can't merge.
  214. if ( !areIndexesInSameSection( rowIndexes, headingRows ) ) {
  215. return false;
  216. }
  217. const headingColumns = parseInt( table.getAttribute( 'headingColumns' ) || 0 );
  218. const columnIndexes = getColumnIndexes( tableCells );
  219. // Similarly cells must be in same column section.
  220. return areIndexesInSameSection( columnIndexes, headingColumns );
  221. }
  222. // Unified check if table rows/columns indexes are in the same heading/body section.
  223. function areIndexesInSameSection( { first, last }, headingSectionSize ) {
  224. const firstCellIsInHeading = first < headingSectionSize;
  225. const lastCellIsInHeading = last < headingSectionSize;
  226. return firstCellIsInHeading === lastCellIsInHeading;
  227. }