tableselection.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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/tableselection
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import first from '@ckeditor/ckeditor5-utils/src/first';
  10. import TableWalker from './tablewalker';
  11. import TableUtils from './tableutils';
  12. import { findAncestor } from './utils/common';
  13. import { cropTableToDimensions, adjustLastRowIndex, adjustLastColumnIndex } from './utils/structure';
  14. import { getColumnIndexes, getRowIndexes, getSelectedTableCells, isSelectionRectangular } from './utils/selection';
  15. import '../theme/tableselection.css';
  16. /**
  17. * This plugin enables the advanced table cells, rows and columns selection.
  18. * It is loaded automatically by the {@link module:table/table~Table} plugin.
  19. *
  20. * @extends module:core/plugin~Plugin
  21. */
  22. export default class TableSelection extends Plugin {
  23. /**
  24. * @inheritDoc
  25. */
  26. static get pluginName() {
  27. return 'TableSelection';
  28. }
  29. /**
  30. * @inheritDoc
  31. */
  32. static get requires() {
  33. return [ TableUtils ];
  34. }
  35. /**
  36. * @inheritDoc
  37. */
  38. init() {
  39. const editor = this.editor;
  40. const model = editor.model;
  41. this.listenTo( model, 'deleteContent', ( evt, args ) => this._handleDeleteContent( evt, args ), { priority: 'high' } );
  42. this._defineSelectionConverter();
  43. this._enablePluginDisabling(); // sic!
  44. }
  45. /**
  46. * Returns the currently selected table cells or `null` if it is not a table cells selection.
  47. *
  48. * @returns {Array.<module:engine/model/element~Element>|null}
  49. */
  50. getSelectedTableCells() {
  51. const selection = this.editor.model.document.selection;
  52. const selectedCells = getSelectedTableCells( selection );
  53. if ( selectedCells.length == 0 ) {
  54. return null;
  55. }
  56. // This should never happen, but let's know if it ever happens.
  57. // @if CK_DEBUG // /* istanbul ignore next */
  58. // @if CK_DEBUG // if ( selectedCells.length != selection.rangeCount ) {
  59. // @if CK_DEBUG // console.warn( 'Mixed selection warning. The selection contains table cells and some other ranges.' );
  60. // @if CK_DEBUG // }
  61. return selectedCells;
  62. }
  63. /**
  64. * Returns the selected table fragment as a document fragment.
  65. *
  66. * @returns {module:engine/model/documentfragment~DocumentFragment|null}
  67. */
  68. getSelectionAsFragment() {
  69. const selectedCells = this.getSelectedTableCells();
  70. if ( !selectedCells ) {
  71. return null;
  72. }
  73. return this.editor.model.change( writer => {
  74. const documentFragment = writer.createDocumentFragment();
  75. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  76. const { first: firstColumn, last: lastColumn } = getColumnIndexes( selectedCells );
  77. const { first: firstRow, last: lastRow } = getRowIndexes( selectedCells );
  78. const sourceTable = findAncestor( 'table', selectedCells[ 0 ] );
  79. let adjustedLastRow = lastRow;
  80. let adjustedLastColumn = lastColumn;
  81. // If the selection is rectangular there could be a case of all cells in the last row/column spanned over
  82. // next row/column so the real lastRow/lastColumn should be updated.
  83. if ( isSelectionRectangular( selectedCells, tableUtils ) ) {
  84. const dimensions = {
  85. firstColumn,
  86. lastColumn,
  87. firstRow,
  88. lastRow
  89. };
  90. adjustedLastRow = adjustLastRowIndex( sourceTable, dimensions );
  91. adjustedLastColumn = adjustLastColumnIndex( sourceTable, dimensions );
  92. }
  93. const cropDimensions = {
  94. startRow: firstRow,
  95. startColumn: firstColumn,
  96. endRow: adjustedLastRow,
  97. endColumn: adjustedLastColumn
  98. };
  99. const table = cropTableToDimensions( sourceTable, cropDimensions, writer );
  100. writer.insert( table, documentFragment, 0 );
  101. return documentFragment;
  102. } );
  103. }
  104. /**
  105. * Sets the model selection based on given anchor and target cells (can be the same cell).
  106. * Takes care of setting the backward flag.
  107. *
  108. * const modelRoot = editor.model.document.getRoot();
  109. * const firstCell = modelRoot.getNodeByPath( [ 0, 0, 0 ] );
  110. * const lastCell = modelRoot.getNodeByPath( [ 0, 0, 1 ] );
  111. *
  112. * const tableSelection = editor.plugins.get( 'TableSelection' );
  113. * tableSelection.setCellSelection( firstCell, lastCell );
  114. *
  115. * @param {module:engine/model/element~Element} anchorCell
  116. * @param {module:engine/model/element~Element} targetCell
  117. */
  118. setCellSelection( anchorCell, targetCell ) {
  119. const cellsToSelect = this._getCellsToSelect( anchorCell, targetCell );
  120. this.editor.model.change( writer => {
  121. writer.setSelection(
  122. cellsToSelect.cells.map( cell => writer.createRangeOn( cell ) ),
  123. { backward: cellsToSelect.backward }
  124. );
  125. } );
  126. }
  127. /**
  128. * Returns the focus cell from the current selection.
  129. *
  130. * @returns {module:engine/model/element~Element}
  131. */
  132. getFocusCell() {
  133. const selection = this.editor.model.document.selection;
  134. const focusCellRange = [ ...selection.getRanges() ].pop();
  135. const element = focusCellRange.getContainedElement();
  136. if ( element && element.is( 'tableCell' ) ) {
  137. return element;
  138. }
  139. return null;
  140. }
  141. /**
  142. * Returns the anchor cell from the current selection.
  143. *
  144. * @returns {module:engine/model/element~Element} anchorCell
  145. */
  146. getAnchorCell() {
  147. const selection = this.editor.model.document.selection;
  148. const anchorCellRange = first( selection.getRanges() );
  149. const element = anchorCellRange.getContainedElement();
  150. if ( element && element.is( 'tableCell' ) ) {
  151. return element;
  152. }
  153. return null;
  154. }
  155. /**
  156. * Defines a selection converter which marks the selected cells with a specific class.
  157. *
  158. * The real DOM selection is put in the last cell. Since the order of ranges is dependent on whether the
  159. * selection is backward or not, the last cell will usually be close to the "focus" end of the selection
  160. * (a selection has anchor and focus).
  161. *
  162. * The real DOM selection is then hidden with CSS.
  163. *
  164. * @private
  165. */
  166. _defineSelectionConverter() {
  167. const editor = this.editor;
  168. const highlighted = new Set();
  169. editor.conversion.for( 'editingDowncast' ).add( dispatcher => dispatcher.on( 'selection', ( evt, data, conversionApi ) => {
  170. const viewWriter = conversionApi.writer;
  171. clearHighlightedTableCells( viewWriter );
  172. const selectedCells = this.getSelectedTableCells();
  173. if ( !selectedCells ) {
  174. return;
  175. }
  176. for ( const tableCell of selectedCells ) {
  177. const viewElement = conversionApi.mapper.toViewElement( tableCell );
  178. viewWriter.addClass( 'ck-editor__editable_selected', viewElement );
  179. highlighted.add( viewElement );
  180. }
  181. const lastViewCell = conversionApi.mapper.toViewElement( selectedCells[ selectedCells.length - 1 ] );
  182. viewWriter.setSelection( lastViewCell, 0 );
  183. }, { priority: 'lowest' } ) );
  184. function clearHighlightedTableCells( writer ) {
  185. for ( const previouslyHighlighted of highlighted ) {
  186. writer.removeClass( 'ck-editor__editable_selected', previouslyHighlighted );
  187. }
  188. highlighted.clear();
  189. }
  190. }
  191. /**
  192. * Creates a listener that reacts to changes in {@link #isEnabled} and, if the plugin was disabled,
  193. * it collapses the multi-cell selection to a regular selection placed inside a table cell.
  194. *
  195. * This listener helps features that disable the table selection plugin bring the selection
  196. * to a clear state they can work with (for instance, because they don't support multiple cell selection).
  197. */
  198. _enablePluginDisabling() {
  199. const editor = this.editor;
  200. this.on( 'change:isEnabled', () => {
  201. if ( !this.isEnabled ) {
  202. const selectedCells = this.getSelectedTableCells();
  203. if ( !selectedCells ) {
  204. return;
  205. }
  206. editor.model.change( writer => {
  207. const position = writer.createPositionAt( selectedCells[ 0 ], 0 );
  208. const range = editor.model.schema.getNearestSelectionRange( position );
  209. writer.setSelection( range );
  210. } );
  211. }
  212. } );
  213. }
  214. /**
  215. * Overrides the default `model.deleteContent()` behavior over a selected table fragment.
  216. *
  217. * @private
  218. * @param {module:utils/eventinfo~EventInfo} event
  219. * @param {Array.<*>} args Delete content method arguments.
  220. */
  221. _handleDeleteContent( event, args ) {
  222. const [ selection, options ] = args;
  223. const model = this.editor.model;
  224. const isBackward = !options || options.direction == 'backward';
  225. const selectedTableCells = getSelectedTableCells( selection );
  226. if ( !selectedTableCells.length ) {
  227. return;
  228. }
  229. event.stop();
  230. model.change( writer => {
  231. const tableCellToSelect = selectedTableCells[ isBackward ? selectedTableCells.length - 1 : 0 ];
  232. model.change( writer => {
  233. for ( const tableCell of selectedTableCells ) {
  234. model.deleteContent( writer.createSelection( tableCell, 'in' ) );
  235. }
  236. } );
  237. const rangeToSelect = model.schema.getNearestSelectionRange( writer.createPositionAt( tableCellToSelect, 0 ) );
  238. // Note: we ignore the case where rangeToSelect may be null because deleteContent() will always (unless someone broke it)
  239. // create an empty paragraph to accommodate the selection.
  240. if ( selection.is( 'documentSelection' ) ) {
  241. writer.setSelection( rangeToSelect );
  242. } else {
  243. selection.setTo( rangeToSelect );
  244. }
  245. } );
  246. }
  247. /**
  248. * Returns an array of table cells that should be selected based on the
  249. * given anchor cell and target (focus) cell.
  250. *
  251. * The cells are returned in a reverse direction if the selection is backward.
  252. *
  253. * @private
  254. * @param {module:engine/model/element~Element} anchorCell
  255. * @param {module:engine/model/element~Element} targetCell
  256. * @returns {Array.<module:engine/model/element~Element>}
  257. */
  258. _getCellsToSelect( anchorCell, targetCell ) {
  259. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  260. const startLocation = tableUtils.getCellLocation( anchorCell );
  261. const endLocation = tableUtils.getCellLocation( targetCell );
  262. const startRow = Math.min( startLocation.row, endLocation.row );
  263. const endRow = Math.max( startLocation.row, endLocation.row );
  264. const startColumn = Math.min( startLocation.column, endLocation.column );
  265. const endColumn = Math.max( startLocation.column, endLocation.column );
  266. // 2-dimensional array of the selected cells to ease flipping the order of cells for backward selections.
  267. const selectionMap = new Array( endRow - startRow + 1 ).fill( null ).map( () => [] );
  268. const walkerOptions = {
  269. startRow,
  270. endRow,
  271. startColumn,
  272. endColumn
  273. };
  274. for ( const { row, cell } of new TableWalker( findAncestor( 'table', anchorCell ), walkerOptions ) ) {
  275. selectionMap[ row - startRow ].push( cell );
  276. }
  277. const flipVertically = endLocation.row < startLocation.row;
  278. const flipHorizontally = endLocation.column < startLocation.column;
  279. if ( flipVertically ) {
  280. selectionMap.reverse();
  281. }
  282. if ( flipHorizontally ) {
  283. selectionMap.forEach( row => row.reverse() );
  284. }
  285. return {
  286. cells: selectionMap.flat(),
  287. backward: flipVertically || flipHorizontally
  288. };
  289. }
  290. }