tableselection.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 } from './utils/structure';
  14. import { getColumnIndexes, getRowIndexes, getSelectedTableCells } 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 { first: startColumn, last: endColumn } = getColumnIndexes( selectedCells );
  76. const { first: startRow, last: endRow } = getRowIndexes( selectedCells );
  77. const sourceTable = findAncestor( 'table', selectedCells[ 0 ] );
  78. const cropDimensions = {
  79. startRow,
  80. startColumn,
  81. endRow,
  82. endColumn
  83. };
  84. const table = cropTableToDimensions( sourceTable, cropDimensions, writer );
  85. writer.insert( table, documentFragment, 0 );
  86. return documentFragment;
  87. } );
  88. }
  89. /**
  90. * Sets the model selection based on given anchor and target cells (can be the same cell).
  91. * Takes care of setting the backward flag.
  92. *
  93. * const modelRoot = editor.model.document.getRoot();
  94. * const firstCell = modelRoot.getNodeByPath( [ 0, 0, 0 ] );
  95. * const lastCell = modelRoot.getNodeByPath( [ 0, 0, 1 ] );
  96. *
  97. * const tableSelection = editor.plugins.get( 'TableSelection' );
  98. * tableSelection.setCellSelection( firstCell, lastCell );
  99. *
  100. * @param {module:engine/model/element~Element} anchorCell
  101. * @param {module:engine/model/element~Element} targetCell
  102. */
  103. setCellSelection( anchorCell, targetCell ) {
  104. const cellsToSelect = this._getCellsToSelect( anchorCell, targetCell );
  105. this.editor.model.change( writer => {
  106. writer.setSelection(
  107. cellsToSelect.cells.map( cell => writer.createRangeOn( cell ) ),
  108. { backward: cellsToSelect.backward }
  109. );
  110. } );
  111. }
  112. /**
  113. * Returns the focus cell from the current selection.
  114. *
  115. * @returns {module:engine/model/element~Element}
  116. */
  117. getFocusCell() {
  118. const selection = this.editor.model.document.selection;
  119. const focusCellRange = [ ...selection.getRanges() ].pop();
  120. const element = focusCellRange.getContainedElement();
  121. if ( element && element.is( 'tableCell' ) ) {
  122. return element;
  123. }
  124. return null;
  125. }
  126. /**
  127. * Returns the anchor cell from the current selection.
  128. *
  129. * @returns {module:engine/model/element~Element} anchorCell
  130. */
  131. getAnchorCell() {
  132. const selection = this.editor.model.document.selection;
  133. const anchorCellRange = first( selection.getRanges() );
  134. const element = anchorCellRange.getContainedElement();
  135. if ( element && element.is( 'tableCell' ) ) {
  136. return element;
  137. }
  138. return null;
  139. }
  140. /**
  141. * Defines a selection converter which marks the selected cells with a specific class.
  142. *
  143. * The real DOM selection is put in the last cell. Since the order of ranges is dependent on whether the
  144. * selection is backward or not, the last cell will usually be close to the "focus" end of the selection
  145. * (a selection has anchor and focus).
  146. *
  147. * The real DOM selection is then hidden with CSS.
  148. *
  149. * @private
  150. */
  151. _defineSelectionConverter() {
  152. const editor = this.editor;
  153. const highlighted = new Set();
  154. editor.conversion.for( 'editingDowncast' ).add( dispatcher => dispatcher.on( 'selection', ( evt, data, conversionApi ) => {
  155. const viewWriter = conversionApi.writer;
  156. clearHighlightedTableCells( viewWriter );
  157. const selectedCells = this.getSelectedTableCells();
  158. if ( !selectedCells ) {
  159. return;
  160. }
  161. for ( const tableCell of selectedCells ) {
  162. const viewElement = conversionApi.mapper.toViewElement( tableCell );
  163. viewWriter.addClass( 'ck-editor__editable_selected', viewElement );
  164. highlighted.add( viewElement );
  165. }
  166. const lastViewCell = conversionApi.mapper.toViewElement( selectedCells[ selectedCells.length - 1 ] );
  167. viewWriter.setSelection( lastViewCell, 0 );
  168. }, { priority: 'lowest' } ) );
  169. function clearHighlightedTableCells( writer ) {
  170. for ( const previouslyHighlighted of highlighted ) {
  171. writer.removeClass( 'ck-editor__editable_selected', previouslyHighlighted );
  172. }
  173. highlighted.clear();
  174. }
  175. }
  176. /**
  177. * Creates a listener that reacts to changes in {@link #isEnabled} and, if the plugin was disabled,
  178. * it collapses the multi-cell selection to a regular selection placed inside a table cell.
  179. *
  180. * This listener helps features that disable the table selection plugin bring the selection
  181. * to a clear state they can work with (for instance, because they don't support multiple cell selection).
  182. */
  183. _enablePluginDisabling() {
  184. const editor = this.editor;
  185. this.on( 'change:isEnabled', () => {
  186. if ( !this.isEnabled ) {
  187. const selectedCells = this.getSelectedTableCells();
  188. if ( !selectedCells ) {
  189. return;
  190. }
  191. editor.model.change( writer => {
  192. const position = writer.createPositionAt( selectedCells[ 0 ], 0 );
  193. const range = editor.model.schema.getNearestSelectionRange( position );
  194. writer.setSelection( range );
  195. } );
  196. }
  197. } );
  198. }
  199. /**
  200. * Overrides the default `model.deleteContent()` behavior over a selected table fragment.
  201. *
  202. * @private
  203. * @param {module:utils/eventinfo~EventInfo} event
  204. * @param {Array.<*>} args Delete content method arguments.
  205. */
  206. _handleDeleteContent( event, args ) {
  207. const [ selection, options ] = args;
  208. const model = this.editor.model;
  209. const isBackward = !options || options.direction == 'backward';
  210. const selectedTableCells = getSelectedTableCells( selection );
  211. if ( !selectedTableCells.length ) {
  212. return;
  213. }
  214. event.stop();
  215. model.change( writer => {
  216. const tableCellToSelect = selectedTableCells[ isBackward ? selectedTableCells.length - 1 : 0 ];
  217. model.change( writer => {
  218. for ( const tableCell of selectedTableCells ) {
  219. model.deleteContent( writer.createSelection( tableCell, 'in' ) );
  220. }
  221. } );
  222. const rangeToSelect = model.schema.getNearestSelectionRange( writer.createPositionAt( tableCellToSelect, 0 ) );
  223. // Note: we ignore the case where rangeToSelect may be null because deleteContent() will always (unless someone broke it)
  224. // create an empty paragraph to accommodate the selection.
  225. if ( selection.is( 'documentSelection' ) ) {
  226. writer.setSelection( rangeToSelect );
  227. } else {
  228. selection.setTo( rangeToSelect );
  229. }
  230. } );
  231. }
  232. /**
  233. * Returns an array of table cells that should be selected based on the
  234. * given anchor cell and target (focus) cell.
  235. *
  236. * The cells are returned in a reverse direction if the selection is backward.
  237. *
  238. * @private
  239. * @param {module:engine/model/element~Element} anchorCell
  240. * @param {module:engine/model/element~Element} targetCell
  241. * @returns {Array.<module:engine/model/element~Element>}
  242. */
  243. _getCellsToSelect( anchorCell, targetCell ) {
  244. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  245. const startLocation = tableUtils.getCellLocation( anchorCell );
  246. const endLocation = tableUtils.getCellLocation( targetCell );
  247. const startRow = Math.min( startLocation.row, endLocation.row );
  248. const endRow = Math.max( startLocation.row, endLocation.row );
  249. const startColumn = Math.min( startLocation.column, endLocation.column );
  250. const endColumn = Math.max( startLocation.column, endLocation.column );
  251. // 2-dimensional array of the selected cells to ease flipping the order of cells for backward selections.
  252. const selectionMap = new Array( endRow - startRow + 1 ).fill( null ).map( () => [] );
  253. const walkerOptions = {
  254. startRow,
  255. endRow,
  256. startColumn,
  257. endColumn
  258. };
  259. for ( const { row, cell } of new TableWalker( findAncestor( 'table', anchorCell ), walkerOptions ) ) {
  260. selectionMap[ row - startRow ].push( cell );
  261. }
  262. const flipVertically = endLocation.row < startLocation.row;
  263. const flipHorizontally = endLocation.column < startLocation.column;
  264. if ( flipVertically ) {
  265. selectionMap.reverse();
  266. }
  267. if ( flipHorizontally ) {
  268. selectionMap.forEach( row => row.reverse() );
  269. }
  270. return {
  271. cells: selectionMap.flat(),
  272. backward: flipVertically || flipHorizontally
  273. };
  274. }
  275. }