tableselection.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 TableWalker from './tablewalker';
  10. import TableUtils from './tableutils';
  11. import MouseEventsObserver from './tableselection/mouseeventsobserver';
  12. import { getSelectedTableCells } from './utils';
  13. import { findAncestor } from './commands/utils';
  14. import cropTable from './tableselection/croptable';
  15. import '../theme/tableselection.css';
  16. /**
  17. * TODO
  18. *
  19. * @extends module:core/plugin~Plugin
  20. */
  21. export default class TableSelection extends Plugin {
  22. /**
  23. * @inheritDoc
  24. */
  25. static get pluginName() {
  26. return 'TableSelection';
  27. }
  28. /**
  29. * @inheritDoc
  30. */
  31. static get requires() {
  32. return [ TableUtils ];
  33. }
  34. /**
  35. * @inheritDoc
  36. */
  37. init() {
  38. const editor = this.editor;
  39. const model = editor.model;
  40. this.listenTo( model, 'deleteContent', ( evt, args ) => this._handleDeleteContent( evt, args ), { priority: 'high' } );
  41. // Currently the MouseObserver only handles `mouseup` events.
  42. // TODO move to the engine?
  43. editor.editing.view.addObserver( MouseEventsObserver );
  44. this._defineSelectionConverter();
  45. this._enableShiftClickSelection();
  46. this._enableMouseDragSelection();
  47. }
  48. /**
  49. * Returns currently selected table cells or `null` if not a table cells selection.
  50. *
  51. * @returns {Array.<module:engine/model/element~Element>|null}
  52. */
  53. getSelectedTableCells() {
  54. const selection = this.editor.model.document.selection;
  55. const selectedCells = getSelectedTableCells( selection );
  56. if ( selectedCells.length == 0 ) {
  57. return null;
  58. }
  59. // This should never happen, but let's know if it ever happens.
  60. // @if CK_DEBUG // if ( selectedCells.length != selection.rangeCount ) {
  61. // @if CK_DEBUG // console.warn( 'Mixed selection warning. The selection contains table cells and some other ranges.' );
  62. // @if CK_DEBUG // }
  63. return selectedCells;
  64. }
  65. /**
  66. * Returns a selected table fragment as a document fragment.
  67. *
  68. * @returns {module:engine/model/documentfragment~DocumentFragment|null}
  69. */
  70. getSelectionAsFragment() {
  71. const selectedCells = this.getSelectedTableCells();
  72. if ( !selectedCells ) {
  73. return null;
  74. }
  75. return this.editor.model.change( writer => {
  76. const documentFragment = writer.createDocumentFragment();
  77. const table = cropTable( selectedCells, this.editor.plugins.get( 'TableUtils' ), writer );
  78. writer.insert( table, documentFragment, 0 );
  79. return documentFragment;
  80. } );
  81. }
  82. /**
  83. * Defines a selection converter which marks selected cells with a specific class.
  84. *
  85. * The real DOM selection is put in the last cell. Since the order of ranges is dependent on whether the
  86. * selection is backward or not, the last cell with usually be close to the "focus" end of the selection
  87. * (a selection has anchor and focus).
  88. *
  89. * The real DOM selection is then hidden with CSS.
  90. *
  91. * @private
  92. */
  93. _defineSelectionConverter() {
  94. const editor = this.editor;
  95. const highlighted = new Set();
  96. editor.conversion.for( 'editingDowncast' ).add( dispatcher => dispatcher.on( 'selection', ( evt, data, conversionApi ) => {
  97. const viewWriter = conversionApi.writer;
  98. clearHighlightedTableCells( viewWriter );
  99. const selectedCells = this.getSelectedTableCells();
  100. if ( !selectedCells ) {
  101. return;
  102. }
  103. for ( const tableCell of selectedCells ) {
  104. const viewElement = conversionApi.mapper.toViewElement( tableCell );
  105. viewWriter.addClass( 'ck-editor__editable_selected', viewElement );
  106. highlighted.add( viewElement );
  107. }
  108. const lastViewCell = conversionApi.mapper.toViewElement( selectedCells[ selectedCells.length - 1 ] );
  109. viewWriter.setSelection( lastViewCell, 0 );
  110. }, { priority: 'lowest' } ) );
  111. function clearHighlightedTableCells( writer ) {
  112. for ( const previouslyHighlighted of highlighted ) {
  113. writer.removeClass( 'ck-editor__editable_selected', previouslyHighlighted );
  114. }
  115. highlighted.clear();
  116. }
  117. }
  118. /**
  119. * Enables making cells selection by Shift+click. Creates a selection from the cell which previously hold
  120. * the selection to the cell which was clicked (can be the same cell, in which case it selects a single cell).
  121. *
  122. * @private
  123. */
  124. _enableShiftClickSelection() {
  125. const editor = this.editor;
  126. let blockSelectionChange = false;
  127. this.listenTo( editor.editing.view.document, 'mousedown', ( evt, domEventData ) => {
  128. if ( !domEventData.domEvent.shiftKey ) {
  129. return;
  130. }
  131. const anchorCell = findAncestor( 'tableCell', editor.model.document.selection.anchor.parent );
  132. if ( !anchorCell ) {
  133. return;
  134. }
  135. const targetCell = this._getModelTableCellFromDomEvent( domEventData );
  136. if ( targetCell && haveSameTableParent( anchorCell, targetCell ) ) {
  137. blockSelectionChange = true;
  138. this._setCellSelection( anchorCell, targetCell );
  139. domEventData.preventDefault();
  140. }
  141. } );
  142. this.listenTo( editor.editing.view.document, 'mouseup', () => {
  143. blockSelectionChange = false;
  144. } );
  145. // We need to ignore a `selectionChange` event that is fired after we render our new table cells selection.
  146. // When downcasting table cells selection to the view, we put the view selection in the last selected cell
  147. // in a place that may not be natively a "correct" location. This is – we put it directly in the `<td>` element.
  148. // All browsers fire the native `selectionchange` event.
  149. // However, all browsers except Safari return the selection in the exact place where we put it
  150. // (even though it's visually normalized). Safari returns `<td><p>^foo` that makes our selection observer
  151. // fire our `selectionChange` event (because the view selection that we set in the first step differs from the DOM selection).
  152. // Since `selectionChange` is fired, we automatically update the model selection that moves it that paragraph.
  153. // This breaks our dear cells selection.
  154. //
  155. // Theoretically this issue concerns only Safari that is the only browser that do normalize the selection.
  156. // However, to avoid code branching and to have a good coverage for this event blocker, I enabled it for all browsers.
  157. //
  158. // Note: I'm keeping the `blockSelectionChange` state separately for shift+click and mouse drag (exact same logic)
  159. // so I don't have to try to analyze whether they don't overlap in some weird cases. Probably they don't.
  160. // But I have other things to do, like writing this comment.
  161. this.listenTo( editor.editing.view.document, 'selectionChange', evt => {
  162. if ( blockSelectionChange ) {
  163. // @if CK_DEBUG // console.log( 'Blocked selectionChange to avoid breaking table cells selection.' );
  164. evt.stop();
  165. }
  166. }, { priority: 'highest' } );
  167. }
  168. /**
  169. * Enables making cells selection by dragging.
  170. *
  171. * The selection is made only on mousemove. We start tracking the mouse on mousedown.
  172. * However, the cells selection is enabled only after the mouse cursor left the anchor cell.
  173. * Thanks to that normal text selection within one cell works just fine. However, you can still select
  174. * just one cell by leaving the anchor cell and moving back to it.
  175. *
  176. * @private
  177. */
  178. _enableMouseDragSelection() {
  179. const editor = this.editor;
  180. let anchorCell, targetCell;
  181. let beganCellSelection = false;
  182. let blockSelectionChange = false;
  183. this.listenTo( editor.editing.view.document, 'mousedown', ( evt, domEventData ) => {
  184. // Make sure to not conflict with the shift+click listener and any other possible handler.
  185. if ( domEventData.domEvent.shiftKey || domEventData.domEvent.ctrlKey || domEventData.domEvent.altKey ) {
  186. return;
  187. }
  188. anchorCell = this._getModelTableCellFromDomEvent( domEventData );
  189. } );
  190. this.listenTo( editor.editing.view.document, 'mousemove', ( evt, domEventData ) => {
  191. if ( !domEventData.domEvent.buttons ) {
  192. return;
  193. }
  194. if ( !anchorCell ) {
  195. return;
  196. }
  197. const newTargetCell = this._getModelTableCellFromDomEvent( domEventData );
  198. if ( newTargetCell && haveSameTableParent( anchorCell, newTargetCell ) ) {
  199. targetCell = newTargetCell;
  200. // Switch to the cell selection mode after the mouse cursor left the anchor cell.
  201. // Switch off only on mouseup (makes selecting a single cell possible).
  202. if ( !beganCellSelection && targetCell != anchorCell ) {
  203. beganCellSelection = true;
  204. }
  205. }
  206. // Yep, not making a cell selection yet. See method docs.
  207. if ( !beganCellSelection ) {
  208. return;
  209. }
  210. blockSelectionChange = true;
  211. this._setCellSelection( anchorCell, targetCell );
  212. domEventData.preventDefault();
  213. } );
  214. this.listenTo( editor.editing.view.document, 'mouseup', () => {
  215. beganCellSelection = false;
  216. blockSelectionChange = false;
  217. anchorCell = null;
  218. targetCell = null;
  219. } );
  220. // See the explanation in `_enableShiftClickSelection()`.
  221. this.listenTo( editor.editing.view.document, 'selectionChange', evt => {
  222. if ( blockSelectionChange ) {
  223. // @if CK_DEBUG // console.log( 'Blocked selectionChange to avoid breaking table cells selection.' );
  224. evt.stop();
  225. }
  226. }, { priority: 'highest' } );
  227. }
  228. /**
  229. * It overrides the default `model.deleteContent()` behavior over a selected table fragment.
  230. *
  231. * @private
  232. * @param {module:utils/eventinfo~EventInfo} event
  233. * @param {Array.<*>} args Delete content method arguments.
  234. */
  235. _handleDeleteContent( event, args ) {
  236. const [ selection, options ] = args;
  237. const model = this.editor.model;
  238. const isBackward = !options || options.direction == 'backward';
  239. const selectedTableCells = getSelectedTableCells( selection );
  240. if ( !selectedTableCells.length ) {
  241. return;
  242. }
  243. event.stop();
  244. model.change( writer => {
  245. const tableCellToSelect = selectedTableCells[ isBackward ? selectedTableCells.length - 1 : 0 ];
  246. model.change( writer => {
  247. for ( const tableCell of selectedTableCells ) {
  248. model.deleteContent( writer.createSelection( tableCell, 'in' ) );
  249. }
  250. } );
  251. // The insertContent() helper passes the actual DocumentSelection,
  252. // while the deleteContent() helper always operates on the abstract clones.
  253. if ( selection.is( 'documentSelection' ) ) {
  254. writer.setSelection( tableCellToSelect, 'in' );
  255. } else {
  256. selection.setTo( tableCellToSelect, 'in' );
  257. }
  258. } );
  259. }
  260. /**
  261. * Sets the model selection based on given anchor and target cells (can be the same cell).
  262. * Takes care of setting backward flag.
  263. *
  264. * @protected
  265. * @param {module:engine/model/element~Element} anchorCell
  266. * @param {module:engine/model/element~Element} targetCell
  267. */
  268. _setCellSelection( anchorCell, targetCell ) {
  269. const cellsToSelect = this._getCellsToSelect( anchorCell, targetCell );
  270. this.editor.model.change( writer => {
  271. writer.setSelection(
  272. cellsToSelect.cells.map( cell => writer.createRangeOn( cell ) ),
  273. { backward: cellsToSelect.backward }
  274. );
  275. } );
  276. }
  277. /**
  278. * Returns the model table cell element based on the target element of the passed DOM event.
  279. *
  280. * @private
  281. * @param {module:engine/view/observer/domeventdata~DomEventData} domEventData
  282. * @returns {module:engine/model/element~Element|undefined} Returns the table cell or `undefined`.
  283. */
  284. _getModelTableCellFromDomEvent( domEventData ) {
  285. // Note: Work with positions (not element mapping) because the target element can be an attribute or other non-mapped element.
  286. const viewTargetElement = domEventData.target;
  287. const viewPosition = this.editor.editing.view.createPositionAt( viewTargetElement, 0 );
  288. const modelPosition = this.editor.editing.mapper.toModelPosition( viewPosition );
  289. const modelElement = modelPosition.parent;
  290. if ( !modelElement ) {
  291. return;
  292. }
  293. if ( modelElement.is( 'tableCell' ) ) {
  294. return modelElement;
  295. }
  296. return findAncestor( 'tableCell', modelElement );
  297. }
  298. /**
  299. * Returns an array of table cells that should be selected based on the
  300. * given anchor cell and target (focus) cell.
  301. *
  302. * The cells are returned in a reverse direction if the selection is backward.
  303. *
  304. * @private
  305. * @param {module:engine/model/element~Element} anchorCell
  306. * @param {module:engine/model/element~Element} targetCell
  307. * @returns {Array.<module:engine/model/element~Element>}
  308. */
  309. _getCellsToSelect( anchorCell, targetCell ) {
  310. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  311. const startLocation = tableUtils.getCellLocation( anchorCell );
  312. const endLocation = tableUtils.getCellLocation( targetCell );
  313. const startRow = Math.min( startLocation.row, endLocation.row );
  314. const endRow = Math.max( startLocation.row, endLocation.row );
  315. const startColumn = Math.min( startLocation.column, endLocation.column );
  316. const endColumn = Math.max( startLocation.column, endLocation.column );
  317. const cells = [];
  318. for ( const cellInfo of new TableWalker( findAncestor( 'table', anchorCell ), { startRow, endRow } ) ) {
  319. if ( cellInfo.column >= startColumn && cellInfo.column <= endColumn ) {
  320. cells.push( cellInfo.cell );
  321. }
  322. }
  323. // A selection started in the bottom right corner and finished in the upper left corner
  324. // should have it ranges returned in the reverse order.
  325. // However, this is only half of the story because the selection could be made to the left (then the left cell is a focus)
  326. // or to the right (then the right cell is a focus), while being a forward selection in both cases
  327. // (because it was made from top to bottom). This isn't handled.
  328. // This method would need to be smarter, but the ROI is microscopic, so I skip this.
  329. if ( checkIsBackward( startLocation, endLocation ) ) {
  330. return { cells: cells.reverse(), backward: true };
  331. }
  332. return { cells, backward: false };
  333. }
  334. }
  335. // Naively check whether the selection should be backward or not. See the longer explanation where this function is used.
  336. function checkIsBackward( startLocation, endLocation ) {
  337. if ( startLocation.row > endLocation.row ) {
  338. return true;
  339. }
  340. if ( startLocation.row == endLocation.row && startLocation.column > endLocation.column ) {
  341. return true;
  342. }
  343. return false;
  344. }
  345. function haveSameTableParent( cellA, cellB ) {
  346. return cellA.parent.parent == cellB.parent.parent;
  347. }