-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathvaadin-grid-keyboard-navigation-mixin.js
1073 lines (951 loc) · 35.6 KB
/
vaadin-grid-keyboard-navigation-mixin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright (c) 2016 - 2022 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
import { addValueToAttribute, removeValueFromAttribute } from '@vaadin/component-base/src/dom-utils.js';
import { isKeyboardActive } from '@vaadin/component-base/src/focus-utils.js';
/**
* @polymerMixin
*/
export const KeyboardNavigationMixin = (superClass) =>
class KeyboardNavigationMixin extends superClass {
static get properties() {
return {
/** @private */
_headerFocusable: {
type: Object,
observer: '_focusableChanged',
},
/**
* @type {!HTMLElement | undefined}
* @protected
*/
_itemsFocusable: {
type: Object,
observer: '_focusableChanged',
},
/** @private */
_footerFocusable: {
type: Object,
observer: '_focusableChanged',
},
/** @private */
_navigatingIsHidden: Boolean,
/**
* @type {number}
* @protected
*/
_focusedItemIndex: {
type: Number,
value: 0,
},
/** @private */
_focusedColumnOrder: Number,
/** @private */
_focusedCell: {
type: Object,
observer: '_focusedCellChanged',
},
/**
* Indicates whether the grid is currently in interaction mode.
* In interaction mode the user is currently interacting with a control,
* such as an input or a select, within a cell.
* In interaction mode keyboard navigation between cells is disabled.
* Interaction mode also prevents the focus target cell of that section of
* the grid from receiving focus, allowing the user to switch focus to
* controls in adjacent cells, rather than focussing the outer cell
* itself.
* @type {boolean}
* @private
*/
interacting: {
type: Boolean,
value: false,
reflectToAttribute: true,
readOnly: true,
observer: '_interactingChanged',
},
};
}
/** @protected */
ready() {
super.ready();
if (this._ios || this._android) {
// Disable keyboard navigation on mobile devices
return;
}
this.addEventListener('keydown', this._onKeyDown);
this.addEventListener('keyup', this._onKeyUp);
this.addEventListener('focusin', this._onFocusIn);
this.addEventListener('focusout', this._onFocusOut);
// When focus goes from cell to another cell, focusin/focusout events do
// not escape the grid’s shadowRoot, thus listening inside the shadowRoot.
this.$.table.addEventListener('focusin', this._onContentFocusIn.bind(this));
this.addEventListener('mousedown', () => {
this.toggleAttribute('navigating', false);
this._isMousedown = true;
// Reset stored order when moving focus with mouse.
this._focusedColumnOrder = undefined;
});
this.addEventListener('mouseup', () => {
this._isMousedown = false;
});
}
/** @private */
get __rowFocusMode() {
return (
this.__isRow(this._itemsFocusable) || this.__isRow(this._headerFocusable) || this.__isRow(this._footerFocusable)
);
}
set __rowFocusMode(value) {
['_itemsFocusable', '_footerFocusable', '_headerFocusable'].forEach((prop) => {
const focusable = this[prop];
if (value) {
const parent = focusable && focusable.parentElement;
if (this.__isCell(focusable)) {
// Cell itself focusable (default)
this[prop] = parent;
} else if (this.__isCell(parent)) {
// Focus button mode is enabled for the column,
// button element inside the cell is focusable.
this[prop] = parent.parentElement;
}
} else if (!value && this.__isRow(focusable)) {
const cell = focusable.firstElementChild;
this[prop] = cell._focusButton || cell;
}
});
}
/** @private */
_focusableChanged(focusable, oldFocusable) {
if (oldFocusable) {
oldFocusable.setAttribute('tabindex', '-1');
}
if (focusable) {
this._updateGridSectionFocusTarget(focusable);
}
}
/** @private */
_focusedCellChanged(focusedCell, oldFocusedCell) {
if (oldFocusedCell) {
removeValueFromAttribute(oldFocusedCell, 'part', 'focused-cell');
}
if (focusedCell) {
addValueToAttribute(focusedCell, 'part', 'focused-cell');
}
}
/** @private */
_interactingChanged() {
// Update focus targets when entering / exiting interaction mode
this._updateGridSectionFocusTarget(this._headerFocusable);
this._updateGridSectionFocusTarget(this._itemsFocusable);
this._updateGridSectionFocusTarget(this._footerFocusable);
}
/**
* Since the focused cell/row state is stored as an element reference, the reference may get
* out of sync when the virtual indexes for elements update due to effective size change.
* This function updates the reference to the correct element after a possible index change.
* @private
*/
__updateItemsFocusable() {
if (!this._itemsFocusable) {
return;
}
const wasFocused = this.shadowRoot.activeElement === this._itemsFocusable;
this._getVisibleRows().forEach((row) => {
if (row.index === this._focusedItemIndex) {
if (this.__rowFocusMode) {
// Row focus mode
this._itemsFocusable = row;
} else {
// Cell focus mode
let parent = this._itemsFocusable.parentElement;
let cell = this._itemsFocusable;
if (parent) {
// Focus button mode is enabled for the column,
// button element inside the cell is focusable.
if (this.__isCell(parent)) {
cell = parent;
parent = parent.parentElement;
}
const cellIndex = [...parent.children].indexOf(cell);
this._itemsFocusable = this.__getFocusable(row, row.children[cellIndex]);
}
}
}
});
if (wasFocused) {
this._itemsFocusable.focus();
}
}
/**
* @param {!KeyboardEvent} e
* @protected
*/
_onKeyDown(e) {
const key = e.key;
let keyGroup;
switch (key) {
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight':
case 'PageUp':
case 'PageDown':
case 'Home':
case 'End':
keyGroup = 'Navigation';
break;
case 'Enter':
case 'Escape':
case 'F2':
keyGroup = 'Interaction';
break;
case 'Tab':
keyGroup = 'Tab';
break;
case ' ':
keyGroup = 'Space';
break;
default:
break;
}
this._detectInteracting(e);
if (this.interacting && keyGroup !== 'Interaction') {
// When in the interacting mode, only the “Interaction” keys are handled.
keyGroup = undefined;
}
if (keyGroup) {
this[`_on${keyGroup}KeyDown`](e, key);
}
}
/** @private */
_ensureScrolledToIndex(index) {
const targetRowInDom = [...this.$.items.children].find((child) => child.index === index);
if (!targetRowInDom) {
this.scrollToIndex(index);
} else {
this.__scrollIntoViewport(index);
}
}
/** @private */
__isRowExpandable(row) {
if (this.itemHasChildrenPath) {
const item = row._item;
return item && this.get(this.itemHasChildrenPath, item) && !this._isExpanded(item);
}
}
/** @private */
__isRowCollapsible(row) {
return this._isExpanded(row._item);
}
/** @private */
__isDetailsCell(element) {
return element.matches('[part~="details-cell"]');
}
/** @private */
__isCell(element) {
return element instanceof HTMLTableCellElement;
}
/** @private */
__isRow(element) {
return element instanceof HTMLTableRowElement;
}
/** @private */
__getIndexOfChildElement(el) {
return Array.prototype.indexOf.call(el.parentNode.children, el);
}
/** @private */
_onNavigationKeyDown(e, key) {
e.preventDefault();
const visibleItemsCount = this._lastVisibleIndex - this._firstVisibleIndex - 1;
// Handle keyboard interaction as defined in:
// https://w3c.github.io/aria-practices/#keyboard-interaction-24
let dx = 0,
dy = 0;
switch (key) {
case 'ArrowRight':
dx = this.__isRTL ? -1 : 1;
break;
case 'ArrowLeft':
dx = this.__isRTL ? 1 : -1;
break;
case 'Home':
if (this.__rowFocusMode) {
// "If focus is on a row, moves focus to the first row. If focus is in the first row, focus does not move."
dy = -Infinity;
} else if (e.ctrlKey) {
// "If focus is on a cell, moves focus to the first cell in the column. If focus is in the first row, focus does not move."
dy = -Infinity;
} else {
// "If focus is on a cell, moves focus to the first cell in the row. If focus is in the first cell of the row, focus does not move."
dx = -Infinity;
}
break;
case 'End':
if (this.__rowFocusMode) {
// "If focus is on a row, moves focus to the last row. If focus is in the last row, focus does not move."
dy = Infinity;
} else if (e.ctrlKey) {
// "If focus is on a cell, moves focus to the last cell in the column. If focus is in the last row, focus does not move."
dy = Infinity;
} else {
// "If focus is on a cell, moves focus to the last cell in the row. If focus is in the last cell of the row, focus does not move."
dx = Infinity;
}
break;
case 'ArrowDown':
dy = 1;
break;
case 'ArrowUp':
dy = -1;
break;
case 'PageDown':
dy = visibleItemsCount;
break;
case 'PageUp':
dy = -visibleItemsCount;
break;
default:
break;
}
const activeRow = e.composedPath().find((el) => this.__isRow(el));
const activeCell = e.composedPath().find((el) => this.__isCell(el));
if ((this.__rowFocusMode && !activeRow) || (!this.__rowFocusMode && !activeCell)) {
// When using a screen reader, it's possible that neither a cell nor a row is focused.
return;
}
const forwardsKey = this.__isRTL ? 'ArrowLeft' : 'ArrowRight';
const backwardsKey = this.__isRTL ? 'ArrowRight' : 'ArrowLeft';
if (key === forwardsKey) {
// "Right Arrow:"
if (this.__rowFocusMode) {
// In row focus mode
if (this.__isRowExpandable(activeRow)) {
// "If focus is on a collapsed row, expands the row."
this.expandItem(activeRow._item);
return;
}
// "If focus is on an expanded row or is on a row that does not have child rows,
// moves focus to the first cell in the row."
this.__rowFocusMode = false;
this._onCellNavigation(activeRow.firstElementChild, 0, 0);
return;
}
} else if (key === backwardsKey) {
// "Left Arrow:"
if (this.__rowFocusMode) {
// In row focus mode
if (this.__isRowCollapsible(activeRow)) {
// "If focus is on an expanded row, collapses the row."
this.collapseItem(activeRow._item);
return;
}
} else {
// In cell focus mode
const activeRowCells = [...activeRow.children].sort((a, b) => a._order - b._order);
if (activeCell === activeRowCells[0] || this.__isDetailsCell(activeCell)) {
// "If focus is on the first cell in a row and row focus is supported, moves focus to the row."
this.__rowFocusMode = true;
this._onRowNavigation(activeRow, 0);
return;
}
}
}
// Navigate
if (this.__rowFocusMode) {
// Navigate the rows
this._onRowNavigation(activeRow, dy);
} else {
// Navigate the cells
this._onCellNavigation(activeCell, dx, dy);
}
}
/**
* Focuses the target row after navigating by the given dy offset.
* If the row is not in the viewport, it is first scrolled to.
* @private
*/
_onRowNavigation(activeRow, dy) {
const { dstRow } = this.__navigateRows(dy, activeRow);
if (dstRow) {
dstRow.focus();
}
}
/** @private */
__getIndexInGroup(row, bodyFallbackIndex) {
const rowGroup = row.parentNode;
// Body rows have index property, otherwise DOM child index of the row is used.
if (rowGroup === this.$.items) {
return bodyFallbackIndex !== undefined ? bodyFallbackIndex : row.index;
}
return this.__getIndexOfChildElement(row);
}
/**
* Returns the target row after navigating by the given dy offset.
* Also returns information whether the details cell should be the target on the target row.
* If the row is not in the viewport, it is first scrolled to.
* @private
*/
__navigateRows(dy, activeRow, activeCell) {
const currentRowIndex = this.__getIndexInGroup(activeRow, this._focusedItemIndex);
const activeRowGroup = activeRow.parentNode;
const maxRowIndex = (activeRowGroup === this.$.items ? this._effectiveSize : activeRowGroup.children.length) - 1;
// Index of the destination row
let dstRowIndex = Math.max(0, Math.min(currentRowIndex + dy, maxRowIndex));
if (activeRowGroup !== this.$.items) {
// Navigating header/footer rows
// Header and footer could have hidden rows, e. g., if none of the columns
// or groups on the given column tree level define template. Skip them
// in vertical keyboard navigation.
if (dstRowIndex > currentRowIndex) {
while (dstRowIndex < maxRowIndex && activeRowGroup.children[dstRowIndex].hidden) {
dstRowIndex += 1;
}
} else if (dstRowIndex < currentRowIndex) {
while (dstRowIndex > 0 && activeRowGroup.children[dstRowIndex].hidden) {
dstRowIndex -= 1;
}
}
this.toggleAttribute('navigating', true);
return { dstRow: activeRowGroup.children[dstRowIndex] };
}
// Navigating body rows
let dstIsRowDetails = false;
if (activeCell) {
const isRowDetails = this.__isDetailsCell(activeCell);
// Row details navigation logic
if (activeRowGroup === this.$.items) {
const item = activeRow._item;
const dstItem = this._cache.getItemForIndex(dstRowIndex);
// Should we navigate to row details?
if (isRowDetails) {
dstIsRowDetails = dy === 0;
} else {
dstIsRowDetails =
(dy === 1 && this._isDetailsOpened(item)) ||
(dy === -1 && dstRowIndex !== currentRowIndex && this._isDetailsOpened(dstItem));
}
// Should we navigate between details and regular cells of the same row?
if (dstIsRowDetails !== isRowDetails && ((dy === 1 && dstIsRowDetails) || (dy === -1 && !dstIsRowDetails))) {
dstRowIndex = currentRowIndex;
}
}
}
// Ensure correct vertical scroll position, destination row is visible
this._ensureScrolledToIndex(dstRowIndex);
// When scrolling with repeated keydown, sometimes FocusEvent listeners
// are too late to update _focusedItemIndex. Ensure next keydown
// listener invocation gets updated _focusedItemIndex value.
this._focusedItemIndex = dstRowIndex;
// This has to be set after scrolling, otherwise it can be removed by
// `_preventScrollerRotatingCellFocus(row, index)` during scrolling.
this.toggleAttribute('navigating', true);
return {
dstRow: [...activeRowGroup.children].find((el) => !el.hidden && el.index === dstRowIndex),
dstIsRowDetails,
};
}
/**
* Focuses the target cell after navigating by the given dx and dy offset.
* If the cell is not in the viewport, it is first scrolled to.
* @private
*/
_onCellNavigation(activeCell, dx, dy) {
const activeRow = activeCell.parentNode;
const { dstRow, dstIsRowDetails } = this.__navigateRows(dy, activeRow, activeCell);
if (!dstRow) {
return;
}
const columnIndex = this.__getIndexOfChildElement(activeCell);
const isCurrentCellRowDetails = this.__isDetailsCell(activeCell);
const activeRowGroup = activeRow.parentNode;
const currentRowIndex = this.__getIndexInGroup(activeRow, this._focusedItemIndex);
// _focusedColumnOrder is memoized — this is to ensure predictable
// navigation when entering and leaving detail and column group cells.
if (this._focusedColumnOrder === undefined) {
if (isCurrentCellRowDetails) {
this._focusedColumnOrder = 0;
} else {
this._focusedColumnOrder = this._getColumns(activeRowGroup, currentRowIndex).filter((c) => !c.hidden)[
columnIndex
]._order;
}
}
if (dstIsRowDetails) {
// Focusing a row details cell on the destination row
const dstCell = [...dstRow.children].find((el) => this.__isDetailsCell(el));
dstCell.focus();
} else {
// Focusing a regular cell on the destination row
// Find orderedColumnIndex — the index of order closest matching the
// original _focusedColumnOrder in the sorted array of orders
// of the visible columns on the destination row.
const dstRowIndex = this.__getIndexInGroup(dstRow, this._focusedItemIndex);
const dstColumns = this._getColumns(activeRowGroup, dstRowIndex).filter((c) => !c.hidden);
const dstSortedColumnOrders = dstColumns.map((c) => c._order).sort((b, a) => b - a);
const maxOrderedColumnIndex = dstSortedColumnOrders.length - 1;
const orderedColumnIndex = dstSortedColumnOrders.indexOf(
dstSortedColumnOrders
.slice(0)
.sort((b, a) => Math.abs(b - this._focusedColumnOrder) - Math.abs(a - this._focusedColumnOrder))[0],
);
// Index of the destination column order
const dstOrderedColumnIndex =
dy === 0 && isCurrentCellRowDetails
? orderedColumnIndex
: Math.max(0, Math.min(orderedColumnIndex + dx, maxOrderedColumnIndex));
if (dstOrderedColumnIndex !== orderedColumnIndex) {
// Horizontal movement invalidates stored _focusedColumnOrder
this._focusedColumnOrder = undefined;
}
const columnIndexByOrder = dstColumns.reduce((acc, col, i) => {
acc[col._order] = i;
return acc;
}, {});
const dstColumnIndex = columnIndexByOrder[dstSortedColumnOrders[dstOrderedColumnIndex]];
const dstCell = dstRow.children[dstColumnIndex];
this._scrollHorizontallyToCell(dstCell);
dstCell.focus();
}
}
/** @private */
_onInteractionKeyDown(e, key) {
const localTarget = e.composedPath()[0];
const localTargetIsTextInput =
localTarget.localName === 'input' &&
!/^(button|checkbox|color|file|image|radio|range|reset|submit)$/i.test(localTarget.type);
let wantInteracting;
switch (key) {
case 'Enter':
wantInteracting = this.interacting ? !localTargetIsTextInput : true;
break;
case 'Escape':
wantInteracting = false;
break;
case 'F2':
wantInteracting = !this.interacting;
break;
default:
break;
}
const { cell } = this._getGridEventLocation(e);
if (this.interacting !== wantInteracting && cell !== null) {
if (wantInteracting) {
const focusTarget =
cell._content.querySelector('[focus-target]') ||
// If a child element hasn't been explicitly marked as a focus target,
// fall back to any focusable element inside the cell.
[...cell._content.querySelectorAll('*')].find((node) => this._isFocusable(node));
if (focusTarget) {
e.preventDefault();
focusTarget.focus();
this._setInteracting(true);
this.toggleAttribute('navigating', false);
}
} else {
e.preventDefault();
this._focusedColumnOrder = undefined;
cell.focus();
this._setInteracting(false);
this.toggleAttribute('navigating', true);
}
}
if (key === 'Escape') {
this._hideTooltip(true);
}
}
/** @private */
_predictFocusStepTarget(srcElement, step) {
const tabOrder = [
this.$.table,
this._headerFocusable,
this._itemsFocusable,
this._footerFocusable,
this.$.focusexit,
];
let index = tabOrder.indexOf(srcElement);
index += step;
while (index >= 0 && index <= tabOrder.length - 1) {
let rowElement = tabOrder[index];
if (rowElement && !this.__rowFocusMode) {
rowElement = tabOrder[index].parentNode;
}
if (!rowElement || rowElement.hidden) {
index += step;
} else {
break;
}
}
let focusStepTarget = tabOrder[index];
// If the target focusable is tied to a column that is not visible,
// find the first visible column and update the target in order to
// prevent scrolling to the start of the row.
if (focusStepTarget && focusStepTarget._column && !this.__isColumnInViewport(focusStepTarget._column)) {
const firstVisibleColumn = this._getColumnsInOrder().find((column) => this.__isColumnInViewport(column));
if (firstVisibleColumn) {
if (focusStepTarget === this._headerFocusable) {
focusStepTarget = firstVisibleColumn._headerCell;
} else if (focusStepTarget === this._itemsFocusable) {
const rowIndex = focusStepTarget._column._cells.indexOf(focusStepTarget);
focusStepTarget = firstVisibleColumn._cells[rowIndex];
} else if (focusStepTarget === this._footerFocusable) {
focusStepTarget = firstVisibleColumn._footerCell;
}
}
}
return focusStepTarget;
}
/**
* Returns true if the given column is horizontally inside the viewport.
* @private
*/
__isColumnInViewport(column) {
if (column.frozen || column.frozenToEnd) {
// Assume frozen columns to always be inside the viewport
return true;
}
return (
column._sizerCell.offsetLeft + column._sizerCell.offsetWidth >= this._scrollLeft &&
column._sizerCell.offsetLeft <= this._scrollLeft + this.clientWidth
);
}
/** @private */
_onTabKeyDown(e) {
const focusTarget = this._predictFocusStepTarget(e.composedPath()[0], e.shiftKey ? -1 : 1);
// Can be undefined if grid has tabindex
if (!focusTarget) {
return;
}
// Prevent focus-trap logic from intercepting the event.
e.stopPropagation();
if (focusTarget === this.$.table) {
// The focus is about to exit the grid to the top.
this.$.table.focus();
} else if (focusTarget === this.$.focusexit) {
// The focus is about to exit the grid to the bottom.
this.$.focusexit.focus();
} else if (focusTarget === this._itemsFocusable) {
let itemsFocusTarget = focusTarget;
const targetRow = this.__isRow(focusTarget) ? focusTarget : focusTarget.parentNode;
this._ensureScrolledToIndex(this._focusedItemIndex);
if (targetRow.index !== this._focusedItemIndex && this.__isCell(focusTarget)) {
// The target row, which is about to be focused next, has been
// assigned with a new index since last focus, probably because of
// scrolling. Focus the row for the stored focused item index instead.
const columnIndex = Array.from(targetRow.children).indexOf(this._itemsFocusable);
const focusedItemRow = Array.from(this.$.items.children).find(
(row) => !row.hidden && row.index === this._focusedItemIndex,
);
if (focusedItemRow) {
itemsFocusTarget = focusedItemRow.children[columnIndex];
}
}
e.preventDefault();
itemsFocusTarget.focus();
} else {
e.preventDefault();
focusTarget.focus();
}
this.toggleAttribute('navigating', true);
}
/** @private */
_onSpaceKeyDown(e) {
e.preventDefault();
const element = e.composedPath()[0];
const isRow = this.__isRow(element);
if (isRow || !element._content || !element._content.firstElementChild) {
this.dispatchEvent(
new CustomEvent(isRow ? 'row-activate' : 'cell-activate', {
detail: {
model: this.__getRowModel(isRow ? element : element.parentElement),
},
}),
);
}
}
/** @private */
_onKeyUp(e) {
if (!/^( |SpaceBar)$/.test(e.key) || this.interacting) {
return;
}
e.preventDefault();
const cell = e.composedPath()[0];
if (cell._content && cell._content.firstElementChild) {
const wasNavigating = this.hasAttribute('navigating');
cell._content.firstElementChild.dispatchEvent(
new MouseEvent('click', {
shiftKey: e.shiftKey,
bubbles: true,
composed: true,
cancelable: true,
}),
);
this.toggleAttribute('navigating', wasNavigating);
}
}
/**
* @param {!FocusEvent} e
* @protected
*/
_onFocusIn(e) {
if (!this._isMousedown) {
this.toggleAttribute('navigating', true);
}
const rootTarget = e.composedPath()[0];
if (rootTarget === this.$.table || rootTarget === this.$.focusexit) {
// The focus enters the top (bottom) of the grid, meaning that user has
// tabbed (shift-tabbed) into the grid. Move the focus to
// the first (the last) focusable.
this._predictFocusStepTarget(rootTarget, rootTarget === this.$.table ? 1 : -1).focus();
this._setInteracting(false);
} else {
this._detectInteracting(e);
}
}
/**
* @param {!FocusEvent} e
* @protected
*/
_onFocusOut(e) {
this.toggleAttribute('navigating', false);
this._detectInteracting(e);
this._hideTooltip();
this._focusedCell = null;
}
/** @private */
_onContentFocusIn(e) {
const { section, cell, row } = this._getGridEventLocation(e);
if (!cell && !this.__rowFocusMode) {
return;
}
this._detectInteracting(e);
if (section && (cell || row)) {
this._activeRowGroup = section;
if (this.$.header === section) {
this._headerFocusable = this.__getFocusable(row, cell);
} else if (this.$.items === section) {
this._itemsFocusable = this.__getFocusable(row, cell);
} else if (this.$.footer === section) {
this._footerFocusable = this.__getFocusable(row, cell);
}
if (cell) {
// Fire a public event for cell.
const context = this.getEventContext(e);
cell.dispatchEvent(new CustomEvent('cell-focus', { bubbles: true, composed: true, detail: { context } }));
this._focusedCell = cell._focusButton || cell;
if (isKeyboardActive() && e.target === cell) {
this._showTooltip(e);
}
} else {
this._focusedCell = null;
}
}
this._detectFocusedItemIndex(e);
}
/**
* Get the focusable element depending on the current focus mode.
* It can be a row, a cell, or a focusable div inside a cell.
*
* @param {HTMLElement} row
* @param {HTMLElement} cell
* @return {HTMLElement}
* @private
*/
__getFocusable(row, cell) {
return this.__rowFocusMode ? row : cell._focusButton || cell;
}
/**
* Enables interaction mode if a cells descendant receives focus or keyboard
* input. Disables it if the event is not related to cell content.
* @param {!KeyboardEvent|!FocusEvent} e
* @private
*/
_detectInteracting(e) {
const isInteracting = e.composedPath().some((el) => el.localName === 'vaadin-grid-cell-content');
this._setInteracting(isInteracting);
this.__updateHorizontalScrollPosition();
}
/** @private */
_detectFocusedItemIndex(e) {
const { section, row } = this._getGridEventLocation(e);
if (section === this.$.items) {
this._focusedItemIndex = row.index;
}
}
/**
* Enables or disables the focus target of the containing section of the
* grid from receiving focus, based on whether the user is interacting with
* that section of the grid.
* @param {HTMLElement} focusTarget
* @private
*/
_updateGridSectionFocusTarget(focusTarget) {
if (!focusTarget) {
return;
}
const section = this._getGridSectionFromFocusTarget(focusTarget);
const isInteractingWithinActiveSection = this.interacting && section === this._activeRowGroup;
focusTarget.tabIndex = isInteractingWithinActiveSection ? -1 : 0;
}
/**
* @param {!HTMLTableRowElement} row
* @param {number} index
* @protected
*/
_preventScrollerRotatingCellFocus(row, index) {
if (
row.index === this._focusedItemIndex &&
this.hasAttribute('navigating') &&
this._activeRowGroup === this.$.items
) {
// Focused item has went, hide navigation mode
this._navigatingIsHidden = true;
this.toggleAttribute('navigating', false);
}
if (index === this._focusedItemIndex && this._navigatingIsHidden) {
// Focused item is back, restore navigation mode
this._navigatingIsHidden = false;
this.toggleAttribute('navigating', true);
}
}
/**
* @param {HTMLTableSectionElement=} rowGroup
* @param {number=} rowIndex
* @return {!Array<!GridColumn>}
* @protected
*/
_getColumns(rowGroup, rowIndex) {
let columnTreeLevel = this._columnTree.length - 1;
if (rowGroup === this.$.header) {
columnTreeLevel = rowIndex;
} else if (rowGroup === this.$.footer) {
columnTreeLevel = this._columnTree.length - 1 - rowIndex;
}
return this._columnTree[columnTreeLevel];
}
/** @private */
__isValidFocusable(element) {
return this.$.table.contains(element) && element.offsetHeight;
}
/** @protected */
_resetKeyboardNavigation() {
// Header / footer
['header', 'footer'].forEach((section) => {
if (!this.__isValidFocusable(this[`_${section}Focusable`])) {
const firstVisibleRow = [...this.$[section].children].find((row) => row.offsetHeight);
const firstVisibleCell = firstVisibleRow ? [...firstVisibleRow.children].find((cell) => !cell.hidden) : null;
if (firstVisibleRow && firstVisibleCell) {
this[`_${section}Focusable`] = this.__getFocusable(firstVisibleRow, firstVisibleCell);
}
}
});
// Body
if (!this.__isValidFocusable(this._itemsFocusable) && this.$.items.firstElementChild) {
const firstVisibleRow = this.__getFirstVisibleItem();
const firstVisibleCell = firstVisibleRow ? [...firstVisibleRow.children].find((cell) => !cell.hidden) : null;
if (firstVisibleCell && firstVisibleRow) {
// Reset memoized column
delete this._focusedColumnOrder;
this._itemsFocusable = this.__getFocusable(firstVisibleRow, firstVisibleCell);
}
} else {
this.__updateItemsFocusable();
}
}
/**
* @param {!HTMLElement} dstCell
* @protected
*/
_scrollHorizontallyToCell(dstCell) {
if (dstCell.hasAttribute('frozen') || dstCell.hasAttribute('frozen-to-end') || this.__isDetailsCell(dstCell)) {
// These cells are, by design, always visible, no need to scroll.
return;
}
const dstCellRect = dstCell.getBoundingClientRect();
const dstRow = dstCell.parentNode;
const dstCellIndex = Array.from(dstRow.children).indexOf(dstCell);
const tableRect = this.$.table.getBoundingClientRect();
let leftBoundary = tableRect.left,
rightBoundary = tableRect.right;
for (let i = dstCellIndex - 1; i >= 0; i--) {
const cell = dstRow.children[i];
if (cell.hasAttribute('hidden') || this.__isDetailsCell(cell)) {
continue;
}
if (cell.hasAttribute('frozen') || cell.hasAttribute('frozen-to-end')) {
leftBoundary = cell.getBoundingClientRect().right;
break;
}
}
for (let i = dstCellIndex + 1; i < dstRow.children.length; i++) {
const cell = dstRow.children[i];