Skip to content

Commit 99cf99c

Browse files
authored
Merge pull request #121 from chrispoupart/fix/quest-pagination
refactor(pagination): 🎨 simplify page number calculation logic
2 parents ffe9b27 + bcf3cfb commit 99cf99c

File tree

1 file changed

+19
-23
lines changed

1 file changed

+19
-23
lines changed

frontend/src/components/ui/pagination.tsx

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,36 +21,32 @@ export const Pagination: React.FC<PaginationProps> = ({
2121

2222
const getVisiblePages = () => {
2323
if (totalPages <= 5) {
24-
// Show all pages if there are 5 or fewer
25-
return Array.from({ length: totalPages }, (_, i) => i + 1);
24+
return Array.from({ length: totalPages }, (_, i) => i + 1)
2625
}
27-
const delta = 2;
28-
const range = [];
29-
const rangeWithDots = [];
3026

31-
for (
32-
let i = Math.max(2, currentPage - delta);
33-
i <= Math.min(totalPages - 1, currentPage + delta);
34-
i++
35-
) {
36-
range.push(i);
37-
}
27+
const pageNumbers = new Set<number | string>()
28+
pageNumbers.add(1)
3829

39-
if (currentPage - delta > 2) {
40-
rangeWithDots.push(1, "...");
41-
} else {
42-
rangeWithDots.push(1);
30+
// Add pages around current page
31+
for (let i = -1; i <= 1; i++) {
32+
const page = currentPage + i
33+
if (page > 1 && page < totalPages) {
34+
pageNumbers.add(page)
35+
}
4336
}
4437

45-
rangeWithDots.push(...range);
38+
pageNumbers.add(totalPages)
4639

47-
if (currentPage + delta < totalPages - 1) {
48-
rangeWithDots.push("...", totalPages);
49-
} else {
50-
rangeWithDots.push(totalPages);
40+
const result: (number | string)[] = []
41+
let lastPage: number | string = 0
42+
for (const page of Array.from(pageNumbers).sort((a, b) => (a as number) - (b as number))) {
43+
if (lastPage !== 0 && (page as number) - (lastPage as number) > 1) {
44+
result.push("...")
45+
}
46+
result.push(page)
47+
lastPage = page
5148
}
52-
53-
return rangeWithDots;
49+
return result
5450
}
5551

5652
const visiblePages = getVisiblePages()

0 commit comments

Comments
 (0)