tablenavigation.js 17 KB

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