-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
103 lines (88 loc) · 2.33 KB
/
index.tsx
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import classNames from "classnames"
import React from "react"
import ArrowLeft from "bootstrap-icons/icons/chevron-left.svg"
import ArrowRight from "bootstrap-icons/icons/chevron-right.svg"
import "./style.scss"
export type OnChangePage = (page: number) => void
export const Spacer = Symbol("...")
interface PaginationProps {
currentPage: number
totalPages: number
/**
* Range of page buttons (in both directions) before/after `currentPage`
*/
spread?: number
onPageChange: OnChangePage
className?: string
}
export default function Pagination({
currentPage,
totalPages,
spread = 2,
onPageChange,
className,
}: PaginationProps): JSX.Element {
const pages = getPages(currentPage, totalPages, spread)
return (
<div className={classNames("Pagination", className)} role="navigation">
<button
onClick={() => onPageChange(currentPage - 1)}
disabled={currentPage === 1}
>
<ArrowLeft />
</button>
{pages.map((page, index) =>
page === Spacer ? (
<button key={index}>...</button>
) : page === currentPage ? (
<button key={index} aria-selected="true">
{page}
</button>
) : (
<button key={index} onClick={() => onPageChange(page)}>
{page}
</button>
)
)}
<button
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage === totalPages}
>
<ArrowRight />
</button>
</div>
)
}
export function getPages(
currentPage: number,
totalPages: number,
spread: number
): Array<number | typeof Spacer> {
if (totalPages === 0) {
return []
}
const range = spread * 2 + 1
if (totalPages <= range + 4) {
// full range:
return fill(1, totalPages)
}
const left = currentPage - spread
const right = currentPage + spread
if (left <= spread + 1) {
// left range:
return [...fill(1, Math.max(range, right)), Spacer, totalPages]
}
if (right >= totalPages - spread) {
// right range:
return [
1,
Spacer,
...fill(Math.min(Math.max(left, 1), totalPages - range), totalPages),
]
}
// middle range:
return [1, Spacer, ...fill(left, right), Spacer, totalPages]
}
function fill(start: number, end: number) {
return new Array(end - start + 1).fill(0).map((_, i) => i + start)
}