tablenavigation.js 18 KB

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