forked from Saulis/iron-data-table
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iron-data-table.html
1065 lines (920 loc) · 34.6 KB
/
iron-data-table.html
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 2016 Sauli Tähkäpää
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-list/iron-list.html">
<link rel="import" href="../iron-resizable-behavior/iron-resizable-behavior.html">
<link rel="import" href="../paper-spinner/paper-spinner-lite.html">
<link rel="import" href="data-table-column.html">
<link rel="import" href="data-table-column-sort.html">
<link rel="import" href="data-table-cell.html">
<link rel="import" href="data-table-row.html">
<link rel="import" href="data-table-checkbox.html">
<link rel="import" href="data-table-row-detail.html">
<script src="array-datasource.js"></script>
<!--
`iron-data-table` displays a table or a grid of data.
It builds on top of `iron-list`, which provides the foundation for features like
virtual scrolling and templating.
It contains an array of `data-table-column` elements, which are used to define a template
for the cells on each row item.
Rows use flex layout which enables cells to fit the available space.
Cell elements are placed outside the shadow root of the `iron-data-table` which
allows them to be styled by the user.
### Template model
Column templates should bind to template models of the following structure:
```js
{
index: 0, // index in the item array
selected: false, // true if the current item is selected
item: {}, // user data corresponding to items[index],
expanded: false // true if row details have been expanded for the current item
}
```
For example, given the following `data` array:
##### data.json
```js
[
{"name": {
"title": "miss",
"first": "donna",
"last": "davis"
}},
{"name": {
"title": "mr",
"first": "samuel",
"last": "kelley"
}},
{"name": {
"title": "ms",
"first": "katie",
"last": "butler"
}}
]
```
The following code would render the table (note the name and checked properties are
bound from the model object provided to the template scope):
```html
<template is="dom-bind">
<iron-ajax url="data.json" last-response="{{data}}" auto></iron-ajax>
<iron-data-table items="[[data]]">
<data-table-column name="First Name">
<template>[[item.name.first]]</template>
</data-table-column>
<data-table-column name="Last Name">
<template>[[item.name.last]]</template>
</data-table-column>
</iron-data-table>
</template>
```
### Styling
There are several custom properties and mixins you can use to style the component:
Custom property | Description
----------------|-------------
`--iron-data-table` | Mixin applied to the main element
`--iron-data-table-header` | Mixin applied to the header element
`--iron-data-table-row` | Mixin applied to the row item element
`--iron-data-table-row-hover` | Mixin applied to the row item element when hovered on
`--iron-data-table-row-selected` | Mixin applied to the selected row item elements
`--iron-data-table-row-after` | Mixin applied to :after pseudoelement of the row item element
`--iron-data-table-row-focused` | Mixin applied to the focused row item elements
`--iron-data-table-row-focused-after` | Mixin applied to :after pseudoelement of the focused row item elements
To get started, you can import `default-styles.html` which provides material design
inspired styles to your `iron-data-table`.
-->
<dom-module id="iron-data-table">
<template>
<style is="custom-style">
:host {
display: block;
position: relative;
overflow-x: auto;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
/* Default height just to help users get started in making stuff visible. */
height: 400px;
@apply(--iron-data-table);
}
#container {
position: absolute;
left: 0;
top: 0;
bottom: 0;
display: flex;
flex-direction: column;
}
#header {
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
transition: box-shadow 200ms;
-webkit-transition: box-shadow 200ms;
z-index: 1;
@apply(--iron-data-table-header);
}
#header.scrolled {
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.06), 0 2px 0 rgba(0, 0, 0, 0.075), 0 3px 0 rgba(0, 0, 0, 0.05), 0 4px 0 rgba(0, 0, 0, 0.015);
}
#list {
overflow-x: hidden !important;
overflow-y: auto !important;
flex: 1;
transition: opacity 200ms;
-webkit-transition: opacity 200ms;
}
:host([loading]) #list {
opacity: 0.25;
}
:host(:not([loading])) paper-spinner-lite {
display: none;
}
:host([loading]) paper-spinner-lite {
position: absolute;
top: 45%;
left: 50%;
--paper-spinner-color: var(--default-primary-color);
}
</style>
<div id="container">
<div id="header">
<data-table-row header>
<data-table-checkbox header hidden$="[[!multiSelection]]" on-tap="_toggleSelectAll" checked="[[_isSelectAllChecked(selectedItems.length, selectedItems.inverted, size)]]" indeterminate="[[_isSelectAllIndeterminate(selectedItems.length, size)]]"></data-table-checkbox>
<template is="dom-repeat" items="[[columns]]" as="column">
<data-table-cell header
align-right="[[column.alignRight]]"
before-bind="[[beforeCellBind]]"
column="[[column]]"
flex="[[column.flex]]"
hidden="[[column.hidden]]"
order="[[column.order]]"
table="[[_this]]"
template="[[column.headerTemplate]]"
width="[[column.width]]">
<data-table-column-sort sort-order="[[sortOrder]]" path="[[column.sortBy]]" on-sort-direction-changed="_sortDirectionChanged" hidden$="[[!column.sortBy]]"></data-table-column-sort>
</data-table-cell>
</template>
</data-table-row>
</div>
<iron-list id="list" as="item" items="[[_cachedItems]]" on-scroll="_onVerticalScroll">
<template>
<div class="item">
<data-table-row before-bind="[[beforeRowBind]]"
even$="[[!_isEven(index)]]"
expanded="[[_isExpanded(item, _expandedItems, _expandedItems.*)]]"
index="[[index]]"
item="[[item]]"
tabindex="-1"
selected="[[_isSelected(item, selectedItems, selectedItems.*)]]">
<data-table-checkbox hidden$="[[!multiSelection]]" tabindex="0" checked="[[_isSelected(item, selectedItems, selectedItems.*)]]" on-tap="_onCheckBoxTap"></data-table-checkbox>
<template is="dom-repeat" items="[[columns]]" as="column" index-as="colIndex">
<data-table-cell template="[[column.template]]"
table="[[_this]]"
align-right="[[column.alignRight]]"
column="[[column]]"
expanded="[[_isExpanded(item, _expandedItems, _expandedItems.*)]]"
flex="[[column.flex]]"
hidden="[[column.hidden]]"
index="[[index]]"
item="[[item]]"
on-click="_onCellClick"
order="[[column.order]]"
selected="[[_isSelected(item, selectedItems, selectedItems.*)]]"
width="[[column.width]]"
before-bind="[[beforeCellBind]]"></data-table-cell>
</template>
<template is="dom-if" if="[[_isExpanded(item, _expandedItems)]]" on-dom-change="_updateSizeForItem">
<data-table-row-detail index="[[index]]"
item="[[item]]"
expanded="[[_isExpanded(item, _expandedItems, _expandedItems.*)]]"
selected="[[_isSelected(item, selectedItems, selectedItems.*)]]"
before-bind="[[beforeDetailsBind]]"
table="[[_this]]"
template="[[rowDetail]]"></data-table-row-detail>
</template>
</data-table-row>
</div>
</template>
</iron-list>
</div>
<paper-spinner-lite active></paper-spinner-lite>
<content select="data-table-column"></content>
<content select="template[is=row-detail]"></content>
</template>
<script>
Polymer({
is: 'iron-data-table',
behaviors: [
Polymer.IronResizableBehavior
],
listeners: {
'column-filter-changed': '_onColumnFilterChanged',
'iron-resize': '_resizeCellContainers',
'item-changed': '_itemChanged',
'scroll': '_onHorizontalScroll'
},
properties: {
/**
* Timeout after which the data on the currently visible page will be automatically
* refreshed after an item has been changed through a two-way binding.
*/
autoRefresh: Number,
/**
* A function that is called before data is bound to a row or header cell.
* Can be used to customize the cell element depending on the data.
* #### Example:
* ```js
* function(data, cell) {
* cell.toggleClass('custom', data.useCustomClass);
* }
* ```
*/
beforeCellBind: Object,
/**
* A function that is called before data is bound to a row details element.
* Can be used to customize the element depending on the data.
* #### Example:
* ```js
* function(data, details) {
* details.toggleClass('custom', data.useCustomClass);
* }
* ```
*/
beforeDetailsBind: Object,
/**
* A function that is called before data is bound to a row.
* Can be used to customize the row element depending on the data.
* #### Example:
* ```js
* function(data, row) {
* row.toggleClass('custom', data.useCustomClass);
* }
* ```
*/
beforeRowBind: Object,
/**
* An array containing the items which will be stamped to the column template
* instances.
*/
items: {
type: Array
},
/**
* If `true`, tapping a row will expand the item details, if available.
*/
detailsEnabled: {
type: Boolean,
value: false
},
/**
* An array containing path/filter value pairs that are used to filter the items
*/
filter: {
type: Array,
notify: true,
value: function() {
return [];
}
},
/**
* When `true`, multiple items may be selected at once (in this case,
* `selected` is an array of currently selected items). When `false`,
* only one item may be selected at a time.
*/
multiSelection: {
type: Boolean,
value: false
},
/**
* Number of items fetched at a time from the datasource.
*/
pageSize: {
type: Number,
value: 50
},
/**
* If `true`, tapping a row will select the item.
*/
selectionEnabled: {
type: Boolean,
value: false
},
/**
* This is the currently selected item, or `null`
* if no item is selected.
*/
selectedItem: {
type: Object,
readOnly: true,
notify: true
},
/**
* When `multiSelection` is true, this is an array that contains the selected items.
* If `selectedItems.inverted` is `true`, the array contains deselected items instead.
* `selectedItems.filters` contains an array of filters that were active when the selection changed.
*/
selectedItems: {
type: Object,
notify: true,
readOnly: true,
value: function() {
var items = [];
items.filters = [];
return items;
}
},
/**
* Size of the data set.
*/
size: {
type: Number,
notify: true,
value: 0,
observer: '_sizeChanged'
},
/**
* An array with a path/sortorder ('asc' or 'desc') pairs that are used to sort the items.
*/
sortOrder: {
type: Array,
notify: true,
value: function() {
return [];
}
},
/**
* An array of `data-table-column` elements which contain the templates
* to be stamped with items.
*/
columns: {
type: Array,
notify: true,
value: function() {
return [];
},
observer: '_columnsChanged'
},
/**
* Function that provides items lazily. Receives parameters `opts`, `callback`, `err`
*
* `opts.page` Requested page index
*
* `opts.pageSize` Current page size
*
* `opts.filter` Current filter parameters
*
* `opts.sortOrder` Current sorting parameters
*/
dataSource: {
type: Object,
notify: true
},
_pagesLoading: {
type: Array,
value: function() {
return [];
},
},
/**
* `true` if the table is currently loading data from the data source.
*/
loading: {
type: Boolean,
notify: true,
reflectToAttribute: true,
value: false
},
_cachedItems: {
type: Array,
value: function() {
return [];
}
},
_cachedPages: {
type: Array,
value: function() {
return [];
}
},
_currentPage: {
type: Number,
value: 0
},
_expandedItems: {
type: Array,
value: function() {
return [];
}
},
_this: {
type: Object,
value: function() {
return this;
}
}
},
observers: ['_itemsChanged(items.*)',
'_currentPageChanged(dataSource, _currentPage)',
'_resetData(dataSource, filter.*, sortOrder.*)'
],
created: function() {
this._observer = Polymer.dom(this).observeNodes(function(info) {
var hasColumns = function(node) {
return (node.nodeType === Node.ELEMENT_NODE && node.tagName.toUpperCase() === 'DATA-TABLE-COLUMN');
};
var hasDetails = function(node) {
return (node.nodeType === Node.ELEMENT_NODE &&
node.tagName.toUpperCase() === 'TEMPLATE' && node.hasAttribute('is') &&
node.getAttribute('is') === 'row-detail');
};
if (info.addedNodes.filter(hasColumns).length > 0 ||
info.removedNodes.filter(hasColumns).length > 0) {
this.set('columns', this.getContentChildren('[select=data-table-column]'));
this.notifyResize();
}
if (info.addedNodes.filter(hasDetails).length > 0) {
this.set('rowDetail', this.getContentChildren('[select="template[is=row-detail]"]')[0]);
// assuming parent element is always a Polymer element.
// set dataHost to the same context the template was declared in
var parent = Polymer.dom(this.rowDetail).parentNode;
this.rowDetail._rootDataHost = parent.dataHost ? (parent.dataHost._rootDataHost || parent.dataHost) : parent;
}
}.bind(this));
},
_stopPropagation: function(e) {
e.stopImmediatePropagation();
},
/**
* Select the list item at the given index.
*
* @method selectItem
* @param {(Object|number)} item The item object or its index
*/
selectItem: function(item) {
if (typeof item === 'number' && item >= 0 && this.items && this.items.length > item) {
this._selectItem(this.items[item]);
} else {
this._selectItem(item);
}
},
_selectItem: function(item) {
this._setSelectedItem(item);
if (this.multiSelection) {
if (this.selectedItems.inverted) {
var index;
if ((index = this.selectedItems.indexOf(item)) > -1) {
this.splice('selectedItems', index, 1);
}
} else {
this.push('selectedItems', item);
}
} else {
this.splice('selectedItems', 0, this.selectedItems.length, item);
}
},
/**
* Deselects the given item list if it is already selected.
*
* @method deselect
* @param {(Object|number)} item The item object or its index
*/
deselectItem: function(item) {
if (typeof item === 'number' && item >= 0 && this.items && this.items.length > item) {
this._deselectItem(this.items[item]);
} else {
this._deselectItem(item);
}
},
_deselectItem: function(item) {
this._setSelectedItem(null);
var index = this.selectedItems.indexOf(item);
if (this.selectedItems.inverted) {
if (index === -1) {
this.push('selectedItems', item);
}
} else {
if (index > -1) {
this.splice('selectedItems', index, 1);
}
}
},
_isSelected: function(item, selectedItems) {
var selected = selectedItems.indexOf(item) > -1;
return selectedItems.inverted ? !selected : selected;
},
/*
* Selects all the items in the list.
*/
selectAll: function() {
var selectedItems = [];
selectedItems.inverted = true;
// use a copy of filter so that we can safely send separate changed
// notifications for both filter and selectedItems.filter
selectedItems.filters = this.filter.slice(0) || [];
this._setSelectedItems(selectedItems);
},
/**
* Clears the current selection state.
*/
clearSelection: function() {
var selectedItems = [];
selectedItems.inverted = false;
// use a copy of filter so that we can safely send separate changed
// notifications for both filter and selectedItems.filter
selectedItems.filters = this.filter.slice(0) || [];
this._setSelectedItems(selectedItems);
if (this.selectedItem !== undefined) {
this._setSelectedItem(null);
}
},
_toggleSelectAll: function() {
if (this._isSelectAllChecked(this.selectedItems.length, this.selectedItems.inverted, this.size)) {
this.clearSelection();
this.fire("deselecting-all", {items: this.selectedItems});
} else {
this.selectAll();
this.fire("selecting-all", {items: this.selectedItems});
}
},
_isSelectAllChecked: function(selectedItemsLength, inverted, size) {
return size > 0 && selectedItemsLength === (inverted ? 0 : size);
},
_isSelectAllIndeterminate: function(length, size) {
return size > 0 && length > 0 && length < size;
},
_isEven: function(index) {
return index % 2 === 0;
},
_resetData: function(dataSource, filter, sortOrder) {
// Resetting scroll position and selection for consistency here. They are
// both reset implicitly when a new _cachedItems is set to iron-list, but
// that doesn't happen when size of the dataset changes only by a few items.
this.clearSelection();
this.clearCache();
this.$.list.scrollToIndex(0);
},
_sortDirectionChanged: function(e) {
for (var i = 0; i < this.sortOrder.length; i++) {
if (this.sortOrder[i].path === e.detail.path) {
if (e.detail.direction) {
this.set('sortOrder.' + i + '.direction', e.detail.direction);
} else {
this.splice('sortOrder', i, 1);
}
return;
}
}
this.push('sortOrder', {
path: e.detail.path,
direction: e.detail.direction
});
},
_columnsChanged: function(columns, oldColumns) {
if (oldColumns) {
oldColumns.forEach(function(column) {
this.unlisten(column, 'filter-value-changed');
}.bind(this));
}
if (columns) {
columns.forEach(function(column) {
column.table = this;
this.listen(column, 'filter-value-changed', '_onColumnFilterChanged');
}.bind(this));
}
},
_onColumnFilterChanged: function(e) {
for (var i = 0; i < this.filter.length; i++) {
if (this.filter[i].path === e.detail.filterBy) {
this.set('filter.' + i + '.filter', e.detail.value);
// selectedItems.filter is actually already set at this point when
// clearSelection is called after filter is set.
this.set('selectedItems.filters.' + i + '.filter', e.detail.value);
return;
}
}
this.push('filter', {
path: e.detail.filterBy,
filter: e.detail.value
});
this.push('selectedItems.filters', {
path: e.detail.filterBy,
filter: e.detail.value
});
},
_resizeCellContainers: function() {
// reset header width first to make the cells and scroll width to reset their widths.
this.$.container.style.width = '';
this.async(function() {
this.$.container.style.width = Math.min(this.scrollWidth, this.clientWidth + this.scrollLeft) + 'px';
// add scrollbar width as padding
this.$.header.style.paddingRight = this.$.list.offsetWidth - this.$.list.clientWidth + 'px';
}.bind(this));
},
_onHorizontalScroll: function() {
if (!this.isDebouncerActive('scrolling')) {
this.$.container.style.width = this.scrollWidth + 'px';
this.debounce('scrolling', function() {
this.$.container.style.width = Math.min(this.scrollWidth, this.clientWidth + this.scrollLeft) + 'px';
// long timeout here to prevent jerkiness with the rubberband effect on iOS especially.
}, 1000);
}
},
_onVerticalScroll: function(e) {
// Toggle shadow when at the top
this.toggleClass("scrolled", this.$.list.scrollTop >= 1, this.$.header);
this._currentPage = Math.max(0, Math.floor(this.$.list.scrollTop / this.$.list._physicalAverage / this.pageSize));
},
/**
* Lazy loading
*/
_itemsChanged: function(items) {
if ((items.path === 'items' || items.path === 'items.splices') && Array.isArray(items.base)) {
this.size = items.base.length;
this.dataSource = new ArrayDataSource(items.base);
} else if (items.path.indexOf('items.#') === 0 && Array.isArray(items.base)) {
var index = items.path.split('.')[1].substring(1);
var item = this.items[index];
var cachedIndex = this._cachedItems.indexOf(item);
if (cachedIndex >= 0) {
this.set(items.path.replace('items.', '_cachedItems.').replace('#' + index, cachedIndex), items.value);
}
}
},
_itemChanged: function(e) {
if (this.items) {
var index = this.items.indexOf(e.detail.item);
if (index >= 0) {
this.set('items.' + index + '.' + e.detail.path, e.detail.value);
}
}
if (this.autoRefresh !== undefined) {
this.debounce('auto-refresh', function() {
this.refreshPage(this._currentPage);
}, this.autoRefresh);
}
},
_currentPageChanged: function(dataSource, page) {
if (!this._isPageCached(page)) {
this.loading = true;
}
this.debounce('loading', function() {
this._loadPage(dataSource, page);
if (page + 1 < (this.size / this.pageSize)) {
this._loadPage(dataSource, page + 1);
}
if (page > 0) {
this._loadPage(dataSource, page - 1);
}
}.bind(this), 100);
},
_isPageLoading: function(page) {
return this._pagesLoading.indexOf(page) > -1;
},
_addLoadingPage: function(page) {
if (!this._isPageLoading(page)) {
this.push('_pagesLoading', page);
}
this.loading = this._pagesLoading.length > 0;
},
_removeLoadingPage: function(page) {
var index = this._pagesLoading.indexOf(page);
if (index !== -1) {
this.splice('_pagesLoading', index, 1);
}
this.loading = this._pagesLoading.length > 0;
},
_isPageCached: function(page) {
return this._cachedPages && this._cachedPages.indexOf(page) > -1;
},
_loadPage: function(dataSource, page) {
if (this._isPageCached(page)) {
this._removeLoadingPage(page);
} else if (!this._isPageLoading(page)) {
this._addLoadingPage(page);
var success = function(items, size) {
this.push('_cachedPages', page);
if (size !== undefined) {
this.size = size;
}
var start = page * this.pageSize;
for (var i = 0; i < this.pageSize; i++) {
var index = start + i;
var item = items[i];
this.set('_cachedItems.' + index, item);
// TODO: send an issue/pr to iron-list, that makes sure the internal
// collection stays up-to-date when `items` change.
// When _collection gets out-of-sync things like selection and
// notifying [[item]] bindings break.
this.$.list._collection.store[index] = item;
if (item && typeof item == 'object') {
this.$.list._collection.omap.set(item, index);
} else {
this.$.list._collection.pmap[item] = index;
}
}
// resize required for variable row height items.
// debouncing for optimizing when multiple requests are running at
// the same time.
this.debounce('resizing', function() {
this.$.list.notifyResize();
}.bind(this), 100);
this._removeLoadingPage(page);
}.bind(this);
var err = function() {
this._removeLoadingPage(page);
}.bind(this);
dataSource({
page: page,
pageSize: this.pageSize,
filter: this.filter,
sortOrder: this.sortOrder
}, success, err);
}
},
_sizeChanged: function(size, oldSize) {
// Optimization: Calling `set` on _cachedItems will reset the scroll position and selections,
// using `push` and `pop` with large changes (more than 1000 items) is a heavy operation
// that jams things up.
if (this._cachedItems && Math.abs(this._cachedItems.length - size) < this.pageSize * 2) {
while (this._cachedItems.length < size) {
this.push('_cachedItems', {});
}
while (this._cachedItems.length > size) {
this.pop('_cachedItems');
}
} else {
var items = [];
while (items.length < size) {
items.push({});
}
this.set('_cachedItems', items);
}
// when size increases, old last page needs to be refreshed.
if (size > oldSize) {
var oldLastPage = Math.floor(oldSize / this.pageSize);
if (this._isPageCached(oldLastPage) || oldLastPage === 0) {
this.refreshPage(oldLastPage);
}
}
},
/**
* Clears the cached pages and reloads data from datasource when needed.
*/
clearCache: function() {
this._cachedPages = [];
// Force reload on currently visible pages.
this.refreshPage(this._currentPage);
},
/**
* Clears the cache for a page and reloads the data from datasource.
*/
refreshPage: function(page) {
if (this._cachedPages) {
var index = this._cachedPages.indexOf(page);
if (index > -1) {
this.splice('_cachedPages', index, 1);
}
}
this._currentPageChanged(this.dataSource, page);
},
_updateSizeForItem: function(event) {
if (event.model.get('item')) {
// notifyResize() doesn't do anything on iOS if the viewport size hasn't changed
// so calling updateSizeForItem(item) is more reliable.
// TODO: However, since we're reusing the same items array in most cases,
// the _collection item map inside <iron-list> gets out of sync and
// that breaks things like selection and updateSizeForItem.
// To mitigate the issue, we'll update height of every row element.
// Can be optimized later if needed to update only the row that has
// expanded or collapsed.
var itemSet = [];
for(var i = 0; i < this.$.list._physicalItems.length; i++) {
itemSet.push(i);
}
// extracted from updateSizeFromItem(item) in <iron-list>
this.$.list._updateMetrics(itemSet);
this.$.list._positionItems();
}
},
/**
* Expands the row details for this item, if available.
*/
expandItem: function(item) {
if (this.rowDetail && this._expandedItems && !this._isExpanded(item, this._expandedItems)) {
// replacing the whole array here to simplify the observers.
this._expandedItems.push(item);
this._expandedItems = this._expandedItems.slice(0);
}
},
/**
* Collapses the row details for this item, if expanded.
*/
collapseItem: function(item) {
if (this.rowDetail && this._expandedItems && this._isExpanded(item, this._expandedItems)) {
var index = this._expandedItems.indexOf(item);
// replacing the whole array here to simplify the obsevers.
this._expandedItems.splice(index, 1);
this._expandedItems = this._expandedItems.slice(0);
}
},
_isExpanded: function(item, items) {
return items && items.indexOf(item) > -1;
},
_isFocusable: function(target) {
if (Polymer.Settings.useNativeShadow) {
// https://nemisj.com/focusable/
// tabIndex is not reliable in IE.
return target.tabIndex >= 0;
} else {
// unreliable with Shadow, document.activeElement doesn't go inside
// the shadow root.
return target.contains(Polymer.dom(document.activeElement).node) || target.tagName.toUpperCase() === 'A';
}
},
/**
* Fired when user clicks on a item to select it. Note that this event is
* not fired when user clicks on a multi-selection checkbox.
*
* @event selecting-item
* @param {Object} detail
* @param {Object} detail.item item to be selected
*/
/**
* Fired when user clicks on a item to deselect it. Note that this event is
* not fired when user clicks on a multi-selection checkbox.
*
* @event deselecting-item
* @param {Object} detail
* @param {Object} detail.item item to be deselected
*/
/**
* Fired when user clicks on a item to expand it.
*
* @event expanding-item
* @param {Object} detail