virtualRepeat.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. /*!
  2. * AngularJS Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v1.1.8-master-aba7b2b
  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. .directive('mdForceHeight', ForceHeightDirective);
  24. /**
  25. * @ngdoc directive
  26. * @name mdVirtualRepeatContainer
  27. * @module material.components.virtualRepeat
  28. * @restrict E
  29. * @description
  30. * `md-virtual-repeat-container` provides the scroll container for md-virtual-repeat.
  31. *
  32. * VirtualRepeat is a limited substitute for ng-repeat that renders only
  33. * enough DOM nodes to fill the container and recycling them as the user scrolls.
  34. *
  35. * Once an element is not visible anymore, the VirtualRepeat recycles it and will reuse it for
  36. * another visible item by replacing the previous dataset with the new one.
  37. *
  38. * ### Common Issues
  39. *
  40. * - When having one-time bindings inside of the view template, the VirtualRepeat will not properly
  41. * update the bindings for new items, since the view will be recycled.
  42. * - Directives inside of a VirtualRepeat will be only compiled (linked) once, because those
  43. * items will be recycled 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" role="presentation">' +
  90. '<div class="md-virtual-repeat-sizer" role="presentation"></div>' +
  91. '<div class="md-virtual-repeat-offsetter" role="presentation">' +
  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 AngularJS 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.$mdUtil = $mdUtil;
  461. this.$rootScope = $rootScope;
  462. this.$$rAF = $$rAF;
  463. /** @type {boolean} Whether we are in on-demand mode. */
  464. this.onDemand = $mdUtil.parseAttributeBoolean($attrs.mdOnDemand);
  465. /** @type {!Function} Backup reference to $browser.$$checkUrlChange */
  466. this.browserCheckUrlChange = $browser.$$checkUrlChange;
  467. /** @type {number} Most recent starting repeat index (based on scroll offset) */
  468. this.newStartIndex = 0;
  469. /** @type {number} Most recent ending repeat index (based on scroll offset) */
  470. this.newEndIndex = 0;
  471. /** @type {number} Most recent end visible index (based on scroll offset) */
  472. this.newVisibleEnd = 0;
  473. /** @type {number} Previous starting repeat index (based on scroll offset) */
  474. this.startIndex = 0;
  475. /** @type {number} Previous ending repeat index (based on scroll offset) */
  476. this.endIndex = 0;
  477. // TODO: measure width/height of first element from dom if not provided.
  478. // getComputedStyle?
  479. /** @type {?number} Height/width of repeated elements. */
  480. this.itemSize = $scope.$eval($attrs.mdItemSize) || null;
  481. /** @type {boolean} Whether this is the first time that items are rendered. */
  482. this.isFirstRender = true;
  483. /**
  484. * @private {boolean} Whether the items in the list are already being updated. Used to prevent
  485. * nested calls to virtualRepeatUpdate_.
  486. */
  487. this.isVirtualRepeatUpdating_ = false;
  488. /** @type {number} Most recently seen length of items. */
  489. this.itemsLength = 0;
  490. /**
  491. * @type {!Function} Unwatch callback for item size (when md-items-size is
  492. * not specified), or angular.noop otherwise.
  493. */
  494. this.unwatchItemSize_ = angular.noop;
  495. /**
  496. * Presently rendered blocks by repeat index.
  497. * @type {Object<number, !VirtualRepeatController.Block}
  498. */
  499. this.blocks = {};
  500. /** @type {Array<!VirtualRepeatController.Block>} A pool of presently unused blocks. */
  501. this.pooledBlocks = [];
  502. $scope.$on('$destroy', angular.bind(this, this.cleanupBlocks_));
  503. }
  504. /**
  505. * An object representing a repeated item.
  506. * @typedef {{element: !jqLite, new: boolean, scope: !angular.Scope}}
  507. */
  508. VirtualRepeatController.Block;
  509. /**
  510. * Called at startup by the md-virtual-repeat postLink function.
  511. * @param {!VirtualRepeatContainerController} container The container's controller.
  512. * @param {!Function} transclude The repeated element's bound transclude function.
  513. * @param {string} repeatName The left hand side of the repeat expression, indicating
  514. * the name for each item in the array.
  515. * @param {!Function} repeatListExpression A compiled expression based on the right hand side
  516. * of the repeat expression. Points to the array to repeat over.
  517. * @param {string|undefined} extraName The optional extra repeatName.
  518. */
  519. VirtualRepeatController.prototype.link_ =
  520. function(container, transclude, repeatName, repeatListExpression, extraName) {
  521. this.container = container;
  522. this.transclude = transclude;
  523. this.repeatName = repeatName;
  524. this.rawRepeatListExpression = repeatListExpression;
  525. this.extraName = extraName;
  526. this.sized = false;
  527. this.repeatListExpression = angular.bind(this, this.repeatListExpression_);
  528. this.container.register(this);
  529. };
  530. /** @private Cleans up unused blocks. */
  531. VirtualRepeatController.prototype.cleanupBlocks_ = function() {
  532. angular.forEach(this.pooledBlocks, function cleanupBlock(block) {
  533. block.element.remove();
  534. });
  535. };
  536. /** @private Attempts to set itemSize by measuring a repeated element in the dom */
  537. VirtualRepeatController.prototype.readItemSize_ = function() {
  538. if (this.itemSize) {
  539. // itemSize was successfully read in a different asynchronous call.
  540. return;
  541. }
  542. this.items = this.repeatListExpression(this.$scope);
  543. this.parentNode = this.$element[0].parentNode;
  544. var block = this.getBlock_(0);
  545. if (!block.element[0].parentNode) {
  546. this.parentNode.appendChild(block.element[0]);
  547. }
  548. this.itemSize = block.element[0][
  549. this.container.isHorizontal() ? 'offsetWidth' : 'offsetHeight'] || null;
  550. this.blocks[0] = block;
  551. this.poolBlock_(0);
  552. if (this.itemSize) {
  553. this.containerUpdated();
  554. }
  555. };
  556. /**
  557. * Returns the user-specified repeat list, transforming it into an array-like
  558. * object in the case of infinite scroll/dynamic load mode.
  559. * @param {!angular.Scope} The scope.
  560. * @return {!Array|!Object} An array or array-like object for iteration.
  561. */
  562. VirtualRepeatController.prototype.repeatListExpression_ = function(scope) {
  563. var repeatList = this.rawRepeatListExpression(scope);
  564. if (this.onDemand && repeatList) {
  565. var virtualList = new VirtualRepeatModelArrayLike(repeatList);
  566. virtualList.$$includeIndexes(this.newStartIndex, this.newVisibleEnd);
  567. return virtualList;
  568. } else {
  569. return repeatList;
  570. }
  571. };
  572. /**
  573. * Called by the container. Informs us that the containers scroll or size has
  574. * changed.
  575. */
  576. VirtualRepeatController.prototype.containerUpdated = function() {
  577. // If itemSize is unknown, attempt to measure it.
  578. if (!this.itemSize) {
  579. // Make sure to clean up watchers if we can (see #8178)
  580. if(this.unwatchItemSize_ && this.unwatchItemSize_ !== angular.noop){
  581. this.unwatchItemSize_();
  582. }
  583. this.unwatchItemSize_ = this.$scope.$watchCollection(
  584. this.repeatListExpression,
  585. angular.bind(this, function(items) {
  586. if (items && items.length) {
  587. this.readItemSize_();
  588. }
  589. }));
  590. if (!this.$rootScope.$$phase) this.$scope.$digest();
  591. return;
  592. } else if (!this.sized) {
  593. this.items = this.repeatListExpression(this.$scope);
  594. }
  595. if (!this.sized) {
  596. this.unwatchItemSize_();
  597. this.sized = true;
  598. this.$scope.$watchCollection(this.repeatListExpression,
  599. angular.bind(this, function(items, oldItems) {
  600. if (!this.isVirtualRepeatUpdating_) {
  601. this.virtualRepeatUpdate_(items, oldItems);
  602. }
  603. }));
  604. }
  605. this.updateIndexes_();
  606. if (this.newStartIndex !== this.startIndex ||
  607. this.newEndIndex !== this.endIndex ||
  608. this.container.getScrollOffset() > this.container.getScrollSize()) {
  609. if (this.items instanceof VirtualRepeatModelArrayLike) {
  610. this.items.$$includeIndexes(this.newStartIndex, this.newEndIndex);
  611. }
  612. this.virtualRepeatUpdate_(this.items, this.items);
  613. }
  614. };
  615. /**
  616. * Called by the container. Returns the size of a single repeated item.
  617. * @return {?number} Size of a repeated item.
  618. */
  619. VirtualRepeatController.prototype.getItemSize = function() {
  620. return this.itemSize;
  621. };
  622. /**
  623. * Called by the container. Returns the size of a single repeated item.
  624. * @return {?number} Size of a repeated item.
  625. */
  626. VirtualRepeatController.prototype.getItemCount = function() {
  627. return this.itemsLength;
  628. };
  629. /**
  630. * Updates the order and visible offset of repeated blocks in response to scrolling
  631. * or items updates.
  632. * @private
  633. */
  634. VirtualRepeatController.prototype.virtualRepeatUpdate_ = function(items, oldItems) {
  635. this.isVirtualRepeatUpdating_ = true;
  636. var itemsLength = items && items.length || 0;
  637. var lengthChanged = false;
  638. // If the number of items shrank, keep the scroll position.
  639. if (this.items && itemsLength < this.items.length && this.container.getScrollOffset() !== 0) {
  640. this.items = items;
  641. var previousScrollOffset = this.container.getScrollOffset();
  642. this.container.resetScroll();
  643. this.container.scrollTo(previousScrollOffset);
  644. }
  645. if (itemsLength !== this.itemsLength) {
  646. lengthChanged = true;
  647. this.itemsLength = itemsLength;
  648. }
  649. this.items = items;
  650. if (items !== oldItems || lengthChanged) {
  651. this.updateIndexes_();
  652. }
  653. this.parentNode = this.$element[0].parentNode;
  654. if (lengthChanged) {
  655. this.container.setScrollSize(itemsLength * this.itemSize);
  656. }
  657. // Detach and pool any blocks that are no longer in the viewport.
  658. Object.keys(this.blocks).forEach(function(blockIndex) {
  659. var index = parseInt(blockIndex, 10);
  660. if (index < this.newStartIndex || index >= this.newEndIndex) {
  661. this.poolBlock_(index);
  662. }
  663. }, this);
  664. // Add needed blocks.
  665. // For performance reasons, temporarily block browser url checks as we digest
  666. // the restored block scopes ($$checkUrlChange reads window.location to
  667. // check for changes and trigger route change, etc, which we don't need when
  668. // trying to scroll at 60fps).
  669. this.$browser.$$checkUrlChange = angular.noop;
  670. var i, block,
  671. newStartBlocks = [],
  672. newEndBlocks = [];
  673. // Collect blocks at the top.
  674. for (i = this.newStartIndex; i < this.newEndIndex && this.blocks[i] == null; i++) {
  675. block = this.getBlock_(i);
  676. this.updateBlock_(block, i);
  677. newStartBlocks.push(block);
  678. }
  679. // Update blocks that are already rendered.
  680. for (; this.blocks[i] != null; i++) {
  681. this.updateBlock_(this.blocks[i], i);
  682. }
  683. var maxIndex = i - 1;
  684. // Collect blocks at the end.
  685. for (; i < this.newEndIndex; i++) {
  686. block = this.getBlock_(i);
  687. this.updateBlock_(block, i);
  688. newEndBlocks.push(block);
  689. }
  690. // Attach collected blocks to the document.
  691. if (newStartBlocks.length) {
  692. this.parentNode.insertBefore(
  693. this.domFragmentFromBlocks_(newStartBlocks),
  694. this.$element[0].nextSibling);
  695. }
  696. if (newEndBlocks.length) {
  697. this.parentNode.insertBefore(
  698. this.domFragmentFromBlocks_(newEndBlocks),
  699. this.blocks[maxIndex] && this.blocks[maxIndex].element[0].nextSibling);
  700. }
  701. // Restore $$checkUrlChange.
  702. this.$browser.$$checkUrlChange = this.browserCheckUrlChange;
  703. this.startIndex = this.newStartIndex;
  704. this.endIndex = this.newEndIndex;
  705. if (this.isFirstRender) {
  706. this.isFirstRender = false;
  707. var firstRenderStartIndex = this.$attrs.mdStartIndex ?
  708. this.$scope.$eval(this.$attrs.mdStartIndex) :
  709. this.container.topIndex;
  710. // The first call to virtualRepeatUpdate_ may not be when the virtual repeater is ready.
  711. // Introduce a slight delay so that the update happens when it is actually ready.
  712. this.$mdUtil.nextTick(function() {
  713. this.container.scrollToIndex(firstRenderStartIndex);
  714. }.bind(this));
  715. }
  716. this.isVirtualRepeatUpdating_ = false;
  717. };
  718. /**
  719. * @param {number} index Where the block is to be in the repeated list.
  720. * @return {!VirtualRepeatController.Block} A new or pooled block to place at the specified index.
  721. * @private
  722. */
  723. VirtualRepeatController.prototype.getBlock_ = function(index) {
  724. if (this.pooledBlocks.length) {
  725. return this.pooledBlocks.pop();
  726. }
  727. var block;
  728. this.transclude(angular.bind(this, function(clone, scope) {
  729. block = {
  730. element: clone,
  731. new: true,
  732. scope: scope
  733. };
  734. this.updateScope_(scope, index);
  735. this.parentNode.appendChild(clone[0]);
  736. }));
  737. return block;
  738. };
  739. /**
  740. * Updates and if not in a digest cycle, digests the specified block's scope to the data
  741. * at the specified index.
  742. * @param {!VirtualRepeatController.Block} block The block whose scope should be updated.
  743. * @param {number} index The index to set.
  744. * @private
  745. */
  746. VirtualRepeatController.prototype.updateBlock_ = function(block, index) {
  747. this.blocks[index] = block;
  748. if (!block.new &&
  749. (block.scope.$index === index && block.scope[this.repeatName] === this.items[index])) {
  750. return;
  751. }
  752. block.new = false;
  753. // Update and digest the block's scope.
  754. this.updateScope_(block.scope, index);
  755. // Perform digest before reattaching the block.
  756. // Any resulting synchronous dom mutations should be much faster as a result.
  757. // This might break some directives, but I'm going to try it for now.
  758. if (!this.$rootScope.$$phase) {
  759. block.scope.$digest();
  760. }
  761. };
  762. /**
  763. * Updates scope to the data at the specified index.
  764. * @param {!angular.Scope} scope The scope which should be updated.
  765. * @param {number} index The index to set.
  766. * @private
  767. */
  768. VirtualRepeatController.prototype.updateScope_ = function(scope, index) {
  769. scope.$index = index;
  770. scope[this.repeatName] = this.items && this.items[index];
  771. if (this.extraName) scope[this.extraName(this.$scope)] = this.items[index];
  772. };
  773. /**
  774. * Pools the block at the specified index (Pulls its element out of the dom and stores it).
  775. * @param {number} index The index at which the block to pool is stored.
  776. * @private
  777. */
  778. VirtualRepeatController.prototype.poolBlock_ = function(index) {
  779. this.pooledBlocks.push(this.blocks[index]);
  780. this.parentNode.removeChild(this.blocks[index].element[0]);
  781. delete this.blocks[index];
  782. };
  783. /**
  784. * Produces a dom fragment containing the elements from the list of blocks.
  785. * @param {!Array<!VirtualRepeatController.Block>} blocks The blocks whose elements
  786. * should be added to the document fragment.
  787. * @return {DocumentFragment}
  788. * @private
  789. */
  790. VirtualRepeatController.prototype.domFragmentFromBlocks_ = function(blocks) {
  791. var fragment = this.$document[0].createDocumentFragment();
  792. blocks.forEach(function(block) {
  793. fragment.appendChild(block.element[0]);
  794. });
  795. return fragment;
  796. };
  797. /**
  798. * Updates start and end indexes based on length of repeated items and container size.
  799. * @private
  800. */
  801. VirtualRepeatController.prototype.updateIndexes_ = function() {
  802. var itemsLength = this.items ? this.items.length : 0;
  803. var containerLength = Math.ceil(this.container.getSize() / this.itemSize);
  804. this.newStartIndex = Math.max(0, Math.min(
  805. itemsLength - containerLength,
  806. Math.floor(this.container.getScrollOffset() / this.itemSize)));
  807. this.newVisibleEnd = this.newStartIndex + containerLength + NUM_EXTRA;
  808. this.newEndIndex = Math.min(itemsLength, this.newVisibleEnd);
  809. this.newStartIndex = Math.max(0, this.newStartIndex - NUM_EXTRA);
  810. };
  811. /**
  812. * This VirtualRepeatModelArrayLike class enforces the interface requirements
  813. * for infinite scrolling within a mdVirtualRepeatContainer. An object with this
  814. * interface must implement the following interface with two (2) methods:
  815. *
  816. * getItemAtIndex: function(index) -> item at that index or null if it is not yet
  817. * loaded (It should start downloading the item in that case).
  818. *
  819. * getLength: function() -> number The data legnth to which the repeater container
  820. * should be sized. Ideally, when the count is known, this method should return it.
  821. * Otherwise, return a higher number than the currently loaded items to produce an
  822. * infinite-scroll behavior.
  823. *
  824. * @usage
  825. * <hljs lang="html">
  826. * <md-virtual-repeat-container md-orient-horizontal>
  827. * <div md-virtual-repeat="i in items" md-on-demand>
  828. * Hello {{i}}!
  829. * </div>
  830. * </md-virtual-repeat-container>
  831. * </hljs>
  832. *
  833. */
  834. function VirtualRepeatModelArrayLike(model) {
  835. if (!angular.isFunction(model.getItemAtIndex) ||
  836. !angular.isFunction(model.getLength)) {
  837. throw Error('When md-on-demand is enabled, the Object passed to md-virtual-repeat must implement ' +
  838. 'functions getItemAtIndex() and getLength() ');
  839. }
  840. this.model = model;
  841. }
  842. VirtualRepeatModelArrayLike.prototype.$$includeIndexes = function(start, end) {
  843. for (var i = start; i < end; i++) {
  844. if (!this.hasOwnProperty(i)) {
  845. this[i] = this.model.getItemAtIndex(i);
  846. }
  847. }
  848. this.length = this.model.getLength();
  849. };
  850. /**
  851. * @ngdoc directive
  852. * @name mdForceHeight
  853. * @module material.components.virtualRepeat
  854. * @restrict A
  855. * @description
  856. *
  857. * Force an element to have a certain px height. This is used in place of a style tag in order to
  858. * conform to the Content Security Policy regarding unsafe-inline style tags.
  859. *
  860. * @usage
  861. * <hljs lang="html">
  862. * <div md-force-height="'100px'"></div>
  863. * </hljs>
  864. */
  865. function ForceHeightDirective($mdUtil) {
  866. return {
  867. restrict: 'A',
  868. link: function(scope, element, attrs) {
  869. var height = scope.$eval(attrs.mdForceHeight) || null;
  870. if (height && element) {
  871. element[0].style.height = height;
  872. }
  873. }
  874. };
  875. }
  876. ForceHeightDirective['$inject'] = ['$mdUtil'];
  877. ngmaterial.components.virtualRepeat = angular.module("material.components.virtualRepeat");