@vaadin/component-base 22.0.0-alpha9 → 22.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,951 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
4
+ * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
5
+ * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
6
+ * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
7
+ * Code distributed by Google as part of the polymer project is also
8
+ * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
9
+ */
10
+ import { animationFrame, idlePeriod, microTask } from './async.js';
11
+ import { Debouncer, enqueueDebouncer, flush } from './debounce.js';
12
+
13
+ const IOS = navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);
14
+ const IOS_TOUCH_SCROLLING = IOS && IOS[1] >= 8;
15
+ const DEFAULT_PHYSICAL_COUNT = 3;
16
+
17
+ /**
18
+ * @private
19
+ */
20
+ export const ironList = {
21
+ /**
22
+ * The ratio of hidden tiles that should remain in the scroll direction.
23
+ * Recommended value ~0.5, so it will distribute tiles evenly in both
24
+ * directions.
25
+ */
26
+ _ratio: 0.5,
27
+
28
+ /**
29
+ * The padding-top value for the list.
30
+ */
31
+ _scrollerPaddingTop: 0,
32
+
33
+ /**
34
+ * This value is a cached value of `scrollTop` from the last `scroll` event.
35
+ */
36
+ _scrollPosition: 0,
37
+
38
+ /**
39
+ * The sum of the heights of all the tiles in the DOM.
40
+ */
41
+ _physicalSize: 0,
42
+
43
+ /**
44
+ * The average `offsetHeight` of the tiles observed till now.
45
+ */
46
+ _physicalAverage: 0,
47
+
48
+ /**
49
+ * The number of tiles which `offsetHeight` > 0 observed until now.
50
+ */
51
+ _physicalAverageCount: 0,
52
+
53
+ /**
54
+ * The Y position of the item rendered in the `_physicalStart`
55
+ * tile relative to the scrolling list.
56
+ */
57
+ _physicalTop: 0,
58
+
59
+ /**
60
+ * The number of items in the list.
61
+ */
62
+ _virtualCount: 0,
63
+
64
+ /**
65
+ * The estimated scroll height based on `_physicalAverage`
66
+ */
67
+ _estScrollHeight: 0,
68
+
69
+ /**
70
+ * The scroll height of the dom node
71
+ */
72
+ _scrollHeight: 0,
73
+
74
+ /**
75
+ * The height of the list. This is referred as the viewport in the context of
76
+ * list.
77
+ */
78
+ _viewportHeight: 0,
79
+
80
+ /**
81
+ * The width of the list. This is referred as the viewport in the context of
82
+ * list.
83
+ */
84
+ _viewportWidth: 0,
85
+
86
+ /**
87
+ * An array of DOM nodes that are currently in the tree
88
+ * @type {?Array<!HTMLElement>}
89
+ */
90
+ _physicalItems: null,
91
+
92
+ /**
93
+ * An array of heights for each item in `_physicalItems`
94
+ * @type {?Array<number>}
95
+ */
96
+ _physicalSizes: null,
97
+
98
+ /**
99
+ * A cached value for the first visible index.
100
+ * See `firstVisibleIndex`
101
+ * @type {?number}
102
+ */
103
+ _firstVisibleIndexVal: null,
104
+
105
+ /**
106
+ * A cached value for the last visible index.
107
+ * See `lastVisibleIndex`
108
+ * @type {?number}
109
+ */
110
+ _lastVisibleIndexVal: null,
111
+
112
+ /**
113
+ * The max number of pages to render. One page is equivalent to the height of
114
+ * the list.
115
+ */
116
+ _maxPages: 2,
117
+
118
+ /**
119
+ * The maximum items per row
120
+ */
121
+ _itemsPerRow: 1,
122
+
123
+ /**
124
+ * The width of each grid item
125
+ */
126
+ _itemWidth: 0,
127
+
128
+ /**
129
+ * The height of the row in grid layout.
130
+ */
131
+ _rowHeight: 0,
132
+
133
+ /**
134
+ * The cost of stamping a template in ms.
135
+ */
136
+ _templateCost: 0,
137
+
138
+ /**
139
+ * Needed to pass event.model property to declarative event handlers -
140
+ * see polymer/polymer#4339.
141
+ */
142
+ _parentModel: true,
143
+
144
+ /**
145
+ * The bottom of the physical content.
146
+ */
147
+ get _physicalBottom() {
148
+ return this._physicalTop + this._physicalSize;
149
+ },
150
+
151
+ /**
152
+ * The bottom of the scroll.
153
+ */
154
+ get _scrollBottom() {
155
+ return this._scrollPosition + this._viewportHeight;
156
+ },
157
+
158
+ /**
159
+ * The n-th item rendered in the last physical item.
160
+ */
161
+ get _virtualEnd() {
162
+ return this._virtualStart + this._physicalCount - 1;
163
+ },
164
+
165
+ /**
166
+ * The height of the physical content that isn't on the screen.
167
+ */
168
+ get _hiddenContentSize() {
169
+ var size = this.grid ? this._physicalRows * this._rowHeight : this._physicalSize;
170
+ return size - this._viewportHeight;
171
+ },
172
+
173
+ /**
174
+ * The maximum scroll top value.
175
+ */
176
+ get _maxScrollTop() {
177
+ return this._estScrollHeight - this._viewportHeight + this._scrollOffset;
178
+ },
179
+
180
+ /**
181
+ * The largest n-th value for an item such that it can be rendered in
182
+ * `_physicalStart`.
183
+ */
184
+ get _maxVirtualStart() {
185
+ var virtualCount = this._convertIndexToCompleteRow(this._virtualCount);
186
+ return Math.max(0, virtualCount - this._physicalCount);
187
+ },
188
+
189
+ set _virtualStart(val) {
190
+ val = this._clamp(val, 0, this._maxVirtualStart);
191
+ if (this.grid) {
192
+ val = val - (val % this._itemsPerRow);
193
+ }
194
+ this._virtualStartVal = val;
195
+ },
196
+
197
+ get _virtualStart() {
198
+ return this._virtualStartVal || 0;
199
+ },
200
+
201
+ /**
202
+ * The k-th tile that is at the top of the scrolling list.
203
+ */
204
+ set _physicalStart(val) {
205
+ val = val % this._physicalCount;
206
+ if (val < 0) {
207
+ val = this._physicalCount + val;
208
+ }
209
+ if (this.grid) {
210
+ val = val - (val % this._itemsPerRow);
211
+ }
212
+ this._physicalStartVal = val;
213
+ },
214
+
215
+ get _physicalStart() {
216
+ return this._physicalStartVal || 0;
217
+ },
218
+
219
+ /**
220
+ * The k-th tile that is at the bottom of the scrolling list.
221
+ */
222
+ get _physicalEnd() {
223
+ return (this._physicalStart + this._physicalCount - 1) % this._physicalCount;
224
+ },
225
+
226
+ set _physicalCount(val) {
227
+ this._physicalCountVal = val;
228
+ },
229
+
230
+ get _physicalCount() {
231
+ return this._physicalCountVal || 0;
232
+ },
233
+
234
+ /**
235
+ * An optimal physical size such that we will have enough physical items
236
+ * to fill up the viewport and recycle when the user scrolls.
237
+ *
238
+ * This default value assumes that we will at least have the equivalent
239
+ * to a viewport of physical items above and below the user's viewport.
240
+ */
241
+ get _optPhysicalSize() {
242
+ return this._viewportHeight === 0 ? Infinity : this._viewportHeight * this._maxPages;
243
+ },
244
+
245
+ /**
246
+ * True if the current list is visible.
247
+ */
248
+ get _isVisible() {
249
+ return Boolean(this.offsetWidth || this.offsetHeight);
250
+ },
251
+
252
+ /**
253
+ * Gets the index of the first visible item in the viewport.
254
+ *
255
+ * @type {number}
256
+ */
257
+ get firstVisibleIndex() {
258
+ var idx = this._firstVisibleIndexVal;
259
+ if (idx == null) {
260
+ var physicalOffset = this._physicalTop + this._scrollOffset;
261
+
262
+ idx =
263
+ this._iterateItems(function (pidx, vidx) {
264
+ physicalOffset += this._getPhysicalSizeIncrement(pidx);
265
+
266
+ if (physicalOffset > this._scrollPosition) {
267
+ return this.grid ? vidx - (vidx % this._itemsPerRow) : vidx;
268
+ }
269
+ // Handle a partially rendered final row in grid mode
270
+ if (this.grid && this._virtualCount - 1 === vidx) {
271
+ return vidx - (vidx % this._itemsPerRow);
272
+ }
273
+ }) || 0;
274
+ this._firstVisibleIndexVal = idx;
275
+ }
276
+ return idx;
277
+ },
278
+
279
+ /**
280
+ * Gets the index of the last visible item in the viewport.
281
+ *
282
+ * @type {number}
283
+ */
284
+ get lastVisibleIndex() {
285
+ var idx = this._lastVisibleIndexVal;
286
+ if (idx == null) {
287
+ if (this.grid) {
288
+ idx = Math.min(this._virtualCount, this.firstVisibleIndex + this._estRowsInView * this._itemsPerRow - 1);
289
+ } else {
290
+ var physicalOffset = this._physicalTop + this._scrollOffset;
291
+ this._iterateItems(function (pidx, vidx) {
292
+ if (physicalOffset < this._scrollBottom) {
293
+ idx = vidx;
294
+ }
295
+ physicalOffset += this._getPhysicalSizeIncrement(pidx);
296
+ });
297
+ }
298
+ this._lastVisibleIndexVal = idx;
299
+ }
300
+ return idx;
301
+ },
302
+
303
+ get _defaultScrollTarget() {
304
+ return this;
305
+ },
306
+
307
+ get _virtualRowCount() {
308
+ return Math.ceil(this._virtualCount / this._itemsPerRow);
309
+ },
310
+
311
+ get _estRowsInView() {
312
+ return Math.ceil(this._viewportHeight / this._rowHeight);
313
+ },
314
+
315
+ get _physicalRows() {
316
+ return Math.ceil(this._physicalCount / this._itemsPerRow);
317
+ },
318
+
319
+ get _scrollOffset() {
320
+ return this._scrollerPaddingTop + this.scrollOffset;
321
+ },
322
+
323
+ /**
324
+ * Recycles the physical items when needed.
325
+ */
326
+ _scrollHandler: function () {
327
+ var scrollTop = Math.max(0, Math.min(this._maxScrollTop, this._scrollTop));
328
+ var delta = scrollTop - this._scrollPosition;
329
+ var isScrollingDown = delta >= 0;
330
+ // Track the current scroll position.
331
+ this._scrollPosition = scrollTop;
332
+ // Clear indexes for first and last visible indexes.
333
+ this._firstVisibleIndexVal = null;
334
+ this._lastVisibleIndexVal = null;
335
+ // Random access.
336
+ if (Math.abs(delta) > this._physicalSize && this._physicalSize > 0) {
337
+ delta = delta - this._scrollOffset;
338
+ var idxAdjustment = Math.round(delta / this._physicalAverage) * this._itemsPerRow;
339
+ this._virtualStart = this._virtualStart + idxAdjustment;
340
+ this._physicalStart = this._physicalStart + idxAdjustment;
341
+ // Estimate new physical offset based on the virtual start index.
342
+ // adjusts the physical start position to stay in sync with the clamped
343
+ // virtual start index. It's critical not to let this value be
344
+ // more than the scroll position however, since that would result in
345
+ // the physical items not covering the viewport, and leading to
346
+ // _increasePoolIfNeeded to run away creating items to try to fill it.
347
+ this._physicalTop = Math.min(
348
+ Math.floor(this._virtualStart / this._itemsPerRow) * this._physicalAverage,
349
+ this._scrollPosition
350
+ );
351
+ this._update();
352
+ } else if (this._physicalCount > 0) {
353
+ var reusables = this._getReusables(isScrollingDown);
354
+ if (isScrollingDown) {
355
+ this._physicalTop = reusables.physicalTop;
356
+ this._virtualStart = this._virtualStart + reusables.indexes.length;
357
+ this._physicalStart = this._physicalStart + reusables.indexes.length;
358
+ } else {
359
+ this._virtualStart = this._virtualStart - reusables.indexes.length;
360
+ this._physicalStart = this._physicalStart - reusables.indexes.length;
361
+ }
362
+ this._update(reusables.indexes, isScrollingDown ? null : reusables.indexes);
363
+ this._debounce('_increasePoolIfNeeded', this._increasePoolIfNeeded.bind(this, 0), microTask);
364
+ }
365
+ },
366
+
367
+ /**
368
+ * Returns an object that contains the indexes of the physical items
369
+ * that might be reused and the physicalTop.
370
+ *
371
+ * @param {boolean} fromTop If the potential reusable items are above the scrolling region.
372
+ */
373
+ _getReusables: function (fromTop) {
374
+ var ith, lastIth, offsetContent, physicalItemHeight;
375
+ var idxs = [];
376
+ var protectedOffsetContent = this._hiddenContentSize * this._ratio;
377
+ var virtualStart = this._virtualStart;
378
+ var virtualEnd = this._virtualEnd;
379
+ var physicalCount = this._physicalCount;
380
+ var top = this._physicalTop + this._scrollOffset;
381
+ var bottom = this._physicalBottom + this._scrollOffset;
382
+ // This may be called outside of a scrollHandler, so use last cached position
383
+ var scrollTop = this._scrollPosition;
384
+ var scrollBottom = this._scrollBottom;
385
+
386
+ if (fromTop) {
387
+ ith = this._physicalStart;
388
+ lastIth = this._physicalEnd;
389
+ offsetContent = scrollTop - top;
390
+ } else {
391
+ ith = this._physicalEnd;
392
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
393
+ lastIth = this._physicalStart;
394
+ offsetContent = bottom - scrollBottom;
395
+ }
396
+ // eslint-disable-next-line no-constant-condition
397
+ while (true) {
398
+ physicalItemHeight = this._getPhysicalSizeIncrement(ith);
399
+ offsetContent = offsetContent - physicalItemHeight;
400
+ if (idxs.length >= physicalCount || offsetContent <= protectedOffsetContent) {
401
+ break;
402
+ }
403
+ if (fromTop) {
404
+ // Check that index is within the valid range.
405
+ if (virtualEnd + idxs.length + 1 >= this._virtualCount) {
406
+ break;
407
+ }
408
+ // Check that the index is not visible.
409
+ if (top + physicalItemHeight >= scrollTop - this._scrollOffset) {
410
+ break;
411
+ }
412
+ idxs.push(ith);
413
+ top = top + physicalItemHeight;
414
+ ith = (ith + 1) % physicalCount;
415
+ } else {
416
+ // Check that index is within the valid range.
417
+ if (virtualStart - idxs.length <= 0) {
418
+ break;
419
+ }
420
+ // Check that the index is not visible.
421
+ if (top + this._physicalSize - physicalItemHeight <= scrollBottom) {
422
+ break;
423
+ }
424
+ idxs.push(ith);
425
+ top = top - physicalItemHeight;
426
+ ith = ith === 0 ? physicalCount - 1 : ith - 1;
427
+ }
428
+ }
429
+ return { indexes: idxs, physicalTop: top - this._scrollOffset };
430
+ },
431
+
432
+ /**
433
+ * Update the list of items, starting from the `_virtualStart` item.
434
+ * @param {!Array<number>=} itemSet
435
+ * @param {!Array<number>=} movingUp
436
+ */
437
+ _update: function (itemSet, movingUp) {
438
+ if ((itemSet && itemSet.length === 0) || this._physicalCount === 0) {
439
+ return;
440
+ }
441
+ this._manageFocus();
442
+ this._assignModels(itemSet);
443
+ this._updateMetrics(itemSet);
444
+ // Adjust offset after measuring.
445
+ if (movingUp) {
446
+ while (movingUp.length) {
447
+ var idx = movingUp.pop();
448
+ this._physicalTop -= this._getPhysicalSizeIncrement(idx);
449
+ }
450
+ }
451
+ this._positionItems();
452
+ this._updateScrollerSize();
453
+ },
454
+
455
+ _isClientFull: function () {
456
+ return (
457
+ this._scrollBottom != 0 &&
458
+ this._physicalBottom - 1 >= this._scrollBottom &&
459
+ this._physicalTop <= this._scrollPosition
460
+ );
461
+ },
462
+
463
+ /**
464
+ * Increases the pool size.
465
+ */
466
+ _increasePoolIfNeeded: function (count) {
467
+ var nextPhysicalCount = this._clamp(
468
+ this._physicalCount + count,
469
+ DEFAULT_PHYSICAL_COUNT,
470
+ this._virtualCount - this._virtualStart
471
+ );
472
+ nextPhysicalCount = this._convertIndexToCompleteRow(nextPhysicalCount);
473
+ if (this.grid) {
474
+ var correction = nextPhysicalCount % this._itemsPerRow;
475
+ if (correction && nextPhysicalCount - correction <= this._physicalCount) {
476
+ nextPhysicalCount += this._itemsPerRow;
477
+ }
478
+ nextPhysicalCount -= correction;
479
+ }
480
+ var delta = nextPhysicalCount - this._physicalCount;
481
+ var nextIncrease = Math.round(this._physicalCount * 0.5);
482
+
483
+ if (delta < 0) {
484
+ return;
485
+ }
486
+ if (delta > 0) {
487
+ var ts = window.performance.now();
488
+ // Concat arrays in place.
489
+ [].push.apply(this._physicalItems, this._createPool(delta));
490
+ // Push 0s into physicalSizes. Can't use Array.fill because IE11 doesn't
491
+ // support it.
492
+ for (var i = 0; i < delta; i++) {
493
+ this._physicalSizes.push(0);
494
+ }
495
+ this._physicalCount = this._physicalCount + delta;
496
+ // Update the physical start if it needs to preserve the model of the
497
+ // focused item. In this situation, the focused item is currently rendered
498
+ // and its model would have changed after increasing the pool if the
499
+ // physical start remained unchanged.
500
+ if (
501
+ this._physicalStart > this._physicalEnd &&
502
+ this._isIndexRendered(this._focusedVirtualIndex) &&
503
+ this._getPhysicalIndex(this._focusedVirtualIndex) < this._physicalEnd
504
+ ) {
505
+ this._physicalStart = this._physicalStart + delta;
506
+ }
507
+ this._update();
508
+ this._templateCost = (window.performance.now() - ts) / delta;
509
+ nextIncrease = Math.round(this._physicalCount * 0.5);
510
+ }
511
+ // The upper bounds is not fixed when dealing with a grid that doesn't
512
+ // fill it's last row with the exact number of items per row.
513
+ if (this._virtualEnd >= this._virtualCount - 1 || nextIncrease === 0) {
514
+ // Do nothing.
515
+ } else if (!this._isClientFull()) {
516
+ this._debounce('_increasePoolIfNeeded', this._increasePoolIfNeeded.bind(this, nextIncrease), microTask);
517
+ } else if (this._physicalSize < this._optPhysicalSize) {
518
+ // Yield and increase the pool during idle time until the physical size is
519
+ // optimal.
520
+ this._debounce(
521
+ '_increasePoolIfNeeded',
522
+ this._increasePoolIfNeeded.bind(this, this._clamp(Math.round(50 / this._templateCost), 1, nextIncrease)),
523
+ idlePeriod
524
+ );
525
+ }
526
+ },
527
+
528
+ /**
529
+ * Renders the a new list.
530
+ */
531
+ _render: function () {
532
+ if (!this.isAttached || !this._isVisible) {
533
+ return;
534
+ }
535
+ if (this._physicalCount !== 0) {
536
+ var reusables = this._getReusables(true);
537
+ this._physicalTop = reusables.physicalTop;
538
+ this._virtualStart = this._virtualStart + reusables.indexes.length;
539
+ this._physicalStart = this._physicalStart + reusables.indexes.length;
540
+ this._update(reusables.indexes);
541
+ this._update();
542
+ this._increasePoolIfNeeded(0);
543
+ } else if (this._virtualCount > 0) {
544
+ // Initial render
545
+ this.updateViewportBoundaries();
546
+ this._increasePoolIfNeeded(DEFAULT_PHYSICAL_COUNT);
547
+ }
548
+ },
549
+
550
+ _gridChanged: function (newGrid, oldGrid) {
551
+ if (typeof oldGrid === 'undefined') return;
552
+ this.notifyResize();
553
+ flush();
554
+ newGrid && this._updateGridMetrics();
555
+ },
556
+
557
+ /**
558
+ * Called when the items have changed. That is, reassignments
559
+ * to `items`, splices or updates to a single item.
560
+ */
561
+ _itemsChanged: function (change) {
562
+ if (change.path === 'items') {
563
+ this._virtualStart = 0;
564
+ this._physicalTop = 0;
565
+ this._virtualCount = this.items ? this.items.length : 0;
566
+ this._physicalIndexForKey = {};
567
+ this._firstVisibleIndexVal = null;
568
+ this._lastVisibleIndexVal = null;
569
+ this._physicalCount = this._physicalCount || 0;
570
+ this._physicalItems = this._physicalItems || [];
571
+ this._physicalSizes = this._physicalSizes || [];
572
+ this._physicalStart = 0;
573
+ if (this._scrollTop > this._scrollOffset) {
574
+ this._resetScrollPosition(0);
575
+ }
576
+ this._removeFocusedItem();
577
+ this._debounce('_render', this._render, animationFrame);
578
+ } else if (change.path === 'items.splices') {
579
+ this._adjustVirtualIndex(change.value.indexSplices);
580
+ this._virtualCount = this.items ? this.items.length : 0;
581
+ // Only blur if at least one item is added or removed.
582
+ var itemAddedOrRemoved = change.value.indexSplices.some(function (splice) {
583
+ return splice.addedCount > 0 || splice.removed.length > 0;
584
+ });
585
+ if (itemAddedOrRemoved) {
586
+ // Only blur activeElement if it is a descendant of the list (#505,
587
+ // #507).
588
+ var activeElement = this._getActiveElement();
589
+ if (this.contains(activeElement)) {
590
+ activeElement.blur();
591
+ }
592
+ }
593
+ // Render only if the affected index is rendered.
594
+ var affectedIndexRendered = change.value.indexSplices.some(function (splice) {
595
+ return splice.index + splice.addedCount >= this._virtualStart && splice.index <= this._virtualEnd;
596
+ }, this);
597
+ if (!this._isClientFull() || affectedIndexRendered) {
598
+ this._debounce('_render', this._render, animationFrame);
599
+ }
600
+ } else if (change.path !== 'items.length') {
601
+ this._forwardItemPath(change.path, change.value);
602
+ }
603
+ },
604
+
605
+ /**
606
+ * Executes a provided function per every physical index in `itemSet`
607
+ * `itemSet` default value is equivalent to the entire set of physical
608
+ * indexes.
609
+ *
610
+ * @param {!function(number, number)} fn
611
+ * @param {!Array<number>=} itemSet
612
+ */
613
+ _iterateItems: function (fn, itemSet) {
614
+ var pidx, vidx, rtn, i;
615
+
616
+ if (arguments.length === 2 && itemSet) {
617
+ for (i = 0; i < itemSet.length; i++) {
618
+ pidx = itemSet[i];
619
+ vidx = this._computeVidx(pidx);
620
+ if ((rtn = fn.call(this, pidx, vidx)) != null) {
621
+ return rtn;
622
+ }
623
+ }
624
+ } else {
625
+ pidx = this._physicalStart;
626
+ vidx = this._virtualStart;
627
+ for (; pidx < this._physicalCount; pidx++, vidx++) {
628
+ if ((rtn = fn.call(this, pidx, vidx)) != null) {
629
+ return rtn;
630
+ }
631
+ }
632
+ for (pidx = 0; pidx < this._physicalStart; pidx++, vidx++) {
633
+ if ((rtn = fn.call(this, pidx, vidx)) != null) {
634
+ return rtn;
635
+ }
636
+ }
637
+ }
638
+ },
639
+
640
+ /**
641
+ * Returns the virtual index for a given physical index
642
+ *
643
+ * @param {number} pidx Physical index
644
+ * @return {number}
645
+ */
646
+ _computeVidx: function (pidx) {
647
+ if (pidx >= this._physicalStart) {
648
+ return this._virtualStart + (pidx - this._physicalStart);
649
+ }
650
+ return this._virtualStart + (this._physicalCount - this._physicalStart) + pidx;
651
+ },
652
+
653
+ /**
654
+ * Updates the height for a given set of items.
655
+ *
656
+ * @param {!Array<number>=} itemSet
657
+ */
658
+ _updateMetrics: function (itemSet) {
659
+ // Make sure we distributed all the physical items
660
+ // so we can measure them.
661
+ flush();
662
+
663
+ var newPhysicalSize = 0;
664
+ var oldPhysicalSize = 0;
665
+ var prevAvgCount = this._physicalAverageCount;
666
+ var prevPhysicalAvg = this._physicalAverage;
667
+
668
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
669
+ this._iterateItems(function (pidx, vidx) {
670
+ oldPhysicalSize += this._physicalSizes[pidx];
671
+ this._physicalSizes[pidx] = this._physicalItems[pidx].offsetHeight;
672
+ newPhysicalSize += this._physicalSizes[pidx];
673
+ this._physicalAverageCount += this._physicalSizes[pidx] ? 1 : 0;
674
+ }, itemSet);
675
+
676
+ if (this.grid) {
677
+ this._updateGridMetrics();
678
+ this._physicalSize = Math.ceil(this._physicalCount / this._itemsPerRow) * this._rowHeight;
679
+ } else {
680
+ oldPhysicalSize =
681
+ this._itemsPerRow === 1
682
+ ? oldPhysicalSize
683
+ : Math.ceil(this._physicalCount / this._itemsPerRow) * this._rowHeight;
684
+ this._physicalSize = this._physicalSize + newPhysicalSize - oldPhysicalSize;
685
+ this._itemsPerRow = 1;
686
+ }
687
+ // Update the average if it measured something.
688
+ if (this._physicalAverageCount !== prevAvgCount) {
689
+ this._physicalAverage = Math.round(
690
+ (prevPhysicalAvg * prevAvgCount + newPhysicalSize) / this._physicalAverageCount
691
+ );
692
+ }
693
+ },
694
+
695
+ _updateGridMetrics: function () {
696
+ this._itemWidth = this._physicalCount > 0 ? this._physicalItems[0].getBoundingClientRect().width : 200;
697
+ this._rowHeight = this._physicalCount > 0 ? this._physicalItems[0].offsetHeight : 200;
698
+ this._itemsPerRow = this._itemWidth ? Math.floor(this._viewportWidth / this._itemWidth) : this._itemsPerRow;
699
+ },
700
+
701
+ /**
702
+ * Updates the position of the physical items.
703
+ */
704
+ _positionItems: function () {
705
+ this._adjustScrollPosition();
706
+
707
+ var y = this._physicalTop;
708
+
709
+ if (this.grid) {
710
+ var totalItemWidth = this._itemsPerRow * this._itemWidth;
711
+ var rowOffset = (this._viewportWidth - totalItemWidth) / 2;
712
+
713
+ this._iterateItems(function (pidx, vidx) {
714
+ var modulus = vidx % this._itemsPerRow;
715
+ var x = Math.floor(modulus * this._itemWidth + rowOffset);
716
+ if (this._isRTL) {
717
+ x = x * -1;
718
+ }
719
+ this.translate3d(x + 'px', y + 'px', 0, this._physicalItems[pidx]);
720
+ if (this._shouldRenderNextRow(vidx)) {
721
+ y += this._rowHeight;
722
+ }
723
+ });
724
+ } else {
725
+ const order = [];
726
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
727
+ this._iterateItems(function (pidx, vidx) {
728
+ const item = this._physicalItems[pidx];
729
+ this.translate3d(0, y + 'px', 0, item);
730
+ y += this._physicalSizes[pidx];
731
+ const itemId = item.id;
732
+ if (itemId) {
733
+ order.push(itemId);
734
+ }
735
+ });
736
+ if (order.length) {
737
+ this.setAttribute('aria-owns', order.join(' '));
738
+ }
739
+ }
740
+ },
741
+
742
+ _getPhysicalSizeIncrement: function (pidx) {
743
+ if (!this.grid) {
744
+ return this._physicalSizes[pidx];
745
+ }
746
+ if (this._computeVidx(pidx) % this._itemsPerRow !== this._itemsPerRow - 1) {
747
+ return 0;
748
+ }
749
+ return this._rowHeight;
750
+ },
751
+
752
+ /**
753
+ * Returns, based on the current index,
754
+ * whether or not the next index will need
755
+ * to be rendered on a new row.
756
+ *
757
+ * @param {number} vidx Virtual index
758
+ * @return {boolean}
759
+ */
760
+ _shouldRenderNextRow: function (vidx) {
761
+ return vidx % this._itemsPerRow === this._itemsPerRow - 1;
762
+ },
763
+
764
+ /**
765
+ * Adjusts the scroll position when it was overestimated.
766
+ */
767
+ _adjustScrollPosition: function () {
768
+ var deltaHeight =
769
+ this._virtualStart === 0 ? this._physicalTop : Math.min(this._scrollPosition + this._physicalTop, 0);
770
+ // Note: the delta can be positive or negative.
771
+ if (deltaHeight !== 0) {
772
+ this._physicalTop = this._physicalTop - deltaHeight;
773
+ // This may be called outside of a scrollHandler, so use last cached position
774
+ var scrollTop = this._scrollPosition;
775
+ // juking scroll position during interial scrolling on iOS is no bueno
776
+ if (!IOS_TOUCH_SCROLLING && scrollTop > 0) {
777
+ this._resetScrollPosition(scrollTop - deltaHeight);
778
+ }
779
+ }
780
+ },
781
+
782
+ /**
783
+ * Sets the position of the scroll.
784
+ */
785
+ _resetScrollPosition: function (pos) {
786
+ if (this.scrollTarget && pos >= 0) {
787
+ this._scrollTop = pos;
788
+ this._scrollPosition = this._scrollTop;
789
+ }
790
+ },
791
+
792
+ /**
793
+ * Sets the scroll height, that's the height of the content,
794
+ *
795
+ * @param {boolean=} forceUpdate If true, updates the height no matter what.
796
+ */
797
+ _updateScrollerSize: function (forceUpdate) {
798
+ if (this.grid) {
799
+ this._estScrollHeight = this._virtualRowCount * this._rowHeight;
800
+ } else {
801
+ this._estScrollHeight =
802
+ this._physicalBottom +
803
+ Math.max(this._virtualCount - this._physicalCount - this._virtualStart, 0) * this._physicalAverage;
804
+ }
805
+ forceUpdate = forceUpdate || this._scrollHeight === 0;
806
+ forceUpdate = forceUpdate || this._scrollPosition >= this._estScrollHeight - this._physicalSize;
807
+ forceUpdate = forceUpdate || (this.grid && this.$.items.style.height < this._estScrollHeight);
808
+ // Amortize height adjustment, so it won't trigger large repaints too often.
809
+ if (forceUpdate || Math.abs(this._estScrollHeight - this._scrollHeight) >= this._viewportHeight) {
810
+ this.$.items.style.height = this._estScrollHeight + 'px';
811
+ this._scrollHeight = this._estScrollHeight;
812
+ }
813
+ },
814
+
815
+ /**
816
+ * Scroll to a specific index in the virtual list regardless
817
+ * of the physical items in the DOM tree.
818
+ *
819
+ * @method scrollToIndex
820
+ * @param {number} idx The index of the item
821
+ */
822
+ scrollToIndex: function (idx) {
823
+ if (typeof idx !== 'number' || idx < 0 || idx > this.items.length - 1) {
824
+ return;
825
+ }
826
+ flush();
827
+ // Items should have been rendered prior scrolling to an index.
828
+ if (this._physicalCount === 0) {
829
+ return;
830
+ }
831
+ idx = this._clamp(idx, 0, this._virtualCount - 1);
832
+ // Update the virtual start only when needed.
833
+ if (!this._isIndexRendered(idx) || idx >= this._maxVirtualStart) {
834
+ this._virtualStart = this.grid ? idx - this._itemsPerRow * 2 : idx - 1;
835
+ }
836
+ this._manageFocus();
837
+ this._assignModels();
838
+ this._updateMetrics();
839
+ // Estimate new physical offset.
840
+ this._physicalTop = Math.floor(this._virtualStart / this._itemsPerRow) * this._physicalAverage;
841
+
842
+ var currentTopItem = this._physicalStart;
843
+ var currentVirtualItem = this._virtualStart;
844
+ var targetOffsetTop = 0;
845
+ var hiddenContentSize = this._hiddenContentSize;
846
+ // scroll to the item as much as we can.
847
+ while (currentVirtualItem < idx && targetOffsetTop <= hiddenContentSize) {
848
+ targetOffsetTop = targetOffsetTop + this._getPhysicalSizeIncrement(currentTopItem);
849
+ currentTopItem = (currentTopItem + 1) % this._physicalCount;
850
+ currentVirtualItem++;
851
+ }
852
+ this._updateScrollerSize(true);
853
+ this._positionItems();
854
+ this._resetScrollPosition(this._physicalTop + this._scrollOffset + targetOffsetTop);
855
+ this._increasePoolIfNeeded(0);
856
+ // clear cached visible index.
857
+ this._firstVisibleIndexVal = null;
858
+ this._lastVisibleIndexVal = null;
859
+ },
860
+
861
+ /**
862
+ * Reset the physical average and the average count.
863
+ */
864
+ _resetAverage: function () {
865
+ this._physicalAverage = 0;
866
+ this._physicalAverageCount = 0;
867
+ },
868
+
869
+ /**
870
+ * A handler for the `iron-resize` event triggered by `IronResizableBehavior`
871
+ * when the element is resized.
872
+ */
873
+ _resizeHandler: function () {
874
+ this._debounce(
875
+ '_render',
876
+ function () {
877
+ // clear cached visible index.
878
+ this._firstVisibleIndexVal = null;
879
+ this._lastVisibleIndexVal = null;
880
+ if (this._isVisible) {
881
+ this.updateViewportBoundaries();
882
+ // Reinstall the scroll event listener.
883
+ this.toggleScrollListener(true);
884
+ this._resetAverage();
885
+ this._render();
886
+ } else {
887
+ // Uninstall the scroll event listener.
888
+ this.toggleScrollListener(false);
889
+ }
890
+ },
891
+ animationFrame
892
+ );
893
+ },
894
+
895
+ /**
896
+ * Updates the size of a given list item.
897
+ *
898
+ * @method updateSizeForItem
899
+ * @param {Object} item The item instance.
900
+ */
901
+ updateSizeForItem: function (item) {
902
+ return this.updateSizeForIndex(this.items.indexOf(item));
903
+ },
904
+
905
+ /**
906
+ * Updates the size of the item at the given index in the items array.
907
+ *
908
+ * @method updateSizeForIndex
909
+ * @param {number} index The index of the item in the items array.
910
+ */
911
+ updateSizeForIndex: function (index) {
912
+ if (!this._isIndexRendered(index)) {
913
+ return null;
914
+ }
915
+ this._updateMetrics([this._getPhysicalIndex(index)]);
916
+ this._positionItems();
917
+ return null;
918
+ },
919
+
920
+ /**
921
+ * Converts a random index to the index of the item that completes it's row.
922
+ * Allows for better order and fill computation when grid == true.
923
+ */
924
+ _convertIndexToCompleteRow: function (idx) {
925
+ // when grid == false _itemPerRow can be unset.
926
+ this._itemsPerRow = this._itemsPerRow || 1;
927
+ return this.grid ? Math.ceil(idx / this._itemsPerRow) * this._itemsPerRow : idx;
928
+ },
929
+
930
+ _isIndexRendered: function (idx) {
931
+ return idx >= this._virtualStart && idx <= this._virtualEnd;
932
+ },
933
+
934
+ _isIndexVisible: function (idx) {
935
+ return idx >= this.firstVisibleIndex && idx <= this.lastVisibleIndex;
936
+ },
937
+
938
+ _getPhysicalIndex: function (vidx) {
939
+ return (this._physicalStart + (vidx - this._virtualStart)) % this._physicalCount;
940
+ },
941
+
942
+ _clamp: function (v, min, max) {
943
+ return Math.min(max, Math.max(min, v));
944
+ },
945
+
946
+ _debounce: function (name, cb, asyncModule) {
947
+ this._debouncers = this._debouncers || {};
948
+ this._debouncers[name] = Debouncer.debounce(this._debouncers[name], asyncModule, cb.bind(this));
949
+ enqueueDebouncer(this._debouncers[name]);
950
+ }
951
+ };