tablekeyboard.js 11 KB

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