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. goog.provide('ngmaterial.components.virtualRepeat');
  8. goog.require('ngmaterial.components.showHide');
  9. goog.require('ngmaterial.core');
  10. /**
  11. * @ngdoc module
  12. * @name material.components.virtualRepeat
  13. */
  14. VirtualRepeatContainerController['$inject'] = ["$$rAF", "$mdUtil", "$mdConstant", "$parse", "$rootScope", "$window", "$scope", "$element", "$attrs"];
  15. VirtualRepeatController['$inject'] = ["$scope", "$element", "$attrs", "$browser", "$document", "$rootScope", "$$rAF", "$mdUtil"];
  16. VirtualRepeatDirective['$inject'] = ["$parse"];
  17. angular.module('material.components.virtualRepeat', [
  18. 'material.core',
  19. 'material.components.showHide'
  20. ])
  21. .directive('mdVirtualRepeatContainer', VirtualRepeatContainerDirective)
  22. .directive('mdVirtualRepeat', VirtualRepeatDirective);
  23. /**
  24. * @ngdoc directive
  25. * @name mdVirtualRepeatContainer
  26. * @module material.components.virtualRepeat
  27. * @restrict E
  28. * @description
  29. * `md-virtual-repeat-container` provides the scroll container for md-virtual-repeat.
  30. *
  31. * VirtualRepeat is a limited substitute for ng-repeat that renders only
  32. * enough DOM nodes to fill the container and recycling them as the user scrolls.
  33. *
  34. * Once an element is not visible anymore, the VirtualRepeat recycles it and will reuse it for
  35. * another visible item by replacing the previous dataset with the new one.
  36. *
  37. * ### Common Issues
  38. *
  39. * - When having one-time bindings inside of the view template, the VirtualRepeat will not properly
  40. * update the bindings for new items, since the view will be recycled.
  41. *
  42. * - Directives inside of a VirtualRepeat will be only compiled (linked) once, because those
  43. * are will be recycled items and used for other items.
  44. * The VirtualRepeat just updates the scope bindings.
  45. *
  46. *
  47. * ### Notes
  48. *
  49. * > The VirtualRepeat is a similar implementation to the Android
  50. * [RecyclerView](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html)
  51. *
  52. * <!-- This comment forces a break between blockquotes //-->
  53. *
  54. * > Please also review the <a ng-href="api/directive/mdVirtualRepeat">VirtualRepeat</a>
  55. * documentation for more information.
  56. *
  57. *
  58. * @usage
  59. * <hljs lang="html">
  60. *
  61. * <md-virtual-repeat-container md-top-index="topIndex">
  62. * <div md-virtual-repeat="i in items" md-item-size="20">Hello {{i}}!</div>
  63. * </md-virtual-repeat-container>
  64. * </hljs>
  65. *
  66. * @param {number=} md-top-index Binds the index of the item that is at the top of the scroll
  67. * container to $scope. It can both read and set the scroll position.
  68. * @param {boolean=} md-orient-horizontal Whether the container should scroll horizontally
  69. * (defaults to orientation and scrolling vertically).
  70. * @param {boolean=} md-auto-shrink When present, the container will shrink to fit
  71. * the number of items when that number is less than its original size.
  72. * @param {number=} md-auto-shrink-min Minimum number of items that md-auto-shrink
  73. * will shrink to (default: 0).
  74. */
  75. function VirtualRepeatContainerDirective() {
  76. return {
  77. controller: VirtualRepeatContainerController,
  78. template: virtualRepeatContainerTemplate,
  79. compile: function virtualRepeatContainerCompile($element, $attrs) {
  80. $element
  81. .addClass('md-virtual-repeat-container')
  82. .addClass($attrs.hasOwnProperty('mdOrientHorizontal')
  83. ? 'md-orient-horizontal'
  84. : 'md-orient-vertical');
  85. }
  86. };
  87. }
  88. function virtualRepeatContainerTemplate($element) {
  89. return '<div class="md-virtual-repeat-scroller">' +
  90. '<div class="md-virtual-repeat-sizer"></div>' +
  91. '<div class="md-virtual-repeat-offsetter">' +
  92. $element[0].innerHTML +
  93. '</div></div>';
  94. }
  95. /**
  96. * Number of additional elements to render above and below the visible area inside
  97. * of the virtual repeat container. A higher number results in less flicker when scrolling
  98. * very quickly in Safari, but comes with a higher rendering and dirty-checking cost.
  99. * @const {number}
  100. */
  101. var NUM_EXTRA = 3;
  102. /** ngInject */
  103. function VirtualRepeatContainerController($$rAF, $mdUtil, $mdConstant, $parse, $rootScope, $window, $scope,
  104. $element, $attrs) {
  105. this.$rootScope = $rootScope;
  106. this.$scope = $scope;
  107. this.$element = $element;
  108. this.$attrs = $attrs;
  109. /** @type {number} The width or height of the container */
  110. this.size = 0;
  111. /** @type {number} The scroll width or height of the scroller */
  112. this.scrollSize = 0;
  113. /** @type {number} The scrollLeft or scrollTop of the scroller */
  114. this.scrollOffset = 0;
  115. /** @type {boolean} Whether the scroller is oriented horizontally */
  116. this.horizontal = this.$attrs.hasOwnProperty('mdOrientHorizontal');
  117. /** @type {!VirtualRepeatController} The repeater inside of this container */
  118. this.repeater = null;
  119. /** @type {boolean} Whether auto-shrink is enabled */
  120. this.autoShrink = this.$attrs.hasOwnProperty('mdAutoShrink');
  121. /** @type {number} Minimum number of items to auto-shrink to */
  122. this.autoShrinkMin = parseInt(this.$attrs.mdAutoShrinkMin, 10) || 0;
  123. /** @type {?number} Original container size when shrank */
  124. this.originalSize = null;
  125. /** @type {number} Amount to offset the total scroll size by. */
  126. this.offsetSize = parseInt(this.$attrs.mdOffsetSize, 10) || 0;
  127. /** @type {?string} height or width element style on the container prior to auto-shrinking. */
  128. this.oldElementSize = null;
  129. /** @type {!number} Maximum amount of pixels allowed for a single DOM element */
  130. this.maxElementPixels = $mdConstant.ELEMENT_MAX_PIXELS;
  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 < this.maxElementPixels) {
  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 / this.maxElementPixels);
  240. // Element template to clone for each max-size piece.
  241. var sizerChild = document.createElement('div');
  242. sizerChild.style[dimension] = this.maxElementPixels + '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 * this.maxElementPixels)) + '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 ltr = document.dir != 'rtl' && document.body.dir != 'rtl';
  326. if(!ltr && !this.maxSize) {
  327. this.scroller.scrollLeft = this.scrollSize;
  328. this.maxSize = this.scroller.scrollLeft;
  329. }
  330. var offset = this.isHorizontal() ?
  331. (ltr?this.scroller.scrollLeft : this.maxSize - this.scroller.scrollLeft)
  332. : this.scroller.scrollTop;
  333. if (offset === this.scrollOffset || offset > this.scrollSize - this.size) return;
  334. var itemSize = this.repeater.getItemSize();
  335. if (!itemSize) return;
  336. var numItems = Math.max(0, Math.floor(offset / itemSize) - NUM_EXTRA);
  337. var transform = (this.isHorizontal() ? 'translateX(' : 'translateY(') +
  338. (!this.isHorizontal() || ltr ? (numItems * itemSize) : - (numItems * itemSize)) + 'px)';
  339. this.scrollOffset = offset;
  340. this.offsetter.style.webkitTransform = transform;
  341. this.offsetter.style.transform = transform;
  342. if (this.bindTopIndex) {
  343. var topIndex = Math.floor(offset / itemSize);
  344. if (topIndex !== this.topIndex && topIndex < this.repeater.getItemCount()) {
  345. this.topIndex = topIndex;
  346. this.bindTopIndex.assign(this.$scope, topIndex);
  347. if (!this.$rootScope.$$phase) this.$scope.$digest();
  348. }
  349. }
  350. this.repeater.containerUpdated();
  351. };
  352. /**
  353. * @ngdoc directive
  354. * @name mdVirtualRepeat
  355. * @module material.components.virtualRepeat
  356. * @restrict A
  357. * @priority 1000
  358. * @description
  359. * `md-virtual-repeat` specifies an element to repeat using virtual scrolling.
  360. *
  361. * Virtual repeat is a limited substitute for ng-repeat that renders only
  362. * enough DOM nodes to fill the container and recycling them as the user scrolls.
  363. *
  364. * Arrays, but not objects are supported for iteration.
  365. * Track by, as alias, and (key, value) syntax are not supported.
  366. *
  367. * ### On-Demand Async Item Loading
  368. *
  369. * When using the `md-on-demand` attribute and loading some asynchronous data, the `getItemAtIndex` function will
  370. * mostly return nothing.
  371. *
  372. * <hljs lang="js">
  373. * DynamicItems.prototype.getItemAtIndex = function(index) {
  374. * if (this.pages[index]) {
  375. * return this.pages[index];
  376. * } else {
  377. * // This is an asynchronous action and does not return any value.
  378. * this.loadPage(index);
  379. * }
  380. * };
  381. * </hljs>
  382. *
  383. * This means that the VirtualRepeat will not have any value for the given index.<br/>
  384. * After the data loading completed, the user expects the VirtualRepeat to recognize the change.
  385. *
  386. * To make sure that the VirtualRepeat properly detects any change, you need to run the operation
  387. * in another digest.
  388. *
  389. * <hljs lang="js">
  390. * DynamicItems.prototype.loadPage = function(index) {
  391. * var self = this;
  392. *
  393. * // Trigger a new digest by using $timeout
  394. * $timeout(function() {
  395. * self.pages[index] = Data;
  396. * });
  397. * };
  398. * </hljs>
  399. *
  400. * > <b>Note:</b> Please also review the
  401. * <a ng-href="api/directive/mdVirtualRepeatContainer">VirtualRepeatContainer</a> documentation
  402. * for more information.
  403. *
  404. * @usage
  405. * <hljs lang="html">
  406. * <md-virtual-repeat-container>
  407. * <div md-virtual-repeat="i in items">Hello {{i}}!</div>
  408. * </md-virtual-repeat-container>
  409. *
  410. * <md-virtual-repeat-container md-orient-horizontal>
  411. * <div md-virtual-repeat="i in items" md-item-size="20">Hello {{i}}!</div>
  412. * </md-virtual-repeat-container>
  413. * </hljs>
  414. *
  415. * @param {number=} md-item-size The height or width of the repeated elements (which must be
  416. * identical for each element). Optional. Will attempt to read the size from the dom if missing,
  417. * but still assumes that all repeated nodes have same height or width.
  418. * @param {string=} md-extra-name Evaluates to an additional name to which the current iterated item
  419. * can be assigned on the repeated scope (needed for use in `md-autocomplete`).
  420. * @param {boolean=} md-on-demand When present, treats the md-virtual-repeat argument as an object
  421. * that can fetch rows rather than an array.
  422. *
  423. * **NOTE:** This object must implement the following interface with two (2) methods:
  424. *
  425. * - `getItemAtIndex: function(index) [object]` The item at that index or null if it is not yet
  426. * loaded (it should start downloading the item in that case).
  427. * - `getLength: function() [number]` The data length to which the repeater container
  428. * should be sized. Ideally, when the count is known, this method should return it.
  429. * Otherwise, return a higher number than the currently loaded items to produce an
  430. * infinite-scroll behavior.
  431. */
  432. function VirtualRepeatDirective($parse) {
  433. return {
  434. controller: VirtualRepeatController,
  435. priority: 1000,
  436. require: ['mdVirtualRepeat', '^^mdVirtualRepeatContainer'],
  437. restrict: 'A',
  438. terminal: true,
  439. transclude: 'element',
  440. compile: function VirtualRepeatCompile($element, $attrs) {
  441. var expression = $attrs.mdVirtualRepeat;
  442. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)\s*$/);
  443. var repeatName = match[1];
  444. var repeatListExpression = $parse(match[2]);
  445. var extraName = $attrs.mdExtraName && $parse($attrs.mdExtraName);
  446. return function VirtualRepeatLink($scope, $element, $attrs, ctrl, $transclude) {
  447. ctrl[0].link_(ctrl[1], $transclude, repeatName, repeatListExpression, extraName);
  448. };
  449. }
  450. };
  451. }
  452. /** ngInject */
  453. function VirtualRepeatController($scope, $element, $attrs, $browser, $document, $rootScope,
  454. $$rAF, $mdUtil) {
  455. this.$scope = $scope;
  456. this.$element = $element;
  457. this.$attrs = $attrs;
  458. this.$browser = $browser;
  459. this.$document = $document;
  460. this.$rootScope = $rootScope;
  461. this.$$rAF = $$rAF;
  462. /** @type {boolean} Whether we are in on-demand mode. */
  463. this.onDemand = $mdUtil.parseAttributeBoolean($attrs.mdOnDemand);
  464. /** @type {!Function} Backup reference to $browser.$$checkUrlChange */
  465. this.browserCheckUrlChange = $browser.$$checkUrlChange;
  466. /** @type {number} Most recent starting repeat index (based on scroll offset) */
  467. this.newStartIndex = 0;
  468. /** @type {number} Most recent ending repeat index (based on scroll offset) */
  469. this.newEndIndex = 0;
  470. /** @type {number} Most recent end visible index (based on scroll offset) */
  471. this.newVisibleEnd = 0;
  472. /** @type {number} Previous starting repeat index (based on scroll offset) */
  473. this.startIndex = 0;
  474. /** @type {number} Previous ending repeat index (based on scroll offset) */
  475. this.endIndex = 0;
  476. // TODO: measure width/height of first element from dom if not provided.
  477. // getComputedStyle?
  478. /** @type {?number} Height/width of repeated elements. */
  479. this.itemSize = $scope.$eval($attrs.mdItemSize) || null;
  480. /** @type {boolean} Whether this is the first time that items are rendered. */
  481. this.isFirstRender = true;
  482. /**
  483. * @private {boolean} Whether the items in the list are already being updated. Used to prevent
  484. * nested calls to virtualRepeatUpdate_.
  485. */
  486. this.isVirtualRepeatUpdating_ = false;
  487. /** @type {number} Most recently seen length of items. */
  488. this.itemsLength = 0;
  489. /**
  490. * @type {!Function} Unwatch callback for item size (when md-items-size is
  491. * not specified), or angular.noop otherwise.
  492. */
  493. this.unwatchItemSize_ = angular.noop;
  494. /**
  495. * Presently rendered blocks by repeat index.
  496. * @type {Object<number, !VirtualRepeatController.Block}
  497. */
  498. this.blocks = {};
  499. /** @type {Array<!VirtualRepeatController.Block>} A pool of presently unused blocks. */
  500. this.pooledBlocks = [];
  501. $scope.$on('$destroy', angular.bind(this, this.cleanupBlocks_));
  502. }
  503. /**
  504. * An object representing a repeated item.
  505. * @typedef {{element: !jqLite, new: boolean, scope: !angular.Scope}}
  506. */
  507. VirtualRepeatController.Block;
  508. /**
  509. * Called at startup by the md-virtual-repeat postLink function.
  510. * @param {!VirtualRepeatContainerController} container The container's controller.
  511. * @param {!Function} transclude The repeated element's bound transclude function.
  512. * @param {string} repeatName The left hand side of the repeat expression, indicating
  513. * the name for each item in the array.
  514. * @param {!Function} repeatListExpression A compiled expression based on the right hand side
  515. * of the repeat expression. Points to the array to repeat over.
  516. * @param {string|undefined} extraName The optional extra repeatName.
  517. */
  518. VirtualRepeatController.prototype.link_ =
  519. function(container, transclude, repeatName, repeatListExpression, extraName) {
  520. this.container = container;
  521. this.transclude = transclude;
  522. this.repeatName = repeatName;
  523. this.rawRepeatListExpression = repeatListExpression;
  524. this.extraName = extraName;
  525. this.sized = false;
  526. this.repeatListExpression = angular.bind(this, this.repeatListExpression_);
  527. this.container.register(this);
  528. };
  529. /** @private Cleans up unused blocks. */
  530. VirtualRepeatController.prototype.cleanupBlocks_ = function() {
  531. angular.forEach(this.pooledBlocks, function cleanupBlock(block) {
  532. block.element.remove();
  533. });
  534. };
  535. /** @private Attempts to set itemSize by measuring a repeated element in the dom */
  536. VirtualRepeatController.prototype.readItemSize_ = function() {
  537. if (this.itemSize) {
  538. // itemSize was successfully read in a different asynchronous call.
  539. return;
  540. }
  541. this.items = this.repeatListExpression(this.$scope);
  542. this.parentNode = this.$element[0].parentNode;
  543. var block = this.getBlock_(0);
  544. if (!block.element[0].parentNode) {
  545. this.parentNode.appendChild(block.element[0]);
  546. }
  547. this.itemSize = block.element[0][
  548. this.container.isHorizontal() ? 'offsetWidth' : 'offsetHeight'] || null;
  549. this.blocks[0] = block;
  550. this.poolBlock_(0);
  551. if (this.itemSize) {
  552. this.containerUpdated();
  553. }
  554. };
  555. /**
  556. * Returns the user-specified repeat list, transforming it into an array-like
  557. * object in the case of infinite scroll/dynamic load mode.
  558. * @param {!angular.Scope} The scope.
  559. * @return {!Array|!Object} An array or array-like object for iteration.
  560. */
  561. VirtualRepeatController.prototype.repeatListExpression_ = function(scope) {
  562. var repeatList = this.rawRepeatListExpression(scope);
  563. if (this.onDemand && repeatList) {
  564. var virtualList = new VirtualRepeatModelArrayLike(repeatList);
  565. virtualList.$$includeIndexes(this.newStartIndex, this.newVisibleEnd);
  566. return virtualList;
  567. } else {
  568. return repeatList;
  569. }
  570. };
  571. /**
  572. * Called by the container. Informs us that the containers scroll or size has
  573. * changed.
  574. */
  575. VirtualRepeatController.prototype.containerUpdated = function() {
  576. // If itemSize is unknown, attempt to measure it.
  577. if (!this.itemSize) {
  578. // Make sure to clean up watchers if we can (see #8178)
  579. if(this.unwatchItemSize_ && this.unwatchItemSize_ !== angular.noop){
  580. this.unwatchItemSize_();
  581. }
  582. this.unwatchItemSize_ = this.$scope.$watchCollection(
  583. this.repeatListExpression,
  584. angular.bind(this, function(items) {
  585. if (items && items.length) {
  586. this.readItemSize_();
  587. }
  588. }));
  589. if (!this.$rootScope.$$phase) this.$scope.$digest();
  590. return;
  591. } else if (!this.sized) {
  592. this.items = this.repeatListExpression(this.$scope);
  593. }
  594. if (!this.sized) {
  595. this.unwatchItemSize_();
  596. this.sized = true;
  597. this.$scope.$watchCollection(this.repeatListExpression,
  598. angular.bind(this, function(items, oldItems) {
  599. if (!this.isVirtualRepeatUpdating_) {
  600. this.virtualRepeatUpdate_(items, oldItems);
  601. }
  602. }));
  603. }
  604. this.updateIndexes_();
  605. if (this.newStartIndex !== this.startIndex ||
  606. this.newEndIndex !== this.endIndex ||
  607. this.container.getScrollOffset() > this.container.getScrollSize()) {
  608. if (this.items instanceof VirtualRepeatModelArrayLike) {
  609. this.items.$$includeIndexes(this.newStartIndex, this.newEndIndex);
  610. }
  611. this.virtualRepeatUpdate_(this.items, this.items);
  612. }
  613. };
  614. /**
  615. * Called by the container. Returns the size of a single repeated item.
  616. * @return {?number} Size of a repeated item.
  617. */
  618. VirtualRepeatController.prototype.getItemSize = function() {
  619. return this.itemSize;
  620. };
  621. /**
  622. * Called by the container. Returns the size of a single repeated item.
  623. * @return {?number} Size of a repeated item.
  624. */
  625. VirtualRepeatController.prototype.getItemCount = function() {
  626. return this.itemsLength;
  627. };
  628. /**
  629. * Updates the order and visible offset of repeated blocks in response to scrolling
  630. * or items updates.
  631. * @private
  632. */
  633. VirtualRepeatController.prototype.virtualRepeatUpdate_ = function(items, oldItems) {
  634. this.isVirtualRepeatUpdating_ = true;
  635. var itemsLength = items && items.length || 0;
  636. var lengthChanged = false;
  637. // If the number of items shrank, keep the scroll position.
  638. if (this.items && itemsLength < this.items.length && this.container.getScrollOffset() !== 0) {
  639. this.items = items;
  640. var previousScrollOffset = this.container.getScrollOffset();
  641. this.container.resetScroll();
  642. this.container.scrollTo(previousScrollOffset);
  643. }
  644. if (itemsLength !== this.itemsLength) {
  645. lengthChanged = true;
  646. this.itemsLength = itemsLength;
  647. }
  648. this.items = items;
  649. if (items !== oldItems || lengthChanged) {
  650. this.updateIndexes_();
  651. }
  652. this.parentNode = this.$element[0].parentNode;
  653. if (lengthChanged) {
  654. this.container.setScrollSize(itemsLength * this.itemSize);
  655. }
  656. if (this.isFirstRender) {
  657. this.isFirstRender = false;
  658. var startIndex = this.$attrs.mdStartIndex ?
  659. this.$scope.$eval(this.$attrs.mdStartIndex) :
  660. this.container.topIndex;
  661. this.container.scrollToIndex(startIndex);
  662. }
  663. // Detach and pool any blocks that are no longer in the viewport.
  664. Object.keys(this.blocks).forEach(function(blockIndex) {
  665. var index = parseInt(blockIndex, 10);
  666. if (index < this.newStartIndex || index >= this.newEndIndex) {
  667. this.poolBlock_(index);
  668. }
  669. }, this);
  670. // Add needed blocks.
  671. // For performance reasons, temporarily block browser url checks as we digest
  672. // the restored block scopes ($$checkUrlChange reads window.location to
  673. // check for changes and trigger route change, etc, which we don't need when
  674. // trying to scroll at 60fps).
  675. this.$browser.$$checkUrlChange = angular.noop;
  676. var i, block,
  677. newStartBlocks = [],
  678. newEndBlocks = [];
  679. // Collect blocks at the top.
  680. for (i = this.newStartIndex; i < this.newEndIndex && this.blocks[i] == null; i++) {
  681. block = this.getBlock_(i);
  682. this.updateBlock_(block, i);
  683. newStartBlocks.push(block);
  684. }
  685. // Update blocks that are already rendered.
  686. for (; this.blocks[i] != null; i++) {
  687. this.updateBlock_(this.blocks[i], i);
  688. }
  689. var maxIndex = i - 1;
  690. // Collect blocks at the end.
  691. for (; i < this.newEndIndex; i++) {
  692. block = this.getBlock_(i);
  693. this.updateBlock_(block, i);
  694. newEndBlocks.push(block);
  695. }
  696. // Attach collected blocks to the document.
  697. if (newStartBlocks.length) {
  698. this.parentNode.insertBefore(
  699. this.domFragmentFromBlocks_(newStartBlocks),
  700. this.$element[0].nextSibling);
  701. }
  702. if (newEndBlocks.length) {
  703. this.parentNode.insertBefore(
  704. this.domFragmentFromBlocks_(newEndBlocks),
  705. this.blocks[maxIndex] && this.blocks[maxIndex].element[0].nextSibling);
  706. }
  707. // Restore $$checkUrlChange.
  708. this.$browser.$$checkUrlChange = this.browserCheckUrlChange;
  709. this.startIndex = this.newStartIndex;
  710. this.endIndex = this.newEndIndex;
  711. this.isVirtualRepeatUpdating_ = false;
  712. };
  713. /**
  714. * @param {number} index Where the block is to be in the repeated list.
  715. * @return {!VirtualRepeatController.Block} A new or pooled block to place at the specified index.
  716. * @private
  717. */
  718. VirtualRepeatController.prototype.getBlock_ = function(index) {
  719. if (this.pooledBlocks.length) {
  720. return this.pooledBlocks.pop();
  721. }
  722. var block;
  723. this.transclude(angular.bind(this, function(clone, scope) {
  724. block = {
  725. element: clone,
  726. new: true,
  727. scope: scope
  728. };
  729. this.updateScope_(scope, index);
  730. this.parentNode.appendChild(clone[0]);
  731. }));
  732. return block;
  733. };
  734. /**
  735. * Updates and if not in a digest cycle, digests the specified block's scope to the data
  736. * at the specified index.
  737. * @param {!VirtualRepeatController.Block} block The block whose scope should be updated.
  738. * @param {number} index The index to set.
  739. * @private
  740. */
  741. VirtualRepeatController.prototype.updateBlock_ = function(block, index) {
  742. this.blocks[index] = block;
  743. if (!block.new &&
  744. (block.scope.$index === index && block.scope[this.repeatName] === this.items[index])) {
  745. return;
  746. }
  747. block.new = false;
  748. // Update and digest the block's scope.
  749. this.updateScope_(block.scope, index);
  750. // Perform digest before reattaching the block.
  751. // Any resulting synchronous dom mutations should be much faster as a result.
  752. // This might break some directives, but I'm going to try it for now.
  753. if (!this.$rootScope.$$phase) {
  754. block.scope.$digest();
  755. }
  756. };
  757. /**
  758. * Updates scope to the data at the specified index.
  759. * @param {!angular.Scope} scope The scope which should be updated.
  760. * @param {number} index The index to set.
  761. * @private
  762. */
  763. VirtualRepeatController.prototype.updateScope_ = function(scope, index) {
  764. scope.$index = index;
  765. scope[this.repeatName] = this.items && this.items[index];
  766. if (this.extraName) scope[this.extraName(this.$scope)] = this.items[index];
  767. };
  768. /**
  769. * Pools the block at the specified index (Pulls its element out of the dom and stores it).
  770. * @param {number} index The index at which the block to pool is stored.
  771. * @private
  772. */
  773. VirtualRepeatController.prototype.poolBlock_ = function(index) {
  774. this.pooledBlocks.push(this.blocks[index]);
  775. this.parentNode.removeChild(this.blocks[index].element[0]);
  776. delete this.blocks[index];
  777. };
  778. /**
  779. * Produces a dom fragment containing the elements from the list of blocks.
  780. * @param {!Array<!VirtualRepeatController.Block>} blocks The blocks whose elements
  781. * should be added to the document fragment.
  782. * @return {DocumentFragment}
  783. * @private
  784. */
  785. VirtualRepeatController.prototype.domFragmentFromBlocks_ = function(blocks) {
  786. var fragment = this.$document[0].createDocumentFragment();
  787. blocks.forEach(function(block) {
  788. fragment.appendChild(block.element[0]);
  789. });
  790. return fragment;
  791. };
  792. /**
  793. * Updates start and end indexes based on length of repeated items and container size.
  794. * @private
  795. */
  796. VirtualRepeatController.prototype.updateIndexes_ = function() {
  797. var itemsLength = this.items ? this.items.length : 0;
  798. var containerLength = Math.ceil(this.container.getSize() / this.itemSize);
  799. this.newStartIndex = Math.max(0, Math.min(
  800. itemsLength - containerLength,
  801. Math.floor(this.container.getScrollOffset() / this.itemSize)));
  802. this.newVisibleEnd = this.newStartIndex + containerLength + NUM_EXTRA;
  803. this.newEndIndex = Math.min(itemsLength, this.newVisibleEnd);
  804. this.newStartIndex = Math.max(0, this.newStartIndex - NUM_EXTRA);
  805. };
  806. /**
  807. * This VirtualRepeatModelArrayLike class enforces the interface requirements
  808. * for infinite scrolling within a mdVirtualRepeatContainer. An object with this
  809. * interface must implement the following interface with two (2) methods:
  810. *
  811. * getItemAtIndex: function(index) -> item at that index or null if it is not yet
  812. * loaded (It should start downloading the item in that case).
  813. *
  814. * getLength: function() -> number The data legnth to which the repeater container
  815. * should be sized. Ideally, when the count is known, this method should return it.
  816. * Otherwise, return a higher number than the currently loaded items to produce an
  817. * infinite-scroll behavior.
  818. *
  819. * @usage
  820. * <hljs lang="html">
  821. * <md-virtual-repeat-container md-orient-horizontal>
  822. * <div md-virtual-repeat="i in items" md-on-demand>
  823. * Hello {{i}}!
  824. * </div>
  825. * </md-virtual-repeat-container>
  826. * </hljs>
  827. *
  828. */
  829. function VirtualRepeatModelArrayLike(model) {
  830. if (!angular.isFunction(model.getItemAtIndex) ||
  831. !angular.isFunction(model.getLength)) {
  832. throw Error('When md-on-demand is enabled, the Object passed to md-virtual-repeat must implement ' +
  833. 'functions getItemAtIndex() and getLength() ');
  834. }
  835. this.model = model;
  836. }
  837. VirtualRepeatModelArrayLike.prototype.$$includeIndexes = function(start, end) {
  838. for (var i = start; i < end; i++) {
  839. if (!this.hasOwnProperty(i)) {
  840. this[i] = this.model.getItemAtIndex(i);
  841. }
  842. }
  843. this.length = this.model.getLength();
  844. };
  845. ngmaterial.components.virtualRepeat = angular.module("material.components.virtualRepeat");