tablenavigation.js 15 KB

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