iron-list.html 23.9 KB
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
<!--
@license
Copyright (c) 2015 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
-->

<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-resizable-behavior/iron-resizable-behavior.html">

<!--

`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 be 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.

__Important:__ `iron-list` must ether 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).

### Template model

List item templates should bind to template models of the following structure:

    {
      index: 0,     // data index for this item
      item: {       // user data corresponding to items[index]
        /* user item data  */
      }
    }

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

    [
      {"name": "Bob"},
      {"name": "Tim"},
      {"name": "Mike"}
    ]

The following code would render the list (note the name and checked properties are
bound from the model object provided to the template scope):

    <template is="dom-bind">
      <iron-ajax url="data.json" last-response="{{data}}" auto></iron-ajax>
      <iron-list items="[[data]]" as="item">
        <template>
          <div>
            Name: <span>[[item.name]]</span>
          </div>
        </template>
      </iron-list>
    </template>


@group Iron Element
@element iron-list
@demo demo/index.html
-->

<dom-module id="iron-list">
  <style>

    :host {
      display: block;
      will-change: transform;
    }

    :host(.has-scroller) {
      overflow: auto;
    }

    #items {
      position: relative;
    }

    #items > ::content > * {
      width: 100%;
      box-sizing: border-box;
      position: absolute;
      top: 0;
    }

  </style>
  <template>
    <div id="items">
      <content></content>
    </div>
  </template>
</dom-module>

<script>

(function() {

  var IOS = navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);
  var IOS_TOUCH_SCROLLING = IOS && IOS[1] >= 8;
  var DEFAULT_PHYSICAL_COUNT = 20;

  Polymer({

    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.  If `sort` is provided, the index will reflect the
       * sorted order (rather than the original array order).
       */
      indexAs: {
        type: String,
        value: 'index'
      }

    },

    observers: [
      '_itemsChanged(items.*)'
    ],

    behaviors: [
      Polymer.Templatizer,
      Polymer.IronResizableBehavior
    ],

    listeners: {
      'iron-resize': '_resizeHandler'
    },

    /**
     * The ratio of hidden tiles that should remain in the scroll direction.
     * Recommended value โ‰ˆ 0.5, so it will distribute tiles evely in both directions.
     */
    _ratio: 0.5,

    /**
     * The element that controls the scroll
     */
    _scroller: null,

    /**
     * The padding-top value of the `scroller` element
     */
    _scrollerPaddingTop: 0,

    /**
     * This value is the same as `scrollTop`.
     */
    _scrollPosition: 0,

    /**
     * The number of tiles in the DOM.
     */
    _physicalCount: DEFAULT_PHYSICAL_COUNT,

    /**
     * The k-th tile that is at the top of the scrolling list.
     */
    _physicalStart: 0,

    /**
     * The k-th tile that is at the bottom of the scrolling list.
     */
    _physicalEnd: 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 n-th item rendered in the `_physicalStart` tile.
     */
    _virtualStartVal: 0,

    /**
     * A map between an item key and its physical item index
     */
    _physicalIndexForKey: {},

    /**
     * The average scroll size
     */
    _scrollSize: 0,

    /**
     * The size of the viewport
     */
    _viewportSize: 0,

    /**
     * An array of DOM nodes that are currently in the tree
     */
    _physicalItems: null,

    /**
     * An array of heights for each item in `_physicalItems`
     */
    _physicalSizes: null,

    /**
     * A cached value for the visible index.
     * See `firstVisibleIndex`
     */
    _firstVisibleIndexVal: null,

    /**
     * A Polymer collection for the items.
     */
    _collection: null,

    get _physicalBottom() {
      return this._physicalTop + this._physicalSize;
    },

    get _scrollBottom() {
      return this._scrollPosition + this._viewportSize - this._scrollerPaddingTop;
    },

    get _virtualEnd() {
      return this._virtualStartVal + this._physicalCount - 1;
    },

    get _maxVirtualStart() {
      return this._virtualCount < this._physicalCount ?
          this._virtualCount : this._virtualCount - this._physicalCount;
    },

    get _hiddenContentSize() {
      return this._physicalSize - this._viewportSize;
    },

    get _minVirtualStart() {
      return 0;
    },

    get _maxScrollTop() {
      return this._scrollSize - this._viewportSize;
    },

    set _virtualStart(val) {
      this._virtualStartVal = Math.min(this._maxVirtualStart, Math.max(this._minVirtualStart, val));
      this._physicalStart = this._virtualStartVal % this._physicalCount;
      this._physicalEnd = (this._physicalStart + this._physicalCount - 1) % this._physicalCount;
    },

    get _virtualStart() {
      return this._virtualStartVal;
    },

    /**
     * Gets the first visible item in the viewport.
     *
     * @property firstVisibleIndex
     */
    get firstVisibleIndex() {
      var physicalOffset;

      if (this._firstVisibleIndexVal === null || 1) {
        physicalOffset = this._physicalTop;

        this._firstVisibleIndexVal = this._iterateItems(
          function(pidx, vidx) {
            physicalOffset += this._physicalSizes[pidx];

            if (physicalOffset > this._scrollPosition) {
              return vidx;
            }
          }) || 0;
      }

      return this._firstVisibleIndexVal;
    },

    attached: function() {
      // delegate to the parent's scroller
      // e.g. paper-scroll-header-panel
      var el = Polymer.dom(this);

      if (el.parentNode && el.parentNode.scroller) {
        this._scroller = el.parentNode.scroller;
        this.updateViewportBoundaries();
      } else {
        this._scroller = this;
        this.classList.add('has-scroller');
      }

      if (IOS_TOUCH_SCROLLING) {
        this._scroller.style.webkitOverflowScrolling = 'touch';

        this._scroller.addEventListener('scroll', function() {
          requestAnimationFrame(this._scrollHandler.bind(this));
        }.bind(this));
      } else {
        this._scroller.addEventListener('scroll', this._scrollHandler.bind(this));
      }
    },

    /**
     * Invoke this method if you dynamically update the viewport's
     * size or CSS padding.
     *
     * @method updateViewportBoundaries
     */
    updateViewportBoundaries: function() {
      var scrollerStyle = window.getComputedStyle(this._scroller);
      this._scrollerPaddingTop = parseInt(scrollerStyle['padding-top']);
      this._viewportSize = this._scroller.offsetHeight;
    },

    /**
     * Update the models, the position of the
     * items in the viewport and recycle tiles as needed.
     */
    _refresh: function() {
      var SCROLL_DIRECTION_UP = -1;
      var SCROLL_DIRECTION_DOWN = 1;
      var SCROLL_DIRECTION_NONE = 0;

      // clamp the `scrollTop` value
      // IE 10|11 scrollTop may go above `_maxScrollTop`
      // iOS `scrollTop` may go below 0 and above `_maxScrollTop`
      var scrollTop = Math.max(0, Math.min(this._maxScrollTop, this._scroller.scrollTop));

      var tileHeight, kth, recycledTileSet;
      var ratio = this._ratio;
      var delta = scrollTop - this._scrollPosition;
      var direction = SCROLL_DIRECTION_NONE;
      var recycledTiles = 0;
      var hiddenContentSize = this._hiddenContentSize;
      var currentRatio = ratio;
      var movingUp = [];

      // track the last `scrollTop`
      this._scrollPosition = scrollTop;

      // clear cached visible index
      this._firstVisibleIndexVal = null;

      // random access
      if (this._scrollBottom > this._physicalBottom || scrollTop < this._physicalTop) {
        this._physicalTop += delta;
        direction = SCROLL_DIRECTION_NONE;
        recycledTiles =  Math.round(delta / this._physicalAverage);
      }
      // scroll up
      else if (delta < 0) {
        var topSpace = scrollTop - this._physicalTop;
        var virtualStart = this._virtualStart;

        direction = SCROLL_DIRECTION_UP;
        recycledTileSet = [];

        kth = this._physicalEnd;
        currentRatio = topSpace / hiddenContentSize;

        // move tiles from bottom to top
        while (
            // approximate `currentRatio` to `ratio`
            currentRatio < ratio &&
            // recycle less physical items than the total
            recycledTiles < this._physicalCount &&
            // ensure that these recycled tiles are needed
            virtualStart - recycledTiles > 0
        ) {

          tileHeight = this._physicalSizes[kth] || this._physicalAverage;
          currentRatio += tileHeight / hiddenContentSize;

          recycledTileSet.push(kth);
          recycledTiles++;
          kth = (kth === 0) ? this._physicalCount - 1 : kth - 1;
        }

        movingUp = recycledTileSet;
        recycledTiles = -recycledTiles;

      }
      // scroll down
      else if (delta > 0) {
        var bottomSpace = this._physicalBottom - (scrollTop + this._viewportSize);
        var virtualEnd = this._virtualEnd;
        var lastVirtualItemIndex = this._virtualCount-1;

        direction = SCROLL_DIRECTION_DOWN;
        recycledTileSet = [];

        kth = this._physicalStart;
        currentRatio = bottomSpace / hiddenContentSize;

        // move tiles from top to bottom
        while (
            // approximate `currentRatio` to `ratio`
            currentRatio < ratio &&
            // recycle less physical items than the total
            recycledTiles < this._physicalCount &&
            // ensure that these recycled tiles are needed
            virtualEnd + recycledTiles < lastVirtualItemIndex
          ) {

          tileHeight = this._physicalSizes[kth] || this._physicalAverage;
          currentRatio += tileHeight / hiddenContentSize;

          this._physicalTop += tileHeight;
          recycledTileSet.push(kth);
          recycledTiles++;
          kth = (kth + 1) % this._physicalCount;
        }
      }

      if (recycledTiles !== 0) {
        this._virtualStart = this._virtualStart + recycledTiles;
        this._update(recycledTileSet, movingUp);
      }
    },

    _update: function(recycledTileSet, movingUp) {
      // update models
      this._assignModels(recycledTileSet);

      // measure heights
      // TODO(blasten) pass `recycledTileSet`
      this._updateMetrics();

      // adjust offset after measuring
      if (movingUp) {
        while (movingUp.length) {
          this._physicalTop -= this._physicalSizes[movingUp.pop()];
        }
      }

     // update the position of the items
      this._positionItems();

      // set the scroller size
      this._updateScrollerSize();
    },

    _refreshAll: function() {
      // polymer/issues/2039
      CustomElements.takeRecords();
      this._update();
    },

    _ensureTemplatized: function() {
      if (!this.ctor) {
        // Template instance props that should be excluded from forwarding
        this._instanceProps = {
          __key__: true
        };
        this._instanceProps[this.as] = true;
        this._instanceProps[this.indexAs] = true;
        this._userTemplate = Polymer.dom(this).querySelector('template');
        if (this._userTemplate) {
          this.templatize(this._userTemplate);
        } else {
          console.warn('x-list requires a template to be provided in light-dom');
        }
      }
    },

    /**
     * Implements extension point from Templatizer mixin.
     */
    _getStampedChildren: function() {
      return this._physicalItems;
    },

    /**
     * Implements extension point from Templatizer
     * Called as a side effect of a template instance path change, responsible
     * for notifying items.<key-for-instance>.<path> change up to host.
     */
    _forwardInstancePath: function(inst, path, value) {
      if (path.indexOf(this.as + '.') === 0) {
        this.notifyPath('items.' + inst.__key__ + '.' +
          path.slice(this.as.length + 1), value);
      }
    },

    /**
     * Implements extension point from Templatizer mixin
     * Called as side-effect of a host property change, responsible for
     * notifying parent path change on each row.
     */
    _forwardParentProp: function(prop, value) {
      if (this._physicalItems) {
        this._physicalItems.forEach(function(item) {
          item._templateInstance[prop] = value;
        }, this);
      }
    },

    /**
     * Implements extension point from Templatizer
     * Called as side-effect of a host path change, responsible for
     * notifying parent.<path> path change on each row.
     */
    _forwardParentPath: function(path, value) {
      if (this._physicalItems) {
        this._physicalItems.forEach(function(item) {
          item._templateInstance.notifyPath(path, value, true);
        }, this);
      }
    },

    /**
     * Called as a side effect of a host items.<key>.<path> path change,
     * responsible for notifying item.<path> changes to row for key.
     */
    _forwardItemPath: function(path, value) {
      if (this._physicalIndexForKey) {
        var dot = path.indexOf('.');
        var key = path.substring(0, dot < 0 ? path.length : dot);
        var idx = this._physicalIndexForKey[key];
        var row = this._physicalItems[idx];
        if (row) {
          var inst = row._templateInstance;
          if (dot >= 0) {
            path = this.as + '.' + path.substring(dot+1);
            inst.notifyPath(path, value, true);
          } else {
            inst[this.as] = value;
          }
        }
      }
    },

    _itemsChanged: function(change) {
      if (change.path === 'items') {
        // update the whole set
        this._virtualStartVal = 0;
        this._physicalTop = 0;
        this._virtualCount = this.items ? this.items.length : 0;

        this._collection = Polymer.Collection.get(this.items);
        this._physicalItems = this._physicalItems || new Array(this._physicalCount);
        this._physicalSizes = this._physicalSizes || new Array(this._physicalCount);

        this._ensureTemplatized();

        for (var i = 0; i < this._physicalCount; i++) {
          if (!this._physicalItems[i]) {
            var inst = this.stamp(this.items[i]);

            // First element child is item; Safari doesn't support children[0]
            // on a doc fragment
            this._physicalItems[i] = inst.root.querySelector('*');
            Polymer.dom(this).appendChild(inst.root);
          }
        }

        this.debounce('refresh', this._refreshAll);

      } else if (change.path === 'items.splices') {

        this._adjustVirtualIndex(change.value.indexSplices);
        this._virtualCount = this.items ? this.items.length : 0;

        this.debounce('refresh', this._refreshAll);

      } else {
        // update a single item
        this._forwardItemPath(change.path.split('.').slice(1).join('.'), change.value);
      }
    },

    _adjustVirtualIndex: function(splices) {
      for (var i = 0; i < splices.length; i++) {
        var splice = splices[i];
        var idx = splice.index;
        // We only need to care about changes happening above the current position
        if (idx >= this._virtualStartVal) {
          break;
        }

        this._virtualStart = this._virtualStart +
            Math.max(splice.addedCount - splice.removed.length, idx - this._virtualStartVal);
      }
    },

    _scrollHandler: function() {
      this._refresh();
    },

    _iterateItems: function(fn, itemSet) {
      var pidx, vidx, rtn, i;

      if (arguments.length === 2 && itemSet) {
        for (i = 0; i < itemSet.length; i++) {
          pidx = itemSet[i];
          if (pidx >= this._physicalStart) {
            vidx = this._virtualStartVal + (pidx - this._physicalStart);
          } else {
            vidx = this._virtualStartVal + (this._physicalCount - this._physicalStart) + pidx;
          }
          if ((rtn = fn.call(this, pidx, vidx)) != null) {
            return rtn;
          }
        }
      } else {
        pidx = this._physicalStart;
        vidx = this._virtualStartVal;

        for (; pidx < this._physicalCount; pidx++, vidx++) {
          if ((rtn = fn.call(this, pidx, vidx)) != null) {
            return rtn;
          }
        }

        pidx = 0;

        for (; pidx < this._physicalStart; pidx++, vidx++) {
          if ((rtn = fn.call(this, pidx, vidx)) != null) {
            return rtn;
          }
        }
      }
    },

    _assignModels: function(itemSet) {
      this._iterateItems(function(pidx, vidx) {
        var el = this._physicalItems[pidx];
        var inst = el._templateInstance;
        var item = this.items && this.items[vidx];

        if (item) {
          inst[this.as] = item;
          inst.__key__ = this._collection.getKey(item);
          inst[this.indexAs] = vidx;
          el.removeAttribute('hidden');
          this._physicalIndexForKey[inst.__key__] = pidx;
        } else {
          inst.__key__ = null;
          el.setAttribute('hidden', '');
        }

      }, itemSet);
    },

    _updateMetrics: function() {
      var total = 0;
      var prevAvgCount = this._physicalAverageCount;
      var prevPhysicalAvg = this._physicalAverage;

      for (var i = 0; i < this._physicalCount; i++) {
        this._physicalSizes[i] = this._physicalItems[i].offsetHeight;
        total += this._physicalSizes[i];
        this._physicalAverageCount += this._physicalSizes[i] ? 1 : 0;
      }

      this._physicalSize = total;
      this._viewportSize = this._scroller.offsetHeight;

      if (this._physicalAverageCount !== prevAvgCount) {
        this._physicalAverage = Math.round(
            ((prevPhysicalAvg * prevAvgCount) + total) /
            this._physicalAverageCount);
      }
    },

    _positionItems: function(itemSet) {
      this._adjustScrollPosition();

      var y = this._physicalTop;

      this._iterateItems(function(pidx) {

        this.transform('translate3d(0, ' + y + 'px, 0)', this._physicalItems[pidx]);
        y += this._physicalSizes[pidx];

      }, itemSet);
    },

    _adjustScrollPosition: function() {
      var deltaHeight = this._virtualStartVal === 0 ? this._physicalTop :
          Math.min(this._scrollPosition + this._physicalTop, 0);

      if (deltaHeight) {
        this._physicalTop = this._physicalTop - deltaHeight;

        // juking scroll position during interial scrolling on iOS is no bueno
        if (!IOS_TOUCH_SCROLLING) {
          this._resetScrollPosition(this._scroller.scrollTop - deltaHeight);
        }
      }
    },

    _resetScrollPosition: function(pos) {
      this._scroller.scrollTop = pos;
      this._scrollPosition = this._scroller.scrollTop;
    },

    _updateScrollerSize: function() {
      this._scrollSize = (this._physicalBottom +
          Math.max(this._virtualCount - this._physicalCount - this._virtualStartVal, 0) * this._physicalAverage);

      this.$.items.style.height = this._scrollSize + 'px';
    },

    /**
     * Scroll to a specific item in the virtual list regardless
     * of the physical items in the DOM tree.
     *
     * @method scrollToIndex
     */
    scrollToIndex: function(idx) {
      if (typeof idx !== 'number') {
        return;
      }

      var firstVisible = this.firstVisibleIndex;

      idx = Math.min(Math.max(idx, 0), this._virtualCount-1);

      // start at the previous virtual item
      // so we have a item above the first visible item
      this._virtualStart = idx - 1;

      // assign new models
      this._assignModels();

      // measure the new sizes
      this._updateMetrics();

      // estimate new physical offset
      this._physicalTop = this._virtualStart * this._physicalAverage;

      var currentTopItem = this._physicalStart;
      var currentVirtualItem = this._virtualStart;
      var targetOffsetTop = 0;
      var hiddenContentSize = this._hiddenContentSize;

      // scroll to the item as much as we can
      while (currentVirtualItem !== idx && targetOffsetTop < hiddenContentSize) {
        targetOffsetTop = targetOffsetTop + this._physicalSizes[currentTopItem];
        currentTopItem = (currentTopItem + 1) % this._physicalCount;
        currentVirtualItem++;
      }

      // update the scroller size
      this._updateScrollerSize();

      // update the position of the items
      this._positionItems();

      // set the new scroll position
      this._resetScrollPosition(this._physicalTop + targetOffsetTop + 1);

      // clear cached visible index
      this._firstVisibleIndexVal = null;
    },

    _resetAverage: function() {
      this._physicalAverage = 0;
      this._physicalAverageCount = 0;
    },

    _resizeHandler: function() {
      if (this._physicalItems) {
        this.debounce('resize', function() {
          this._resetAverage();
          this.updateViewportBoundaries();
          this.scrollToIndex(this.firstVisibleIndex);
        });
      }
    }
  });

})();

</script>