8
0

tablekeyboard.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. import { findAncestor } from './utils/common';
  19. /**
  20. * This plugin enables keyboard navigation for tables.
  21. * It is loaded automatically by the {@link module:table/table~Table} plugin.
  22. *
  23. * @extends module:core/plugin~Plugin
  24. */
  25. export default class TableKeyboard extends Plugin {
  26. /**
  27. * @inheritDoc
  28. */
  29. static get pluginName() {
  30. return 'TableKeyboard';
  31. }
  32. /**
  33. * @inheritDoc
  34. */
  35. static get requires() {
  36. return [ TableSelection ];
  37. }
  38. /**
  39. * @inheritDoc
  40. */
  41. init() {
  42. const view = this.editor.editing.view;
  43. const viewDocument = view.document;
  44. // Handle Tab key navigation.
  45. this.editor.keystrokes.set( 'Tab', ( ...args ) => this._handleTabOnSelectedTable( ...args ), { priority: 'low' } );
  46. this.editor.keystrokes.set( 'Tab', this._getTabHandler( true ), { priority: 'low' } );
  47. this.editor.keystrokes.set( 'Shift+Tab', this._getTabHandler( false ), { priority: 'low' } );
  48. // Note: This listener has the "high+1" priority because we would like to avoid collisions with other features
  49. // (like Widgets), which take over the keydown events with the "high" priority. Table navigation takes precedence
  50. // over Widgets in that matter (widget arrow handler stops propagation of event if object element was selected
  51. // but getNearestSelectionRange didn't returned any range).
  52. this.listenTo( viewDocument, 'keydown', ( ...args ) => this._onKeydown( ...args ), { priority: priorities.get( 'high' ) + 1 } );
  53. }
  54. /**
  55. * Handles {@link module:engine/view/document~Document#event:keydown keydown} events for the <kbd>Tab</kbd> key executed
  56. * when the table widget is selected.
  57. *
  58. * @private
  59. * @param {module:engine/view/observer/keyobserver~KeyEventData} data Key event data.
  60. * @param {Function} cancel The stop/stopPropagation/preventDefault function.
  61. */
  62. _handleTabOnSelectedTable( data, cancel ) {
  63. const editor = this.editor;
  64. const selection = editor.model.document.selection;
  65. if ( !selection.isCollapsed && selection.rangeCount === 1 && selection.getFirstRange().isFlat ) {
  66. const selectedElement = selection.getSelectedElement();
  67. if ( !selectedElement || !selectedElement.is( 'table' ) ) {
  68. return;
  69. }
  70. cancel();
  71. editor.model.change( writer => {
  72. writer.setSelection( writer.createRangeIn( selectedElement.getChild( 0 ).getChild( 0 ) ) );
  73. } );
  74. }
  75. }
  76. /**
  77. * Returns a handler for {@link module:engine/view/document~Document#event:keydown keydown} events for the <kbd>Tab</kbd> key executed
  78. * inside table cells.
  79. *
  80. * @private
  81. * @param {Boolean} isForward Whether this handler will move the selection to the next or the previous cell.
  82. */
  83. _getTabHandler( isForward ) {
  84. const editor = this.editor;
  85. return ( domEventData, cancel ) => {
  86. const selection = editor.model.document.selection;
  87. const tableCell = getTableCellsContainingSelection( selection )[ 0 ];
  88. if ( !tableCell ) {
  89. return;
  90. }
  91. cancel();
  92. const tableRow = tableCell.parent;
  93. const table = tableRow.parent;
  94. const currentRowIndex = table.getChildIndex( tableRow );
  95. const currentCellIndex = tableRow.getChildIndex( tableCell );
  96. const isFirstCellInRow = currentCellIndex === 0;
  97. if ( !isForward && isFirstCellInRow && currentRowIndex === 0 ) {
  98. // It's the first cell of the table - don't do anything (stay in the current position).
  99. return;
  100. }
  101. const isLastCellInRow = currentCellIndex === tableRow.childCount - 1;
  102. const isLastRow = currentRowIndex === table.childCount - 1;
  103. if ( isForward && isLastRow && isLastCellInRow ) {
  104. editor.execute( 'insertTableRowBelow' );
  105. // Check if the command actually added a row. If `insertTableRowBelow` execution didn't add a row (because it was disabled
  106. // or it got overwritten) do not change the selection.
  107. if ( currentRowIndex === table.childCount - 1 ) {
  108. return;
  109. }
  110. }
  111. let cellToFocus;
  112. // Move to the first cell in the next row.
  113. if ( isForward && isLastCellInRow ) {
  114. const nextRow = table.getChild( currentRowIndex + 1 );
  115. cellToFocus = nextRow.getChild( 0 );
  116. }
  117. // Move to the last cell in the previous row.
  118. else if ( !isForward && isFirstCellInRow ) {
  119. const previousRow = table.getChild( currentRowIndex - 1 );
  120. cellToFocus = previousRow.getChild( previousRow.childCount - 1 );
  121. }
  122. // Move to the next/previous cell.
  123. else {
  124. cellToFocus = tableRow.getChild( currentCellIndex + ( isForward ? 1 : -1 ) );
  125. }
  126. editor.model.change( writer => {
  127. writer.setSelection( writer.createRangeIn( cellToFocus ) );
  128. } );
  129. };
  130. }
  131. /**
  132. * Handles {@link module:engine/view/document~Document#event:keydown keydown} events.
  133. *
  134. * @private
  135. * @param {module:utils/eventinfo~EventInfo} eventInfo
  136. * @param {module:engine/view/observer/domeventdata~DomEventData} domEventData
  137. */
  138. _onKeydown( eventInfo, domEventData ) {
  139. const editor = this.editor;
  140. const keyCode = domEventData.keyCode;
  141. if ( !isArrowKeyCode( keyCode ) ) {
  142. return;
  143. }
  144. const direction = getLocalizedArrowKeyCodeDirection( keyCode, editor.locale.contentLanguageDirection );
  145. const wasHandled = this._handleArrowKeys( direction, domEventData.shiftKey );
  146. if ( wasHandled ) {
  147. domEventData.preventDefault();
  148. domEventData.stopPropagation();
  149. eventInfo.stop();
  150. }
  151. }
  152. /**
  153. * Handles arrow keys to move the selection around the table.
  154. *
  155. * @private
  156. * @param {'left'|'up'|'right'|'down'} direction The direction of the arrow key.
  157. * @param {Boolean} expandSelection If the current selection should be expanded.
  158. * @returns {Boolean} Returns `true` if key was handled.
  159. */
  160. _handleArrowKeys( direction, expandSelection ) {
  161. const model = this.editor.model;
  162. const selection = model.document.selection;
  163. const isForward = [ 'right', 'down' ].includes( direction );
  164. // In case one or more table cells are selected (from outside),
  165. // move the selection to a cell adjacent to the selected table fragment.
  166. const selectedCells = getSelectedTableCells( selection );
  167. if ( selectedCells.length ) {
  168. let focusCell;
  169. if ( expandSelection ) {
  170. focusCell = this.editor.plugins.get( 'TableSelection' ).getFocusCell();
  171. } else {
  172. focusCell = isForward ? selectedCells[ selectedCells.length - 1 ] : selectedCells[ 0 ];
  173. }
  174. this._navigateFromCellInDirection( focusCell, direction, expandSelection );
  175. return true;
  176. }
  177. // Abort if we're not in a table cell.
  178. const tableCell = findAncestor( 'tableCell', selection.focus );
  179. if ( !tableCell ) {
  180. return false;
  181. }
  182. const cellRange = model.createRangeIn( tableCell );
  183. // Let's check if the selection is at the beginning/end of the cell.
  184. if ( this._isSelectionAtCellEdge( selection, isForward ) ) {
  185. this._navigateFromCellInDirection( tableCell, direction, expandSelection );
  186. return true;
  187. }
  188. // If this is an object selected and it's not at the start or the end of cell content
  189. // then let's allow widget handler to take care of it.
  190. const objectElement = selection.getSelectedElement();
  191. if ( objectElement && model.schema.isObject( objectElement ) ) {
  192. return false;
  193. }
  194. // If next to the selection there is an object then this is not the cell boundary (widget handler should handle this).
  195. if ( this._isObjectElementNextToSelection( selection, isForward ) ) {
  196. return false;
  197. }
  198. // If there isn't any $text position between cell edge and selection then we shall move the selection to next cell.
  199. const textRange = this._findTextRangeFromSelection( cellRange, selection, isForward );
  200. if ( !textRange ) {
  201. this._navigateFromCellInDirection( tableCell, direction, expandSelection );
  202. return true;
  203. }
  204. // If the navigation is horizontal then we have no more custom cases.
  205. if ( [ 'left', 'right' ].includes( direction ) ) {
  206. return false;
  207. }
  208. // If the range is a single line then move the selection to the beginning/end of a cell content.
  209. //
  210. // We can't move the selection directly to the another cell because of dual position at the end/beginning
  211. // of wrapped line (it's at the same time at the end of one line and at the start of the next line).
  212. if ( this._isSingleLineRange( textRange, isForward ) ) {
  213. model.change( writer => {
  214. const newPosition = isForward ? cellRange.end : cellRange.start;
  215. if ( expandSelection ) {
  216. const newSelection = model.createSelection( selection.anchor );
  217. newSelection.setFocus( newPosition );
  218. writer.setSelection( newSelection );
  219. } else {
  220. writer.setSelection( newPosition );
  221. }
  222. } );
  223. return true;
  224. }
  225. }
  226. /**
  227. * Returns `true` if the selection is at the boundary of a table cell according to the navigation direction.
  228. *
  229. * @private
  230. * @param {module:engine/model/selection~Selection} selection The current selection.
  231. * @param {Boolean} isForward The expected navigation direction.
  232. * @returns {Boolean}
  233. */
  234. _isSelectionAtCellEdge( selection, isForward ) {
  235. const model = this.editor.model;
  236. const schema = this.editor.model.schema;
  237. const focus = isForward ? selection.getLastPosition() : selection.getFirstPosition();
  238. // If the current limit element is not table cell we are for sure not at the cell edge.
  239. // Also `modifySelection` will not let us out of it.
  240. if ( !schema.getLimitElement( focus ).is( 'tableCell' ) ) {
  241. return false;
  242. }
  243. const probe = model.createSelection( focus );
  244. model.modifySelection( probe, { direction: isForward ? 'forward' : 'backward' } );
  245. // If there was no change in the focus position, then it's not possible to move the selection there.
  246. return focus.isEqual( probe.focus );
  247. }
  248. /**
  249. * Checks if there is an {@link module:engine/model/element~Element element} next to the current
  250. * {@link module:engine/model/selection~Selection model selection} marked in the
  251. * {@link module:engine/model/schema~Schema schema} as an `object`.
  252. *
  253. * @private
  254. * @param {module:engine/model/selection~Selection} modelSelection The selection.
  255. * @param {Boolean} isForward The direction of checking.
  256. * @returns {Boolean}
  257. */
  258. _isObjectElementNextToSelection( modelSelection, isForward ) {
  259. const model = this.editor.model;
  260. const schema = model.schema;
  261. const probe = model.createSelection( modelSelection );
  262. model.modifySelection( probe, { direction: isForward ? 'forward' : 'backward' } );
  263. const objectElement = isForward ? probe.focus.nodeBefore : probe.focus.nodeAfter;
  264. return objectElement && schema.isObject( objectElement );
  265. }
  266. /**
  267. * Truncates the range so that it spans from the last selection position
  268. * to the last allowed `$text` position (mirrored if `isForward` is false).
  269. *
  270. * Returns `null` if, according to the schema, the resulting range cannot contain a `$text` element.
  271. *
  272. * @private
  273. * @param {module:engine/model/range~Range} range The current table cell content range.
  274. * @param {module:engine/model/selection~Selection} selection The current selection.
  275. * @param {Boolean} isForward The expected navigation direction.
  276. * @returns {module:engine/model/range~Range|null}
  277. */
  278. _findTextRangeFromSelection( range, selection, isForward ) {
  279. const model = this.editor.model;
  280. if ( isForward ) {
  281. const position = selection.getLastPosition();
  282. const lastRangePosition = this._getNearestVisibleTextPosition( range, 'backward' );
  283. if ( lastRangePosition && position.isBefore( lastRangePosition ) ) {
  284. return model.createRange( position, lastRangePosition );
  285. }
  286. return null;
  287. } else {
  288. const position = selection.getFirstPosition();
  289. const firstRangePosition = this._getNearestVisibleTextPosition( range, 'forward' );
  290. if ( firstRangePosition && position.isAfter( firstRangePosition ) ) {
  291. return model.createRange( firstRangePosition, position );
  292. }
  293. return null;
  294. }
  295. }
  296. /**
  297. * Basing on the provided range, finds the first or last (depending on `direction`) position inside the range
  298. * that can contain `$text` (according to schema) and is visible in the view.
  299. *
  300. * @private
  301. * @param {module:engine/model/range~Range} range The range to find the position in.
  302. * @param {'forward'|'backward'} direction Search direction.
  303. * @returns {module:engine/model/position~Position} The nearest selection range.
  304. */
  305. _getNearestVisibleTextPosition( range, direction ) {
  306. const schema = this.editor.model.schema;
  307. const mapper = this.editor.editing.mapper;
  308. for ( const { nextPosition, item } of range.getWalker( { direction } ) ) {
  309. if ( schema.checkChild( nextPosition, '$text' ) ) {
  310. const viewElement = mapper.toViewElement( item );
  311. if ( viewElement && !viewElement.hasClass( 'ck-hidden' ) ) {
  312. return nextPosition;
  313. }
  314. }
  315. }
  316. }
  317. /**
  318. * Checks if the DOM range corresponding to the provided model range renders as a single line by analyzing DOMRects
  319. * (verifying if they visually wrap content to the next line).
  320. *
  321. * @private
  322. * @param {module:engine/model/range~Range} modelRange The current table cell content range.
  323. * @param {Boolean} isForward The expected navigation direction.
  324. * @returns {Boolean}
  325. */
  326. _isSingleLineRange( modelRange, isForward ) {
  327. const model = this.editor.model;
  328. const editing = this.editor.editing;
  329. const domConverter = editing.view.domConverter;
  330. // Wrapped lines contain exactly the same position at the end of current line
  331. // and at the beginning of next line. That position's client rect is at the end
  332. // of current line. In case of caret at first position of the last line that 'dual'
  333. // position would be detected as it's not the last line.
  334. if ( isForward ) {
  335. const probe = model.createSelection( modelRange.start );
  336. model.modifySelection( probe );
  337. // If the new position is at the end of the container then we can't use this position
  338. // because it would provide incorrect result for eg caption of image and selection
  339. // just before end of it. Also in this case there is no "dual" position.
  340. if ( !probe.focus.isAtEnd && !modelRange.start.isEqual( probe.focus ) ) {
  341. modelRange = model.createRange( probe.focus, modelRange.end );
  342. }
  343. }
  344. const viewRange = editing.mapper.toViewRange( modelRange );
  345. const domRange = domConverter.viewRangeToDom( viewRange );
  346. const rects = Rect.getDomRangeRects( domRange );
  347. let boundaryVerticalPosition;
  348. for ( const rect of rects ) {
  349. if ( boundaryVerticalPosition === undefined ) {
  350. boundaryVerticalPosition = Math.round( rect.bottom );
  351. continue;
  352. }
  353. // Let's check if this rect is in new line.
  354. if ( Math.round( rect.top ) >= boundaryVerticalPosition ) {
  355. return false;
  356. }
  357. boundaryVerticalPosition = Math.max( boundaryVerticalPosition, Math.round( rect.bottom ) );
  358. }
  359. return true;
  360. }
  361. /**
  362. * Moves the selection from the given table cell in the specified direction.
  363. *
  364. * @protected
  365. * @param {module:engine/model/element~Element} focusCell The table cell that is current multi-cell selection focus.
  366. * @param {'left'|'up'|'right'|'down'} direction Direction in which selection should move.
  367. * @param {Boolean} [expandSelection=false] If the current selection should be expanded.
  368. */
  369. _navigateFromCellInDirection( focusCell, direction, expandSelection = false ) {
  370. const model = this.editor.model;
  371. const table = findAncestor( 'table', focusCell );
  372. const tableMap = [ ...new TableWalker( table, { includeAllSlots: true } ) ];
  373. const { row: lastRow, column: lastColumn } = tableMap[ tableMap.length - 1 ];
  374. const currentCellInfo = tableMap.find( ( { cell } ) => cell == focusCell );
  375. let { row, column } = currentCellInfo;
  376. switch ( direction ) {
  377. case 'left':
  378. column--;
  379. break;
  380. case 'up':
  381. row--;
  382. break;
  383. case 'right':
  384. column += currentCellInfo.cellWidth;
  385. break;
  386. case 'down':
  387. row += currentCellInfo.cellHeight;
  388. break;
  389. }
  390. const isOutsideVertically = row < 0 || row > lastRow;
  391. const isBeforeFirstCell = column < 0 && row <= 0;
  392. const isAfterLastCell = column > lastColumn && row >= lastRow;
  393. // Note that if the table cell at the end of a row is row-spanned then isAfterLastCell will never be true.
  394. // However, we don't know if user was navigating on the last row or not, so let's stay in the table.
  395. if ( isOutsideVertically || isBeforeFirstCell || isAfterLastCell ) {
  396. model.change( writer => {
  397. writer.setSelection( writer.createRangeOn( table ) );
  398. } );
  399. return;
  400. }
  401. if ( column < 0 ) {
  402. column = expandSelection ? 0 : lastColumn;
  403. row--;
  404. } else if ( column > lastColumn ) {
  405. column = expandSelection ? lastColumn : 0;
  406. row++;
  407. }
  408. const cellToSelect = tableMap.find( cellInfo => cellInfo.row == row && cellInfo.column == column ).cell;
  409. const isForward = [ 'right', 'down' ].includes( direction );
  410. if ( expandSelection ) {
  411. const tableSelection = this.editor.plugins.get( 'TableSelection' );
  412. const anchorCell = tableSelection.getAnchorCell() || focusCell;
  413. tableSelection.setCellSelection( anchorCell, cellToSelect );
  414. } else {
  415. const positionToSelect = model.createPositionAt( cellToSelect, isForward ? 0 : 'end' );
  416. model.change( writer => {
  417. writer.setSelection( positionToSelect );
  418. } );
  419. }
  420. }
  421. }