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