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.

998 lines
33 KiB

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