-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpaginator.js
88 lines (69 loc) · 1.94 KB
/
paginator.js
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
const AbstractPaginator = require('./abstractPaginator');
const Collection = require('@ostro/support/collection');
const { rtrim } = require('@ostro/support/function')
class Paginator extends AbstractPaginator {
$hasMore;
constructor($items, $perPage, $currentPage = null, $options = {}, $request = {}) {
super();
this.$options = $options;
this.$request = $request;
for (let $key in $options) {
this[$key] = $options[$key];
}
this.$perPage = $perPage;
this.$currentPage = this.setCurrentPage($currentPage);
this.$path = this.$path !== '/' ? rtrim(this.$path, '/') : this.$path;
this.setItems($items);
}
setCurrentPage($currentPage) {
$currentPage = $currentPage ? null : this.resolveCurrentPage();
return this.isValidPageNumber($currentPage) ? parseInt($currentPage) : 1;
}
setItems($items) {
this.$items = $items instanceof Collection ? $items : Collection.make($items);
this.$hasMore = this.$items.count() > this.$perPage;
this.$items = this.$items.slice(0, this.$perPage);
}
nextPageUrl() {
if (this.hasMorePages()) {
return this.url(this.currentPage() + 1);
}
}
nextPage() {
if (this.hasMorePages()) {
return this.currentPage() + 1;
}
}
links($view = null, $data = []) {
return this.render($view, $data);
}
render($view = null, $data = {}) {
return this.viewFactory().make($view ? null : this.$defaultSimpleView, Object.assign($data, {
'paginator': this,
}));
}
hasMorePagesWhen($hasMore = true) {
this.$hasMore = $hasMore;
return this;
}
hasMorePages() {
return this.$hasMore;
}
toJson() {
return {
'current_page': this.currentPage(),
'data': this.$items.toArray(),
'first_page_url': this.url(1),
'from': this.firstItem(),
'next_page_url': this.nextPageUrl(),
'path': this.path(),
'per_page': this.perPage(),
'prev_page_url': this.previousPageUrl(),
'to': this.lastItem(),
};
}
jsonSerialize() {
return this.toJson();
}
}
module.exports = Paginator