You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nodebb/src/pagination.js

84 lines
2.3 KiB
JavaScript

10 years ago
'use strict';
var qs = require('querystring');
var _ = require('lodash');
10 years ago
7 years ago
var pagination = module.exports;
10 years ago
pagination.create = function (currentPage, pageCount, queryObj) {
10 years ago
if (pageCount <= 1) {
return {
prev: { page: 1, active: currentPage > 1 },
next: { page: 1, active: currentPage < pageCount },
6 years ago
first: { page: 1, active: currentPage === 1 },
last: { page: 1, active: currentPage === pageCount },
10 years ago
rel: [],
9 years ago
pages: [],
currentPage: 1,
pageCount: 1,
10 years ago
};
}
10 years ago
pageCount = parseInt(pageCount, 10);
10 years ago
var pagesToShow = [1, 2, pageCount - 1, pageCount];
10 years ago
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) {
10 years ago
pagesToShow.push(startPage + i);
10 years ago
}
pagesToShow = _.uniq(pagesToShow).filter(page => page > 0 && page <= pageCount).sort(function (a, b) {
10 years ago
return a - b;
});
queryObj = { ...(queryObj || {}) };
8 years ago
delete queryObj._;
var pages = pagesToShow.map(function (page) {
queryObj.page = page;
return { page: page, active: page === currentPage, qs: qs.stringify(queryObj) };
10 years ago
});
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 });
10 years ago
}
}
var data = { rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount };
10 years ago
queryObj.page = previous;
data.prev = { page: previous, active: currentPage > 1, qs: qs.stringify(queryObj) };
10 years ago
queryObj.page = next;
data.next = { page: next, active: currentPage < pageCount, qs: qs.stringify(queryObj) };
10 years ago
6 years ago
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) };
10 years ago
if (currentPage < pageCount) {
data.rel.push({
10 years ago
rel: 'next',
href: '?' + qs.stringify({ ...queryObj, page: next }),
10 years ago
});
}
if (currentPage > 1) {
data.rel.push({
10 years ago
rel: 'prev',
href: '?' + qs.stringify({ ...queryObj, page: previous }),
10 years ago
});
}
return data;
10 years ago
};