-
Notifications
You must be signed in to change notification settings - Fork 80
/
vaadin-grid.js
1185 lines (1059 loc) · 41.9 KB
/
vaadin-grid.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 './vaadin-grid-column.js';
import './vaadin-grid-styles.js';
import { beforeNextRender } from '@polymer/polymer/lib/utils/render-status.js';
import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
import { microTask } from '@vaadin/component-base/src/async.js';
import { isAndroid, isChrome, isFirefox, isIOS, isSafari, isTouch } from '@vaadin/component-base/src/browser-utils.js';
import { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';
import { Debouncer } from '@vaadin/component-base/src/debounce.js';
import { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';
import { isElementHidden } from '@vaadin/component-base/src/focus-utils.js';
import { TabindexMixin } from '@vaadin/component-base/src/tabindex-mixin.js';
import { processTemplates } from '@vaadin/component-base/src/templates.js';
import { TooltipController } from '@vaadin/component-base/src/tooltip-controller.js';
import { Virtualizer } from '@vaadin/component-base/src/virtualizer.js';
import { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
import { A11yMixin } from './vaadin-grid-a11y-mixin.js';
import { ActiveItemMixin } from './vaadin-grid-active-item-mixin.js';
import { ArrayDataProviderMixin } from './vaadin-grid-array-data-provider-mixin.js';
import { ColumnReorderingMixin } from './vaadin-grid-column-reordering-mixin.js';
import { ColumnResizingMixin } from './vaadin-grid-column-resizing-mixin.js';
import { DataProviderMixin } from './vaadin-grid-data-provider-mixin.js';
import { DragAndDropMixin } from './vaadin-grid-drag-and-drop-mixin.js';
import { DynamicColumnsMixin } from './vaadin-grid-dynamic-columns-mixin.js';
import { EventContextMixin } from './vaadin-grid-event-context-mixin.js';
import { FilterMixin } from './vaadin-grid-filter-mixin.js';
import { KeyboardNavigationMixin } from './vaadin-grid-keyboard-navigation-mixin.js';
import { RowDetailsMixin } from './vaadin-grid-row-details-mixin.js';
import { ScrollMixin } from './vaadin-grid-scroll-mixin.js';
import { SelectionMixin } from './vaadin-grid-selection-mixin.js';
import { SortMixin } from './vaadin-grid-sort-mixin.js';
import { StylingMixin } from './vaadin-grid-styling-mixin.js';
/**
* `<vaadin-grid>` is a free, high quality data grid / data table Web Component. The content of the
* the grid can be populated by using renderer callback function.
*
* ### Quick Start
*
* Start with an assigning an array to the [`items`](#/elements/vaadin-grid#property-items) property to visualize your data.
*
* Use the [`<vaadin-grid-column>`](#/elements/vaadin-grid-column) element to configure the grid columns. Set `path` and `header`
* shorthand properties for the columns to define what gets rendered in the cells of the column.
*
* #### Example:
* ```html
* <vaadin-grid>
* <vaadin-grid-column path="name.first" header="First name"></vaadin-grid-column>
* <vaadin-grid-column path="name.last" header="Last name"></vaadin-grid-column>
* <vaadin-grid-column path="email"></vaadin-grid-column>
* </vaadin-grid>
* ```
*
* For custom content `vaadin-grid-column` element provides you with three types of `renderer` callback functions: `headerRenderer`,
* `renderer` and `footerRenderer`.
*
* Each of those renderer functions provides `root`, `column`, `model` arguments when applicable.
* Generate DOM content, append it to the `root` element and control the state
* of the host element by accessing `column`. Before generating new content,
* users are able to check if there is already content in `root` for reusing it.
*
* Renderers are called on initialization of new column cells and each time the
* related row model is updated. DOM generated during the renderer call can be reused
* in the next renderer call and will be provided with the `root` argument.
* On first call it will be empty.
*
* #### Example:
* ```html
* <vaadin-grid>
* <vaadin-grid-column></vaadin-grid-column>
* <vaadin-grid-column></vaadin-grid-column>
* <vaadin-grid-column></vaadin-grid-column>
* </vaadin-grid>
* ```
* ```js
* const grid = document.querySelector('vaadin-grid');
* grid.items = [{'name': 'John', 'surname': 'Lennon', 'role': 'singer'},
* {'name': 'Ringo', 'surname': 'Starr', 'role': 'drums'}];
*
* const columns = grid.querySelectorAll('vaadin-grid-column');
*
* columns[0].headerRenderer = function(root) {
* root.textContent = 'Name';
* };
* columns[0].renderer = function(root, column, model) {
* root.textContent = model.item.name;
* };
*
* columns[1].headerRenderer = function(root) {
* root.textContent = 'Surname';
* };
* columns[1].renderer = function(root, column, model) {
* root.textContent = model.item.surname;
* };
*
* columns[2].headerRenderer = function(root) {
* root.textContent = 'Role';
* };
* columns[2].renderer = function(root, column, model) {
* root.textContent = model.item.role;
* };
* ```
*
* The following properties are available in the `model` argument:
*
* Property name | Type | Description
* --------------|------|------------
* `index`| Number | The index of the item.
* `item` | String or Object | The item.
* `level` | Number | Number of the item's tree sublevel, starts from 0.
* `expanded` | Boolean | True if the item's tree sublevel is expanded.
* `selected` | Boolean | True if the item is selected.
* `detailsOpened` | Boolean | True if the item's row details are open.
*
* The following helper elements can be used for further customization:
* - [`<vaadin-grid-column-group>`](#/elements/vaadin-grid-column-group)
* - [`<vaadin-grid-filter>`](#/elements/vaadin-grid-filter)
* - [`<vaadin-grid-sorter>`](#/elements/vaadin-grid-sorter)
* - [`<vaadin-grid-selection-column>`](#/elements/vaadin-grid-selection-column)
* - [`<vaadin-grid-tree-toggle>`](#/elements/vaadin-grid-tree-toggle)
*
* __Note that the helper elements must be explicitly imported.__
* If you want to import everything at once you can use the `all-imports.html` bundle.
*
* ### Lazy Loading with Function Data Provider
*
* In addition to assigning an array to the items property, you can alternatively
* provide the `<vaadin-grid>` data through the
* [`dataProvider`](#/elements/vaadin-grid#property-dataProvider) function property.
* The `<vaadin-grid>` calls this function lazily, only when it needs more data
* to be displayed.
*
* See the [`dataProvider`](#/elements/vaadin-grid#property-dataProvider) in
* the API reference below for the detailed data provider arguments description,
* and the “Assigning Data” page in the demos.
*
* __Note that expanding the tree grid's item will trigger a call to the `dataProvider`.__
*
* __Also, note that when using function data providers, the total number of items
* needs to be set manually. The total number of items can be returned
* in the second argument of the data provider callback:__
*
* ```javascript
* grid.dataProvider = ({page, pageSize}, callback) => {
* // page: the requested page index
* // pageSize: number of items on one page
* const url = `https://api.example/data?page=${page}&per_page=${pageSize}`;
*
* fetch(url)
* .then((res) => res.json())
* .then(({ employees, totalSize }) => {
* callback(employees, totalSize);
* });
* };
* ```
*
* __Alternatively, you can use the `size` property to set the total number of items:__
*
* ```javascript
* grid.size = 200; // The total number of items
* grid.dataProvider = ({page, pageSize}, callback) => {
* const url = `https://api.example/data?page=${page}&per_page=${pageSize}`;
*
* fetch(url)
* .then((res) => res.json())
* .then((resJson) => callback(resJson.employees));
* };
* ```
*
* ### Styling
*
* The following shadow DOM parts are available for styling:
*
* Part name | Description
* ----------------|----------------
* `row` | Row in the internal table
* `cell` | Cell in the internal table
* `header-cell` | Header cell in the internal table
* `body-cell` | Body cell in the internal table
* `footer-cell` | Footer cell in the internal table
* `details-cell` | Row details cell in the internal table
* `focused-cell` | Focused cell in the internal table
* `resize-handle` | Handle for resizing the columns
* `reorder-ghost` | Ghost element of the header cell being dragged
*
* The following state attributes are available for styling:
*
* Attribute | Description | Part name
* ----------------------|---------------------------------------------------------------------------------------------------|-----------
* `loading` | Set when the grid is loading data from data provider | :host
* `interacting` | Keyboard navigation in interaction mode | :host
* `navigating` | Keyboard navigation in navigation mode | :host
* `overflow` | Set when rows are overflowing the grid viewport. Possible values: `top`, `bottom`, `start`, `end` | :host
* `reordering` | Set when the grid's columns are being reordered | :host
* `dragover` | Set when the grid (not a specific row) is dragged over | :host
* `dragging-rows` | Set when grid rows are dragged | :host
* `reorder-status` | Reflects the status of a cell while columns are being reordered | cell
* `frozen` | Frozen cell | cell
* `frozen-to-end` | Cell frozen to end | cell
* `last-frozen` | Last frozen cell | cell
* `first-frozen-to-end` | First cell frozen to end | cell
* `first-column` | First visible cell on a row | cell
* `last-column` | Last visible cell on a row | cell
* `selected` | Selected row | row
* `expanded` | Expanded row | row
* `details-opened` | Row with details open | row
* `loading` | Row that is waiting for data from data provider | row
* `odd` | Odd row | row
* `first` | The first body row | row
* `last` | The last body row | row
* `dragstart` | Set for one frame when starting to drag a row. The value is a number when dragging multiple rows | row
* `dragover` | Set when the row is dragged over | row
* `drag-disabled` | Set to a row that isn't available for dragging | row
* `drop-disabled` | Set to a row that can't be dropped on top of | row
*
* See [Styling Components](https://vaadin.com/docs/latest/styling/custom-theme/styling-components) documentation.
*
* @fires {CustomEvent} active-item-changed - Fired when the `activeItem` property changes.
* @fires {CustomEvent} cell-activate - Fired when the cell is activated with click or keyboard.
* @fires {CustomEvent} cell-focus - Fired when a cell is focused with click or keyboard navigation.
* @fires {CustomEvent} column-reorder - Fired when the columns in the grid are reordered.
* @fires {CustomEvent} column-resize - Fired when the grid column resize is finished.
* @fires {CustomEvent} data-provider-changed - Fired when the `dataProvider` property changes.
* @fires {CustomEvent} expanded-items-changed - Fired when the `expandedItems` property changes.
* @fires {CustomEvent} grid-dragstart - Fired when starting to drag grid rows.
* @fires {CustomEvent} grid-dragend - Fired when the dragging of the rows ends.
* @fires {CustomEvent} grid-drop - Fired when a drop occurs on top of the grid.
* @fires {CustomEvent} loading-changed - Fired when the `loading` property changes.
* @fires {CustomEvent} selected-items-changed - Fired when the `selectedItems` property changes.
* @fires {CustomEvent} size-changed - Fired when the `size` property changes.
*
* @extends HTMLElement
* @mixes ElementMixin
* @mixes ThemableMixin
* @mixes A11yMixin
* @mixes ActiveItemMixin
* @mixes ArrayDataProviderMixin
* @mixes ColumnResizingMixin
* @mixes DataProviderMixin
* @mixes DynamicColumnsMixin
* @mixes FilterMixin
* @mixes RowDetailsMixin
* @mixes ScrollMixin
* @mixes SelectionMixin
* @mixes SortMixin
* @mixes KeyboardNavigationMixin
* @mixes ColumnReorderingMixin
* @mixes EventContextMixin
* @mixes StylingMixin
* @mixes DragAndDropMixin
*/
class Grid extends ElementMixin(
ThemableMixin(
DataProviderMixin(
ArrayDataProviderMixin(
DynamicColumnsMixin(
ActiveItemMixin(
ScrollMixin(
SelectionMixin(
SortMixin(
RowDetailsMixin(
KeyboardNavigationMixin(
A11yMixin(
FilterMixin(
ColumnReorderingMixin(
ColumnResizingMixin(
ControllerMixin(
EventContextMixin(DragAndDropMixin(StylingMixin(TabindexMixin(PolymerElement)))),
),
),
),
),
),
),
),
),
),
),
),
),
),
),
),
) {
static get template() {
return html`
<div
id="scroller"
safari$="[[_safari]]"
ios$="[[_ios]]"
loading$="[[loading]]"
column-reordering-allowed$="[[columnReorderingAllowed]]"
>
<table id="table" role="treegrid" aria-multiselectable="true" tabindex="0">
<caption id="sizer" part="row"></caption>
<thead id="header" role="rowgroup"></thead>
<tbody id="items" role="rowgroup"></tbody>
<tfoot id="footer" role="rowgroup"></tfoot>
</table>
<div part="reorder-ghost"></div>
</div>
<slot name="tooltip"></slot>
<div id="focusexit" tabindex="0"></div>
`;
}
static get is() {
return 'vaadin-grid';
}
static get observers() {
return [
'_columnTreeChanged(_columnTree, _columnTree.*)',
'_effectiveSizeChanged(_effectiveSize, __virtualizer, _hasData, _columnTree)',
];
}
static get properties() {
return {
/** @private */
_safari: {
type: Boolean,
value: isSafari,
},
/** @private */
_ios: {
type: Boolean,
value: isIOS,
},
/** @private */
_firefox: {
type: Boolean,
value: isFirefox,
},
/** @private */
_android: {
type: Boolean,
value: isAndroid,
},
/** @private */
_touchDevice: {
type: Boolean,
value: isTouch,
},
/**
* If true, the grid's height is defined by its rows.
*
* Effectively, this disables the grid's virtual scrolling so that all the rows are rendered in the DOM at once.
* If the grid has a large number of items, using the feature is discouraged to avoid performance issues.
* @attr {boolean} all-rows-visible
* @type {boolean}
*/
allRowsVisible: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/** @private */
_recalculateColumnWidthOnceLoadingFinished: {
type: Boolean,
value: true,
},
/** @private */
isAttached: {
value: false,
},
/**
* An internal property that is mainly used by `vaadin-template-renderer`
* to identify grid elements.
*
* @private
*/
__gridElement: {
type: Boolean,
value: true,
},
};
}
constructor() {
super();
this.addEventListener('animationend', this._onAnimationEnd);
}
/** @protected */
connectedCallback() {
super.connectedCallback();
this.isAttached = true;
this.recalculateColumnWidths();
}
/** @protected */
disconnectedCallback() {
super.disconnectedCallback();
this.isAttached = false;
this._hideTooltip(true);
}
/** @private */
__getFirstVisibleItem() {
return this._getVisibleRows().find((row) => this._isInViewport(row));
}
/** @private */
get _firstVisibleIndex() {
const firstVisibleItem = this.__getFirstVisibleItem();
return firstVisibleItem ? firstVisibleItem.index : undefined;
}
/** @private */
__getLastVisibleItem() {
return this._getVisibleRows()
.reverse()
.find((row) => this._isInViewport(row));
}
/** @private */
get _lastVisibleIndex() {
const lastVisibleItem = this.__getLastVisibleItem();
return lastVisibleItem ? lastVisibleItem.index : undefined;
}
/** @private */
_isInViewport(item) {
const scrollTargetRect = this.$.table.getBoundingClientRect();
const itemRect = item.getBoundingClientRect();
const headerHeight = this.$.header.getBoundingClientRect().height;
const footerHeight = this.$.footer.getBoundingClientRect().height;
return (
itemRect.bottom > scrollTargetRect.top + headerHeight && itemRect.top < scrollTargetRect.bottom - footerHeight
);
}
/** @private */
_getVisibleRows() {
return Array.from(this.$.items.children)
.filter((item) => !item.hidden)
.sort((a, b) => a.index - b.index);
}
/** @protected */
ready() {
super.ready();
this.__virtualizer = new Virtualizer({
createElements: this._createScrollerRows.bind(this),
updateElement: this._updateScrollerItem.bind(this),
scrollContainer: this.$.items,
scrollTarget: this.$.table,
reorderElements: true,
});
new ResizeObserver(() =>
setTimeout(() => {
this.__updateFooterPositioning();
if (this._recalculateColumnWidthOnceVisible) {
this._recalculateColumnWidthOnceVisible = false;
this.recalculateColumnWidths();
}
}),
).observe(this.$.table);
processTemplates(this);
this._tooltipController = new TooltipController(this);
this.addController(this._tooltipController);
this._tooltipController.setManual(true);
}
/**
* @param {string} name
* @param {?string} oldValue
* @param {?string} newValue
* @protected
*/
attributeChangedCallback(name, oldValue, newValue) {
super.attributeChangedCallback(name, oldValue, newValue);
if (name === 'dir') {
this.__isRTL = newValue === 'rtl';
}
}
/** @private */
__getBodyCellCoordinates(cell) {
if (this.$.items.contains(cell) && cell.localName === 'td') {
return {
item: cell.parentElement._item,
column: cell._column,
};
}
}
/** @private */
__focusBodyCell({ item, column }) {
const row = this._getVisibleRows().find((row) => row._item === item);
const cell = row && [...row.children].find((cell) => cell._column === column);
if (cell) {
cell.focus();
}
}
/** @private */
_effectiveSizeChanged(effectiveSize, virtualizer, hasData, columnTree) {
if (virtualizer && hasData && columnTree) {
// Changing the virtualizer size may result in the row with focus getting hidden
const cell = this.shadowRoot.activeElement;
const cellCoordinates = this.__getBodyCellCoordinates(cell);
virtualizer.size = effectiveSize;
virtualizer.update();
virtualizer.flush();
// If the focused cell's parent row got hidden by the size change, focus the corresponding new cell
if (cellCoordinates && cell.parentElement.hidden) {
this.__focusBodyCell(cellCoordinates);
}
// Make sure the body has a tabbable element
this._resetKeyboardNavigation();
}
}
/** @protected */
__itemsReceived() {
if (!this._recalculateColumnWidthOnceLoadingFinished || this._cache.isLoading()) {
return;
}
// Delay recalculation if any rows are missing an index.
// This can happen during the grid's initialization if the recalculation is triggered
// as a result of the data provider responding synchronously to a page request created
// in the middle of the virtualizer update loop. In this case, rows after the one that
// triggered the page request may not have an index property yet. The lack of index
// prevents _onDataProviderPageReceived from requesting children for these rows,
// resulting in loading state being set to false and the recalculation beginning
// before all the data is loaded. Note, rows without index get updated in later iterations
// of the virtualizer update loop, ensuring the grid eventually reaches a stable state.
const hasRowsWithUndefinedIndex = [...this.$.items.children].some((row) => row.index === undefined);
if (hasRowsWithUndefinedIndex) {
return;
}
const hasRowsWithClientHeight = [...this.$.items.children].some((row) => row.clientHeight > 0);
if (hasRowsWithClientHeight) {
this._recalculateColumnWidthOnceLoadingFinished = false;
this.recalculateColumnWidths();
}
}
/** @private */
__getIntrinsicWidth(col) {
if (this.__intrinsicWidthCache.has(col)) {
return this.__intrinsicWidthCache.get(col);
}
const width = this.__calculateIntrinsicWidth(col);
this.__intrinsicWidthCache.set(col, width);
return width;
}
/** @private */
__calculateIntrinsicWidth(col) {
const initialWidth = col.width;
const initialFlexGrow = col.flexGrow;
col.width = 'auto';
col.flexGrow = 0;
// Note: _allCells only contains cells which are currently rendered in DOM
const width = col._allCells
.filter((cell) => {
// Exclude body cells that are out of the visible viewport
return !this.$.items.contains(cell) || this._isInViewport(cell.parentElement);
})
.reduce((width, cell) => {
// Add 1px buffer to the offset width to avoid too narrow columns (sub-pixel rendering)
return Math.max(width, cell.offsetWidth + 1);
}, 0);
col.flexGrow = initialFlexGrow;
col.width = initialWidth;
return width;
}
/** @private */
__getDistributedWidth(col, innerColumn) {
if (col == null || col === this) {
return 0;
}
const columnWidth = Math.max(
this.__getIntrinsicWidth(col),
this.__getDistributedWidth((col.assignedSlot || col).parentElement, col),
);
// We're processing a regular grid-column and not a grid-column-group
if (!innerColumn) {
return columnWidth;
}
// At the end, the width of each vaadin-grid-column-group is determined by the sum of the width of its children.
// Here we determine how much space the vaadin-grid-column-group actually needs to render properly and then we distribute that space
// to its children, so when we actually do the summation it will be rendered properly.
// Check out vaadin-grid-column-group:_updateFlexAndWidth
const columnGroup = col;
const columnGroupWidth = columnWidth;
const sumOfWidthOfAllChildColumns = columnGroup._visibleChildColumns
.map((col) => this.__getIntrinsicWidth(col))
.reduce((sum, curr) => sum + curr, 0);
const extraNecessarySpaceForGridColumnGroup = Math.max(0, columnGroupWidth - sumOfWidthOfAllChildColumns);
// The distribution of the extra necessary space is done according to the intrinsic width of each child column.
// Lets say we need 100 pixels of extra space for the grid-column-group to render properly
// it has two grid-column children, |100px|300px| in total 400px
// the first column gets 25px of the additional space (100/400)*100 = 25
// the second column gets the 75px of the additional space (300/400)*100 = 75
const proportionOfExtraSpace = this.__getIntrinsicWidth(innerColumn) / sumOfWidthOfAllChildColumns;
const shareOfInnerColumnFromNecessaryExtraSpace = proportionOfExtraSpace * extraNecessarySpaceForGridColumnGroup;
return this.__getIntrinsicWidth(innerColumn) + shareOfInnerColumnFromNecessaryExtraSpace;
}
/**
* @param {!Array<!GridColumn>} cols the columns to auto size based on their content width
* @private
*/
_recalculateColumnWidths(cols) {
// Flush to make sure DOM is up-to-date when measuring the column widths
this.__virtualizer.flush();
[...this.$.header.children, ...this.$.footer.children].forEach((row) => {
if (row.__debounceUpdateHeaderFooterRowVisibility) {
row.__debounceUpdateHeaderFooterRowVisibility.flush();
}
});
// Flush to account for any changes to the visibility of the columns
if (this._debouncerHiddenChanged) {
this._debouncerHiddenChanged.flush();
}
this.__intrinsicWidthCache = new Map();
cols.forEach((col) => {
col.width = `${this.__getDistributedWidth(col)}px`;
});
}
/**
* Updates the `width` of all columns which have `autoWidth` set to `true`.
*/
recalculateColumnWidths() {
if (!this._columnTree) {
return; // No columns
}
if (isElementHidden(this)) {
this._recalculateColumnWidthOnceVisible = true;
return;
}
if (this._cache.isLoading()) {
this._recalculateColumnWidthOnceLoadingFinished = true;
return;
}
const cols = this._getColumns().filter((col) => !col.hidden && col.autoWidth);
this._recalculateColumnWidths(cols);
}
/** @private */
_createScrollerRows(count) {
const rows = [];
for (let i = 0; i < count; i++) {
const row = document.createElement('tr');
row.setAttribute('part', 'row');
row.setAttribute('role', 'row');
row.setAttribute('tabindex', '-1');
if (this._columnTree) {
this._updateRow(row, this._columnTree[this._columnTree.length - 1], 'body', false, true);
}
rows.push(row);
}
if (this._columnTree) {
this._columnTree[this._columnTree.length - 1].forEach(
(c) => c.isConnected && c.notifyPath && c.notifyPath('_cells.*', c._cells),
);
}
beforeNextRender(this, () => {
this._updateFirstAndLastColumn();
this._resetKeyboardNavigation();
this._afterScroll();
this.__itemsReceived();
});
return rows;
}
/** @private */
_createCell(tagName, column) {
const contentId = (this._contentIndex = this._contentIndex + 1 || 0);
const slotName = `vaadin-grid-cell-content-${contentId}`;
const cellContent = document.createElement('vaadin-grid-cell-content');
cellContent.setAttribute('slot', slotName);
const cell = document.createElement(tagName);
cell.id = slotName.replace('-content-', '-');
cell.setAttribute('role', tagName === 'td' ? 'gridcell' : 'columnheader');
// For now we only support tooltip on desktop
if (!isAndroid && !isIOS) {
cell.addEventListener('mouseenter', (event) => {
if (!this.$.scroller.hasAttribute('scrolling')) {
this._showTooltip(event);
}
});
cell.addEventListener('mouseleave', () => {
this._hideTooltip();
});
cell.addEventListener('mousedown', () => {
this._hideTooltip(true);
});
}
const slot = document.createElement('slot');
slot.setAttribute('name', slotName);
if (column && column._focusButtonMode) {
const div = document.createElement('div');
div.setAttribute('role', 'button');
div.setAttribute('tabindex', '-1');
cell.appendChild(div);
// Patch `focus()` to use the button
cell._focusButton = div;
cell.focus = function () {
cell._focusButton.focus();
};
div.appendChild(slot);
} else {
cell.setAttribute('tabindex', '-1');
cell.appendChild(slot);
}
cell._content = cellContent;
// With native Shadow DOM, mousedown on slotted element does not focus
// focusable slot wrapper, that is why cells are not focused with
// mousedown. Workaround: listen for mousedown and focus manually.
cellContent.addEventListener('mousedown', () => {
if (isChrome) {
// Chrome bug: focusing before mouseup prevents text selection, see http://crbug.com/771903
const mouseUpListener = (event) => {
// If focus is on element within the cell content — respect it, do not change
const contentContainsFocusedElement = cellContent.contains(this.getRootNode().activeElement);
// Only focus if mouse is released on cell content itself
const mouseUpWithinCell = event.composedPath().includes(cellContent);
if (!contentContainsFocusedElement && mouseUpWithinCell) {
cell.focus();
}
document.removeEventListener('mouseup', mouseUpListener, true);
};
document.addEventListener('mouseup', mouseUpListener, true);
} else {
// Focus on mouseup, on the other hand, removes selection on Safari.
// Watch out sync focus removal issue, only async focus works here.
setTimeout(() => {
if (!cellContent.contains(this.getRootNode().activeElement)) {
cell.focus();
}
});
}
});
return cell;
}
/**
* @param {!HTMLTableRowElement} row
* @param {!Array<!GridColumn>} columns
* @param {?string} section
* @param {boolean} isColumnRow
* @param {boolean} noNotify
* @protected
*/
// eslint-disable-next-line max-params
_updateRow(row, columns, section, isColumnRow, noNotify) {
section = section || 'body';
const contentsFragment = document.createDocumentFragment();
Array.from(row.children).forEach((cell) => {
cell._vacant = true;
});
row.innerHTML = '';
columns
.filter((column) => !column.hidden)
.forEach((column, index, cols) => {
let cell;
if (section === 'body') {
// Body
column._cells = column._cells || [];
cell = column._cells.find((cell) => cell._vacant);
if (!cell) {
cell = this._createCell('td', column);
column._cells.push(cell);
}
cell.setAttribute('part', 'cell body-cell');
row.appendChild(cell);
if (row === this.$.sizer) {
column._sizerCell = cell;
}
if (index === cols.length - 1 && this.rowDetailsRenderer) {
// Add details cell as last cell to body rows
this._detailsCells = this._detailsCells || [];
const detailsCell = this._detailsCells.find((cell) => cell._vacant) || this._createCell('td');
if (this._detailsCells.indexOf(detailsCell) === -1) {
this._detailsCells.push(detailsCell);
}
if (!detailsCell._content.parentElement) {
contentsFragment.appendChild(detailsCell._content);
}
this._configureDetailsCell(detailsCell);
row.appendChild(detailsCell);
this._a11ySetRowDetailsCell(row, detailsCell);
detailsCell._vacant = false;
}
if (column.notifyPath && !noNotify) {
column.notifyPath('_cells.*', column._cells);
}
} else {
// Header & footer
const tagName = section === 'header' ? 'th' : 'td';
if (isColumnRow || column.localName === 'vaadin-grid-column-group') {
cell = column[`_${section}Cell`] || this._createCell(tagName);
cell._column = column;
row.appendChild(cell);
column[`_${section}Cell`] = cell;
} else {
column._emptyCells = column._emptyCells || [];
cell = column._emptyCells.find((cell) => cell._vacant) || this._createCell(tagName);
cell._column = column;
row.appendChild(cell);
if (column._emptyCells.indexOf(cell) === -1) {
column._emptyCells.push(cell);
}
}
cell.setAttribute('part', `cell ${section}-cell`);
}
if (!cell._content.parentElement) {
contentsFragment.appendChild(cell._content);
}
cell._vacant = false;
cell._column = column;
});
if (section !== 'body') {
this.__debounceUpdateHeaderFooterRowVisibility(row);
}
// Might be empty if only cache was used
this.appendChild(contentsFragment);
this._frozenCellsChanged();
this._updateFirstAndLastColumnForRow(row);
}
/**
* @param {HTMLTableRowElement} row
* @protected
*/
__debounceUpdateHeaderFooterRowVisibility(row) {
row.__debounceUpdateHeaderFooterRowVisibility = Debouncer.debounce(
row.__debounceUpdateHeaderFooterRowVisibility,
microTask,
() => this.__updateHeaderFooterRowVisibility(row),
);
}
/**
* @param {HTMLTableRowElement} row
* @protected
*/
__updateHeaderFooterRowVisibility(row) {
if (!row) {
return;
}
const visibleRowCells = Array.from(row.children).filter((cell) => {
const column = cell._column;
if (column._emptyCells && column._emptyCells.indexOf(cell) > -1) {
// The cell is an "empty cell" -> doesn't block hiding the row
return false;
}
if (row.parentElement === this.$.header) {
if (column.headerRenderer) {
// The cell is the header cell of a column that has a header renderer
// -> row should be visible
return true;
}
if (column.header === null) {
// The column header is explicilty set to null -> doesn't block hiding the row
return false;
}
if (column.path || column.header !== undefined) {
// The column has an explicit non-null header or a path that generates a header
// -> row should be visible
return true;
}
} else if (column.footerRenderer) {
// The cell is the footer cell of a column that has a footer renderer
// -> row should be visible
return true;
}
return false;
});
if (row.hidden !== !visibleRowCells.length) {
row.hidden = !visibleRowCells.length;
}
// Make sure the section has a tabbable element
this._resetKeyboardNavigation();
}
/** @private */
_updateScrollerItem(row, index) {
this._preventScrollerRotatingCellFocus(row, index);
if (!this._columnTree) {
return;
}
row.toggleAttribute('first', index === 0);
row.toggleAttribute('last', index === this._effectiveSize - 1);
row.toggleAttribute('odd', index % 2);
this._a11yUpdateRowRowindex(row, index);
this._getItem(index, row);
}
/** @private */
_columnTreeChanged(columnTree) {
this._renderColumnTree(columnTree);
this.recalculateColumnWidths();
}
/**
* @param {!Array<!GridColumn>} columnTree
* @protected
*/
_renderColumnTree(columnTree) {
Array.from(this.$.items.children).forEach((row) =>
this._updateRow(row, columnTree[columnTree.length - 1], null, false, true),
);
while (this.$.header.children.length < columnTree.length) {
const headerRow = document.createElement('tr');
headerRow.setAttribute('part', 'row');
headerRow.setAttribute('role', 'row');
headerRow.setAttribute('tabindex', '-1');
this.$.header.appendChild(headerRow);
const footerRow = document.createElement('tr');
footerRow.setAttribute('part', 'row');
footerRow.setAttribute('role', 'row');
footerRow.setAttribute('tabindex', '-1');
this.$.footer.appendChild(footerRow);
}
while (this.$.header.children.length > columnTree.length) {
this.$.header.removeChild(this.$.header.firstElementChild);
this.$.footer.removeChild(this.$.footer.firstElementChild);
}
Array.from(this.$.header.children).forEach((headerRow, index) =>
this._updateRow(headerRow, columnTree[index], 'header', index === columnTree.length - 1),