Skip to content

Commit 05af874

Browse files
committed
added neighbors parameters to getPaginationItems to show more surrounding pages
1 parent 68c5555 commit 05af874

1 file changed

Lines changed: 22 additions & 10 deletions

File tree

src/components/PaginationRow.tsx

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,26 +37,38 @@ type PaginationRowProps = {
3737

3838
type PaginationItemsType = (number | 'start-ellipsis' | 'end-ellipsis')[]
3939

40-
const getPaginationItems = (current: number, total: number) => {
41-
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1)
40+
const getPaginationItems = (current: number, total: number, neighbors = 1): PaginationItemsType => {
41+
// total visible items including neighbors, first/last, current and 2 ellipses
42+
const visible = 2 * neighbors + 5
43+
44+
if (total <= visible) return Array.from({ length: total }, (_, i) => i + 1)
4245

4346
const items: PaginationItemsType = []
4447

45-
if (current <= 4) {
46-
// beginning: 1..5, ellipsis, last
47-
items.push(1, 2, 3, 4, 5, 'end-ellipsis', total)
48+
// compute start/end blocks so that the total returned length is V
49+
const startBlockRight = visible - 2 // pages shown from 1..startBlockRight when near start
50+
const endBlockLeft = total - (visible - 3) // pages shown from endBlockLeft..total when near end
51+
52+
// start block when current is near start
53+
if (current <= startBlockRight - neighbors) {
54+
for (let p = 1; p <= startBlockRight; p++) items.push(p)
55+
items.push('end-ellipsis', total)
4856
return items
4957
}
5058

51-
if (current >= total - 3) {
52-
// ending: first, ellipsis, last-4..last
59+
// end block when current is near the end
60+
if (current >= endBlockLeft + neighbors) {
5361
items.push(1, 'start-ellipsis')
54-
for (let p = total - 4; p <= total; p++) items.push(p)
62+
for (let p = endBlockLeft; p <= total; p++) items.push(p)
5563
return items
5664
}
5765

58-
// middle: first, ellipsis, current-1, current, current+1, ellipsis, last
59-
items.push(1, 'start-ellipsis', current - 1, current, current + 1, 'end-ellipsis', total)
66+
// middle: center current with 'neighbors' on each side, total length will be 'visible'
67+
items.push(1, 'start-ellipsis')
68+
const left = Math.max(2, current - neighbors)
69+
const right = Math.min(total - 1, current + neighbors)
70+
for (let p = left; p <= right; p++) items.push(p)
71+
items.push('end-ellipsis', total)
6072
return items
6173
}
6274

0 commit comments

Comments
 (0)