dataTables.keyTable.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. /*! KeyTable 2.6.0
  2. * ©2009-2021 SpryMedia Ltd - datatables.net/license
  3. */
  4. /**
  5. * @summary KeyTable
  6. * @description Spreadsheet like keyboard navigation for DataTables
  7. * @version 2.6.0
  8. * @file dataTables.keyTable.js
  9. * @author SpryMedia Ltd (www.sprymedia.co.uk)
  10. * @contact www.sprymedia.co.uk/contact
  11. * @copyright Copyright 2009-2021 SpryMedia Ltd.
  12. *
  13. * This source file is free software, available under the following license:
  14. * MIT license - http://datatables.net/license/mit
  15. *
  16. * This source file is distributed in the hope that it will be useful, but
  17. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  18. * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
  19. *
  20. * For details please refer to: http://www.datatables.net
  21. */
  22. (function( factory ){
  23. if ( typeof define === 'function' && define.amd ) {
  24. // AMD
  25. define( ['jquery', 'datatables.net'], function ( $ ) {
  26. return factory( $, window, document );
  27. } );
  28. }
  29. else if ( typeof exports === 'object' ) {
  30. // CommonJS
  31. module.exports = function (root, $) {
  32. if ( ! root ) {
  33. root = window;
  34. }
  35. if ( ! $ || ! $.fn.dataTable ) {
  36. $ = require('datatables.net')(root, $).$;
  37. }
  38. return factory( $, root, root.document );
  39. };
  40. }
  41. else {
  42. // Browser
  43. factory( jQuery, window, document );
  44. }
  45. }(function( $, window, document, undefined ) {
  46. 'use strict';
  47. var DataTable = $.fn.dataTable;
  48. var namespaceCounter = 0;
  49. var editorNamespaceCounter = 0;
  50. var KeyTable = function ( dt, opts ) {
  51. // Sanity check that we are using DataTables 1.10 or newer
  52. if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.8' ) ) {
  53. throw 'KeyTable requires DataTables 1.10.8 or newer';
  54. }
  55. // User and defaults configuration object
  56. this.c = $.extend( true, {},
  57. DataTable.defaults.keyTable,
  58. KeyTable.defaults,
  59. opts
  60. );
  61. // Internal settings
  62. this.s = {
  63. /** @type {DataTable.Api} DataTables' API instance */
  64. dt: new DataTable.Api( dt ),
  65. enable: true,
  66. /** @type {bool} Flag for if a draw is triggered by focus */
  67. focusDraw: false,
  68. /** @type {bool} Flag to indicate when waiting for a draw to happen.
  69. * Will ignore key presses at this point
  70. */
  71. waitingForDraw: false,
  72. /** @type {object} Information about the last cell that was focused */
  73. lastFocus: null,
  74. /** @type {string} Unique namespace per instance */
  75. namespace: '.keyTable-'+(namespaceCounter++),
  76. /** @type {Node} Input element for tabbing into the table */
  77. tabInput: null
  78. };
  79. // DOM items
  80. this.dom = {
  81. };
  82. // Check if row reorder has already been initialised on this table
  83. var settings = this.s.dt.settings()[0];
  84. var exisiting = settings.keytable;
  85. if ( exisiting ) {
  86. return exisiting;
  87. }
  88. settings.keytable = this;
  89. this._constructor();
  90. };
  91. $.extend( KeyTable.prototype, {
  92. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  93. * API methods for DataTables API interface
  94. */
  95. /**
  96. * Blur the table's cell focus
  97. */
  98. blur: function ()
  99. {
  100. this._blur();
  101. },
  102. /**
  103. * Enable cell focus for the table
  104. *
  105. * @param {string} state Can be `true`, `false` or `-string navigation-only`
  106. */
  107. enable: function ( state )
  108. {
  109. this.s.enable = state;
  110. },
  111. /**
  112. * Get enable status
  113. */
  114. enabled: function () {
  115. return this.s.enable;
  116. },
  117. /**
  118. * Focus on a cell
  119. * @param {integer} row Row index
  120. * @param {integer} column Column index
  121. */
  122. focus: function ( row, column )
  123. {
  124. this._focus( this.s.dt.cell( row, column ) );
  125. },
  126. /**
  127. * Is the cell focused
  128. * @param {object} cell Cell index to check
  129. * @returns {boolean} true if focused, false otherwise
  130. */
  131. focused: function ( cell )
  132. {
  133. var lastFocus = this.s.lastFocus;
  134. if ( ! lastFocus ) {
  135. return false;
  136. }
  137. var lastIdx = this.s.lastFocus.cell.index();
  138. return cell.row === lastIdx.row && cell.column === lastIdx.column;
  139. },
  140. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  141. * Constructor
  142. */
  143. /**
  144. * Initialise the KeyTable instance
  145. *
  146. * @private
  147. */
  148. _constructor: function ()
  149. {
  150. this._tabInput();
  151. var that = this;
  152. var dt = this.s.dt;
  153. var table = $( dt.table().node() );
  154. var namespace = this.s.namespace;
  155. var editorBlock = false;
  156. // Need to be able to calculate the cell positions relative to the table
  157. if ( table.css('position') === 'static' ) {
  158. table.css( 'position', 'relative' );
  159. }
  160. // Click to focus
  161. $( dt.table().body() ).on( 'click'+namespace, 'th, td', function (e) {
  162. if ( that.s.enable === false ) {
  163. return;
  164. }
  165. var cell = dt.cell( this );
  166. if ( ! cell.any() ) {
  167. return;
  168. }
  169. that._focus( cell, null, false, e );
  170. } );
  171. // Key events
  172. $( document ).on( 'keydown'+namespace, function (e) {
  173. if ( ! editorBlock ) {
  174. that._key( e );
  175. }
  176. } );
  177. // Click blur
  178. if ( this.c.blurable ) {
  179. $( document ).on( 'mousedown'+namespace, function ( e ) {
  180. // Click on the search input will blur focus
  181. if ( $(e.target).parents( '.dataTables_filter' ).length ) {
  182. that._blur();
  183. }
  184. // If the click was inside the DataTables container, don't blur
  185. if ( $(e.target).parents().filter( dt.table().container() ).length ) {
  186. return;
  187. }
  188. // Don't blur in Editor form
  189. if ( $(e.target).parents('div.DTE').length ) {
  190. return;
  191. }
  192. // Or an Editor date input
  193. if (
  194. $(e.target).parents('div.editor-datetime').length ||
  195. $(e.target).parents('div.dt-datetime').length
  196. ) {
  197. return;
  198. }
  199. //If the click was inside the fixed columns container, don't blur
  200. if ( $(e.target).parents().filter('.DTFC_Cloned').length ) {
  201. return;
  202. }
  203. that._blur();
  204. } );
  205. }
  206. if ( this.c.editor ) {
  207. var editor = this.c.editor;
  208. // Need to disable KeyTable when the main editor is shown
  209. editor.on( 'open.keyTableMain', function (e, mode, action) {
  210. if ( mode !== 'inline' && that.s.enable ) {
  211. that.enable( false );
  212. editor.one( 'close'+namespace, function () {
  213. that.enable( true );
  214. } );
  215. }
  216. } );
  217. if ( this.c.editOnFocus ) {
  218. dt.on( 'key-focus'+namespace+' key-refocus'+namespace, function ( e, dt, cell, orig ) {
  219. that._editor( null, orig, true );
  220. } );
  221. }
  222. // Activate Editor when a key is pressed (will be ignored, if
  223. // already active).
  224. dt.on( 'key'+namespace, function ( e, dt, key, cell, orig ) {
  225. that._editor( key, orig, false );
  226. } );
  227. // Active editing on double click - it will already have focus from
  228. // the click event handler above
  229. $( dt.table().body() ).on( 'dblclick'+namespace, 'th, td', function (e) {
  230. if ( that.s.enable === false ) {
  231. return;
  232. }
  233. var cell = dt.cell( this );
  234. if ( ! cell.any() ) {
  235. return;
  236. }
  237. if ( that.s.lastFocus && this !== that.s.lastFocus.cell.node() ) {
  238. return;
  239. }
  240. that._editor( null, e, true );
  241. } );
  242. // While Editor is busy processing, we don't want to process any key events
  243. editor
  244. .on('preSubmit', function () {
  245. editorBlock = true;
  246. } )
  247. .on('preSubmitCancelled', function () {
  248. editorBlock = false;
  249. } )
  250. .on('submitComplete', function () {
  251. editorBlock = false;
  252. } );
  253. }
  254. // Stave saving
  255. if ( dt.settings()[0].oFeatures.bStateSave ) {
  256. dt.on( 'stateSaveParams'+namespace, function (e, s, d) {
  257. d.keyTable = that.s.lastFocus ?
  258. that.s.lastFocus.cell.index() :
  259. null;
  260. } );
  261. }
  262. dt.on( 'column-visibility'+namespace, function (e) {
  263. that._tabInput();
  264. } );
  265. // Redraw - retain focus on the current cell
  266. dt.on( 'draw'+namespace, function (e) {
  267. that._tabInput();
  268. if ( that.s.focusDraw ) {
  269. return;
  270. }
  271. var lastFocus = that.s.lastFocus;
  272. if ( lastFocus ) {
  273. var relative = that.s.lastFocus.relative;
  274. var info = dt.page.info();
  275. var row = relative.row + info.start;
  276. if ( info.recordsDisplay === 0 ) {
  277. return;
  278. }
  279. // Reverse if needed
  280. if ( row >= info.recordsDisplay ) {
  281. row = info.recordsDisplay - 1;
  282. }
  283. that._focus( row, relative.column, true, e );
  284. }
  285. } );
  286. // Clipboard support
  287. if ( this.c.clipboard ) {
  288. this._clipboard();
  289. }
  290. dt.on( 'destroy'+namespace, function () {
  291. that._blur( true );
  292. // Event tidy up
  293. dt.off( namespace );
  294. $( dt.table().body() )
  295. .off( 'click'+namespace, 'th, td' )
  296. .off( 'dblclick'+namespace, 'th, td' );
  297. $( document )
  298. .off( 'mousedown'+namespace )
  299. .off( 'keydown'+namespace )
  300. .off( 'copy'+namespace )
  301. .off( 'paste'+namespace );
  302. } );
  303. // Initial focus comes from state or options
  304. var state = dt.state.loaded();
  305. if ( state && state.keyTable ) {
  306. // Wait until init is done
  307. dt.one( 'init', function () {
  308. var cell = dt.cell( state.keyTable );
  309. // Ensure that the saved cell still exists
  310. if ( cell.any() ) {
  311. cell.focus();
  312. }
  313. } );
  314. }
  315. else if ( this.c.focus ) {
  316. dt.cell( this.c.focus ).focus();
  317. }
  318. },
  319. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  320. * Private methods
  321. */
  322. /**
  323. * Blur the control
  324. *
  325. * @param {boolean} [noEvents=false] Don't trigger updates / events (for destroying)
  326. * @private
  327. */
  328. _blur: function (noEvents)
  329. {
  330. if ( ! this.s.enable || ! this.s.lastFocus ) {
  331. return;
  332. }
  333. var cell = this.s.lastFocus.cell;
  334. $( cell.node() ).removeClass( this.c.className );
  335. this.s.lastFocus = null;
  336. if ( ! noEvents ) {
  337. this._updateFixedColumns(cell.index().column);
  338. this._emitEvent( 'key-blur', [ this.s.dt, cell ] );
  339. }
  340. },
  341. /**
  342. * Clipboard interaction handlers
  343. *
  344. * @private
  345. */
  346. _clipboard: function () {
  347. var dt = this.s.dt;
  348. var that = this;
  349. var namespace = this.s.namespace;
  350. // IE8 doesn't support getting selected text
  351. if ( ! window.getSelection ) {
  352. return;
  353. }
  354. $(document).on( 'copy'+namespace, function (ejq) {
  355. var e = ejq.originalEvent;
  356. var selection = window.getSelection().toString();
  357. var focused = that.s.lastFocus;
  358. // Only copy cell text to clipboard if there is no other selection
  359. // and there is a focused cell
  360. if ( ! selection && focused ) {
  361. e.clipboardData.setData(
  362. 'text/plain',
  363. focused.cell.render( that.c.clipboardOrthogonal )
  364. );
  365. e.preventDefault();
  366. }
  367. } );
  368. $(document).on( 'paste'+namespace, function (ejq) {
  369. var e = ejq.originalEvent;
  370. var focused = that.s.lastFocus;
  371. var activeEl = document.activeElement;
  372. var editor = that.c.editor;
  373. var pastedText;
  374. if ( focused && (! activeEl || activeEl.nodeName.toLowerCase() === 'body') ) {
  375. e.preventDefault();
  376. if ( window.clipboardData && window.clipboardData.getData ) {
  377. // IE
  378. pastedText = window.clipboardData.getData('Text');
  379. }
  380. else if ( e.clipboardData && e.clipboardData.getData ) {
  381. // Everything else
  382. pastedText = e.clipboardData.getData('text/plain');
  383. }
  384. if ( editor ) {
  385. // Got Editor - need to activate inline editing,
  386. // set the value and submit
  387. editor
  388. .inline( focused.cell.index() )
  389. .set( editor.displayed()[0], pastedText )
  390. .submit();
  391. }
  392. else {
  393. // No editor, so just dump the data in
  394. focused.cell.data( pastedText );
  395. dt.draw(false);
  396. }
  397. }
  398. } );
  399. },
  400. /**
  401. * Get an array of the column indexes that KeyTable can operate on. This
  402. * is a merge of the user supplied columns and the visible columns.
  403. *
  404. * @private
  405. */
  406. _columns: function ()
  407. {
  408. var dt = this.s.dt;
  409. var user = dt.columns( this.c.columns ).indexes();
  410. var out = [];
  411. dt.columns( ':visible' ).every( function (i) {
  412. if ( user.indexOf( i ) !== -1 ) {
  413. out.push( i );
  414. }
  415. } );
  416. return out;
  417. },
  418. /**
  419. * Perform excel like navigation for Editor by triggering an edit on key
  420. * press
  421. *
  422. * @param {integer} key Key code for the pressed key
  423. * @param {object} orig Original event
  424. * @private
  425. */
  426. _editor: function ( key, orig, hardEdit )
  427. {
  428. // If nothing focused, we can't take any action
  429. if (! this.s.lastFocus) {
  430. return;
  431. }
  432. // DataTables draw event
  433. if (orig.type === 'draw') {
  434. return;
  435. }
  436. var that = this;
  437. var dt = this.s.dt;
  438. var editor = this.c.editor;
  439. var editCell = this.s.lastFocus.cell;
  440. var namespace = this.s.namespace + 'e' + editorNamespaceCounter++;
  441. // Do nothing if there is already an inline edit in this cell
  442. if ( $('div.DTE', editCell.node()).length ) {
  443. return;
  444. }
  445. // Don't activate Editor on control key presses
  446. if ( key !== null && (
  447. (key >= 0x00 && key <= 0x09) ||
  448. key === 0x0b ||
  449. key === 0x0c ||
  450. (key >= 0x0e && key <= 0x1f) ||
  451. (key >= 0x70 && key <= 0x7b) ||
  452. (key >= 0x7f && key <= 0x9f)
  453. ) ) {
  454. return;
  455. }
  456. orig.stopPropagation();
  457. // Return key should do nothing - for textareas it would empty the
  458. // contents
  459. if ( key === 13 ) {
  460. orig.preventDefault();
  461. }
  462. var editInline = function () {
  463. editor
  464. .one( 'open'+namespace, function () {
  465. // Remove cancel open
  466. editor.off( 'cancelOpen'+namespace );
  467. // Excel style - select all text
  468. if ( ! hardEdit ) {
  469. $('div.DTE_Field_InputControl input, div.DTE_Field_InputControl textarea').select();
  470. }
  471. // Reduce the keys the Keys listens for
  472. dt.keys.enable( hardEdit ? 'tab-only' : 'navigation-only' );
  473. // On blur of the navigation submit
  474. dt.on( 'key-blur.editor', function (e, dt, cell) {
  475. if ( editor.displayed() && cell.node() === editCell.node() ) {
  476. editor.submit();
  477. }
  478. } );
  479. // Highlight the cell a different colour on full edit
  480. if ( hardEdit ) {
  481. $( dt.table().container() ).addClass('dtk-focus-alt');
  482. }
  483. // If the dev cancels the submit, we need to return focus
  484. editor.on( 'preSubmitCancelled'+namespace, function () {
  485. setTimeout( function () {
  486. that._focus( editCell, null, false );
  487. }, 50 );
  488. } );
  489. editor.on( 'submitUnsuccessful'+namespace, function () {
  490. that._focus( editCell, null, false );
  491. } );
  492. // Restore full key navigation on close
  493. editor.one( 'close'+namespace, function () {
  494. dt.keys.enable( true );
  495. dt.off( 'key-blur.editor' );
  496. editor.off( namespace );
  497. $( dt.table().container() ).removeClass('dtk-focus-alt');
  498. if (that.s.returnSubmit) {
  499. that._emitEvent( 'key-return-submit', [dt, editCell] );
  500. }
  501. } );
  502. } )
  503. .one( 'cancelOpen'+namespace, function () {
  504. // `preOpen` can cancel the display of the form, so it
  505. // might be that the open event handler isn't needed
  506. editor.off( namespace );
  507. } )
  508. .inline( editCell.index() );
  509. };
  510. // Editor 1.7 listens for `return` on keyup, so if return is the trigger
  511. // key, we need to wait for `keyup` otherwise Editor would just submit
  512. // the content triggered by this keypress.
  513. if ( key === 13 ) {
  514. hardEdit = true;
  515. $(document).one( 'keyup', function () { // immediately removed
  516. editInline();
  517. } );
  518. }
  519. else {
  520. editInline();
  521. }
  522. },
  523. /**
  524. * Emit an event on the DataTable for listeners
  525. *
  526. * @param {string} name Event name
  527. * @param {array} args Event arguments
  528. * @private
  529. */
  530. _emitEvent: function ( name, args )
  531. {
  532. this.s.dt.iterator( 'table', function ( ctx, i ) {
  533. $(ctx.nTable).triggerHandler( name, args );
  534. } );
  535. },
  536. /**
  537. * Focus on a particular cell, shifting the table's paging if required
  538. *
  539. * @param {DataTables.Api|integer} row Can be given as an API instance that
  540. * contains the cell to focus or as an integer. As the latter it is the
  541. * visible row index (from the whole data set) - NOT the data index
  542. * @param {integer} [column] Not required if a cell is given as the first
  543. * parameter. Otherwise this is the column data index for the cell to
  544. * focus on
  545. * @param {boolean} [shift=true] Should the viewport be moved to show cell
  546. * @private
  547. */
  548. _focus: function ( row, column, shift, originalEvent )
  549. {
  550. var that = this;
  551. var dt = this.s.dt;
  552. var pageInfo = dt.page.info();
  553. var lastFocus = this.s.lastFocus;
  554. if ( ! originalEvent) {
  555. originalEvent = null;
  556. }
  557. if ( ! this.s.enable ) {
  558. return;
  559. }
  560. if ( typeof row !== 'number' ) {
  561. // Its an API instance - check that there is actually a row
  562. if ( ! row.any() ) {
  563. return;
  564. }
  565. // Convert the cell to a row and column
  566. var index = row.index();
  567. column = index.column;
  568. row = dt
  569. .rows( { filter: 'applied', order: 'applied' } )
  570. .indexes()
  571. .indexOf( index.row );
  572. // Don't focus rows that were filtered out.
  573. if ( row < 0 ) {
  574. return;
  575. }
  576. // For server-side processing normalise the row by adding the start
  577. // point, since `rows().indexes()` includes only rows that are
  578. // available at the client-side
  579. if ( pageInfo.serverSide ) {
  580. row += pageInfo.start;
  581. }
  582. }
  583. // Is the row on the current page? If not, we need to redraw to show the
  584. // page
  585. if ( pageInfo.length !== -1 && (row < pageInfo.start || row >= pageInfo.start+pageInfo.length) ) {
  586. this.s.focusDraw = true;
  587. this.s.waitingForDraw = true;
  588. dt
  589. .one( 'draw', function () {
  590. that.s.focusDraw = false;
  591. that.s.waitingForDraw = false;
  592. that._focus( row, column, undefined, originalEvent );
  593. } )
  594. .page( Math.floor( row / pageInfo.length ) )
  595. .draw( false );
  596. return;
  597. }
  598. // In the available columns?
  599. if ( $.inArray( column, this._columns() ) === -1 ) {
  600. return;
  601. }
  602. // De-normalise the server-side processing row, so we select the row
  603. // in its displayed position
  604. if ( pageInfo.serverSide ) {
  605. row -= pageInfo.start;
  606. }
  607. // Get the cell from the current position - ignoring any cells which might
  608. // not have been rendered (therefore can't use `:eq()` selector).
  609. var cells = dt.cells( null, column, {search: 'applied', order: 'applied'} ).flatten();
  610. var cell = dt.cell( cells[ row ] );
  611. if ( lastFocus ) {
  612. // Don't trigger a refocus on the same cell
  613. if ( lastFocus.node === cell.node() ) {
  614. this._emitEvent( 'key-refocus', [ this.s.dt, cell, originalEvent || null ] );
  615. return;
  616. }
  617. // Otherwise blur the old focus
  618. this._blur();
  619. }
  620. // Clear focus from other tables
  621. this._removeOtherFocus();
  622. var node = $( cell.node() );
  623. node.addClass( this.c.className );
  624. this._updateFixedColumns(column);
  625. // Shift viewpoint and page to make cell visible
  626. if ( shift === undefined || shift === true ) {
  627. this._scroll( $(window), $(document.body), node, 'offset' );
  628. var bodyParent = dt.table().body().parentNode;
  629. if ( bodyParent !== dt.table().header().parentNode ) {
  630. var parent = $(bodyParent.parentNode);
  631. this._scroll( parent, parent, node, 'position' );
  632. }
  633. }
  634. // Event and finish
  635. this.s.lastFocus = {
  636. cell: cell,
  637. node: cell.node(),
  638. relative: {
  639. row: dt.rows( { page: 'current' } ).indexes().indexOf( cell.index().row ),
  640. column: cell.index().column
  641. }
  642. };
  643. this._emitEvent( 'key-focus', [ this.s.dt, cell, originalEvent || null ] );
  644. dt.state.save();
  645. },
  646. /**
  647. * Handle key press
  648. *
  649. * @param {object} e Event
  650. * @private
  651. */
  652. _key: function ( e )
  653. {
  654. // If we are waiting for a draw to happen from another key event, then
  655. // do nothing for this new key press.
  656. if ( this.s.waitingForDraw ) {
  657. e.preventDefault();
  658. return;
  659. }
  660. var enable = this.s.enable;
  661. this.s.returnSubmit = (enable === 'navigation-only' || enable === 'tab-only') && e.keyCode === 13
  662. ? true
  663. : false;
  664. var navEnable = enable === true || enable === 'navigation-only';
  665. if ( ! enable ) {
  666. return;
  667. }
  668. if ( (e.keyCode === 0 || e.ctrlKey || e.metaKey || e.altKey) && !(e.ctrlKey && e.altKey) ) {
  669. return;
  670. }
  671. // If not focused, then there is no key action to take
  672. var lastFocus = this.s.lastFocus;
  673. if ( ! lastFocus ) {
  674. return;
  675. }
  676. // And the last focus still exists!
  677. if ( ! this.s.dt.cell(lastFocus.node).any() ) {
  678. this.s.lastFocus = null;
  679. return;
  680. }
  681. var that = this;
  682. var dt = this.s.dt;
  683. var scrolling = this.s.dt.settings()[0].oScroll.sY ? true : false;
  684. // If we are not listening for this key, do nothing
  685. if ( this.c.keys && $.inArray( e.keyCode, this.c.keys ) === -1 ) {
  686. return;
  687. }
  688. switch( e.keyCode ) {
  689. case 9: // tab
  690. // `enable` can be tab-only
  691. this._shift( e, e.shiftKey ? 'left' : 'right', true );
  692. break;
  693. case 27: // esc
  694. if ( this.s.blurable && enable === true ) {
  695. this._blur();
  696. }
  697. break;
  698. case 33: // page up (previous page)
  699. case 34: // page down (next page)
  700. if ( navEnable && !scrolling ) {
  701. e.preventDefault();
  702. dt
  703. .page( e.keyCode === 33 ? 'previous' : 'next' )
  704. .draw( false );
  705. }
  706. break;
  707. case 35: // end (end of current page)
  708. case 36: // home (start of current page)
  709. if ( navEnable ) {
  710. e.preventDefault();
  711. var indexes = dt.cells( {page: 'current'} ).indexes();
  712. var colIndexes = this._columns();
  713. this._focus( dt.cell(
  714. indexes[ e.keyCode === 35 ? indexes.length-1 : colIndexes[0] ]
  715. ), null, true, e );
  716. }
  717. break;
  718. case 37: // left arrow
  719. if ( navEnable ) {
  720. this._shift( e, 'left' );
  721. }
  722. break;
  723. case 38: // up arrow
  724. if ( navEnable ) {
  725. this._shift( e, 'up' );
  726. }
  727. break;
  728. case 39: // right arrow
  729. if ( navEnable ) {
  730. this._shift( e, 'right' );
  731. }
  732. break;
  733. case 40: // down arrow
  734. if ( navEnable ) {
  735. this._shift( e, 'down' );
  736. }
  737. break;
  738. case 113: // F2 - Excel like hard edit
  739. if ( this.c.editor ) {
  740. this._editor(null, e, true);
  741. break;
  742. }
  743. // else fallthrough
  744. default:
  745. // Everything else - pass through only when fully enabled
  746. if ( enable === true ) {
  747. this._emitEvent( 'key', [ dt, e.keyCode, this.s.lastFocus.cell, e ] );
  748. }
  749. break;
  750. }
  751. },
  752. /**
  753. * Remove focus from all tables other than this one
  754. */
  755. _removeOtherFocus: function ()
  756. {
  757. var thisTable = this.s.dt.table().node();
  758. $.fn.dataTable.tables({api:true}).iterator('table', function (settings) {
  759. if (this.table().node() !== thisTable) {
  760. this.cell.blur();
  761. }
  762. });
  763. },
  764. /**
  765. * Scroll a container to make a cell visible in it. This can be used for
  766. * both DataTables scrolling and native window scrolling.
  767. *
  768. * @param {jQuery} container Scrolling container
  769. * @param {jQuery} scroller Item being scrolled
  770. * @param {jQuery} cell Cell in the scroller
  771. * @param {string} posOff `position` or `offset` - which to use for the
  772. * calculation. `offset` for the document, otherwise `position`
  773. * @private
  774. */
  775. _scroll: function ( container, scroller, cell, posOff )
  776. {
  777. var offset = cell[posOff]();
  778. var height = cell.outerHeight();
  779. var width = cell.outerWidth();
  780. var scrollTop = scroller.scrollTop();
  781. var scrollLeft = scroller.scrollLeft();
  782. var containerHeight = container.height();
  783. var containerWidth = container.width();
  784. // If Scroller is being used, the table can be `position: absolute` and that
  785. // needs to be taken account of in the offset. If no Scroller, this will be 0
  786. if ( posOff === 'position' ) {
  787. offset.top += parseInt( cell.closest('table').css('top'), 10 );
  788. }
  789. // Top correction
  790. if ( offset.top < scrollTop ) {
  791. scroller.scrollTop( offset.top );
  792. }
  793. // Left correction
  794. if ( offset.left < scrollLeft ) {
  795. scroller.scrollLeft( offset.left );
  796. }
  797. // Bottom correction
  798. if ( offset.top + height > scrollTop + containerHeight && height < containerHeight ) {
  799. scroller.scrollTop( offset.top + height - containerHeight );
  800. }
  801. // Right correction
  802. if ( offset.left + width > scrollLeft + containerWidth && width < containerWidth ) {
  803. scroller.scrollLeft( offset.left + width - containerWidth );
  804. }
  805. },
  806. /**
  807. * Calculate a single offset movement in the table - up, down, left and
  808. * right and then perform the focus if possible
  809. *
  810. * @param {object} e Event object
  811. * @param {string} direction Movement direction
  812. * @param {boolean} keyBlurable `true` if the key press can result in the
  813. * table being blurred. This is so arrow keys won't blur the table, but
  814. * tab will.
  815. * @private
  816. */
  817. _shift: function ( e, direction, keyBlurable )
  818. {
  819. var that = this;
  820. var dt = this.s.dt;
  821. var pageInfo = dt.page.info();
  822. var rows = pageInfo.recordsDisplay;
  823. var columns = this._columns();
  824. var last = this.s.lastFocus;
  825. if ( ! last ) {
  826. return;
  827. }
  828. var currentCell = last.cell;
  829. if ( ! currentCell ) {
  830. return;
  831. }
  832. var currRow = dt
  833. .rows( { filter: 'applied', order: 'applied' } )
  834. .indexes()
  835. .indexOf( currentCell.index().row );
  836. // When server-side processing, `rows().indexes()` only gives the rows
  837. // that are available at the client-side, so we need to normalise the
  838. // row's current position by the display start point
  839. if ( pageInfo.serverSide ) {
  840. currRow += pageInfo.start;
  841. }
  842. var currCol = dt
  843. .columns( columns )
  844. .indexes()
  845. .indexOf( currentCell.index().column );
  846. var
  847. row = currRow,
  848. column = columns[ currCol ]; // row is the display, column is an index
  849. if ( direction === 'right' ) {
  850. if ( currCol >= columns.length - 1 ) {
  851. row++;
  852. column = columns[0];
  853. }
  854. else {
  855. column = columns[ currCol+1 ];
  856. }
  857. }
  858. else if ( direction === 'left' ) {
  859. if ( currCol === 0 ) {
  860. row--;
  861. column = columns[ columns.length - 1 ];
  862. }
  863. else {
  864. column = columns[ currCol-1 ];
  865. }
  866. }
  867. else if ( direction === 'up' ) {
  868. row--;
  869. }
  870. else if ( direction === 'down' ) {
  871. row++;
  872. }
  873. if ( row >= 0 && row < rows && $.inArray( column, columns ) !== -1 ) {
  874. if (e) {
  875. e.preventDefault();
  876. }
  877. this._focus( row, column, true, e );
  878. }
  879. else if ( ! keyBlurable || ! this.c.blurable ) {
  880. // No new focus, but if the table isn't blurable, then don't loose
  881. // focus
  882. if (e) {
  883. e.preventDefault();
  884. }
  885. }
  886. else {
  887. this._blur();
  888. }
  889. },
  890. /**
  891. * Create and insert a hidden input element that can receive focus on behalf
  892. * of the table
  893. *
  894. * @private
  895. */
  896. _tabInput: function ()
  897. {
  898. var that = this;
  899. var dt = this.s.dt;
  900. var tabIndex = this.c.tabIndex !== null ?
  901. this.c.tabIndex :
  902. dt.settings()[0].iTabIndex;
  903. if ( tabIndex == -1 ) {
  904. return;
  905. }
  906. // Only create the input element once on first class
  907. if (! this.s.tabInput) {
  908. var div = $('<div><input type="text" tabindex="'+tabIndex+'"/></div>')
  909. .css( {
  910. position: 'absolute',
  911. height: 1,
  912. width: 0,
  913. overflow: 'hidden'
  914. } );
  915. div.children().on( 'focus', function (e) {
  916. var cell = dt.cell(':eq(0)', that._columns(), {page: 'current'});
  917. if ( cell.any() ) {
  918. that._focus( cell, null, true, e );
  919. }
  920. } );
  921. this.s.tabInput = div;
  922. }
  923. // Insert the input element into the first cell in the table's body
  924. var cell = this.s.dt.cell(':eq(0)', '0:visible', {page: 'current', order: 'current'}).node();
  925. if (cell) {
  926. $(cell).prepend(this.s.tabInput);
  927. }
  928. },
  929. /**
  930. * Update fixed columns if they are enabled and if the cell we are
  931. * focusing is inside a fixed column
  932. * @param {integer} column Index of the column being changed
  933. * @private
  934. */
  935. _updateFixedColumns: function( column )
  936. {
  937. var dt = this.s.dt;
  938. var settings = dt.settings()[0];
  939. if ( settings._oFixedColumns ) {
  940. var leftCols = settings._oFixedColumns.s.iLeftColumns;
  941. var rightCols = settings.aoColumns.length - settings._oFixedColumns.s.iRightColumns;
  942. if (column < leftCols || column >= rightCols) {
  943. dt.fixedColumns().update();
  944. }
  945. }
  946. }
  947. } );
  948. /**
  949. * KeyTable default settings for initialisation
  950. *
  951. * @namespace
  952. * @name KeyTable.defaults
  953. * @static
  954. */
  955. KeyTable.defaults = {
  956. /**
  957. * Can focus be removed from the table
  958. * @type {Boolean}
  959. */
  960. blurable: true,
  961. /**
  962. * Class to give to the focused cell
  963. * @type {String}
  964. */
  965. className: 'focus',
  966. /**
  967. * Enable or disable clipboard support
  968. * @type {Boolean}
  969. */
  970. clipboard: true,
  971. /**
  972. * Orthogonal data that should be copied to clipboard
  973. * @type {string}
  974. */
  975. clipboardOrthogonal: 'display',
  976. /**
  977. * Columns that can be focused. This is automatically merged with the
  978. * visible columns as only visible columns can gain focus.
  979. * @type {String}
  980. */
  981. columns: '', // all
  982. /**
  983. * Editor instance to automatically perform Excel like navigation
  984. * @type {Editor}
  985. */
  986. editor: null,
  987. /**
  988. * Trigger editing immediately on focus
  989. * @type {boolean}
  990. */
  991. editOnFocus: false,
  992. /**
  993. * Select a cell to automatically select on start up. `null` for no
  994. * automatic selection
  995. * @type {cell-selector}
  996. */
  997. focus: null,
  998. /**
  999. * Array of keys to listen for
  1000. * @type {null|array}
  1001. */
  1002. keys: null,
  1003. /**
  1004. * Tab index for where the table should sit in the document's tab flow
  1005. * @type {integer|null}
  1006. */
  1007. tabIndex: null
  1008. };
  1009. KeyTable.version = "2.6.0";
  1010. $.fn.dataTable.KeyTable = KeyTable;
  1011. $.fn.DataTable.KeyTable = KeyTable;
  1012. DataTable.Api.register( 'cell.blur()', function () {
  1013. return this.iterator( 'table', function (ctx) {
  1014. if ( ctx.keytable ) {
  1015. ctx.keytable.blur();
  1016. }
  1017. } );
  1018. } );
  1019. DataTable.Api.register( 'cell().focus()', function () {
  1020. return this.iterator( 'cell', function (ctx, row, column) {
  1021. if ( ctx.keytable ) {
  1022. ctx.keytable.focus( row, column );
  1023. }
  1024. } );
  1025. } );
  1026. DataTable.Api.register( 'keys.disable()', function () {
  1027. return this.iterator( 'table', function (ctx) {
  1028. if ( ctx.keytable ) {
  1029. ctx.keytable.enable( false );
  1030. }
  1031. } );
  1032. } );
  1033. DataTable.Api.register( 'keys.enable()', function ( opts ) {
  1034. return this.iterator( 'table', function (ctx) {
  1035. if ( ctx.keytable ) {
  1036. ctx.keytable.enable( opts === undefined ? true : opts );
  1037. }
  1038. } );
  1039. } );
  1040. DataTable.Api.register( 'keys.enabled()', function ( opts ) {
  1041. let ctx = this.context;
  1042. if (ctx.length) {
  1043. return ctx[0].keytable
  1044. ? ctx[0].keytable.enabled()
  1045. : false;
  1046. }
  1047. return false;
  1048. } );
  1049. DataTable.Api.register( 'keys.move()', function ( dir ) {
  1050. return this.iterator( 'table', function (ctx) {
  1051. if ( ctx.keytable ) {
  1052. ctx.keytable._shift( null, dir, false );
  1053. }
  1054. } );
  1055. } );
  1056. // Cell selector
  1057. DataTable.ext.selector.cell.push( function ( settings, opts, cells ) {
  1058. var focused = opts.focused;
  1059. var kt = settings.keytable;
  1060. var out = [];
  1061. if ( ! kt || focused === undefined ) {
  1062. return cells;
  1063. }
  1064. for ( var i=0, ien=cells.length ; i<ien ; i++ ) {
  1065. if ( (focused === true && kt.focused( cells[i] ) ) ||
  1066. (focused === false && ! kt.focused( cells[i] ) )
  1067. ) {
  1068. out.push( cells[i] );
  1069. }
  1070. }
  1071. return out;
  1072. } );
  1073. // Attach a listener to the document which listens for DataTables initialisation
  1074. // events so we can automatically initialise
  1075. $(document).on( 'preInit.dt.dtk', function (e, settings, json) {
  1076. if ( e.namespace !== 'dt' ) {
  1077. return;
  1078. }
  1079. var init = settings.oInit.keys;
  1080. var defaults = DataTable.defaults.keys;
  1081. if ( init || defaults ) {
  1082. var opts = $.extend( {}, defaults, init );
  1083. if ( init !== false ) {
  1084. new KeyTable( settings, opts );
  1085. }
  1086. }
  1087. } );
  1088. return KeyTable;
  1089. }));