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. (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. .directive('mdForceHeight', ForceHeightDirective);
  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. * - Directives inside of a VirtualRepeat will be only compiled (linked) once, because those
  42. * items will be recycled 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" role="presentation">' +
  89. '<div class="md-virtual-repeat-sizer" role="presentation"></div>' +
  90. '<div class="md-virtual-repeat-offsetter" role="presentation">' +
  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 AngularJS 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.$mdUtil = $mdUtil;
  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. // Detach and pool any blocks that are no longer in the viewport.
  657. Object.keys(this.blocks).forEach(function(blockIndex) {
  658. var index = parseInt(blockIndex, 10);
  659. if (index < this.newStartIndex || index >= this.newEndIndex) {
  660. this.poolBlock_(index);
  661. }
  662. }, this);
  663. // Add needed blocks.
  664. // For performance reasons, temporarily block browser url checks as we digest
  665. // the restored block scopes ($$checkUrlChange reads window.location to
  666. // check for changes and trigger route change, etc, which we don't need when
  667. // trying to scroll at 60fps).
  668. this.$browser.$$checkUrlChange = angular.noop;
  669. var i, block,
  670. newStartBlocks = [],
  671. newEndBlocks = [];
  672. // Collect blocks at the top.
  673. for (i = this.newStartIndex; i < this.newEndIndex && this.blocks[i] == null; i++) {
  674. block = this.getBlock_(i);
  675. this.updateBlock_(block, i);
  676. newStartBlocks.push(block);
  677. }
  678. // Update blocks that are already rendered.
  679. for (; this.blocks[i] != null; i++) {
  680. this.updateBlock_(this.blocks[i], i);
  681. }
  682. var maxIndex = i - 1;
  683. // Collect blocks at the end.
  684. for (; i < this.newEndIndex; i++) {
  685. block = this.getBlock_(i);
  686. this.updateBlock_(block, i);
  687. newEndBlocks.push(block);
  688. }
  689. // Attach collected blocks to the document.
  690. if (newStartBlocks.length) {
  691. this.parentNode.insertBefore(
  692. this.domFragmentFromBlocks_(newStartBlocks),
  693. this.$element[0].nextSibling);
  694. }
  695. if (newEndBlocks.length) {
  696. this.parentNode.insertBefore(
  697. this.domFragmentFromBlocks_(newEndBlocks),
  698. this.blocks[maxIndex] && this.blocks[maxIndex].element[0].nextSibling);
  699. }
  700. // Restore $$checkUrlChange.
  701. this.$browser.$$checkUrlChange = this.browserCheckUrlChange;
  702. this.startIndex = this.newStartIndex;
  703. this.endIndex = this.newEndIndex;
  704. if (this.isFirstRender) {
  705. this.isFirstRender = false;
  706. var firstRenderStartIndex = this.$attrs.mdStartIndex ?
  707. this.$scope.$eval(this.$attrs.mdStartIndex) :
  708. this.container.topIndex;
  709. // The first call to virtualRepeatUpdate_ may not be when the virtual repeater is ready.
  710. // Introduce a slight delay so that the update happens when it is actually ready.
  711. this.$mdUtil.nextTick(function() {
  712. this.container.scrollToIndex(firstRenderStartIndex);
  713. }.bind(this));
  714. }
  715. this.isVirtualRepeatUpdating_ = false;
  716. };
  717. /**
  718. * @param {number} index Where the block is to be in the repeated list.
  719. * @return {!VirtualRepeatController.Block} A new or pooled block to place at the specified index.
  720. * @private
  721. */
  722. VirtualRepeatController.prototype.getBlock_ = function(index) {
  723. if (this.pooledBlocks.length) {
  724. return this.pooledBlocks.pop();
  725. }
  726. var block;
  727. this.transclude(angular.bind(this, function(clone, scope) {
  728. block = {
  729. element: clone,
  730. new: true,
  731. scope: scope
  732. };
  733. this.updateScope_(scope, index);
  734. this.parentNode.appendChild(clone[0]);
  735. }));
  736. return block;
  737. };
  738. /**
  739. * Updates and if not in a digest cycle, digests the specified block's scope to the data
  740. * at the specified index.
  741. * @param {!VirtualRepeatController.Block} block The block whose scope should be updated.
  742. * @param {number} index The index to set.
  743. * @private
  744. */
  745. VirtualRepeatController.prototype.updateBlock_ = function(block, index) {
  746. this.blocks[index] = block;
  747. if (!block.new &&
  748. (block.scope.$index === index && block.scope[this.repeatName] === this.items[index])) {
  749. return;
  750. }
  751. block.new = false;
  752. // Update and digest the block's scope.
  753. this.updateScope_(block.scope, index);
  754. // Perform digest before reattaching the block.
  755. // Any resulting synchronous dom mutations should be much faster as a result.
  756. // This might break some directives, but I'm going to try it for now.
  757. if (!this.$rootScope.$$phase) {
  758. block.scope.$digest();
  759. }
  760. };
  761. /**
  762. * Updates scope to the data at the specified index.
  763. * @param {!angular.Scope} scope The scope which should be updated.
  764. * @param {number} index The index to set.
  765. * @private
  766. */
  767. VirtualRepeatController.prototype.updateScope_ = function(scope, index) {
  768. scope.$index = index;
  769. scope[this.repeatName] = this.items && this.items[index];
  770. if (this.extraName) scope[this.extraName(this.$scope)] = this.items[index];
  771. };
  772. /**
  773. * Pools the block at the specified index (Pulls its element out of the dom and stores it).
  774. * @param {number} index The index at which the block to pool is stored.
  775. * @private
  776. */
  777. VirtualRepeatController.prototype.poolBlock_ = function(index) {
  778. this.pooledBlocks.push(this.blocks[index]);
  779. this.parentNode.removeChild(this.blocks[index].element[0]);
  780. delete this.blocks[index];
  781. };
  782. /**
  783. * Produces a dom fragment containing the elements from the list of blocks.
  784. * @param {!Array<!VirtualRepeatController.Block>} blocks The blocks whose elements
  785. * should be added to the document fragment.
  786. * @return {DocumentFragment}
  787. * @private
  788. */
  789. VirtualRepeatController.prototype.domFragmentFromBlocks_ = function(blocks) {
  790. var fragment = this.$document[0].createDocumentFragment();
  791. blocks.forEach(function(block) {
  792. fragment.appendChild(block.element[0]);
  793. });
  794. return fragment;
  795. };
  796. /**
  797. * Updates start and end indexes based on length of repeated items and container size.
  798. * @private
  799. */
  800. VirtualRepeatController.prototype.updateIndexes_ = function() {
  801. var itemsLength = this.items ? this.items.length : 0;
  802. var containerLength = Math.ceil(this.container.getSize() / this.itemSize);
  803. this.newStartIndex = Math.max(0, Math.min(
  804. itemsLength - containerLength,
  805. Math.floor(this.container.getScrollOffset() / this.itemSize)));
  806. this.newVisibleEnd = this.newStartIndex + containerLength + NUM_EXTRA;
  807. this.newEndIndex = Math.min(itemsLength, this.newVisibleEnd);
  808. this.newStartIndex = Math.max(0, this.newStartIndex - NUM_EXTRA);
  809. };
  810. /**
  811. * This VirtualRepeatModelArrayLike class enforces the interface requirements
  812. * for infinite scrolling within a mdVirtualRepeatContainer. An object with this
  813. * interface must implement the following interface with two (2) methods:
  814. *
  815. * getItemAtIndex: function(index) -> item at that index or null if it is not yet
  816. * loaded (It should start downloading the item in that case).
  817. *
  818. * getLength: function() -> number The data legnth to which the repeater container
  819. * should be sized. Ideally, when the count is known, this method should return it.
  820. * Otherwise, return a higher number than the currently loaded items to produce an
  821. * infinite-scroll behavior.
  822. *
  823. * @usage
  824. * <hljs lang="html">
  825. * <md-virtual-repeat-container md-orient-horizontal>
  826. * <div md-virtual-repeat="i in items" md-on-demand>
  827. * Hello {{i}}!
  828. * </div>
  829. * </md-virtual-repeat-container>
  830. * </hljs>
  831. *
  832. */
  833. function VirtualRepeatModelArrayLike(model) {
  834. if (!angular.isFunction(model.getItemAtIndex) ||
  835. !angular.isFunction(model.getLength)) {
  836. throw Error('When md-on-demand is enabled, the Object passed to md-virtual-repeat must implement ' +
  837. 'functions getItemAtIndex() and getLength() ');
  838. }
  839. this.model = model;
  840. }
  841. VirtualRepeatModelArrayLike.prototype.$$includeIndexes = function(start, end) {
  842. for (var i = start; i < end; i++) {
  843. if (!this.hasOwnProperty(i)) {
  844. this[i] = this.model.getItemAtIndex(i);
  845. }
  846. }
  847. this.length = this.model.getLength();
  848. };
  849. /**
  850. * @ngdoc directive
  851. * @name mdForceHeight
  852. * @module material.components.virtualRepeat
  853. * @restrict A
  854. * @description
  855. *
  856. * Force an element to have a certain px height. This is used in place of a style tag in order to
  857. * conform to the Content Security Policy regarding unsafe-inline style tags.
  858. *
  859. * @usage
  860. * <hljs lang="html">
  861. * <div md-force-height="'100px'"></div>
  862. * </hljs>
  863. */
  864. function ForceHeightDirective($mdUtil) {
  865. return {
  866. restrict: 'A',
  867. link: function(scope, element, attrs) {
  868. var height = scope.$eval(attrs.mdForceHeight) || null;
  869. if (height && element) {
  870. element[0].style.height = height;
  871. }
  872. }
  873. };
  874. }
  875. ForceHeightDirective['$inject'] = ['$mdUtil'];
  876. })(window, window.angular);