You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

972 lines
32 KiB

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