GPQAPP

Форк
0
/
dataTables.keyTable.js 
1349 строк · 30.9 Кб
1
/*! KeyTable 2.6.4
2
 * ©2009-2021 SpryMedia Ltd - datatables.net/license
3
 */
4

5
/**
6
 * @summary     KeyTable
7
 * @description Spreadsheet like keyboard navigation for DataTables
8
 * @version     2.6.4
9
 * @file        dataTables.keyTable.js
10
 * @author      SpryMedia Ltd (www.sprymedia.co.uk)
11
 * @contact     www.sprymedia.co.uk/contact
12
 * @copyright   Copyright 2009-2021 SpryMedia Ltd.
13
 *
14
 * This source file is free software, available under the following license:
15
 *   MIT license - http://datatables.net/license/mit
16
 *
17
 * This source file is distributed in the hope that it will be useful, but
18
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19
 * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
20
 *
21
 * For details please refer to: http://www.datatables.net
22
 */
23

24
(function( factory ){
25
	if ( typeof define === 'function' && define.amd ) {
26
		// AMD
27
		define( ['jquery', 'datatables.net'], function ( $ ) {
28
			return factory( $, window, document );
29
		} );
30
	}
31
	else if ( typeof exports === 'object' ) {
32
		// CommonJS
33
		module.exports = function (root, $) {
34
			if ( ! root ) {
35
				root = window;
36
			}
37

38
			if ( ! $ || ! $.fn.dataTable ) {
39
				$ = require('datatables.net')(root, $).$;
40
			}
41

42
			return factory( $, root, root.document );
43
		};
44
	}
45
	else {
46
		// Browser
47
		factory( jQuery, window, document );
48
	}
49
}(function( $, window, document, undefined ) {
50
'use strict';
51
var DataTable = $.fn.dataTable;
52
var namespaceCounter = 0;
53
var editorNamespaceCounter = 0;
54

55

56
var KeyTable = function ( dt, opts ) {
57
	// Sanity check that we are using DataTables 1.10 or newer
58
	if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.8' ) ) {
59
		throw 'KeyTable requires DataTables 1.10.8 or newer';
60
	}
61

62
	// User and defaults configuration object
63
	this.c = $.extend( true, {},
64
		DataTable.defaults.keyTable,
65
		KeyTable.defaults,
66
		opts
67
	);
68

69
	// Internal settings
70
	this.s = {
71
		/** @type {DataTable.Api} DataTables' API instance */
72
		dt: new DataTable.Api( dt ),
73

74
		enable: true,
75

76
		/** @type {bool} Flag for if a draw is triggered by focus */
77
		focusDraw: false,
78

79
		/** @type {bool} Flag to indicate when waiting for a draw to happen.
80
		  *   Will ignore key presses at this point
81
		  */
82
		waitingForDraw: false,
83

84
		/** @type {object} Information about the last cell that was focused */
85
		lastFocus: null,
86

87
		/** @type {string} Unique namespace per instance */
88
		namespace: '.keyTable-'+(namespaceCounter++),
89

90
		/** @type {Node} Input element for tabbing into the table */
91
		tabInput: null
92
	};
93

94
	// DOM items
95
	this.dom = {
96

97
	};
98

99
	// Check if row reorder has already been initialised on this table
100
	var settings = this.s.dt.settings()[0];
101
	var exisiting = settings.keytable;
102
	if ( exisiting ) {
103
		return exisiting;
104
	}
105

106
	settings.keytable = this;
107
	this._constructor();
108
};
109

110

111
$.extend( KeyTable.prototype, {
112
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
113
	 * API methods for DataTables API interface
114
	 */
115

116
	/**
117
	 * Blur the table's cell focus
118
	 */
119
	blur: function ()
120
	{
121
		this._blur();
122
	},
123

124
	/**
125
	 * Enable cell focus for the table
126
	 *
127
	 * @param  {string} state Can be `true`, `false` or `-string navigation-only`
128
	 */
129
	enable: function ( state )
130
	{
131
		this.s.enable = state;
132
	},
133

134
	/**
135
	 * Get enable status
136
	 */
137
	enabled: function () {
138
		return this.s.enable;
139
	},
140

141
	/**
142
	 * Focus on a cell
143
	 * @param  {integer} row    Row index
144
	 * @param  {integer} column Column index
145
	 */
146
	focus: function ( row, column )
147
	{
148
		this._focus( this.s.dt.cell( row, column ) );
149
	},
150

151
	/**
152
	 * Is the cell focused
153
	 * @param  {object} cell Cell index to check
154
	 * @returns {boolean} true if focused, false otherwise
155
	 */
156
	focused: function ( cell )
157
	{
158
		var lastFocus = this.s.lastFocus;
159

160
		if ( ! lastFocus ) {
161
			return false;
162
		}
163

164
		var lastIdx = this.s.lastFocus.cell.index();
165
		return cell.row === lastIdx.row && cell.column === lastIdx.column;
166
	},
167

168

169
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
170
	 * Constructor
171
	 */
172

173
	/**
174
	 * Initialise the KeyTable instance
175
	 *
176
	 * @private
177
	 */
178
	_constructor: function ()
179
	{
180
		this._tabInput();
181

182
		var that = this;
183
		var dt = this.s.dt;
184
		var table = $( dt.table().node() );
185
		var namespace = this.s.namespace;
186
		var editorBlock = false;
187

188
		// Need to be able to calculate the cell positions relative to the table
189
		if ( table.css('position') === 'static' ) {
190
			table.css( 'position', 'relative' );
191
		}
192

193
		// Click to focus
194
		$( dt.table().body() ).on( 'click'+namespace, 'th, td', function (e) {
195
			if ( that.s.enable === false ) {
196
				return;
197
			}
198

199
			var cell = dt.cell( this );
200

201
			if ( ! cell.any() ) {
202
				return;
203
			}
204

205
			that._focus( cell, null, false, e );
206
		} );
207

208
		// Key events
209
		$( document ).on( 'keydown'+namespace, function (e) {
210
			if ( ! editorBlock ) {
211
				that._key( e );
212
			}
213
		} );
214

215
		// Click blur
216
		if ( this.c.blurable ) {
217
			$( document ).on( 'mousedown'+namespace, function ( e ) {
218
				// Click on the search input will blur focus
219
				if ( $(e.target).parents( '.dataTables_filter' ).length ) {
220
					that._blur();
221
				}
222

223
				// If the click was inside the DataTables container, don't blur
224
				if ( $(e.target).parents().filter( dt.table().container() ).length ) {
225
					return;
226
				}
227

228
				// Don't blur in Editor form
229
				if ( $(e.target).parents('div.DTE').length ) {
230
					return;
231
				}
232

233
				// Or an Editor date input
234
				if (
235
					$(e.target).parents('div.editor-datetime').length ||
236
					$(e.target).parents('div.dt-datetime').length 
237
				) {
238
					return;
239
				}
240

241
				//If the click was inside the fixed columns container, don't blur
242
				if ( $(e.target).parents().filter('.DTFC_Cloned').length ) {
243
					return;
244
				}
245

246
				that._blur();
247
			} );
248
		}
249

250
		if ( this.c.editor ) {
251
			var editor = this.c.editor;
252

253
			// Need to disable KeyTable when the main editor is shown
254
			editor.on( 'open.keyTableMain', function (e, mode, action) {
255
				if ( mode !== 'inline' && that.s.enable ) {
256
					that.enable( false );
257

258
					editor.one( 'close'+namespace, function () {
259
						that.enable( true );
260
					} );
261
				}
262
			} );
263

264
			if ( this.c.editOnFocus ) {
265
				dt.on( 'key-focus'+namespace+' key-refocus'+namespace, function ( e, dt, cell, orig ) {
266
					that._editor( null, orig, true );
267
				} );
268
			}
269

270
			// Activate Editor when a key is pressed (will be ignored, if
271
			// already active).
272
			dt.on( 'key'+namespace, function ( e, dt, key, cell, orig ) {
273
				that._editor( key, orig, false );
274
			} );
275

276
			// Active editing on double click - it will already have focus from
277
			// the click event handler above
278
			$( dt.table().body() ).on( 'dblclick'+namespace, 'th, td', function (e) {
279
				if ( that.s.enable === false ) {
280
					return;
281
				}
282

283
				var cell = dt.cell( this );
284

285
				if ( ! cell.any() ) {
286
					return;
287
				}
288

289
				if ( that.s.lastFocus && this !== that.s.lastFocus.cell.node() ) {
290
					return;
291
				}
292

293
				that._editor( null, e, true );
294
			} );
295

296
			// While Editor is busy processing, we don't want to process any key events
297
			editor
298
				.on('preSubmit', function () {
299
					editorBlock = true;
300
				} )
301
				.on('preSubmitCancelled', function () {
302
					editorBlock = false;
303
				} )
304
				.on('submitComplete', function () {
305
					editorBlock = false;
306
				} );
307
		}
308

309
		// Stave saving
310
		if ( dt.settings()[0].oFeatures.bStateSave ) {
311
			dt.on( 'stateSaveParams'+namespace, function (e, s, d) {
312
				d.keyTable = that.s.lastFocus ?
313
					that.s.lastFocus.cell.index() :
314
					null;
315
			} );
316
		}
317

318
		dt.on( 'column-visibility'+namespace, function (e) {
319
			that._tabInput();
320
		} );
321

322
		// Redraw - retain focus on the current cell
323
		dt.on( 'draw'+namespace, function (e) {
324
			that._tabInput();
325

326
			if ( that.s.focusDraw ) {
327
				return;
328
			}
329

330
			var lastFocus = that.s.lastFocus;
331

332
			if ( lastFocus ) {
333
				var relative = that.s.lastFocus.relative;
334
				var info = dt.page.info();
335
				var row = relative.row + info.start;
336

337
				if ( info.recordsDisplay === 0 ) {
338
					return;
339
				}
340

341
				// Reverse if needed
342
				if ( row >= info.recordsDisplay ) {
343
					row = info.recordsDisplay - 1;
344
				}
345

346
				that._focus( row, relative.column, true, e );
347
			}
348
		} );
349

350
		// Clipboard support
351
		if ( this.c.clipboard ) {
352
			this._clipboard();
353
		}
354

355
		dt.on( 'destroy'+namespace, function () {
356
			that._blur( true );
357

358
			// Event tidy up
359
			dt.off( namespace );
360

361
			$( dt.table().body() )
362
				.off( 'click'+namespace, 'th, td' )
363
				.off( 'dblclick'+namespace, 'th, td' );
364

365
			$( document )
366
				.off( 'mousedown'+namespace )
367
				.off( 'keydown'+namespace )
368
				.off( 'copy'+namespace )
369
				.off( 'paste'+namespace );
370
		} );
371

372
		// Initial focus comes from state or options
373
		var state = dt.state.loaded();
374

375
		if ( state && state.keyTable ) {
376
			// Wait until init is done
377
			dt.one( 'init', function () {
378
				var cell = dt.cell( state.keyTable );
379

380
				// Ensure that the saved cell still exists
381
				if ( cell.any() ) {
382
					cell.focus();
383
				}
384
			} );
385
		}
386
		else if ( this.c.focus ) {
387
			dt.cell( this.c.focus ).focus();
388
		}
389
	},
390

391

392
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
393
	 * Private methods
394
	 */
395

396
	/**
397
	 * Blur the control
398
	 *
399
	 * @param {boolean} [noEvents=false] Don't trigger updates / events (for destroying)
400
	 * @private
401
	 */
402
	_blur: function (noEvents)
403
	{
404
		if ( ! this.s.enable || ! this.s.lastFocus ) {
405
			return;
406
		}
407

408
		var cell = this.s.lastFocus.cell;
409

410
		$( cell.node() ).removeClass( this.c.className );
411
		this.s.lastFocus = null;
412

413
		if ( ! noEvents ) {
414
			this._updateFixedColumns(cell.index().column);
415

416
			this._emitEvent( 'key-blur', [ this.s.dt, cell ] );
417
		}
418
	},
419

420

421
	/**
422
	 * Clipboard interaction handlers
423
	 *
424
	 * @private
425
	 */
426
	_clipboard: function () {
427
		var dt = this.s.dt;
428
		var that = this;
429
		var namespace = this.s.namespace;
430

431
		// IE8 doesn't support getting selected text
432
		if ( ! window.getSelection ) {
433
			return;
434
		}
435

436
		$(document).on( 'copy'+namespace, function (ejq) {
437
			var e = ejq.originalEvent;
438
			var selection = window.getSelection().toString();
439
			var focused = that.s.lastFocus;
440

441
			// Only copy cell text to clipboard if there is no other selection
442
			// and there is a focused cell
443
			if ( ! selection && focused ) {
444
				e.clipboardData.setData(
445
					'text/plain',
446
					focused.cell.render( that.c.clipboardOrthogonal )
447
				);
448
				e.preventDefault();
449
			}
450
		} );
451

452
		$(document).on( 'paste'+namespace, function (ejq) {
453
			var e = ejq.originalEvent;
454
			var focused = that.s.lastFocus;
455
			var activeEl = document.activeElement;
456
			var editor = that.c.editor;
457
			var pastedText;
458

459
			if ( focused && (! activeEl || activeEl.nodeName.toLowerCase() === 'body') ) {
460
				e.preventDefault();
461

462
				if ( window.clipboardData && window.clipboardData.getData ) {
463
					// IE
464
					pastedText = window.clipboardData.getData('Text');
465
				}
466
				else if ( e.clipboardData && e.clipboardData.getData ) {
467
					// Everything else
468
					pastedText = e.clipboardData.getData('text/plain');
469
				}
470

471
				if ( editor ) {
472
					// Got Editor - need to activate inline editing,
473
					// set the value and submit
474
					var options = that._inlineOptions(focused.cell.index());
475

476
					editor
477
						.inline(options.cell, options.field, options.options)
478
						.set( editor.displayed()[0], pastedText )
479
						.submit();
480
				}
481
				else {
482
					// No editor, so just dump the data in
483
					focused.cell.data( pastedText );
484
					dt.draw(false);
485
				}
486
			}
487
		} );
488
	},
489

490

491
	/**
492
	 * Get an array of the column indexes that KeyTable can operate on. This
493
	 * is a merge of the user supplied columns and the visible columns.
494
	 *
495
	 * @private
496
	 */
497
	_columns: function ()
498
	{
499
		var dt = this.s.dt;
500
		var user = dt.columns( this.c.columns ).indexes();
501
		var out = [];
502

503
		dt.columns( ':visible' ).every( function (i) {
504
			if ( user.indexOf( i ) !== -1 ) {
505
				out.push( i );
506
			}
507
		} );
508

509
		return out;
510
	},
511

512

513
	/**
514
	 * Perform excel like navigation for Editor by triggering an edit on key
515
	 * press
516
	 *
517
	 * @param  {integer} key Key code for the pressed key
518
	 * @param  {object} orig Original event
519
	 * @private
520
	 */
521
	_editor: function ( key, orig, hardEdit )
522
	{
523
		// If nothing focused, we can't take any action
524
		if (! this.s.lastFocus) {
525
			return;	
526
		}
527

528
		// DataTables draw event
529
		if (orig && orig.type === 'draw') {
530
			return;
531
		}
532

533
		var that = this;
534
		var dt = this.s.dt;
535
		var editor = this.c.editor;
536
		var editCell = this.s.lastFocus.cell;
537
		var namespace = this.s.namespace + 'e' + editorNamespaceCounter++;
538

539
		// Do nothing if there is already an inline edit in this cell
540
		if ( $('div.DTE', editCell.node()).length ) {
541
			return;
542
		}
543

544
		// Don't activate Editor on control key presses
545
		if ( key !== null && (
546
			(key >= 0x00 && key <= 0x09) ||
547
			key === 0x0b ||
548
			key === 0x0c ||
549
			(key >= 0x0e && key <= 0x1f) ||
550
			(key >= 0x70 && key <= 0x7b) ||
551
			(key >= 0x7f && key <= 0x9f)
552
		) ) {
553
			return;
554
		}
555

556
		if ( orig ) {
557
			orig.stopPropagation();
558

559
			// Return key should do nothing - for textareas it would empty the
560
			// contents
561
			if ( key === 13 ) {
562
				orig.preventDefault();
563
			}
564
		}
565

566
		var editInline = function () {
567
			var options = that._inlineOptions(editCell.index());
568

569
			editor
570
				.one( 'open'+namespace, function () {
571
					// Remove cancel open
572
					editor.off( 'cancelOpen'+namespace );
573

574
					// Excel style - select all text
575
					if ( ! hardEdit ) {
576
						$('div.DTE_Field_InputControl input, div.DTE_Field_InputControl textarea').select();
577
					}
578

579
					// Reduce the keys the Keys listens for
580
					dt.keys.enable( hardEdit ? 'tab-only' : 'navigation-only' );
581

582
					// On blur of the navigation submit
583
					dt.on( 'key-blur.editor', function (e, dt, cell) {
584
						if ( editor.displayed() && cell.node() === editCell.node() ) {
585
							editor.submit();
586
						}
587
					} );
588

589
					// Highlight the cell a different colour on full edit
590
					if ( hardEdit ) {
591
						$( dt.table().container() ).addClass('dtk-focus-alt');
592
					}
593

594
					// If the dev cancels the submit, we need to return focus
595
					editor.on( 'preSubmitCancelled'+namespace, function () {
596
						setTimeout( function () {
597
							that._focus( editCell, null, false );
598
						}, 50 );
599
					} );
600

601
					editor.on( 'submitUnsuccessful'+namespace, function () {
602
						that._focus( editCell, null, false );
603
					} );
604

605
					// Restore full key navigation on close
606
					editor.one( 'close'+namespace, function () {
607
						dt.keys.enable( true );
608
						dt.off( 'key-blur.editor' );
609
						editor.off( namespace );
610
						$( dt.table().container() ).removeClass('dtk-focus-alt');
611

612
						if (that.s.returnSubmit) {
613
							that.s.returnSubmit = false;
614
							that._emitEvent( 'key-return-submit', [dt, editCell] );
615
						}
616
					} );
617
				} )
618
				.one( 'cancelOpen'+namespace, function () {
619
					// `preOpen` can cancel the display of the form, so it
620
					// might be that the open event handler isn't needed
621
					editor.off( namespace );
622
				} )
623
				.inline(options.cell, options.field, options.options);
624
		};
625

626
		// Editor 1.7 listens for `return` on keyup, so if return is the trigger
627
		// key, we need to wait for `keyup` otherwise Editor would just submit
628
		// the content triggered by this keypress.
629
		if ( key === 13 ) {
630
			hardEdit = true;
631

632
			$(document).one( 'keyup', function () { // immediately removed
633
				editInline();
634
			} );
635
		}
636
		else {
637
			editInline();
638
		}
639
	},
640

641

642
	_inlineOptions: function (cellIdx)
643
	{
644
		if (this.c.editorOptions) {
645
			return this.c.editorOptions(cellIdx);
646
		}
647

648
		return {
649
			cell: cellIdx,
650
			field: undefined,
651
			options: undefined
652
		};
653
	},
654

655

656
	/**
657
	 * Emit an event on the DataTable for listeners
658
	 *
659
	 * @param  {string} name Event name
660
	 * @param  {array} args Event arguments
661
	 * @private
662
	 */
663
	_emitEvent: function ( name, args )
664
	{
665
		this.s.dt.iterator( 'table', function ( ctx, i ) {
666
			$(ctx.nTable).triggerHandler( name, args );
667
		} );
668
	},
669

670

671
	/**
672
	 * Focus on a particular cell, shifting the table's paging if required
673
	 *
674
	 * @param  {DataTables.Api|integer} row Can be given as an API instance that
675
	 *   contains the cell to focus or as an integer. As the latter it is the
676
	 *   visible row index (from the whole data set) - NOT the data index
677
	 * @param  {integer} [column] Not required if a cell is given as the first
678
	 *   parameter. Otherwise this is the column data index for the cell to
679
	 *   focus on
680
	 * @param {boolean} [shift=true] Should the viewport be moved to show cell
681
	 * @private
682
	 */
683
	_focus: function ( row, column, shift, originalEvent )
684
	{
685
		var that = this;
686
		var dt = this.s.dt;
687
		var pageInfo = dt.page.info();
688
		var lastFocus = this.s.lastFocus;
689

690
		if ( ! originalEvent) {
691
			originalEvent = null;
692
		}
693

694
		if ( ! this.s.enable ) {
695
			return;
696
		}
697

698
		if ( typeof row !== 'number' ) {
699
			// Its an API instance - check that there is actually a row
700
			if ( ! row.any() ) {
701
				return;
702
			}
703

704
			// Convert the cell to a row and column
705
			var index = row.index();
706
			column = index.column;
707
			row = dt
708
				.rows( { filter: 'applied', order: 'applied' } )
709
				.indexes()
710
				.indexOf( index.row );
711
			
712
			// Don't focus rows that were filtered out.
713
			if ( row < 0 ) {
714
				return;
715
			}
716

717
			// For server-side processing normalise the row by adding the start
718
			// point, since `rows().indexes()` includes only rows that are
719
			// available at the client-side
720
			if ( pageInfo.serverSide ) {
721
				row += pageInfo.start;
722
			}
723
		}
724

725
		// Is the row on the current page? If not, we need to redraw to show the
726
		// page
727
		if ( pageInfo.length !== -1 && (row < pageInfo.start || row >= pageInfo.start+pageInfo.length) ) {
728
			this.s.focusDraw = true;
729
			this.s.waitingForDraw = true;
730

731
			dt
732
				.one( 'draw', function () {
733
					that.s.focusDraw = false;
734
					that.s.waitingForDraw = false;
735
					that._focus( row, column, undefined, originalEvent );
736
				} )
737
				.page( Math.floor( row / pageInfo.length ) )
738
				.draw( false );
739

740
			return;
741
		}
742

743
		// In the available columns?
744
		if ( $.inArray( column, this._columns() ) === -1 ) {
745
			return;
746
		}
747

748
		// De-normalise the server-side processing row, so we select the row
749
		// in its displayed position
750
		if ( pageInfo.serverSide ) {
751
			row -= pageInfo.start;
752
		}
753

754
		// Get the cell from the current position - ignoring any cells which might
755
		// not have been rendered (therefore can't use `:eq()` selector).
756
		var cells = dt.cells( null, column, {search: 'applied', order: 'applied'} ).flatten();
757
		var cell = dt.cell( cells[ row ] );
758

759
		if ( lastFocus ) {
760
			// Don't trigger a refocus on the same cell
761
			if ( lastFocus.node === cell.node() ) {
762
				this._emitEvent( 'key-refocus', [ this.s.dt, cell, originalEvent || null ] );
763
				return;
764
			}
765

766
			// Otherwise blur the old focus
767
			this._blur();
768
		}
769

770
		// Clear focus from other tables
771
		this._removeOtherFocus();
772

773
		var node = $( cell.node() );
774
		node.addClass( this.c.className );
775

776
		this._updateFixedColumns(column);
777

778
		// Shift viewpoint and page to make cell visible
779
		if ( shift === undefined || shift === true ) {
780
			this._scroll( $(window), $(document.body), node, 'offset' );
781

782
			var bodyParent = dt.table().body().parentNode;
783
			if ( bodyParent !== dt.table().header().parentNode ) {
784
				var parent = $(bodyParent.parentNode);
785

786
				this._scroll( parent, parent, node, 'position' );
787
			}
788
		}
789

790
		// Event and finish
791
		this.s.lastFocus = {
792
			cell: cell,
793
			node: cell.node(),
794
			relative: {
795
				row: dt.rows( { page: 'current' } ).indexes().indexOf( cell.index().row ),
796
				column: cell.index().column
797
			}
798
		};
799

800
		this._emitEvent( 'key-focus', [ this.s.dt, cell, originalEvent || null ] );
801
		dt.state.save();
802
	},
803

804

805
	/**
806
	 * Handle key press
807
	 *
808
	 * @param  {object} e Event
809
	 * @private
810
	 */
811
	_key: function ( e )
812
	{
813
		// If we are waiting for a draw to happen from another key event, then
814
		// do nothing for this new key press.
815
		if ( this.s.waitingForDraw ) {
816
			e.preventDefault();
817
			return;
818
		}
819

820
		var enable = this.s.enable;
821
		this.s.returnSubmit = (enable === 'navigation-only' || enable === 'tab-only') && e.keyCode === 13
822
			? true
823
			: false;
824

825
		var navEnable = enable === true || enable === 'navigation-only';
826
		if ( ! enable ) {
827
			return;
828
		}
829

830
		if ( (e.keyCode === 0 || e.ctrlKey || e.metaKey || e.altKey) && !(e.ctrlKey && e.altKey) ) {
831
			return;
832
		}
833

834
		// If not focused, then there is no key action to take
835
		var lastFocus = this.s.lastFocus;
836
		if ( ! lastFocus ) {
837
			return;
838
		}
839

840
		// And the last focus still exists!
841
		if ( ! this.s.dt.cell(lastFocus.node).any() ) {
842
			this.s.lastFocus = null;
843
			return;
844
		}
845

846
		var that = this;
847
		var dt = this.s.dt;
848
		var scrolling = this.s.dt.settings()[0].oScroll.sY ? true : false;
849

850
		// If we are not listening for this key, do nothing
851
		if ( this.c.keys && $.inArray( e.keyCode, this.c.keys ) === -1 ) {
852
			return;
853
		}
854

855
		switch( e.keyCode ) {
856
			case 9: // tab
857
				// `enable` can be tab-only
858
				this._shift( e, e.shiftKey ? 'left' : 'right', true );
859
				break;
860

861
			case 27: // esc
862
				if ( this.c.blurable && enable === true ) {
863
					this._blur();
864
				}
865
				break;
866

867
			case 33: // page up (previous page)
868
			case 34: // page down (next page)
869
				if ( navEnable && !scrolling ) {
870
					e.preventDefault();
871

872
					dt
873
						.page( e.keyCode === 33 ? 'previous' : 'next' )
874
						.draw( false );
875
				}
876
				break;
877

878
			case 35: // end (end of current page)
879
			case 36: // home (start of current page)
880
				if ( navEnable ) {
881
					e.preventDefault();
882
					var indexes = dt.cells( {page: 'current'} ).indexes();
883
					var colIndexes = this._columns();
884

885
					this._focus( dt.cell(
886
						indexes[ e.keyCode === 35 ? indexes.length-1 : colIndexes[0] ]
887
					), null, true, e );
888
				}
889
				break;
890

891
			case 37: // left arrow
892
				if ( navEnable ) {
893
					this._shift( e, 'left' );
894
				}
895
				break;
896

897
			case 38: // up arrow
898
				if ( navEnable ) {
899
					this._shift( e, 'up' );
900
				}
901
				break;
902

903
			case 39: // right arrow
904
				if ( navEnable ) {
905
					this._shift( e, 'right' );
906
				}
907
				break;
908

909
			case 40: // down arrow
910
				if ( navEnable ) {
911
					this._shift( e, 'down' );
912
				}
913
				break;
914

915
			case 113: // F2 - Excel like hard edit
916
				if ( this.c.editor ) {
917
					this._editor(null, e, true);
918
					break;
919
				}
920
				// else fallthrough
921

922
			default:
923
				// Everything else - pass through only when fully enabled
924
				if ( enable === true ) {
925
					this._emitEvent( 'key', [ dt, e.keyCode, this.s.lastFocus.cell, e ] );
926
				}
927
				break;
928
		}
929
	},
930

931
	/**
932
	 * Remove focus from all tables other than this one
933
	 */
934
	_removeOtherFocus: function ()
935
	{
936
		var thisTable = this.s.dt.table().node();
937

938
		$.fn.dataTable.tables({api:true}).iterator('table', function (settings) {
939
			if (this.table().node() !== thisTable) {
940
				this.cell.blur();
941
			}
942
		});
943
	},
944

945
	/**
946
	 * Scroll a container to make a cell visible in it. This can be used for
947
	 * both DataTables scrolling and native window scrolling.
948
	 *
949
	 * @param  {jQuery} container Scrolling container
950
	 * @param  {jQuery} scroller  Item being scrolled
951
	 * @param  {jQuery} cell      Cell in the scroller
952
	 * @param  {string} posOff    `position` or `offset` - which to use for the
953
	 *   calculation. `offset` for the document, otherwise `position`
954
	 * @private
955
	 */
956
	_scroll: function ( container, scroller, cell, posOff )
957
	{
958
		var offset = cell[posOff]();
959
		var height = cell.outerHeight();
960
		var width = cell.outerWidth();
961

962
		var scrollTop = scroller.scrollTop();
963
		var scrollLeft = scroller.scrollLeft();
964
		var containerHeight = container.height();
965
		var containerWidth = container.width();
966

967
		// If Scroller is being used, the table can be `position: absolute` and that
968
		// needs to be taken account of in the offset. If no Scroller, this will be 0
969
		if ( posOff === 'position' ) {
970
			offset.top += parseInt( cell.closest('table').css('top'), 10 );
971
		}
972

973
		// Top correction
974
		if ( offset.top < scrollTop ) {
975
			scroller.scrollTop( offset.top );
976
		}
977

978
		// Left correction
979
		if ( offset.left < scrollLeft ) {
980
			scroller.scrollLeft( offset.left );
981
		}
982

983
		// Bottom correction
984
		if ( offset.top + height > scrollTop + containerHeight && height < containerHeight ) {
985
			scroller.scrollTop( offset.top + height - containerHeight );
986
		}
987

988
		// Right correction
989
		if ( offset.left + width > scrollLeft + containerWidth && width < containerWidth ) {
990
			scroller.scrollLeft( offset.left + width - containerWidth );
991
		}
992
	},
993

994

995
	/**
996
	 * Calculate a single offset movement in the table - up, down, left and
997
	 * right and then perform the focus if possible
998
	 *
999
	 * @param  {object}  e           Event object
1000
	 * @param  {string}  direction   Movement direction
1001
	 * @param  {boolean} keyBlurable `true` if the key press can result in the
1002
	 *   table being blurred. This is so arrow keys won't blur the table, but
1003
	 *   tab will.
1004
	 * @private
1005
	 */
1006
	_shift: function ( e, direction, keyBlurable )
1007
	{
1008
		var that      = this;
1009
		var dt        = this.s.dt;
1010
		var pageInfo  = dt.page.info();
1011
		var rows      = pageInfo.recordsDisplay;
1012
		var columns   = this._columns();
1013
		var last      = this.s.lastFocus;
1014
		if ( ! last ) {
1015
			return;
1016
		}
1017
	
1018
		var currentCell  = last.cell;
1019
		if ( ! currentCell ) {
1020
			return;
1021
		}
1022

1023
		var currRow = dt
1024
			.rows( { filter: 'applied', order: 'applied' } )
1025
			.indexes()
1026
			.indexOf( currentCell.index().row );
1027

1028
		// When server-side processing, `rows().indexes()` only gives the rows
1029
		// that are available at the client-side, so we need to normalise the
1030
		// row's current position by the display start point
1031
		if ( pageInfo.serverSide ) {
1032
			currRow += pageInfo.start;
1033
		}
1034

1035
		var currCol = dt
1036
			.columns( columns )
1037
			.indexes()
1038
			.indexOf( currentCell.index().column );
1039

1040
		var
1041
			row = currRow,
1042
			column = columns[ currCol ]; // row is the display, column is an index
1043

1044
		// If the direction is rtl then the logic needs to be inverted from this point forwards
1045
		if($(dt.table().node()).css('direction') === 'rtl') {
1046
			if(direction === 'right') {
1047
				direction = 'left';
1048
			}
1049
			else if(direction === 'left'){
1050
				direction = 'right';
1051
			}
1052
		}
1053

1054
		if ( direction === 'right' ) {
1055
			if ( currCol >= columns.length - 1 ) {
1056
				row++;
1057
				column = columns[0];
1058
			}
1059
			else {
1060
				column = columns[ currCol+1 ];
1061
			}
1062
		}
1063
		else if ( direction === 'left' ) {
1064
			if ( currCol === 0 ) {
1065
				row--;
1066
				column = columns[ columns.length - 1 ];
1067
			}
1068
			else {
1069
				column = columns[ currCol-1 ];
1070
			}
1071
		}
1072
		else if ( direction === 'up' ) {
1073
			row--;
1074
		}
1075
		else if ( direction === 'down' ) {
1076
			row++;
1077
		}
1078

1079
		if ( row >= 0 && row < rows && $.inArray( column, columns ) !== -1 ) {
1080
			if (e) {
1081
				e.preventDefault();
1082
			}
1083

1084
			this._focus( row, column, true, e );
1085
		}
1086
		else if ( ! keyBlurable || ! this.c.blurable ) {
1087
			// No new focus, but if the table isn't blurable, then don't loose
1088
			// focus
1089
			if (e) {
1090
				e.preventDefault();
1091
			}
1092
		}
1093
		else {
1094
			this._blur();
1095
		}
1096
	},
1097

1098

1099
	/**
1100
	 * Create and insert a hidden input element that can receive focus on behalf
1101
	 * of the table
1102
	 *
1103
	 * @private
1104
	 */
1105
	_tabInput: function ()
1106
	{
1107
		var that = this;
1108
		var dt = this.s.dt;
1109
		var tabIndex = this.c.tabIndex !== null ?
1110
			this.c.tabIndex :
1111
			dt.settings()[0].iTabIndex;
1112

1113
		if ( tabIndex == -1 ) {
1114
			return;
1115
		}
1116

1117
		// Only create the input element once on first class
1118
		if (! this.s.tabInput) {
1119
			var div = $('<div><input type="text" tabindex="'+tabIndex+'"/></div>')
1120
				.css( {
1121
					position: 'absolute',
1122
					height: 1,
1123
					width: 0,
1124
					overflow: 'hidden'
1125
				} );
1126

1127
			div.children().on( 'focus', function (e) {
1128
				var cell = dt.cell(':eq(0)', that._columns(), {page: 'current'});
1129
	
1130
				if ( cell.any() ) {
1131
					that._focus( cell, null, true, e );
1132
				}
1133
			} );
1134

1135
			this.s.tabInput = div;
1136
		}
1137

1138
		// Insert the input element into the first cell in the table's body
1139
		var cell = this.s.dt.cell(':eq(0)', '0:visible', {page: 'current', order: 'current'}).node();
1140
		if (cell) {
1141
			$(cell).prepend(this.s.tabInput);
1142
		}
1143
	},
1144

1145
	/**
1146
	 * Update fixed columns if they are enabled and if the cell we are
1147
	 * focusing is inside a fixed column
1148
	 * @param  {integer} column Index of the column being changed
1149
	 * @private
1150
	 */
1151
	_updateFixedColumns: function( column )
1152
	{
1153
		var dt = this.s.dt;
1154
		var settings = dt.settings()[0];
1155

1156
		if ( settings._oFixedColumns ) {
1157
			var leftCols = settings._oFixedColumns.s.iLeftColumns;
1158
			var rightCols = settings.aoColumns.length - settings._oFixedColumns.s.iRightColumns;
1159

1160
			if (column < leftCols || column >= rightCols) {
1161
				dt.fixedColumns().update();
1162
			}
1163
		}
1164
	}
1165
} );
1166

1167

1168
/**
1169
 * KeyTable default settings for initialisation
1170
 *
1171
 * @namespace
1172
 * @name KeyTable.defaults
1173
 * @static
1174
 */
1175
KeyTable.defaults = {
1176
	/**
1177
	 * Can focus be removed from the table
1178
	 * @type {Boolean}
1179
	 */
1180
	blurable: true,
1181

1182
	/**
1183
	 * Class to give to the focused cell
1184
	 * @type {String}
1185
	 */
1186
	className: 'focus',
1187

1188
	/**
1189
	 * Enable or disable clipboard support
1190
	 * @type {Boolean}
1191
	 */
1192
	clipboard: true,
1193

1194
	/**
1195
	 * Orthogonal data that should be copied to clipboard
1196
	 * @type {string}
1197
	 */
1198
	clipboardOrthogonal: 'display',
1199

1200
	/**
1201
	 * Columns that can be focused. This is automatically merged with the
1202
	 * visible columns as only visible columns can gain focus.
1203
	 * @type {String}
1204
	 */
1205
	columns: '', // all
1206

1207
	/**
1208
	 * Editor instance to automatically perform Excel like navigation
1209
	 * @type {Editor}
1210
	 */
1211
	editor: null,
1212

1213
	/**
1214
	 * Trigger editing immediately on focus
1215
	 * @type {boolean}
1216
	 */
1217
	editOnFocus: false,
1218

1219
	/**
1220
	 * Options to pass to Editor's inline method
1221
	 * @type {function}
1222
	 */
1223
	editorOptions: null,
1224

1225
	/**
1226
	 * Select a cell to automatically select on start up. `null` for no
1227
	 * automatic selection
1228
	 * @type {cell-selector}
1229
	 */
1230
	focus: null,
1231

1232
	/**
1233
	 * Array of keys to listen for
1234
	 * @type {null|array}
1235
	 */
1236
	keys: null,
1237

1238
	/**
1239
	 * Tab index for where the table should sit in the document's tab flow
1240
	 * @type {integer|null}
1241
	 */
1242
	tabIndex: null
1243
};
1244

1245

1246

1247
KeyTable.version = "2.6.4";
1248

1249

1250
$.fn.dataTable.KeyTable = KeyTable;
1251
$.fn.DataTable.KeyTable = KeyTable;
1252

1253

1254
DataTable.Api.register( 'cell.blur()', function () {
1255
	return this.iterator( 'table', function (ctx) {
1256
		if ( ctx.keytable ) {
1257
			ctx.keytable.blur();
1258
		}
1259
	} );
1260
} );
1261

1262
DataTable.Api.register( 'cell().focus()', function () {
1263
	return this.iterator( 'cell', function (ctx, row, column) {
1264
		if ( ctx.keytable ) {
1265
			ctx.keytable.focus( row, column );
1266
		}
1267
	} );
1268
} );
1269

1270
DataTable.Api.register( 'keys.disable()', function () {
1271
	return this.iterator( 'table', function (ctx) {
1272
		if ( ctx.keytable ) {
1273
			ctx.keytable.enable( false );
1274
		}
1275
	} );
1276
} );
1277

1278
DataTable.Api.register( 'keys.enable()', function ( opts ) {
1279
	return this.iterator( 'table', function (ctx) {
1280
		if ( ctx.keytable ) {
1281
			ctx.keytable.enable( opts === undefined ? true : opts );
1282
		}
1283
	} );
1284
} );
1285

1286
DataTable.Api.register( 'keys.enabled()', function ( opts ) {
1287
	var ctx = this.context;
1288

1289
	if (ctx.length) {
1290
		return ctx[0].keytable
1291
			? ctx[0].keytable.enabled()
1292
			: false;
1293
	}
1294

1295
	return false;
1296
} );
1297

1298
DataTable.Api.register( 'keys.move()', function ( dir ) {
1299
	return this.iterator( 'table', function (ctx) {
1300
		if ( ctx.keytable ) {
1301
			ctx.keytable._shift( null, dir, false );
1302
		}
1303
	} );
1304
} );
1305

1306
// Cell selector
1307
DataTable.ext.selector.cell.push( function ( settings, opts, cells ) {
1308
	var focused = opts.focused;
1309
	var kt = settings.keytable;
1310
	var out = [];
1311

1312
	if ( ! kt || focused === undefined ) {
1313
		return cells;
1314
	}
1315

1316
	for ( var i=0, ien=cells.length ; i<ien ; i++ ) {
1317
		if ( (focused === true &&  kt.focused( cells[i] ) ) ||
1318
			 (focused === false && ! kt.focused( cells[i] ) )
1319
		) {
1320
			out.push( cells[i] );
1321
		}
1322
	}
1323

1324
	return out;
1325
} );
1326

1327

1328
// Attach a listener to the document which listens for DataTables initialisation
1329
// events so we can automatically initialise
1330
$(document).on( 'preInit.dt.dtk', function (e, settings, json) {
1331
	if ( e.namespace !== 'dt' ) {
1332
		return;
1333
	}
1334

1335
	var init = settings.oInit.keys;
1336
	var defaults = DataTable.defaults.keys;
1337

1338
	if ( init || defaults ) {
1339
		var opts = $.extend( {}, defaults, init );
1340

1341
		if ( init !== false ) {
1342
			new KeyTable( settings, opts  );
1343
		}
1344
	}
1345
} );
1346

1347

1348
return KeyTable;
1349
}));
1350

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.