Skip to content

Commit

Permalink
feat(virtualRepeat): Infinite scroll and deferred data loading
Browse files Browse the repository at this point in the history
includes demos for both infinite scroll and deferred loading.

Closes angular#4002.
  • Loading branch information
kseamon authored and kennethcachia committed Sep 23, 2015
1 parent 795f025 commit 5e653ec
Show file tree
Hide file tree
Showing 7 changed files with 296 additions and 3 deletions.
22 changes: 22 additions & 0 deletions src/components/virtualRepeat/demoDeferredLoading/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<div ng-controller="AppCtrl as ctrl">
<md-content layout="column">
<p>
Display a list of 50,000 items that load on demand in a viewport of only 7 rows (height=40px).
<br/><br/>
This demo shows scroll and rendering performance gains when using <code>md-virtual-repeat</code>;
achieved with the dynamic reuse of rows visible in the viewport area. Developers are required to
explicitly use <code>md-virtual-repeat-container</code> as a wrapping parent container.
<br/><br/>
To enable load-on-demand behavior, developers must pass in a custom instance of
mdVirtualRepeatModel (see the example's source for more info).
</p>

<md-virtual-repeat-container id="vertical-container">
<div md-virtual-repeat="item in ctrl.dynamicItems" md-on-demand
class="repeated-item" flex>
{{item}}
</div>
</md-virtual-repeat-container>
</md-content>

</div>
70 changes: 70 additions & 0 deletions src/components/virtualRepeat/demoDeferredLoading/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
(function () {
'use strict';

angular
.module('virtualRepeatDeferredLoadingDemo', ['ngMaterial'])
.controller('AppCtrl', function($timeout) {

// In this example, we set up our model using a class.
// Using a plain object works too. All that matters
// is that we implement getItemAtIndex and getLength.
var DynamicItems = function() {
/**
* @type {!Object<?Array>} Data pages, keyed by page number (0-index).
*/
this.loadedPages = {};

/** @type {number} Total number of items. */
this.numItems = 0;

/** @const {number} Number of items to fetch per request. */
this.PAGE_SIZE = 50;

this.fetchNumItems_();
};

// Required.
DynamicItems.prototype.getItemAtIndex = function(index) {
var pageNumber = Math.floor(index / this.PAGE_SIZE);
var page = this.loadedPages[pageNumber];

if (page) {
return page[index % this.PAGE_SIZE];
} else if (page !== null) {
this.fetchPage_(pageNumber);
}
};

// Required.
DynamicItems.prototype.getLength = function() {
return this.numItems;
};

DynamicItems.prototype.fetchPage_ = function(pageNumber) {
// Set the page to null so we know it is already being fetched.
this.loadedPages[pageNumber] = null;

// For demo purposes, we simulate loading more items with a timed
// promise. In real code, this function would likely contain an
// $http request.
$timeout(angular.noop, 300).then(angular.bind(this, function() {
this.loadedPages[pageNumber] = [];
var pageOffset = pageNumber * this.PAGE_SIZE;
for (var i = pageOffset; i < pageOffset + this.PAGE_SIZE; i++) {
this.loadedPages[pageNumber].push(i);
}
}));
};

DynamicItems.prototype.fetchNumItems_ = function() {
// For demo purposes, we simulate loading the item count with a timed
// promise. In real code, this function would likely contain an
// $http request.
$timeout(angular.noop, 300).then(angular.bind(this, function() {
this.numItems = 50000;
}));
};

this.dynamicItems = new DynamicItems();
});
})();
23 changes: 23 additions & 0 deletions src/components/virtualRepeat/demoDeferredLoading/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#vertical-container {
height: 292px;
width: 400px;
}

.repeated-item {
border-bottom: 1px solid #ddd;
box-sizing: border-box;
height: 40px;
padding-top: 10px;
}

md-content {
margin: 16px;
}

md-virtual-repeat-container {
border: solid 1px grey;
}

.md-virtual-repeat-container .md-virtual-repeat-offsetter {
padding-left: 16px;
}
22 changes: 22 additions & 0 deletions src/components/virtualRepeat/demoInfiniteScroll/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<div ng-controller="AppCtrl as ctrl">
<md-content layout="column">
<p>
Display an infinitely growing list of items in a viewport of only 7 rows (height=40px).
<br/><br/>
This demo shows scroll and rendering performance gains when using <code>md-virtual-repeat</code>;
achieved with the dynamic reuse of rows visible in the viewport area. Developers are required to
explicitly use <code>md-virtual-repeat-container</code> as a wrapping parent container.
<br/><br/>
To enable infinite scroll behavior, developers must pass in a custom instance of
mdVirtualRepeatModel (see the example's source for more info).
</p>

<md-virtual-repeat-container id="vertical-container">
<div md-virtual-repeat="item in ctrl.infiniteItems" md-on-demand
class="repeated-item" flex>
{{item}}
</div>
</md-virtual-repeat-container>
</md-content>

</div>
47 changes: 47 additions & 0 deletions src/components/virtualRepeat/demoInfiniteScroll/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
(function () {
'use strict';

angular
.module('virtualRepeatInfiniteScrollDemo', ['ngMaterial'])
.controller('AppCtrl', function($timeout) {

// In this example, we set up our model using a plain object.
// Using a class works too. All that matters is that we implement
// getItemAtIndex and getLength.
this.infiniteItems = {
numLoaded_: 0,
toLoad_: 0,

// Required.
getItemAtIndex: function(index) {
if (index > this.numLoaded_) {
this.fetchMoreItems_(index);
return null;
}

return index;
},

// Required.
// For infinite scroll behavior, we always return a slightly higher
// number than the previously loaded items.
getLength: function() {
return this.numLoaded_ + 5;
},

fetchMoreItems_: function(index) {
// For demo purposes, we simulate loading more items with a timed
// promise. In real code, this function would likely contain an
// $http request.

if (this.toLoad_ < index) {
this.toLoad_ += 20;
$timeout(angular.noop, 300).then(angular.bind(this, function() {
this.numLoaded_ = this.toLoad_;
}));
}
}
};
});

})();
23 changes: 23 additions & 0 deletions src/components/virtualRepeat/demoInfiniteScroll/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#vertical-container {
height: 292px;
width: 400px;
}

.repeated-item {
border-bottom: 1px solid #ddd;
box-sizing: border-box;
height: 40px;
padding-top: 10px;
}

md-content {
margin: 16px;
}

md-virtual-repeat-container {
border: solid 1px grey;
}

.md-virtual-repeat-container .md-virtual-repeat-offsetter {
padding-left: 16px;
}
92 changes: 89 additions & 3 deletions src/components/virtualRepeat/virtualRepeater.js
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,15 @@ VirtualRepeatContainerController.prototype.handleScroll_ = function() {
* @param {string=} md-extra-name Evaluates to an additional name to which
* the current iterated item can be assigned on the repeated scope. (Needed
* for use in md-autocomplete).
* @param {boolean=} md-on-demand When present, treats the md-virtual-repeat argument
* as an object that can fetch rows rather than an array.
* NOTE: This object must implement the following interface with two (2) methods:
* getItemAtIndex: function(index) -> item at that index or null if it is not yet
* loaded (It should start downloading the item in that case).
* getLength: function() -> number The data legnth to which the repeater container
* should be sized. Ideally, when the count is known, this method should return it.
* Otherwise, return a higher number than the currently loaded items to produce an
* infinite-scroll behavior.
*/
function VirtualRepeatDirective($parse) {
return {
Expand Down Expand Up @@ -344,12 +353,16 @@ function VirtualRepeatController($scope, $element, $attrs, $browser, $document,
this.$document = $document;
this.$$rAF = $$rAF;

/** @type {boolean} Whether we are in on-demand mode. */
this.onDemand = $attrs.hasOwnProperty('mdOnDemand');
/** @type {!Function} Backup reference to $browser.$$checkUrlChange */
this.browserCheckUrlChange = $browser.$$checkUrlChange;
/** @type {number} Most recent starting repeat index (based on scroll offset) */
this.newStartIndex = 0;
/** @type {number} Most recent ending repeat index (based on scroll offset) */
this.newEndIndex = 0;
/** @type {number} Most recent end visible index (based on scroll offset) */
this.newVisibleEnd = 0;
/** @type {number} Previous starting repeat index (based on scroll offset) */
this.startIndex = 0;
/** @type {number} Previous ending repeat index (based on scroll offset) */
Expand Down Expand Up @@ -403,10 +416,12 @@ VirtualRepeatController.prototype.link_ =
this.container = container;
this.transclude = transclude;
this.repeatName = repeatName;
this.repeatListExpression = repeatListExpression;
this.rawRepeatListExpression = repeatListExpression;
this.extraName = extraName;
this.sized = false;

this.repeatListExpression = angular.bind(this, this.repeatListExpression_);

this.container.register(this);
};

Expand Down Expand Up @@ -434,6 +449,25 @@ VirtualRepeatController.prototype.readItemSize_ = function() {
};


/**
* Returns the user-specified repeat list, transforming it into an array-like
* object in the case of infinite scroll/dynamic load mode.
* @param {!angular.Scope} The scope.
* @return {!Array|!Object} An array or array-like object for iteration.
*/
VirtualRepeatController.prototype.repeatListExpression_ = function(scope) {
var repeatList = this.rawRepeatListExpression(scope);

if (this.onDemand && repeatList) {
var virtualList = new VirtualRepeatModelArrayLike(repeatList);
virtualList.$$includeIndexes(this.newStartIndex, this.newVisibleEnd);
return virtualList;
} else {
return repeatList;
}
};


/**
* Called by the container. Informs us that the containers scroll or size has
* changed.
Expand Down Expand Up @@ -467,6 +501,9 @@ VirtualRepeatController.prototype.containerUpdated = function() {
if (this.newStartIndex !== this.startIndex ||
this.newEndIndex !== this.endIndex ||
this.container.getScrollOffset() > this.container.getScrollSize()) {
if (this.items instanceof VirtualRepeatModelArrayLike) {
this.items.$$includeIndexes(this.newStartIndex, this.newEndIndex);
}
this.virtualRepeatUpdate_(this.items, this.items);
}
};
Expand Down Expand Up @@ -503,7 +540,7 @@ VirtualRepeatController.prototype.virtualRepeatUpdate_ = function(items, oldItem
}

this.items = items;
if (items !== oldItems) {
if (items !== oldItems || lengthChanged) {
this.updateIndexes_();
}

Expand Down Expand Up @@ -684,6 +721,55 @@ VirtualRepeatController.prototype.updateIndexes_ = function() {
this.newStartIndex = Math.max(0, Math.min(
itemsLength - containerLength,
Math.floor(this.container.getScrollOffset() / this.itemSize)));
this.newEndIndex = Math.min(itemsLength, this.newStartIndex + containerLength + NUM_EXTRA);
this.newVisibleEnd = this.newStartIndex + containerLength + NUM_EXTRA;
this.newEndIndex = Math.min(itemsLength, this.newVisibleEnd);
this.newStartIndex = Math.max(0, this.newStartIndex - NUM_EXTRA);
};

/**
* This VirtualRepeatModelArrayLike class enforces the interface requirements
* for infinite scrolling within a mdVirtualRepeatContainer. An object with this
* interface must implement the following interface with two (2) methods:
*
* getItemAtIndex: function(index) -> item at that index or null if it is not yet
* loaded (It should start downloading the item in that case).
*
* getLength: function() -> number The data legnth to which the repeater container
* should be sized. Ideally, when the count is known, this method should return it.
* Otherwise, return a higher number than the currently loaded items to produce an
* infinite-scroll behavior.
*
* @usage
* <hljs lang="html">
* <md-virtual-repeat-container md-orient-horizontal>
* <div md-virtual-repeat="i in items" md-on-demand>
* Hello {{i}}!
* </div>
* </md-virtual-repeat-container>
* </hljs>
*
*/
function VirtualRepeatModelArrayLike(model) {
if (!angular.isFunction(model.getItemAtIndex) ||
!angular.isFunction(model.getLength)) {
throw Error('When md-on-demand is enabled, the Object passed to md-virtual-repeat must implement ' +
'functions getItemAtIndex() and getLength() ');
}

this.model = model;
}


VirtualRepeatModelArrayLike.prototype.$$includeIndexes = function(start, end) {
for (var i = start; i < end; i++) {
if (!this.hasOwnProperty(i)) {
this[i] = this.model.getItemAtIndex(i);
}
}
this.length = this.model.getLength();
};


function abstractMethod() {
throw Error('Non-overridden abstract method called.');
}

0 comments on commit 5e653ec

Please sign in to comment.