-
Notifications
You must be signed in to change notification settings - Fork 0
/
paging-source.html
106 lines (93 loc) · 3.57 KB
/
paging-source.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
'use strict';
/* jshint esversion:6 */
<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="paging-source">
<script>
Polymer({
is: 'paging-source',
properties: {
url: {
type: String,
observer: '_reset'
},
pageSize: {
type: Number,
observer: '_reset'
},
firstVisibleIndex: {
type: Number,
observer: '_scrollCheck'
},
lastVisibleIndex: {
type: Number,
observer: '_scrollCheck'
},
readAhead: {
type: Number,
observer: '_scrollCheck'
},
readBehind: {
type: Number,
observer: '_scrollCheck'
},
items: {
type: Array,
notify: true
}
},
ready: function() {
this.version = 0;
this._reset();
},
_reset: function() {
this.set('items', []);
this.pageStatus = {};
this.lastPage = -1;
this.version += 1;
this._getPage(this.url, 0, this.pageSize);
},
_pageFromIndex: function(index) {
return Math.floor(index / this.pageSize);
},
_scrollCheck: function() {
let firstLoadedPage = this._pageFromIndex(Math.max(0, this.firstVisibleIndex - this.readBehind));
let lastLoadedPage = this._pageFromIndex(this.lastVisibleIndex + this.readAhead);
if (this.lastPage >= 0 && lastLoadedPage > this.lastPage) {
lastLoadedPage = this.lastPage;
}
for (let page = firstLoadedPage; page <= lastLoadedPage; page++) {
if (!this.pageStatus[page] || this.pageStatus[page] === 'error') {
this._getPage(this.url, page, this.pageSize);
}
}
},
_getPage: function(url, page, pageSize) {
if (!this.url || this.url.length < 1 || this.url === 'undefined' || this.pageStatus[page] === 'done') return;
let skip = page * pageSize;
let limit = pageSize;
let version = this.version;
this.pageStatus[page] = 'loading';
let self = this;
fetch(url + '?skip=' + skip + '&limit=' + limit)
.then(function(response) {
return response.json();
})
.then(function(results) {
if (version === self.version) {
self.pageStatus[page] = 'done';
if (results.length < pageSize && self.lastPage === -1) {
self.lastPage = page;
}
if (results.length > 0) {
self.splice.apply(self, Array.prototype.concat(['items', skip, results.length], results));
}
}
})
.catch(function(error) {
console.error('error downloading items', error.message);
self.pageStatus[page] = 'error';
});
}
});
</script>
</dom-module>