arnaucube
arnaucube/socketioMEANseedPublic Self-hosted repository
socketioMEANseed/www/bower_components/angular-material/modules/js/virtualRepeat/virtualRepeat.js
www/bower_components/angular-material/modules/js/virtualRepeat/virtualRepeat.jsRaw
  1/*!
  2 * Angular Material Design
  3 * https://github.com/angular/material
  4 * @license MIT
  5 * v1.1.3
  6 */
  7(function( window, angular, undefined ){
  8"use strict";
  9
 10/**
 11 * @ngdoc module
 12 * @name material.components.virtualRepeat
 13 */
 14VirtualRepeatContainerController['$inject'] = ["$$rAF", "$mdUtil", "$mdConstant", "$parse", "$rootScope", "$window", "$scope", "$element", "$attrs"];
 15VirtualRepeatController['$inject'] = ["$scope", "$element", "$attrs", "$browser", "$document", "$rootScope", "$$rAF", "$mdUtil"];
 16VirtualRepeatDirective['$inject'] = ["$parse"];
 17angular.module('material.components.virtualRepeat', [
 18  'material.core',
 19  'material.components.showHide'
 20])
 21.directive('mdVirtualRepeatContainer', VirtualRepeatContainerDirective)
 22.directive('mdVirtualRepeat', VirtualRepeatDirective);
 23
 24
 25/**
 26 * @ngdoc directive
 27 * @name mdVirtualRepeatContainer
 28 * @module material.components.virtualRepeat
 29 * @restrict E
 30 * @description
 31 * `md-virtual-repeat-container` provides the scroll container for md-virtual-repeat.
 32 *
 33 * VirtualRepeat is a limited substitute for ng-repeat that renders only
 34 * enough DOM nodes to fill the container and recycling them as the user scrolls.
 35 *
 36 * Once an element is not visible anymore, the VirtualRepeat recycles it and will reuse it for
 37 * another visible item by replacing the previous dataset with the new one.
 38 *
 39 * ### Common Issues
 40 *
 41 * - When having one-time bindings inside of the view template, the VirtualRepeat will not properly
 42 *   update the bindings for new items, since the view will be recycled.
 43 *
 44 * - Directives inside of a VirtualRepeat will be only compiled (linked) once, because those
 45 *   are will be recycled items and used for other items.
 46 *   The VirtualRepeat just updates the scope bindings.
 47 *
 48 *
 49 * ### Notes
 50 *
 51 * > The VirtualRepeat is a similar implementation to the Android
 52 * [RecyclerView](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html)
 53 *
 54 * <!-- This comment forces a break between blockquotes //-->
 55 *
 56 * > Please also review the <a ng-href="api/directive/mdVirtualRepeat">VirtualRepeat</a>
 57 * documentation for more information.
 58 *
 59 *
 60 * @usage
 61 * <hljs lang="html">
 62 *
 63 * <md-virtual-repeat-container md-top-index="topIndex">
 64 *   <div md-virtual-repeat="i in items" md-item-size="20">Hello {{i}}!</div>
 65 * </md-virtual-repeat-container>
 66 * </hljs>
 67 *
 68 * @param {number=} md-top-index Binds the index of the item that is at the top of the scroll
 69 *     container to $scope. It can both read and set the scroll position.
 70 * @param {boolean=} md-orient-horizontal Whether the container should scroll horizontally
 71 *     (defaults to orientation and scrolling vertically).
 72 * @param {boolean=} md-auto-shrink When present, the container will shrink to fit
 73 *     the number of items when that number is less than its original size.
 74 * @param {number=} md-auto-shrink-min Minimum number of items that md-auto-shrink
 75 *     will shrink to (default: 0).
 76 */
 77function VirtualRepeatContainerDirective() {
 78  return {
 79    controller: VirtualRepeatContainerController,
 80    template: virtualRepeatContainerTemplate,
 81    compile: function virtualRepeatContainerCompile($element, $attrs) {
 82      $element
 83          .addClass('md-virtual-repeat-container')
 84          .addClass($attrs.hasOwnProperty('mdOrientHorizontal')
 85              ? 'md-orient-horizontal'
 86              : 'md-orient-vertical');
 87    }
 88  };
 89}
 90
 91
 92function virtualRepeatContainerTemplate($element) {
 93  return '<div class="md-virtual-repeat-scroller">' +
 94    '<div class="md-virtual-repeat-sizer"></div>' +
 95    '<div class="md-virtual-repeat-offsetter">' +
 96      $element[0].innerHTML +
 97    '</div></div>';
 98}
 99
100/**
101 * Number of additional elements to render above and below the visible area inside
102 * of the virtual repeat container. A higher number results in less flicker when scrolling
103 * very quickly in Safari, but comes with a higher rendering and dirty-checking cost.
104 * @const {number}
105 */
106var NUM_EXTRA = 3;
107
108/** ngInject */
109function VirtualRepeatContainerController($$rAF, $mdUtil, $mdConstant, $parse, $rootScope, $window, $scope,
110                                          $element, $attrs) {
111  this.$rootScope = $rootScope;
112  this.$scope = $scope;
113  this.$element = $element;
114  this.$attrs = $attrs;
115
116  /** @type {number} The width or height of the container */
117  this.size = 0;
118  /** @type {number} The scroll width or height of the scroller */
119  this.scrollSize = 0;
120  /** @type {number} The scrollLeft or scrollTop of the scroller */
121  this.scrollOffset = 0;
122  /** @type {boolean} Whether the scroller is oriented horizontally */
123  this.horizontal = this.$attrs.hasOwnProperty('mdOrientHorizontal');
124  /** @type {!VirtualRepeatController} The repeater inside of this container */
125  this.repeater = null;
126  /** @type {boolean} Whether auto-shrink is enabled */
127  this.autoShrink = this.$attrs.hasOwnProperty('mdAutoShrink');
128  /** @type {number} Minimum number of items to auto-shrink to */
129  this.autoShrinkMin = parseInt(this.$attrs.mdAutoShrinkMin, 10) || 0;
130  /** @type {?number} Original container size when shrank */
131  this.originalSize = null;
132  /** @type {number} Amount to offset the total scroll size by. */
133  this.offsetSize = parseInt(this.$attrs.mdOffsetSize, 10) || 0;
134  /** @type {?string} height or width element style on the container prior to auto-shrinking. */
135  this.oldElementSize = null;
136  /** @type {!number} Maximum amount of pixels allowed for a single DOM element */
137  this.maxElementPixels = $mdConstant.ELEMENT_MAX_PIXELS;
138
139  if (this.$attrs.mdTopIndex) {
140    /** @type {function(angular.Scope): number} Binds to topIndex on Angular scope */
141    this.bindTopIndex = $parse(this.$attrs.mdTopIndex);
142    /** @type {number} The index of the item that is at the top of the scroll container */
143    this.topIndex = this.bindTopIndex(this.$scope);
144
145    if (!angular.isDefined(this.topIndex)) {
146      this.topIndex = 0;
147      this.bindTopIndex.assign(this.$scope, 0);
148    }
149
150    this.$scope.$watch(this.bindTopIndex, angular.bind(this, function(newIndex) {
151      if (newIndex !== this.topIndex) {
152        this.scrollToIndex(newIndex);
153      }
154    }));
155  } else {
156    this.topIndex = 0;
157  }
158
159  this.scroller = $element[0].querySelector('.md-virtual-repeat-scroller');
160  this.sizer = this.scroller.querySelector('.md-virtual-repeat-sizer');
161  this.offsetter = this.scroller.querySelector('.md-virtual-repeat-offsetter');
162
163  // After the dom stablizes, measure the initial size of the container and
164  // make a best effort at re-measuring as it changes.
165  var boundUpdateSize = angular.bind(this, this.updateSize);
166
167  $$rAF(angular.bind(this, function() {
168    boundUpdateSize();
169
170    var debouncedUpdateSize = $mdUtil.debounce(boundUpdateSize, 10, null, false);
171    var jWindow = angular.element($window);
172
173    // Make one more attempt to get the size if it is 0.
174    // This is not by any means a perfect approach, but there's really no
175    // silver bullet here.
176    if (!this.size) {
177      debouncedUpdateSize();
178    }
179
180    jWindow.on('resize', debouncedUpdateSize);
181    $scope.$on('$destroy', function() {
182      jWindow.off('resize', debouncedUpdateSize);
183    });
184
185    $scope.$emit('$md-resize-enable');
186    $scope.$on('$md-resize', boundUpdateSize);
187  }));
188}
189
190
191/** Called by the md-virtual-repeat inside of the container at startup. */
192VirtualRepeatContainerController.prototype.register = function(repeaterCtrl) {
193  this.repeater = repeaterCtrl;
194
195  angular.element(this.scroller)
196      .on('scroll wheel touchmove touchend', angular.bind(this, this.handleScroll_));
197};
198
199
200/** @return {boolean} Whether the container is configured for horizontal scrolling. */
201VirtualRepeatContainerController.prototype.isHorizontal = function() {
202  return this.horizontal;
203};
204
205
206/** @return {number} The size (width or height) of the container. */
207VirtualRepeatContainerController.prototype.getSize = function() {
208  return this.size;
209};
210
211
212/**
213 * Resizes the container.
214 * @private
215 * @param {number} size The new size to set.
216 */
217VirtualRepeatContainerController.prototype.setSize_ = function(size) {
218  var dimension = this.getDimensionName_();
219
220  this.size = size;
221  this.$element[0].style[dimension] = size + 'px';
222};
223
224
225VirtualRepeatContainerController.prototype.unsetSize_ = function() {
226  this.$element[0].style[this.getDimensionName_()] = this.oldElementSize;
227  this.oldElementSize = null;
228};
229
230
231/** Instructs the container to re-measure its size. */
232VirtualRepeatContainerController.prototype.updateSize = function() {
233  // If the original size is already determined, we can skip the update.
234  if (this.originalSize) return;
235
236  this.size = this.isHorizontal()
237      ? this.$element[0].clientWidth
238      : this.$element[0].clientHeight;
239
240  // Recheck the scroll position after updating the size. This resolves
241  // problems that can result if the scroll position was measured while the
242  // element was display: none or detached from the document.
243  this.handleScroll_();
244
245  this.repeater && this.repeater.containerUpdated();
246};
247
248
249/** @return {number} The container's scrollHeight or scrollWidth. */
250VirtualRepeatContainerController.prototype.getScrollSize = function() {
251  return this.scrollSize;
252};
253
254
255VirtualRepeatContainerController.prototype.getDimensionName_ = function() {
256  return this.isHorizontal() ? 'width' : 'height';
257};
258
259
260/**
261 * Sets the scroller element to the specified size.
262 * @private
263 * @param {number} size The new size.
264 */
265VirtualRepeatContainerController.prototype.sizeScroller_ = function(size) {
266  var dimension =  this.getDimensionName_();
267  var crossDimension = this.isHorizontal() ? 'height' : 'width';
268
269  // Clear any existing dimensions.
270  this.sizer.innerHTML = '';
271
272  // If the size falls within the browser's maximum explicit size for a single element, we can
273  // set the size and be done. Otherwise, we have to create children that add up the the desired
274  // size.
275  if (size < this.maxElementPixels) {
276    this.sizer.style[dimension] = size + 'px';
277  } else {
278    this.sizer.style[dimension] = 'auto';
279    this.sizer.style[crossDimension] = 'auto';
280
281    // Divide the total size we have to render into N max-size pieces.
282    var numChildren = Math.floor(size / this.maxElementPixels);
283
284    // Element template to clone for each max-size piece.
285    var sizerChild = document.createElement('div');
286    sizerChild.style[dimension] = this.maxElementPixels + 'px';
287    sizerChild.style[crossDimension] = '1px';
288
289    for (var i = 0; i < numChildren; i++) {
290      this.sizer.appendChild(sizerChild.cloneNode(false));
291    }
292
293    // Re-use the element template for the remainder.
294    sizerChild.style[dimension] = (size - (numChildren * this.maxElementPixels)) + 'px';
295    this.sizer.appendChild(sizerChild);
296  }
297};
298
299
300/**
301 * If auto-shrinking is enabled, shrinks or unshrinks as appropriate.
302 * @private
303 * @param {number} size The new size.
304 */
305VirtualRepeatContainerController.prototype.autoShrink_ = function(size) {
306  var shrinkSize = Math.max(size, this.autoShrinkMin * this.repeater.getItemSize());
307
308  if (this.autoShrink && shrinkSize !== this.size) {
309    if (this.oldElementSize === null) {
310      this.oldElementSize = this.$element[0].style[this.getDimensionName_()];
311    }
312
313    var currentSize = this.originalSize || this.size;
314
315    if (!currentSize || shrinkSize < currentSize) {
316      if (!this.originalSize) {
317        this.originalSize = this.size;
318      }
319
320      // Now we update the containers size, because shrinking is enabled.
321      this.setSize_(shrinkSize);
322    } else if (this.originalSize !== null) {
323      // Set the size back to our initial size.
324      this.unsetSize_();
325
326      var _originalSize = this.originalSize;
327      this.originalSize = null;
328
329      // We determine the repeaters size again, if the original size was zero.
330      // The originalSize needs to be null, to be able to determine the size.
331      if (!_originalSize) this.updateSize();
332
333      // Apply the original size or the determined size back to the container, because
334      // it has been overwritten before, in the shrink block.
335      this.setSize_(_originalSize || this.size);
336    }
337
338    this.repeater.containerUpdated();
339  }
340};
341
342
343/**
344 * Sets the scrollHeight or scrollWidth. Called by the repeater based on
345 * its item count and item size.
346 * @param {number} itemsSize The total size of the items.
347 */
348VirtualRepeatContainerController.prototype.setScrollSize = function(itemsSize) {
349  var size = itemsSize + this.offsetSize;
350  if (this.scrollSize === size) return;
351
352  this.sizeScroller_(size);
353  this.autoShrink_(size);
354  this.scrollSize = size;
355};
356
357
358/** @return {number} The container's current scroll offset. */
359VirtualRepeatContainerController.prototype.getScrollOffset = function() {
360  return this.scrollOffset;
361};
362
363/**
364 * Scrolls to a given scrollTop position.
365 * @param {number} position
366 */
367VirtualRepeatContainerController.prototype.scrollTo = function(position) {
368  this.scroller[this.isHorizontal() ? 'scrollLeft' : 'scrollTop'] = position;
369  this.handleScroll_();
370};
371
372/**
373 * Scrolls the item with the given index to the top of the scroll container.
374 * @param {number} index
375 */
376VirtualRepeatContainerController.prototype.scrollToIndex = function(index) {
377  var itemSize = this.repeater.getItemSize();
378  var itemsLength = this.repeater.itemsLength;
379  if(index > itemsLength) {
380    index = itemsLength - 1;
381  }
382  this.scrollTo(itemSize * index);
383};
384
385VirtualRepeatContainerController.prototype.resetScroll = function() {
386  this.scrollTo(0);
387};
388
389
390VirtualRepeatContainerController.prototype.handleScroll_ = function() {
391  var ltr = document.dir != 'rtl' && document.body.dir != 'rtl';
392  if(!ltr && !this.maxSize) {
393    this.scroller.scrollLeft = this.scrollSize;
394    this.maxSize = this.scroller.scrollLeft;
395  }
396  var offset = this.isHorizontal() ?
397      (ltr?this.scroller.scrollLeft : this.maxSize - this.scroller.scrollLeft)
398      : this.scroller.scrollTop;
399  if (offset === this.scrollOffset || offset > this.scrollSize - this.size) return;
400
401  var itemSize = this.repeater.getItemSize();
402  if (!itemSize) return;
403
404  var numItems = Math.max(0, Math.floor(offset / itemSize) - NUM_EXTRA);
405
406  var transform = (this.isHorizontal() ? 'translateX(' : 'translateY(') +
407      (!this.isHorizontal() || ltr ? (numItems * itemSize) : - (numItems * itemSize))  + 'px)';
408
409  this.scrollOffset = offset;
410  this.offsetter.style.webkitTransform = transform;
411  this.offsetter.style.transform = transform;
412
413  if (this.bindTopIndex) {
414    var topIndex = Math.floor(offset / itemSize);
415    if (topIndex !== this.topIndex && topIndex < this.repeater.getItemCount()) {
416      this.topIndex = topIndex;
417      this.bindTopIndex.assign(this.$scope, topIndex);
418      if (!this.$rootScope.$$phase) this.$scope.$digest();
419    }
420  }
421
422  this.repeater.containerUpdated();
423};
424
425
426/**
427 * @ngdoc directive
428 * @name mdVirtualRepeat
429 * @module material.components.virtualRepeat
430 * @restrict A
431 * @priority 1000
432 * @description
433 * `md-virtual-repeat` specifies an element to repeat using virtual scrolling.
434 *
435 * Virtual repeat is a limited substitute for ng-repeat that renders only
436 * enough DOM nodes to fill the container and recycling them as the user scrolls.
437 *
438 * Arrays, but not objects are supported for iteration.
439 * Track by, as alias, and (key, value) syntax are not supported.
440 *
441 * ### On-Demand Async Item Loading
442 *
443 * When using the `md-on-demand` attribute and loading some asynchronous data, the `getItemAtIndex` function will
444 * mostly return nothing.
445 *
446 * <hljs lang="js">
447 *   DynamicItems.prototype.getItemAtIndex = function(index) {
448 *     if (this.pages[index]) {
449 *       return this.pages[index];
450 *     } else {
451 *       // This is an asynchronous action and does not return any value.
452 *       this.loadPage(index);
453 *     }
454 *   };
455 * </hljs>
456 *
457 * This means that the VirtualRepeat will not have any value for the given index.<br/>
458 * After the data loading completed, the user expects the VirtualRepeat to recognize the change.
459 *
460 * To make sure that the VirtualRepeat properly detects any change, you need to run the operation
461 * in another digest.
462 *
463 * <hljs lang="js">
464 *   DynamicItems.prototype.loadPage = function(index) {
465 *     var self = this;
466 *
467 *     // Trigger a new digest by using $timeout
468 *     $timeout(function() {
469 *       self.pages[index] = Data;
470 *     });
471 *   };
472 * </hljs>
473 *
474 * > <b>Note:</b> Please also review the
475 *   <a ng-href="api/directive/mdVirtualRepeatContainer">VirtualRepeatContainer</a> documentation
476 *   for more information.
477 *
478 * @usage
479 * <hljs lang="html">
480 * <md-virtual-repeat-container>
481 *   <div md-virtual-repeat="i in items">Hello {{i}}!</div>
482 * </md-virtual-repeat-container>
483 *
484 * <md-virtual-repeat-container md-orient-horizontal>
485 *   <div md-virtual-repeat="i in items" md-item-size="20">Hello {{i}}!</div>
486 * </md-virtual-repeat-container>
487 * </hljs>
488 *
489 * @param {number=} md-item-size The height or width of the repeated elements (which must be
490 *   identical for each element). Optional. Will attempt to read the size from the dom if missing,
491 *   but still assumes that all repeated nodes have same height or width.
492 * @param {string=} md-extra-name Evaluates to an additional name to which the current iterated item
493 *   can be assigned on the repeated scope (needed for use in `md-autocomplete`).
494 * @param {boolean=} md-on-demand When present, treats the md-virtual-repeat argument as an object
495 *   that can fetch rows rather than an array.
496 *
497 *   **NOTE:** This object must implement the following interface with two (2) methods:
498 *
499 *   - `getItemAtIndex: function(index) [object]` The item at that index or null if it is not yet
500 *     loaded (it should start downloading the item in that case).
501 *   - `getLength: function() [number]` The data length to which the repeater container
502 *     should be sized. Ideally, when the count is known, this method should return it.
503 *     Otherwise, return a higher number than the currently loaded items to produce an
504 *     infinite-scroll behavior.
505 */
506function VirtualRepeatDirective($parse) {
507  return {
508    controller: VirtualRepeatController,
509    priority: 1000,
510    require: ['mdVirtualRepeat', '^^mdVirtualRepeatContainer'],
511    restrict: 'A',
512    terminal: true,
513    transclude: 'element',
514    compile: function VirtualRepeatCompile($element, $attrs) {
515      var expression = $attrs.mdVirtualRepeat;
516      var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)\s*$/);
517      var repeatName = match[1];
518      var repeatListExpression = $parse(match[2]);
519      var extraName = $attrs.mdExtraName && $parse($attrs.mdExtraName);
520
521      return function VirtualRepeatLink($scope, $element, $attrs, ctrl, $transclude) {
522        ctrl[0].link_(ctrl[1], $transclude, repeatName, repeatListExpression, extraName);
523      };
524    }
525  };
526}
527
528
529/** ngInject */
530function VirtualRepeatController($scope, $element, $attrs, $browser, $document, $rootScope,
531    $$rAF, $mdUtil) {
532  this.$scope = $scope;
533  this.$element = $element;
534  this.$attrs = $attrs;
535  this.$browser = $browser;
536  this.$document = $document;
537  this.$rootScope = $rootScope;
538  this.$$rAF = $$rAF;
539
540  /** @type {boolean} Whether we are in on-demand mode. */
541  this.onDemand = $mdUtil.parseAttributeBoolean($attrs.mdOnDemand);
542  /** @type {!Function} Backup reference to $browser.$$checkUrlChange */
543  this.browserCheckUrlChange = $browser.$$checkUrlChange;
544  /** @type {number} Most recent starting repeat index (based on scroll offset) */
545  this.newStartIndex = 0;
546  /** @type {number} Most recent ending repeat index (based on scroll offset) */
547  this.newEndIndex = 0;
548  /** @type {number} Most recent end visible index (based on scroll offset) */
549  this.newVisibleEnd = 0;
550  /** @type {number} Previous starting repeat index (based on scroll offset) */
551  this.startIndex = 0;
552  /** @type {number} Previous ending repeat index (based on scroll offset) */
553  this.endIndex = 0;
554  // TODO: measure width/height of first element from dom if not provided.
555  // getComputedStyle?
556  /** @type {?number} Height/width of repeated elements. */
557  this.itemSize = $scope.$eval($attrs.mdItemSize) || null;
558
559  /** @type {boolean} Whether this is the first time that items are rendered. */
560  this.isFirstRender = true;
561
562  /**
563   * @private {boolean} Whether the items in the list are already being updated. Used to prevent
564   *     nested calls to virtualRepeatUpdate_.
565   */
566  this.isVirtualRepeatUpdating_ = false;
567
568  /** @type {number} Most recently seen length of items. */
569  this.itemsLength = 0;
570
571  /**
572   * @type {!Function} Unwatch callback for item size (when md-items-size is
573   *     not specified), or angular.noop otherwise.
574   */
575  this.unwatchItemSize_ = angular.noop;
576
577  /**
578   * Presently rendered blocks by repeat index.
579   * @type {Object<number, !VirtualRepeatController.Block}
580   */
581  this.blocks = {};
582  /** @type {Array<!VirtualRepeatController.Block>} A pool of presently unused blocks. */
583  this.pooledBlocks = [];
584
585  $scope.$on('$destroy', angular.bind(this, this.cleanupBlocks_));
586}
587
588
589/**
590 * An object representing a repeated item.
591 * @typedef {{element: !jqLite, new: boolean, scope: !angular.Scope}}
592 */
593VirtualRepeatController.Block;
594
595
596/**
597 * Called at startup by the md-virtual-repeat postLink function.
598 * @param {!VirtualRepeatContainerController} container The container's controller.
599 * @param {!Function} transclude The repeated element's bound transclude function.
600 * @param {string} repeatName The left hand side of the repeat expression, indicating
601 *     the name for each item in the array.
602 * @param {!Function} repeatListExpression A compiled expression based on the right hand side
603 *     of the repeat expression. Points to the array to repeat over.
604 * @param {string|undefined} extraName The optional extra repeatName.
605 */
606VirtualRepeatController.prototype.link_ =
607    function(container, transclude, repeatName, repeatListExpression, extraName) {
608  this.container = container;
609  this.transclude = transclude;
610  this.repeatName = repeatName;
611  this.rawRepeatListExpression = repeatListExpression;
612  this.extraName = extraName;
613  this.sized = false;
614
615  this.repeatListExpression = angular.bind(this, this.repeatListExpression_);
616
617  this.container.register(this);
618};
619
620
621/** @private Cleans up unused blocks. */
622VirtualRepeatController.prototype.cleanupBlocks_ = function() {
623  angular.forEach(this.pooledBlocks, function cleanupBlock(block) {
624    block.element.remove();
625  });
626};
627
628
629/** @private Attempts to set itemSize by measuring a repeated element in the dom */
630VirtualRepeatController.prototype.readItemSize_ = function() {
631  if (this.itemSize) {
632    // itemSize was successfully read in a different asynchronous call.
633    return;
634  }
635
636  this.items = this.repeatListExpression(this.$scope);
637  this.parentNode = this.$element[0].parentNode;
638  var block = this.getBlock_(0);
639  if (!block.element[0].parentNode) {
640    this.parentNode.appendChild(block.element[0]);
641  }
642
643  this.itemSize = block.element[0][
644      this.container.isHorizontal() ? 'offsetWidth' : 'offsetHeight'] || null;
645
646  this.blocks[0] = block;
647  this.poolBlock_(0);
648
649  if (this.itemSize) {
650    this.containerUpdated();
651  }
652};
653
654
655/**
656 * Returns the user-specified repeat list, transforming it into an array-like
657 * object in the case of infinite scroll/dynamic load mode.
658 * @param {!angular.Scope} The scope.
659 * @return {!Array|!Object} An array or array-like object for iteration.
660 */
661VirtualRepeatController.prototype.repeatListExpression_ = function(scope) {
662  var repeatList = this.rawRepeatListExpression(scope);
663
664  if (this.onDemand && repeatList) {
665    var virtualList = new VirtualRepeatModelArrayLike(repeatList);
666    virtualList.$$includeIndexes(this.newStartIndex, this.newVisibleEnd);
667    return virtualList;
668  } else {
669    return repeatList;
670  }
671};
672
673
674/**
675 * Called by the container. Informs us that the containers scroll or size has
676 * changed.
677 */
678VirtualRepeatController.prototype.containerUpdated = function() {
679  // If itemSize is unknown, attempt to measure it.
680  if (!this.itemSize) {
681    // Make sure to clean up watchers if we can (see #8178)
682    if(this.unwatchItemSize_ && this.unwatchItemSize_ !== angular.noop){
683      this.unwatchItemSize_();
684    }
685    this.unwatchItemSize_ = this.$scope.$watchCollection(
686        this.repeatListExpression,
687        angular.bind(this, function(items) {
688          if (items && items.length) {
689            this.readItemSize_();
690          }
691        }));
692    if (!this.$rootScope.$$phase) this.$scope.$digest();
693
694    return;
695  } else if (!this.sized) {
696    this.items = this.repeatListExpression(this.$scope);
697  }
698
699  if (!this.sized) {
700    this.unwatchItemSize_();
701    this.sized = true;
702    this.$scope.$watchCollection(this.repeatListExpression,
703        angular.bind(this, function(items, oldItems) {
704          if (!this.isVirtualRepeatUpdating_) {
705            this.virtualRepeatUpdate_(items, oldItems);
706          }
707        }));
708  }
709
710  this.updateIndexes_();
711
712  if (this.newStartIndex !== this.startIndex ||
713      this.newEndIndex !== this.endIndex ||
714      this.container.getScrollOffset() > this.container.getScrollSize()) {
715    if (this.items instanceof VirtualRepeatModelArrayLike) {
716      this.items.$$includeIndexes(this.newStartIndex, this.newEndIndex);
717    }
718    this.virtualRepeatUpdate_(this.items, this.items);
719  }
720};
721
722
723/**
724 * Called by the container. Returns the size of a single repeated item.
725 * @return {?number} Size of a repeated item.
726 */
727VirtualRepeatController.prototype.getItemSize = function() {
728  return this.itemSize;
729};
730
731
732/**
733 * Called by the container. Returns the size of a single repeated item.
734 * @return {?number} Size of a repeated item.
735 */
736VirtualRepeatController.prototype.getItemCount = function() {
737  return this.itemsLength;
738};
739
740
741/**
742 * Updates the order and visible offset of repeated blocks in response to scrolling
743 * or items updates.
744 * @private
745 */
746VirtualRepeatController.prototype.virtualRepeatUpdate_ = function(items, oldItems) {
747  this.isVirtualRepeatUpdating_ = true;
748
749  var itemsLength = items && items.length || 0;
750  var lengthChanged = false;
751
752  // If the number of items shrank, keep the scroll position.
753  if (this.items && itemsLength < this.items.length && this.container.getScrollOffset() !== 0) {
754    this.items = items;
755    var previousScrollOffset = this.container.getScrollOffset();
756    this.container.resetScroll();
757    this.container.scrollTo(previousScrollOffset);
758  }
759
760  if (itemsLength !== this.itemsLength) {
761    lengthChanged = true;
762    this.itemsLength = itemsLength;
763  }
764
765  this.items = items;
766  if (items !== oldItems || lengthChanged) {
767    this.updateIndexes_();
768  }
769
770  this.parentNode = this.$element[0].parentNode;
771
772  if (lengthChanged) {
773    this.container.setScrollSize(itemsLength * this.itemSize);
774  }
775
776  if (this.isFirstRender) {
777    this.isFirstRender = false;
778    var startIndex = this.$attrs.mdStartIndex ?
779      this.$scope.$eval(this.$attrs.mdStartIndex) :
780      this.container.topIndex;
781    this.container.scrollToIndex(startIndex);
782  }
783
784  // Detach and pool any blocks that are no longer in the viewport.
785  Object.keys(this.blocks).forEach(function(blockIndex) {
786    var index = parseInt(blockIndex, 10);
787    if (index < this.newStartIndex || index >= this.newEndIndex) {
788      this.poolBlock_(index);
789    }
790  }, this);
791
792  // Add needed blocks.
793  // For performance reasons, temporarily block browser url checks as we digest
794  // the restored block scopes ($$checkUrlChange reads window.location to
795  // check for changes and trigger route change, etc, which we don't need when
796  // trying to scroll at 60fps).
797  this.$browser.$$checkUrlChange = angular.noop;
798
799  var i, block,
800      newStartBlocks = [],
801      newEndBlocks = [];
802
803  // Collect blocks at the top.
804  for (i = this.newStartIndex; i < this.newEndIndex && this.blocks[i] == null; i++) {
805    block = this.getBlock_(i);
806    this.updateBlock_(block, i);
807    newStartBlocks.push(block);
808  }
809
810  // Update blocks that are already rendered.
811  for (; this.blocks[i] != null; i++) {
812    this.updateBlock_(this.blocks[i], i);
813  }
814  var maxIndex = i - 1;
815
816  // Collect blocks at the end.
817  for (; i < this.newEndIndex; i++) {
818    block = this.getBlock_(i);
819    this.updateBlock_(block, i);
820    newEndBlocks.push(block);
821  }
822
823  // Attach collected blocks to the document.
824  if (newStartBlocks.length) {
825    this.parentNode.insertBefore(
826        this.domFragmentFromBlocks_(newStartBlocks),
827        this.$element[0].nextSibling);
828  }
829  if (newEndBlocks.length) {
830    this.parentNode.insertBefore(
831        this.domFragmentFromBlocks_(newEndBlocks),
832        this.blocks[maxIndex] && this.blocks[maxIndex].element[0].nextSibling);
833  }
834
835  // Restore $$checkUrlChange.
836  this.$browser.$$checkUrlChange = this.browserCheckUrlChange;
837
838  this.startIndex = this.newStartIndex;
839  this.endIndex = this.newEndIndex;
840
841  this.isVirtualRepeatUpdating_ = false;
842};
843
844
845/**
846 * @param {number} index Where the block is to be in the repeated list.
847 * @return {!VirtualRepeatController.Block} A new or pooled block to place at the specified index.
848 * @private
849 */
850VirtualRepeatController.prototype.getBlock_ = function(index) {
851  if (this.pooledBlocks.length) {
852    return this.pooledBlocks.pop();
853  }
854
855  var block;
856  this.transclude(angular.bind(this, function(clone, scope) {
857    block = {
858      element: clone,
859      new: true,
860      scope: scope
861    };
862
863    this.updateScope_(scope, index);
864    this.parentNode.appendChild(clone[0]);
865  }));
866
867  return block;
868};
869
870
871/**
872 * Updates and if not in a digest cycle, digests the specified block's scope to the data
873 * at the specified index.
874 * @param {!VirtualRepeatController.Block} block The block whose scope should be updated.
875 * @param {number} index The index to set.
876 * @private
877 */
878VirtualRepeatController.prototype.updateBlock_ = function(block, index) {
879  this.blocks[index] = block;
880
881  if (!block.new &&
882      (block.scope.$index === index && block.scope[this.repeatName] === this.items[index])) {
883    return;
884  }
885  block.new = false;
886
887  // Update and digest the block's scope.
888  this.updateScope_(block.scope, index);
889
890  // Perform digest before reattaching the block.
891  // Any resulting synchronous dom mutations should be much faster as a result.
892  // This might break some directives, but I'm going to try it for now.
893  if (!this.$rootScope.$$phase) {
894    block.scope.$digest();
895  }
896};
897
898
899/**
900 * Updates scope to the data at the specified index.
901 * @param {!angular.Scope} scope The scope which should be updated.
902 * @param {number} index The index to set.
903 * @private
904 */
905VirtualRepeatController.prototype.updateScope_ = function(scope, index) {
906  scope.$index = index;
907  scope[this.repeatName] = this.items && this.items[index];
908  if (this.extraName) scope[this.extraName(this.$scope)] = this.items[index];
909};
910
911
912/**
913 * Pools the block at the specified index (Pulls its element out of the dom and stores it).
914 * @param {number} index The index at which the block to pool is stored.
915 * @private
916 */
917VirtualRepeatController.prototype.poolBlock_ = function(index) {
918  this.pooledBlocks.push(this.blocks[index]);
919  this.parentNode.removeChild(this.blocks[index].element[0]);
920  delete this.blocks[index];
921};
922
923
924/**
925 * Produces a dom fragment containing the elements from the list of blocks.
926 * @param {!Array<!VirtualRepeatController.Block>} blocks The blocks whose elements
927 *     should be added to the document fragment.
928 * @return {DocumentFragment}
929 * @private
930 */
931VirtualRepeatController.prototype.domFragmentFromBlocks_ = function(blocks) {
932  var fragment = this.$document[0].createDocumentFragment();
933  blocks.forEach(function(block) {
934    fragment.appendChild(block.element[0]);
935  });
936  return fragment;
937};
938
939
940/**
941 * Updates start and end indexes based on length of repeated items and container size.
942 * @private
943 */
944VirtualRepeatController.prototype.updateIndexes_ = function() {
945  var itemsLength = this.items ? this.items.length : 0;
946  var containerLength = Math.ceil(this.container.getSize() / this.itemSize);
947
948  this.newStartIndex = Math.max(0, Math.min(
949      itemsLength - containerLength,
950      Math.floor(this.container.getScrollOffset() / this.itemSize)));
951  this.newVisibleEnd = this.newStartIndex + containerLength + NUM_EXTRA;
952  this.newEndIndex = Math.min(itemsLength, this.newVisibleEnd);
953  this.newStartIndex = Math.max(0, this.newStartIndex - NUM_EXTRA);
954};
955
956/**
957 * This VirtualRepeatModelArrayLike class enforces the interface requirements
958 * for infinite scrolling within a mdVirtualRepeatContainer. An object with this
959 * interface must implement the following interface with two (2) methods:
960 *
961 * getItemAtIndex: function(index) -> item at that index or null if it is not yet
962 *     loaded (It should start downloading the item in that case).
963 *
964 * getLength: function() -> number The data legnth to which the repeater container
965 *     should be sized. Ideally, when the count is known, this method should return it.
966 *     Otherwise, return a higher number than the currently loaded items to produce an
967 *     infinite-scroll behavior.
968 *
969 * @usage
970 * <hljs lang="html">
971 *  <md-virtual-repeat-container md-orient-horizontal>
972 *    <div md-virtual-repeat="i in items" md-on-demand>
973 *      Hello {{i}}!
974 *    </div>
975 *  </md-virtual-repeat-container>
976 * </hljs>
977 *
978 */
979function VirtualRepeatModelArrayLike(model) {
980  if (!angular.isFunction(model.getItemAtIndex) ||
981      !angular.isFunction(model.getLength)) {
982    throw Error('When md-on-demand is enabled, the Object passed to md-virtual-repeat must implement ' +
983        'functions getItemAtIndex() and getLength() ');
984  }
985
986  this.model = model;
987}
988
989
990VirtualRepeatModelArrayLike.prototype.$$includeIndexes = function(start, end) {
991  for (var i = start; i < end; i++) {
992    if (!this.hasOwnProperty(i)) {
993      this[i] = this.model.getItemAtIndex(i);
994    }
995  }
996  this.length = this.model.getLength();
997};
998
999})(window, window.angular);