-
Notifications
You must be signed in to change notification settings - Fork 131
/
iron-list.js
1984 lines (1791 loc) · 59.3 KB
/
iron-list.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 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at
http://polymer.github.io/LICENSE.txt The complete set of authors may be found at
http://polymer.github.io/AUTHORS.txt The complete set of contributors may be
found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as
part of the polymer project is also subject to an additional IP rights grant
found at http://polymer.github.io/PATENTS.txt
*/
import '@polymer/polymer/polymer-legacy.js';
import '@polymer/iron-a11y-keys-behavior/iron-a11y-keys-behavior.js';
import {IronResizableBehavior} from '@polymer/iron-resizable-behavior/iron-resizable-behavior.js';
import {IronScrollTargetBehavior} from '@polymer/iron-scroll-target-behavior/iron-scroll-target-behavior.js';
import {OptionalMutableDataBehavior} from '@polymer/polymer/lib/legacy/mutable-data-behavior.js';
import {Polymer as Polymer} from '@polymer/polymer/lib/legacy/polymer-fn.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {Templatizer} from '@polymer/polymer/lib/legacy/templatizer-behavior.js';
import {animationFrame, idlePeriod, microTask} from '@polymer/polymer/lib/utils/async.js';
import {Debouncer} from '@polymer/polymer/lib/utils/debounce.js';
import {enqueueDebouncer, flush} from '@polymer/polymer/lib/utils/flush.js';
import {html} from '@polymer/polymer/lib/utils/html-tag.js';
import {matches, translate} from '@polymer/polymer/lib/utils/path.js';
import {TemplateInstanceBase} from '@polymer/polymer/lib/utils/templatize.js';
var IOS = navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);
var IOS_TOUCH_SCROLLING = IOS && IOS[1] >= 8;
var DEFAULT_PHYSICAL_COUNT = 3;
var HIDDEN_Y = '-10000px';
var SECRET_TABINDEX = -100;
/**
`iron-list` displays a virtual, 'infinite' list. The template inside
the iron-list element represents the DOM to create for each list item.
The `items` property specifies an array of list item data.
For performance reasons, not every item in the list is rendered at once;
instead a small subset of actual template elements *(enough to fill the
viewport)* are rendered and reused as the user scrolls. As such, it is important
that all state of the list template is bound to the model driving it, since the
view may be reused with a new model at any time. Particularly, any state that
may change as the result of a user interaction with the list item must be bound
to the model to avoid view state inconsistency.
### Sizing iron-list
`iron-list` must either be explicitly sized, or delegate scrolling to an
explicitly sized parent. By "explicitly sized", we mean it either has an
explicit CSS `height` property set via a class or inline style, or else is sized
by other layout means (e.g. the `flex` or `fit` classes).
#### Flexbox - [jsbin](https://jsbin.com/vejoni/edit?html,output)
```html
<template is="x-list">
<style>
:host {
display: block;
height: 100vh;
display: flex;
flex-direction: column;
}
iron-list {
flex: 1 1 auto;
}
</style>
<app-toolbar>App name</app-toolbar>
<iron-list items="[[items]]">
<template>
<div>
...
</div>
</template>
</iron-list>
</template>
```
#### Explicit size - [jsbin](https://jsbin.com/vopucus/edit?html,output)
```html
<template is="x-list">
<style>
:host {
display: block;
}
iron-list {
height: 100vh; /* don't use % values unless the parent element is sized.
*\/
}
</style>
<iron-list items="[[items]]">
<template>
<div>
...
</div>
</template>
</iron-list>
</template>
```
#### Main document scrolling -
[jsbin](https://jsbin.com/wevirow/edit?html,output)
```html
<head>
<style>
body {
height: 100vh;
margin: 0;
display: flex;
flex-direction: column;
}
app-toolbar {
position: fixed;
top: 0;
left: 0;
right: 0;
}
iron-list {
/* add padding since the app-toolbar is fixed at the top *\/
padding-top: 64px;
}
</style>
</head>
<body>
<app-toolbar>App name</app-toolbar>
<iron-list scroll-target="document">
<template>
<div>
...
</div>
</template>
</iron-list>
</body>
```
`iron-list` must be given a `<template>` which contains exactly one element. In
the examples above we used a `<div>`, but you can provide any element (including
custom elements).
### Template model
List item 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
tabIndex: -1, // a dynamically generated tabIndex for focus management
item: {} // user data corresponding to items[index]
}
```
Alternatively, you can change the property name used as data index by changing
the `indexAs` property. The `as` property defines the name of the variable to
add to the binding scope for the array.
For example, given the following `data` array:
##### data.json
```js
[
{"name": "Bob"},
{"name": "Tim"},
{"name": "Mike"}
]
```
The following code would render the list (note the name property is bound from
the model object provided to the template scope):
```html
<iron-ajax url="data.json" last-response="{{data}}" auto></iron-ajax>
<iron-list items="[[data]]" as="item">
<template>
<div>
Name: [[item.name]]
</div>
</template>
</iron-list>
```
### Grid layout
`iron-list` supports a grid layout in addition to linear layout by setting
the `grid` attribute. In this case, the list template item must have both fixed
width and height (e.g. via CSS). Based on this, the number of items
per row are determined automatically based on the size of the list viewport.
### Accessibility
`iron-list` automatically manages the focus state for the items. It also
provides a `tabIndex` property within the template scope that can be used for
keyboard navigation. For example, users can press the up and down keys to move
to previous and next items in the list:
```html
<iron-list items="[[data]]" as="item">
<template>
<div tabindex$="[[tabIndex]]">
Name: [[item.name]]
</div>
</template>
</iron-list>
```
### Styling
You can use the `--iron-list-items-container` mixin to style the container of
items:
```css
iron-list {
--iron-list-items-container: {
margin: auto;
};
}
```
### Resizing
`iron-list` lays out the items when it receives a notification via the
`iron-resize` event. This event is fired by any element that implements
`IronResizableBehavior`.
By default, elements such as `iron-pages`, `paper-tabs` or `paper-dialog` will
trigger this event automatically. If you hide the list manually (e.g. you use
`display: none`) you might want to implement `IronResizableBehavior` or fire
this event manually right after the list became visible again. For example:
```js
document.querySelector('iron-list').fire('iron-resize');
```
### When should `<iron-list>` be used?
`iron-list` should be used when a page has significantly more DOM nodes than the
ones visible on the screen. e.g. the page has 500 nodes, but only 20 are visible
at a time. This is why we refer to it as a `virtual` list. In this case, a
`dom-repeat` will still create 500 nodes which could slow down the web app, but
`iron-list` will only create 20.
However, having an `iron-list` does not mean that you can load all the data at
once. Say you have a million records in the database, you want to split the data
into pages so you can bring in a page at the time. The page could contain 500
items, and iron-list will only render 20.
@element iron-list
@demo demo/index.html
*/
Polymer({
/** @override */
_template: html`
<style>
:host {
display: block;
}
@media only screen and (-webkit-max-device-pixel-ratio: 1) {
:host {
will-change: transform;
}
}
#items {
@apply --iron-list-items-container;
position: relative;
}
:host(:not([grid])) #items > ::slotted(*) {
width: 100%;
}
#items > ::slotted(*) {
box-sizing: border-box;
margin: 0;
position: absolute;
top: 0;
will-change: transform;
}
</style>
<array-selector id="selector" items="{{items}}" selected="{{selectedItems}}" selected-item="{{selectedItem}}"></array-selector>
<div id="items">
<slot></slot>
</div>
`,
is: 'iron-list',
properties: {
/**
* An array containing items determining how many instances of the template
* to stamp and that that each template instance should bind to.
*/
items: {type: Array},
/**
* The name of the variable to add to the binding scope for the array
* element associated with a given template instance.
*/
as: {type: String, value: 'item'},
/**
* The name of the variable to add to the binding scope with the index
* for the row.
*/
indexAs: {type: String, value: 'index'},
/**
* The name of the variable to add to the binding scope to indicate
* if the row is selected.
*/
selectedAs: {type: String, value: 'selected'},
/**
* When true, the list is rendered as a grid. Grid items must have
* fixed width and height set via CSS. e.g.
*
* ```html
* <iron-list grid>
* <template>
* <div style="width: 100px; height: 100px;"> 100x100 </div>
* </template>
* </iron-list>
* ```
*/
grid: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: '_gridChanged'
},
/**
* When true, tapping a row will select the item, placing its data model
* in the set of selected items retrievable via the selection property.
*
* Note that tapping focusable elements within the list item will not
* result in selection, since they are presumed to have their * own action.
*/
selectionEnabled: {type: Boolean, value: false},
/**
* When `multiSelection` is false, this is the currently selected item, or
* `null` if no item is selected.
*/
selectedItem: {type: Object, notify: true},
/**
* When `multiSelection` is true, this is an array that contains the
* selected items.
*/
selectedItems: {type: Object, notify: true},
/**
* 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},
/**
* The offset top from the scrolling element to the iron-list element.
* This value can be computed using the position returned by
* `getBoundingClientRect()` although it's preferred to use a constant value
* when possible.
*
* This property is useful when an external scrolling element is used and
* there's some offset between the scrolling element and the list. For
* example: a header is placed above the list.
*/
scrollOffset: {type: Number, value: 0}
},
observers: [
'_itemsChanged(items.*)',
'_selectionEnabledChanged(selectionEnabled)',
'_multiSelectionChanged(multiSelection)',
'_setOverflow(scrollTarget, scrollOffset)'
],
behaviors: [
Templatizer,
IronResizableBehavior,
IronScrollTargetBehavior,
OptionalMutableDataBehavior
],
/**
* The ratio of hidden tiles that should remain in the scroll direction.
* Recommended value ~0.5, so it will distribute tiles evenly in both
* directions.
*/
_ratio: 0.5,
/**
* The padding-top value for the list.
*/
_scrollerPaddingTop: 0,
/**
* This value is a cached value of `scrollTop` from the last `scroll` event.
*/
_scrollPosition: 0,
/**
* The sum of the heights of all the tiles in the DOM.
*/
_physicalSize: 0,
/**
* The average `offsetHeight` of the tiles observed till now.
*/
_physicalAverage: 0,
/**
* The number of tiles which `offsetHeight` > 0 observed until now.
*/
_physicalAverageCount: 0,
/**
* The Y position of the item rendered in the `_physicalStart`
* tile relative to the scrolling list.
*/
_physicalTop: 0,
/**
* The number of items in the list.
*/
_virtualCount: 0,
/**
* The estimated scroll height based on `_physicalAverage`
*/
_estScrollHeight: 0,
/**
* The scroll height of the dom node
*/
_scrollHeight: 0,
/**
* The height of the list. This is referred as the viewport in the context of
* list.
*/
_viewportHeight: 0,
/**
* The width of the list. This is referred as the viewport in the context of
* list.
*/
_viewportWidth: 0,
/**
* An array of DOM nodes that are currently in the tree
* @type {?Array<!HTMLElement>}
*/
_physicalItems: null,
/**
* An array of heights for each item in `_physicalItems`
* @type {?Array<number>}
*/
_physicalSizes: null,
/**
* A cached value for the first visible index.
* See `firstVisibleIndex`
* @type {?number}
*/
_firstVisibleIndexVal: null,
/**
* A cached value for the last visible index.
* See `lastVisibleIndex`
* @type {?number}
*/
_lastVisibleIndexVal: null,
/**
* The max number of pages to render. One page is equivalent to the height of
* the list.
*/
_maxPages: 2,
/**
* The currently focused physical item.
*/
_focusedItem: null,
/**
* The virtual index of the focused item.
*/
_focusedVirtualIndex: -1,
/**
* The physical index of the focused item.
*/
_focusedPhysicalIndex: -1,
/**
* The the item that is focused if it is moved offscreen.
* @private {?HTMLElement}
*/
_offscreenFocusedItem: null,
/**
* The item that backfills the `_offscreenFocusedItem` in the physical items
* list when that item is moved offscreen.
* @type {?HTMLElement}
*/
_focusBackfillItem: null,
/**
* The maximum items per row
*/
_itemsPerRow: 1,
/**
* The width of each grid item
*/
_itemWidth: 0,
/**
* The height of the row in grid layout.
*/
_rowHeight: 0,
/**
* The cost of stamping a template in ms.
*/
_templateCost: 0,
/**
* Needed to pass event.model property to declarative event handlers -
* see polymer/polymer#4339.
*/
_parentModel: true,
/**
* The bottom of the physical content.
*/
get _physicalBottom() {
return this._physicalTop + this._physicalSize;
},
/**
* The bottom of the scroll.
*/
get _scrollBottom() {
return this._scrollPosition + this._viewportHeight;
},
/**
* The n-th item rendered in the last physical item.
*/
get _virtualEnd() {
return this._virtualStart + this._physicalCount - 1;
},
/**
* The height of the physical content that isn't on the screen.
*/
get _hiddenContentSize() {
var size =
this.grid ? this._physicalRows * this._rowHeight : this._physicalSize;
return size - this._viewportHeight;
},
/**
* The parent node for the _userTemplate.
*/
get _itemsParent() {
return dom(dom(this._userTemplate).parentNode);
},
/**
* The maximum scroll top value.
*/
get _maxScrollTop() {
return this._estScrollHeight - this._viewportHeight + this._scrollOffset;
},
/**
* The largest n-th value for an item such that it can be rendered in
* `_physicalStart`.
*/
get _maxVirtualStart() {
var virtualCount = this._convertIndexToCompleteRow(this._virtualCount);
return Math.max(0, virtualCount - this._physicalCount);
},
set _virtualStart(val) {
val = this._clamp(val, 0, this._maxVirtualStart);
if (this.grid) {
val = val - (val % this._itemsPerRow);
}
this._virtualStartVal = val;
},
get _virtualStart() {
return this._virtualStartVal || 0;
},
/**
* The k-th tile that is at the top of the scrolling list.
*/
set _physicalStart(val) {
val = val % this._physicalCount;
if (val < 0) {
val = this._physicalCount + val;
}
if (this.grid) {
val = val - (val % this._itemsPerRow);
}
this._physicalStartVal = val;
},
get _physicalStart() {
return this._physicalStartVal || 0;
},
/**
* The k-th tile that is at the bottom of the scrolling list.
*/
get _physicalEnd() {
return (this._physicalStart + this._physicalCount - 1) %
this._physicalCount;
},
set _physicalCount(val) {
this._physicalCountVal = val;
},
get _physicalCount() {
return this._physicalCountVal || 0;
},
/**
* An optimal physical size such that we will have enough physical items
* to fill up the viewport and recycle when the user scrolls.
*
* This default value assumes that we will at least have the equivalent
* to a viewport of physical items above and below the user's viewport.
*/
get _optPhysicalSize() {
return this._viewportHeight === 0 ? Infinity :
this._viewportHeight * this._maxPages;
},
/**
* True if the current list is visible.
*/
get _isVisible() {
return Boolean(this.offsetWidth || this.offsetHeight);
},
/**
* Gets the index of the first visible item in the viewport.
*
* @type {number}
*/
get firstVisibleIndex() {
var idx = this._firstVisibleIndexVal;
if (idx == null) {
var physicalOffset = this._physicalTop + this._scrollOffset;
idx = this._iterateItems(function(pidx, vidx) {
physicalOffset += this._getPhysicalSizeIncrement(pidx);
if (physicalOffset > this._scrollPosition) {
return this.grid ? vidx - (vidx % this._itemsPerRow) : vidx;
}
// Handle a partially rendered final row in grid mode
if (this.grid && this._virtualCount - 1 === vidx) {
return vidx - (vidx % this._itemsPerRow);
}
}) ||
0;
this._firstVisibleIndexVal = idx;
}
return idx;
},
/**
* Gets the index of the last visible item in the viewport.
*
* @type {number}
*/
get lastVisibleIndex() {
var idx = this._lastVisibleIndexVal;
if (idx == null) {
if (this.grid) {
idx = Math.min(
this._virtualCount,
this.firstVisibleIndex + this._estRowsInView * this._itemsPerRow -
1);
} else {
var physicalOffset = this._physicalTop + this._scrollOffset;
this._iterateItems(function(pidx, vidx) {
if (physicalOffset < this._scrollBottom) {
idx = vidx;
}
physicalOffset += this._getPhysicalSizeIncrement(pidx);
});
}
this._lastVisibleIndexVal = idx;
}
return idx;
},
get _defaultScrollTarget() {
return this;
},
get _virtualRowCount() {
return Math.ceil(this._virtualCount / this._itemsPerRow);
},
get _estRowsInView() {
return Math.ceil(this._viewportHeight / this._rowHeight);
},
get _physicalRows() {
return Math.ceil(this._physicalCount / this._itemsPerRow);
},
get _scrollOffset() {
return this._scrollerPaddingTop + this.scrollOffset;
},
/** @override */
ready: function() {
this.addEventListener('focus', this._didFocus.bind(this), true);
},
/** @override */
attached: function() {
this._debounce('_render', this._render, animationFrame);
// `iron-resize` is fired when the list is attached if the event is added
// before attached causing unnecessary work.
this.listen(this, 'iron-resize', '_resizeHandler');
this.listen(this, 'keydown', '_keydownHandler');
},
/** @override */
detached: function() {
this.unlisten(this, 'iron-resize', '_resizeHandler');
this.unlisten(this, 'keydown', '_keydownHandler');
},
/**
* Set the overflow property if this element has its own scrolling region
*/
_setOverflow: function(scrollTarget) {
this.style.webkitOverflowScrolling = scrollTarget === this ? 'touch' : '';
this.style.overflowY = scrollTarget === this ? 'auto' : '';
// Clear cache.
this._lastVisibleIndexVal = null;
this._firstVisibleIndexVal = null;
this._debounce('_render', this._render, animationFrame);
},
/**
* Invoke this method if you dynamically update the viewport's
* size or CSS padding.
*
* @method updateViewportBoundaries
*/
updateViewportBoundaries: function() {
var styles = window.getComputedStyle(this);
this._scrollerPaddingTop =
this.scrollTarget === this ? 0 : parseInt(styles['padding-top'], 10);
this._isRTL = Boolean(styles.direction === 'rtl');
this._viewportWidth = this.$.items.offsetWidth;
this._viewportHeight = this._scrollTargetHeight;
this.grid && this._updateGridMetrics();
},
/**
* Recycles the physical items when needed.
*/
_scrollHandler: function() {
var scrollTop = Math.max(0, Math.min(this._maxScrollTop, this._scrollTop));
var delta = scrollTop - this._scrollPosition;
var isScrollingDown = delta >= 0;
// Track the current scroll position.
this._scrollPosition = scrollTop;
// Clear indexes for first and last visible indexes.
this._firstVisibleIndexVal = null;
this._lastVisibleIndexVal = null;
// Random access.
if (Math.abs(delta) > this._physicalSize && this._physicalSize > 0) {
delta = delta - this._scrollOffset;
var idxAdjustment =
Math.round(delta / this._physicalAverage) * this._itemsPerRow;
this._virtualStart = this._virtualStart + idxAdjustment;
this._physicalStart = this._physicalStart + idxAdjustment;
// Estimate new physical offset based on the virtual start index.
// adjusts the physical start position to stay in sync with the clamped
// virtual start index. It's critical not to let this value be
// more than the scroll position however, since that would result in
// the physical items not covering the viewport, and leading to
// _increasePoolIfNeeded to run away creating items to try to fill it.
this._physicalTop = Math.min(
Math.floor(this._virtualStart / this._itemsPerRow) *
this._physicalAverage,
this._scrollPosition);
this._update();
} else if (this._physicalCount > 0) {
var reusables = this._getReusables(isScrollingDown);
if (isScrollingDown) {
this._physicalTop = reusables.physicalTop;
this._virtualStart = this._virtualStart + reusables.indexes.length;
this._physicalStart = this._physicalStart + reusables.indexes.length;
} else {
this._virtualStart = this._virtualStart - reusables.indexes.length;
this._physicalStart = this._physicalStart - reusables.indexes.length;
}
this._update(
reusables.indexes, isScrollingDown ? null : reusables.indexes);
this._debounce(
'_increasePoolIfNeeded',
this._increasePoolIfNeeded.bind(this, 0),
microTask);
}
},
/**
* Returns an object that contains the indexes of the physical items
* that might be reused and the physicalTop.
*
* @param {boolean} fromTop If the potential reusable items are above the scrolling region.
*/
_getReusables: function(fromTop) {
var ith, lastIth, offsetContent, physicalItemHeight;
var idxs = [];
var protectedOffsetContent = this._hiddenContentSize * this._ratio;
var virtualStart = this._virtualStart;
var virtualEnd = this._virtualEnd;
var physicalCount = this._physicalCount;
var top = this._physicalTop + this._scrollOffset;
var bottom = this._physicalBottom + this._scrollOffset;
// This may be called outside of a scrollHandler, so use last cached position
var scrollTop = this._scrollPosition;
var scrollBottom = this._scrollBottom;
if (fromTop) {
ith = this._physicalStart;
lastIth = this._physicalEnd;
offsetContent = scrollTop - top;
} else {
ith = this._physicalEnd;
lastIth = this._physicalStart;
offsetContent = bottom - scrollBottom;
}
while (true) {
physicalItemHeight = this._getPhysicalSizeIncrement(ith);
offsetContent = offsetContent - physicalItemHeight;
if (idxs.length >= physicalCount ||
offsetContent <= protectedOffsetContent) {
break;
}
if (fromTop) {
// Check that index is within the valid range.
if (virtualEnd + idxs.length + 1 >= this._virtualCount) {
break;
}
// Check that the index is not visible.
if (top + physicalItemHeight >= scrollTop - this._scrollOffset) {
break;
}
idxs.push(ith);
top = top + physicalItemHeight;
ith = (ith + 1) % physicalCount;
} else {
// Check that index is within the valid range.
if (virtualStart - idxs.length <= 0) {
break;
}
// Check that the index is not visible.
if (top + this._physicalSize - physicalItemHeight <= scrollBottom) {
break;
}
idxs.push(ith);
top = top - physicalItemHeight;
ith = (ith === 0) ? physicalCount - 1 : ith - 1;
}
}
return {indexes: idxs, physicalTop: top - this._scrollOffset};
},
/**
* Update the list of items, starting from the `_virtualStart` item.
* @param {!Array<number>=} itemSet
* @param {!Array<number>=} movingUp
*/
_update: function(itemSet, movingUp) {
if ((itemSet && itemSet.length === 0) || this._physicalCount === 0) {
return;
}
this._manageFocus();
this._assignModels(itemSet);
this._updateMetrics(itemSet);
// Adjust offset after measuring.
if (movingUp) {
while (movingUp.length) {
var idx = movingUp.pop();
this._physicalTop -= this._getPhysicalSizeIncrement(idx);
}
}
this._positionItems();
this._updateScrollerSize();
},
/**
* Creates a pool of DOM elements and attaches them to the local dom.
*
* @param {number} size Size of the pool
*/
_createPool: function(size) {
this._ensureTemplatized();
var i, inst;
var physicalItems = new Array(size);
for (i = 0; i < size; i++) {
inst = this.stamp(null);
// TODO(blasten):
// First element child is item; Safari doesn't support children[0]
// on a doc fragment. Test this to see if it still matters.
physicalItems[i] = inst.root.querySelector('*');
this._itemsParent.appendChild(inst.root);
}
return physicalItems;
},
_isClientFull: function() {
return this._scrollBottom != 0 &&
this._physicalBottom - 1 >= this._scrollBottom &&
this._physicalTop <= this._scrollPosition;
},
/**
* Increases the pool size.
*/
_increasePoolIfNeeded: function(count) {
var nextPhysicalCount = this._clamp(
this._physicalCount + count,
DEFAULT_PHYSICAL_COUNT,
this._virtualCount - this._virtualStart);
nextPhysicalCount = this._convertIndexToCompleteRow(nextPhysicalCount);
if (this.grid) {
var correction = nextPhysicalCount % this._itemsPerRow;
if (correction && nextPhysicalCount - correction <= this._physicalCount) {
nextPhysicalCount += this._itemsPerRow;
}
nextPhysicalCount -= correction;
}
var delta = nextPhysicalCount - this._physicalCount;
var nextIncrease = Math.round(this._physicalCount * 0.5);
if (delta < 0) {
return;
}
if (delta > 0) {
var ts = window.performance.now();
// Concat arrays in place.
[].push.apply(this._physicalItems, this._createPool(delta));
// Push 0s into physicalSizes. Can't use Array.fill because IE11 doesn't
// support it.
for (var i = 0; i < delta; i++) {
this._physicalSizes.push(0);
}
this._physicalCount = this._physicalCount + delta;
// Update the physical start if it needs to preserve the model of the
// focused item. In this situation, the focused item is currently rendered
// and its model would have changed after increasing the pool if the
// physical start remained unchanged.
if (this._physicalStart > this._physicalEnd &&
this._isIndexRendered(this._focusedVirtualIndex) &&
this._getPhysicalIndex(this._focusedVirtualIndex) <
this._physicalEnd) {
this._physicalStart = this._physicalStart + delta;
}
this._update();
this._templateCost = (window.performance.now() - ts) / delta;
nextIncrease = Math.round(this._physicalCount * 0.5);
}
// The upper bounds is not fixed when dealing with a grid that doesn't
// fill it's last row with the exact number of items per row.
if (this._virtualEnd >= this._virtualCount - 1 || nextIncrease === 0) {
// Do nothing.
} else if (!this._isClientFull()) {
this._debounce(