tablekeyboard.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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/tablekeyboard
  7. */
  8. import TableSelection from './tableselection';
  9. import TableWalker from './tablewalker';
  10. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  11. import priorities from '@ckeditor/ckeditor5-utils/src/priorities';
  12. import {
  13. isArrowKeyCode,
  14. getLocalizedArrowKeyCodeDirection
  15. } from '@ckeditor/ckeditor5-utils/src/keyboard';
  16. import { getSelectedTableCells, getTableCellsContainingSelection } from './utils/selection';
  17. /**
  18. * This plugin enables keyboard navigation for tables.
  19. * It is loaded automatically by the {@link module:table/table~Table} plugin.
  20. *
  21. * @extends module:core/plugin~Plugin
  22. */
  23. export default class TableKeyboard extends Plugin {
  24. /**
  25. * @inheritDoc
  26. */
  27. static get pluginName() {
  28. return 'TableKeyboard';
  29. }
  30. /**
  31. * @inheritDoc
  32. */
  33. static get requires() {
  34. return [ TableSelection ];
  35. }
  36. /**
  37. * @inheritDoc
  38. */
  39. init() {
  40. const view = this.editor.editing.view;
  41. const viewDocument = view.document;
  42. // Handle Tab key navigation.
  43. this.editor.keystrokes.set( 'Tab', ( ...args ) => this._handleTabOnSelectedTable( ...args ), { priority: 'low' } );
  44. this.editor.keystrokes.set( 'Tab', this._getTabHandler( true ), { priority: 'low' } );
  45. this.editor.keystrokes.set( 'Shift+Tab', this._getTabHandler( false ), { priority: 'low' } );
  46. // Note: This listener has the "high-10" priority because it should allow the Widget plugin to handle the default
  47. // behavior first ("high") but it should not be "prevent–defaulted" by the Widget plugin ("high-20") because of
  48. // the fake selection retention on the fully selected widget.
  49. this.listenTo( viewDocument, 'keydown', ( ...args ) => this._onKeydown( ...args ), { priority: priorities.get( 'high' ) - 10 } );
  50. }
  51. /**
  52. * Handles {@link module:engine/view/document~Document#event:keydown keydown} events for the <kbd>Tab</kbd> key executed
  53. * when the table widget is selected.
  54. *
  55. * @private
  56. * @param {module:engine/view/observer/keyobserver~KeyEventData} data Key event data.
  57. * @param {Function} cancel The stop/stopPropagation/preventDefault function.
  58. */
  59. _handleTabOnSelectedTable( data, cancel ) {
  60. const editor = this.editor;
  61. const selection = editor.model.document.selection;
  62. const selectedElement = selection.getSelectedElement();
  63. if ( !selectedElement || !selectedElement.is( 'element', 'table' ) ) {
  64. return;
  65. }
  66. cancel();
  67. editor.model.change( writer => {
  68. writer.setSelection( writer.createRangeIn( selectedElement.getChild( 0 ).getChild( 0 ) ) );
  69. } );
  70. }
  71. /**
  72. * Returns a handler for {@link module:engine/view/document~Document#event:keydown keydown} events for the <kbd>Tab</kbd> key executed
  73. * inside table cells.
  74. *
  75. * @private
  76. * @param {Boolean} isForward Whether this handler will move the selection to the next or the previous cell.
  77. */
  78. _getTabHandler( isForward ) {
  79. const editor = this.editor;
  80. return ( domEventData, cancel ) => {
  81. const selection = editor.model.document.selection;
  82. let tableCell = getTableCellsContainingSelection( selection )[ 0 ];
  83. if ( !tableCell ) {
  84. tableCell = this.editor.plugins.get( 'TableSelection' ).getFocusCell();
  85. }
  86. if ( !tableCell ) {
  87. return;
  88. }
  89. cancel();
  90. const tableRow = tableCell.parent;
  91. const table = tableRow.parent;
  92. const currentRowIndex = table.getChildIndex( tableRow );
  93. const currentCellIndex = tableRow.getChildIndex( tableCell );
  94. const isFirstCellInRow = currentCellIndex === 0;
  95. if ( !isForward && isFirstCellInRow && currentRowIndex === 0 ) {
  96. // Set the selection over the whole table if the selection was in the first table cell.
  97. editor.model.change( writer => {
  98. writer.setSelection( writer.createRangeOn( table ) );
  99. } );
  100. return;
  101. }
  102. const isLastCellInRow = currentCellIndex === tableRow.childCount - 1;
  103. const isLastRow = currentRowIndex === table.childCount - 1;
  104. if ( isForward && isLastRow && isLastCellInRow ) {
  105. editor.execute( 'insertTableRowBelow' );
  106. // Check if the command actually added a row. If `insertTableRowBelow` execution didn't add a row (because it was disabled
  107. // or it got overwritten) set the selection over the whole table to mirror the first cell case.
  108. if ( currentRowIndex === table.childCount - 1 ) {
  109. editor.model.change( writer => {
  110. writer.setSelection( writer.createRangeOn( table ) );
  111. } );
  112. return;
  113. }
  114. }
  115. let cellToFocus;
  116. // Move to the first cell in the next row.
  117. if ( isForward && isLastCellInRow ) {
  118. const nextRow = table.getChild( currentRowIndex + 1 );
  119. cellToFocus = nextRow.getChild( 0 );
  120. }
  121. // Move to the last cell in the previous row.
  122. else if ( !isForward && isFirstCellInRow ) {
  123. const previousRow = table.getChild( currentRowIndex - 1 );
  124. cellToFocus = previousRow.getChild( previousRow.childCount - 1 );
  125. }
  126. // Move to the next/previous cell.
  127. else {
  128. cellToFocus = tableRow.getChild( currentCellIndex + ( isForward ? 1 : -1 ) );
  129. }
  130. editor.model.change( writer => {
  131. writer.setSelection( writer.createRangeIn( cellToFocus ) );
  132. } );
  133. };
  134. }
  135. /**
  136. * Handles {@link module:engine/view/document~Document#event:keydown keydown} events.
  137. *
  138. * @private
  139. * @param {module:utils/eventinfo~EventInfo} eventInfo
  140. * @param {module:engine/view/observer/domeventdata~DomEventData} domEventData
  141. */
  142. _onKeydown( eventInfo, domEventData ) {
  143. const editor = this.editor;
  144. const keyCode = domEventData.keyCode;
  145. if ( !isArrowKeyCode( keyCode ) ) {
  146. return;
  147. }
  148. const direction = getLocalizedArrowKeyCodeDirection( keyCode, editor.locale.contentLanguageDirection );
  149. const wasHandled = this._handleArrowKeys( direction, domEventData.shiftKey );
  150. if ( wasHandled ) {
  151. domEventData.preventDefault();
  152. domEventData.stopPropagation();
  153. eventInfo.stop();
  154. }
  155. }
  156. /**
  157. * Handles arrow keys to move the selection around the table.
  158. *
  159. * @private
  160. * @param {'left'|'up'|'right'|'down'} direction The direction of the arrow key.
  161. * @param {Boolean} expandSelection If the current selection should be expanded.
  162. * @returns {Boolean} Returns `true` if key was handled.
  163. */
  164. _handleArrowKeys( direction, expandSelection ) {
  165. const model = this.editor.model;
  166. const selection = model.document.selection;
  167. const isForward = [ 'right', 'down' ].includes( direction );
  168. // In case one or more table cells are selected (from outside),
  169. // move the selection to a cell adjacent to the selected table fragment.
  170. const selectedCells = getSelectedTableCells( selection );
  171. if ( selectedCells.length ) {
  172. let focusCell;
  173. if ( expandSelection ) {
  174. focusCell = this.editor.plugins.get( 'TableSelection' ).getFocusCell();
  175. } else {
  176. focusCell = isForward ? selectedCells[ selectedCells.length - 1 ] : selectedCells[ 0 ];
  177. }
  178. this._navigateFromCellInDirection( focusCell, direction, expandSelection );
  179. return true;
  180. }
  181. // Abort if we're not in a table cell.
  182. const tableCell = selection.focus.findAncestor( 'tableCell' );
  183. if ( !tableCell ) {
  184. return false;
  185. }
  186. // Navigation is in the opposite direction than the selection direction so this is shrinking of the selection.
  187. // Selection for sure will not approach cell edge.
  188. if ( expandSelection && !selection.isCollapsed && selection.isBackward == isForward ) {
  189. return false;
  190. }
  191. // Let's check if the selection is at the beginning/end of the cell.
  192. if ( this._isSelectionAtCellEdge( selection, tableCell, isForward ) ) {
  193. this._navigateFromCellInDirection( tableCell, direction, expandSelection );
  194. return true;
  195. }
  196. return false;
  197. }
  198. /**
  199. * Returns `true` if the selection is at the boundary of a table cell according to the navigation direction.
  200. *
  201. * @private
  202. * @param {module:engine/model/selection~Selection} selection The current selection.
  203. * @param {module:engine/model/element~Element} tableCell The current table cell element.
  204. * @param {Boolean} isForward The expected navigation direction.
  205. * @returns {Boolean}
  206. */
  207. _isSelectionAtCellEdge( selection, tableCell, isForward ) {
  208. const model = this.editor.model;
  209. const schema = this.editor.model.schema;
  210. const focus = isForward ? selection.getLastPosition() : selection.getFirstPosition();
  211. // If the current limit element is not table cell we are for sure not at the cell edge.
  212. // Also `modifySelection` will not let us out of it.
  213. if ( !schema.getLimitElement( focus ).is( 'element', 'tableCell' ) ) {
  214. const boundaryPosition = model.createPositionAt( tableCell, isForward ? 'end' : 0 );
  215. return boundaryPosition.isTouching( focus );
  216. }
  217. const probe = model.createSelection( focus );
  218. model.modifySelection( probe, { direction: isForward ? 'forward' : 'backward' } );
  219. // If there was no change in the focus position, then it's not possible to move the selection there.
  220. return focus.isEqual( probe.focus );
  221. }
  222. /**
  223. * Moves the selection from the given table cell in the specified direction.
  224. *
  225. * @protected
  226. * @param {module:engine/model/element~Element} focusCell The table cell that is current multi-cell selection focus.
  227. * @param {'left'|'up'|'right'|'down'} direction Direction in which selection should move.
  228. * @param {Boolean} [expandSelection=false] If the current selection should be expanded.
  229. */
  230. _navigateFromCellInDirection( focusCell, direction, expandSelection = false ) {
  231. const model = this.editor.model;
  232. const table = focusCell.findAncestor( 'table' );
  233. const tableMap = [ ...new TableWalker( table, { includeAllSlots: true } ) ];
  234. const { row: lastRow, column: lastColumn } = tableMap[ tableMap.length - 1 ];
  235. const currentCellInfo = tableMap.find( ( { cell } ) => cell == focusCell );
  236. let { row, column } = currentCellInfo;
  237. switch ( direction ) {
  238. case 'left':
  239. column--;
  240. break;
  241. case 'up':
  242. row--;
  243. break;
  244. case 'right':
  245. column += currentCellInfo.cellWidth;
  246. break;
  247. case 'down':
  248. row += currentCellInfo.cellHeight;
  249. break;
  250. }
  251. const isOutsideVertically = row < 0 || row > lastRow;
  252. const isBeforeFirstCell = column < 0 && row <= 0;
  253. const isAfterLastCell = column > lastColumn && row >= lastRow;
  254. // Note that if the table cell at the end of a row is row-spanned then isAfterLastCell will never be true.
  255. // However, we don't know if user was navigating on the last row or not, so let's stay in the table.
  256. if ( isOutsideVertically || isBeforeFirstCell || isAfterLastCell ) {
  257. model.change( writer => {
  258. writer.setSelection( writer.createRangeOn( table ) );
  259. } );
  260. return;
  261. }
  262. if ( column < 0 ) {
  263. column = expandSelection ? 0 : lastColumn;
  264. row--;
  265. } else if ( column > lastColumn ) {
  266. column = expandSelection ? lastColumn : 0;
  267. row++;
  268. }
  269. const cellToSelect = tableMap.find( cellInfo => cellInfo.row == row && cellInfo.column == column ).cell;
  270. const isForward = [ 'right', 'down' ].includes( direction );
  271. const tableSelection = this.editor.plugins.get( 'TableSelection' );
  272. if ( expandSelection && tableSelection.isEnabled ) {
  273. const anchorCell = tableSelection.getAnchorCell() || focusCell;
  274. tableSelection.setCellSelection( anchorCell, cellToSelect );
  275. } else {
  276. const positionToSelect = model.createPositionAt( cellToSelect, isForward ? 0 : 'end' );
  277. model.change( writer => {
  278. writer.setSelection( positionToSelect );
  279. } );
  280. }
  281. }
  282. }