Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / server / web / paginate-helper.js
blob0b62fd75a267656fce62ead446339b4c17429f07
1 'use strict';
3 function requiredBlock(context, page, pageCount, fn) {
4 if (page > 1 || pageCount > 1) {
5 return fn(context);
6 } else {
7 return '';
11 function middleBlock(page, pageCount, limit, fn) {
12 function contextForItem(pageNumber) {
13 return {
14 n: pageNumber,
15 active: pageNumber === page
19 var i;
20 var ret = '';
21 if (typeof limit === 'number') {
22 i = 0;
23 var leftCount = Math.ceil(limit / 2) - 1;
24 var rightCount = limit - leftCount - 1;
25 if (page + rightCount > pageCount) leftCount = limit - (pageCount - page) - 1;
26 if (page - leftCount < 1) leftCount = page - 1;
27 var start = page - leftCount;
29 while (i < limit && i < pageCount) {
30 ret = ret + fn(contextForItem(start));
31 start++;
32 i++;
34 } else {
35 for (i = 1; i <= pageCount; i++) {
36 ret = ret + fn(contextForItem(i));
40 return ret;
43 function previousBlock(page, pageCount, fn) {
44 if (page === 1) {
45 return fn({ disabled: true, n: 1 });
46 } else {
47 return fn({ n: page - 1 });
51 function nextBlock(page, pageCount, fn) {
52 if (page === pageCount) {
53 return fn({ disabled: true, n: pageCount });
54 } else {
55 return fn({ n: page + 1 });
59 function firstBlock(page, pageCount, fn) {
60 if (page === 1) {
61 return fn({ disabled: true, n: 1 });
62 } else {
63 return fn({ n: 1 });
67 function lastBlock(page, pageCount, fn) {
68 if (page === pageCount) {
69 return fn({ disabled: true, n: pageCount });
70 } else {
71 return fn({ n: pageCount });
75 module.exports = function(pagination, options) {
76 var type = options.hash.type || 'middle';
78 var pageCount = Number(pagination.pageCount);
79 var page = Number(pagination.page);
80 var limit;
81 if (options.hash.limit) limit = +options.hash.limit;
82 var fn = options.fn;
84 switch (type) {
85 case 'required':
86 return requiredBlock(this, page, pageCount, fn);
88 case 'middle':
89 return middleBlock(page, pageCount, limit, fn);
91 case 'previous':
92 return previousBlock(page, pageCount, fn);
94 case 'next':
95 return nextBlock(page, pageCount, fn);
97 case 'first':
98 return firstBlock(page, pageCount, fn);
100 case 'last':
101 return lastBlock(page, pageCount, fn);
104 return '';