8
0

tablekeyboard.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 Rect from '@ckeditor/ckeditor5-utils/src/dom/rect';
  12. import priorities from '@ckeditor/ckeditor5-utils/src/priorities';
  13. import {
  14. isArrowKeyCode,
  15. getLocalizedArrowKeyCodeDirection
  16. } from '@ckeditor/ckeditor5-utils/src/keyboard';
  17. import { getSelectedTableCells, getTableCellsContainingSelection } from './utils/selection';
  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 = selection.focus.findAncestor( 'tableCell' );
  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, isForward ) ) {
  183. this._navigateFromCellInDirection( tableCell, direction, expandSelection );
  184. return true;
  185. }
  186. // If there isn't any $text position between cell edge and selection then we shall move the selection to next cell.
  187. const textRange = this._findTextRangeFromSelection( cellRange, selection, isForward );
  188. if ( !textRange ) {
  189. this._navigateFromCellInDirection( tableCell, direction, expandSelection );
  190. return true;
  191. }
  192. // If the navigation is horizontal then we have no more custom cases.
  193. if ( [ 'left', 'right' ].includes( direction ) ) {
  194. return false;
  195. }
  196. // If the range is a single line then move the selection to the beginning/end of a cell content.
  197. //
  198. // We can't move the selection directly to the another cell because of dual position at the end/beginning
  199. // of wrapped line (it's at the same time at the end of one line and at the start of the next line).
  200. if ( this._isSingleLineRange( textRange, isForward ) ) {
  201. model.change( writer => {
  202. const newPosition = isForward ? cellRange.end : cellRange.start;
  203. if ( expandSelection ) {
  204. const newSelection = model.createSelection( selection.anchor );
  205. newSelection.setFocus( newPosition );
  206. writer.setSelection( newSelection );
  207. } else {
  208. writer.setSelection( newPosition );
  209. }
  210. } );
  211. return true;
  212. }
  213. }
  214. /**
  215. * Returns `true` if the selection is at the boundary of a table cell according to the navigation direction.
  216. *
  217. * @private
  218. * @param {module:engine/model/selection~Selection} selection The current selection.
  219. * @param {Boolean} isForward The expected navigation direction.
  220. * @returns {Boolean}
  221. */
  222. _isSelectionAtCellEdge( selection, isForward ) {
  223. const model = this.editor.model;
  224. const schema = this.editor.model.schema;
  225. const focus = isForward ? selection.getLastPosition() : selection.getFirstPosition();
  226. // If the current limit element is not table cell we are for sure not at the cell edge.
  227. // Also `modifySelection` will not let us out of it.
  228. if ( !schema.getLimitElement( focus ).is( 'tableCell' ) ) {
  229. return false;
  230. }
  231. const probe = model.createSelection( focus );
  232. model.modifySelection( probe, { direction: isForward ? 'forward' : 'backward' } );
  233. // If there was no change in the focus position, then it's not possible to move the selection there.
  234. return focus.isEqual( probe.focus );
  235. }
  236. /**
  237. * Truncates the range so that it spans from the last selection position
  238. * to the last allowed `$text` position (mirrored if `isForward` is false).
  239. *
  240. * Returns `null` if, according to the schema, the resulting range cannot contain a `$text` element.
  241. *
  242. * @private
  243. * @param {module:engine/model/range~Range} range The current table cell content range.
  244. * @param {module:engine/model/selection~Selection} selection The current selection.
  245. * @param {Boolean} isForward The expected navigation direction.
  246. * @returns {module:engine/model/range~Range|null}
  247. */
  248. _findTextRangeFromSelection( range, selection, isForward ) {
  249. const model = this.editor.model;
  250. if ( isForward ) {
  251. const position = selection.getLastPosition();
  252. const lastRangePosition = this._getNearestVisibleTextPosition( range, 'backward' );
  253. if ( lastRangePosition && position.isBefore( lastRangePosition ) ) {
  254. return model.createRange( position, lastRangePosition );
  255. }
  256. return null;
  257. } else {
  258. const position = selection.getFirstPosition();
  259. const firstRangePosition = this._getNearestVisibleTextPosition( range, 'forward' );
  260. if ( firstRangePosition && position.isAfter( firstRangePosition ) ) {
  261. return model.createRange( firstRangePosition, position );
  262. }
  263. return null;
  264. }
  265. }
  266. /**
  267. * Basing on the provided range, finds the first or last (depending on `direction`) position inside the range
  268. * that can contain `$text` (according to schema) and is visible in the view.
  269. *
  270. * @private
  271. * @param {module:engine/model/range~Range} range The range to find the position in.
  272. * @param {'forward'|'backward'} direction Search direction.
  273. * @returns {module:engine/model/position~Position} The nearest selection range.
  274. */
  275. _getNearestVisibleTextPosition( range, direction ) {
  276. const schema = this.editor.model.schema;
  277. const mapper = this.editor.editing.mapper;
  278. for ( const { nextPosition, item } of range.getWalker( { direction } ) ) {
  279. if ( schema.checkChild( nextPosition, '$text' ) ) {
  280. const viewElement = mapper.toViewElement( item );
  281. if ( viewElement && !viewElement.hasClass( 'ck-hidden' ) ) {
  282. return nextPosition;
  283. }
  284. }
  285. }
  286. }
  287. /**
  288. * Checks if the DOM range corresponding to the provided model range renders as a single line by analyzing DOMRects
  289. * (verifying if they visually wrap content to the next line).
  290. *
  291. * @private
  292. * @param {module:engine/model/range~Range} modelRange The current table cell content range.
  293. * @param {Boolean} isForward The expected navigation direction.
  294. * @returns {Boolean}
  295. */
  296. _isSingleLineRange( modelRange, isForward ) {
  297. const model = this.editor.model;
  298. const editing = this.editor.editing;
  299. const domConverter = editing.view.domConverter;
  300. // Wrapped lines contain exactly the same position at the end of current line
  301. // and at the beginning of next line. That position's client rect is at the end
  302. // of current line. In case of caret at first position of the last line that 'dual'
  303. // position would be detected as it's not the last line.
  304. if ( isForward ) {
  305. const probe = model.createSelection( modelRange.start );
  306. model.modifySelection( probe );
  307. // If the new position is at the end of the container then we can't use this position
  308. // because it would provide incorrect result for eg caption of image and selection
  309. // just before end of it. Also in this case there is no "dual" position.
  310. if ( !probe.focus.isAtEnd && !modelRange.start.isEqual( probe.focus ) ) {
  311. modelRange = model.createRange( probe.focus, modelRange.end );
  312. }
  313. }
  314. const viewRange = editing.mapper.toViewRange( modelRange );
  315. const domRange = domConverter.viewRangeToDom( viewRange );
  316. const rects = Rect.getDomRangeRects( domRange );
  317. let boundaryVerticalPosition;
  318. for ( const rect of rects ) {
  319. if ( boundaryVerticalPosition === undefined ) {
  320. boundaryVerticalPosition = Math.round( rect.bottom );
  321. continue;
  322. }
  323. // Let's check if this rect is in new line.
  324. if ( Math.round( rect.top ) >= boundaryVerticalPosition ) {
  325. return false;
  326. }
  327. boundaryVerticalPosition = Math.max( boundaryVerticalPosition, Math.round( rect.bottom ) );
  328. }
  329. return true;
  330. }
  331. /**
  332. * Moves the selection from the given table cell in the specified direction.
  333. *
  334. * @protected
  335. * @param {module:engine/model/element~Element} focusCell The table cell that is current multi-cell selection focus.
  336. * @param {'left'|'up'|'right'|'down'} direction Direction in which selection should move.
  337. * @param {Boolean} [expandSelection=false] If the current selection should be expanded.
  338. */
  339. _navigateFromCellInDirection( focusCell, direction, expandSelection = false ) {
  340. const model = this.editor.model;
  341. const table = focusCell.findAncestor( 'table' );
  342. const tableMap = [ ...new TableWalker( table, { includeAllSlots: true } ) ];
  343. const { row: lastRow, column: lastColumn } = tableMap[ tableMap.length - 1 ];
  344. const currentCellInfo = tableMap.find( ( { cell } ) => cell == focusCell );
  345. let { row, column } = currentCellInfo;
  346. switch ( direction ) {
  347. case 'left':
  348. column--;
  349. break;
  350. case 'up':
  351. row--;
  352. break;
  353. case 'right':
  354. column += currentCellInfo.cellWidth;
  355. break;
  356. case 'down':
  357. row += currentCellInfo.cellHeight;
  358. break;
  359. }
  360. const isOutsideVertically = row < 0 || row > lastRow;
  361. const isBeforeFirstCell = column < 0 && row <= 0;
  362. const isAfterLastCell = column > lastColumn && row >= lastRow;
  363. // Note that if the table cell at the end of a row is row-spanned then isAfterLastCell will never be true.
  364. // However, we don't know if user was navigating on the last row or not, so let's stay in the table.
  365. if ( isOutsideVertically || isBeforeFirstCell || isAfterLastCell ) {
  366. model.change( writer => {
  367. writer.setSelection( writer.createRangeOn( table ) );
  368. } );
  369. return;
  370. }
  371. if ( column < 0 ) {
  372. column = expandSelection ? 0 : lastColumn;
  373. row--;
  374. } else if ( column > lastColumn ) {
  375. column = expandSelection ? lastColumn : 0;
  376. row++;
  377. }
  378. const cellToSelect = tableMap.find( cellInfo => cellInfo.row == row && cellInfo.column == column ).cell;
  379. const isForward = [ 'right', 'down' ].includes( direction );
  380. const tableSelection = this.editor.plugins.get( 'TableSelection' );
  381. if ( expandSelection && tableSelection.isEnabled ) {
  382. const anchorCell = tableSelection.getAnchorCell() || focusCell;
  383. tableSelection.setCellSelection( anchorCell, cellToSelect );
  384. } else {
  385. const positionToSelect = model.createPositionAt( cellToSelect, isForward ? 0 : 'end' );
  386. model.change( writer => {
  387. writer.setSelection( positionToSelect );
  388. } );
  389. }
  390. }
  391. }