virtualRepeat.js 28 KB

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