forked from NodeBB/NodeBB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagination.js
83 lines (69 loc) · 2.28 KB
/
pagination.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
'use strict';
var qs = require('querystring');
var _ = require('lodash');
var pagination = module.exports;
pagination.create = function (currentPage, pageCount, queryObj) {
if (pageCount <= 1) {
return {
prev: { page: 1, active: currentPage > 1 },
next: { page: 1, active: currentPage < pageCount },
first: { page: 1, active: currentPage === 1 },
last: { page: 1, active: currentPage === pageCount },
rel: [],
pages: [],
currentPage: 1,
pageCount: 1,
};
}
pageCount = parseInt(pageCount, 10);
var pagesToShow = [1, 2, pageCount - 1, pageCount];
currentPage = parseInt(currentPage, 10) || 1;
var previous = Math.max(1, currentPage - 1);
var next = Math.min(pageCount, currentPage + 1);
var startPage = Math.max(1, currentPage - 2);
if (startPage > pageCount - 5) {
startPage -= 2 - (pageCount - currentPage);
}
var i;
for (i = 0; i < 5; i += 1) {
pagesToShow.push(startPage + i);
}
pagesToShow = _.uniq(pagesToShow).filter(page => page > 0 && page <= pageCount).sort(function (a, b) {
return a - b;
});
queryObj = _.clone(queryObj || {});
delete queryObj._;
var pages = pagesToShow.map(function (page) {
queryObj.page = page;
return { page: page, active: page === currentPage, qs: qs.stringify(queryObj) };
});
for (i = pages.length - 1; i > 0; i -= 1) {
if (pages[i].page - 2 === pages[i - 1].page) {
pages.splice(i, 0, { page: pages[i].page - 1, active: false, qs: qs.stringify(queryObj) });
} else if (pages[i].page - 1 !== pages[i - 1].page) {
pages.splice(i, 0, { separator: true });
}
}
var data = { rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount };
queryObj.page = previous;
data.prev = { page: previous, active: currentPage > 1, qs: qs.stringify(queryObj) };
queryObj.page = next;
data.next = { page: next, active: currentPage < pageCount, qs: qs.stringify(queryObj) };
queryObj.page = 1;
data.first = { page: 1, active: currentPage === 1, qs: qs.stringify(queryObj) };
queryObj.page = pageCount;
data.last = { page: pageCount, active: currentPage === pageCount, qs: qs.stringify(queryObj) };
if (currentPage < pageCount) {
data.rel.push({
rel: 'next',
href: '?page=' + next,
});
}
if (currentPage > 1) {
data.rel.push({
rel: 'prev',
href: '?page=' + previous,
});
}
return data;
};