|
| 1 | +import { useState } from 'react' |
| 2 | + |
| 3 | +import type { PaginationState } from '@/types/hooks' |
| 4 | + |
| 5 | +interface UsePaginationProps { |
| 6 | + totalItems: number // 전체 아이템 수 |
| 7 | + itemsPerPage: number // 페이지당 아이템 수 |
| 8 | + buttonsPerPage?: number // 한 번에 보여줄 페이지네이션 버튼 수 (기본값: 10) |
| 9 | +} |
| 10 | + |
| 11 | +export function usePagination({ |
| 12 | + totalItems, |
| 13 | + itemsPerPage, |
| 14 | + buttonsPerPage = 10, |
| 15 | +}: UsePaginationProps): PaginationState { |
| 16 | + if (totalItems <= 0 || itemsPerPage <= 0 || buttonsPerPage <= 0) { |
| 17 | + throw new Error('0보다 같거나 작은 페이지를 인자로 전달할 수 없습니다.') |
| 18 | + } |
| 19 | + |
| 20 | + const totalPages = Math.ceil(totalItems / itemsPerPage) // 총 페이지 수 |
| 21 | + const totalGroups = Math.ceil(totalPages / buttonsPerPage) // 총 그룹 수 |
| 22 | + const [currentPage, setCurrentPage] = useState(1) // 현재 페이지 |
| 23 | + const [currentGroupIndex, setCurrentGroupIndex] = useState(0) // 현재 페이지 그룹 인덱스 |
| 24 | + |
| 25 | + const firstPageInGroup = currentGroupIndex * buttonsPerPage + 1 |
| 26 | + const lastPageInGroup = Math.min( |
| 27 | + firstPageInGroup + buttonsPerPage - 1, |
| 28 | + totalPages |
| 29 | + ) |
| 30 | + |
| 31 | + // 현재 그룹에 표시될 페이지 번호 계산 |
| 32 | + const pageButtons = Array.from( |
| 33 | + { length: lastPageInGroup - firstPageInGroup + 1 }, |
| 34 | + (_, idx) => firstPageInGroup + idx |
| 35 | + ) |
| 36 | + |
| 37 | + const hasNextPageGroup = currentGroupIndex < totalGroups - 1 |
| 38 | + const hasPreviousPageGroup = currentGroupIndex > 0 |
| 39 | + |
| 40 | + const goToPage = (page: number) => { |
| 41 | + if (page < 1 || page > totalPages) { |
| 42 | + console.warn('Invalid page number') |
| 43 | + return |
| 44 | + } |
| 45 | + setCurrentPage(page) |
| 46 | + } |
| 47 | + |
| 48 | + const goToNextPageGroup = () => { |
| 49 | + if (hasNextPageGroup) { |
| 50 | + setCurrentGroupIndex(prev => prev + 1) |
| 51 | + setCurrentPage((currentGroupIndex + 1) * buttonsPerPage + 1) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + const goToPreviousPageGroup = () => { |
| 56 | + if (hasPreviousPageGroup) { |
| 57 | + setCurrentGroupIndex(prev => prev - 1) |
| 58 | + setCurrentPage((currentGroupIndex - 1) * buttonsPerPage + buttonsPerPage) |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return { |
| 63 | + currentPage, |
| 64 | + pageButtons, |
| 65 | + hasNextPageGroup, |
| 66 | + hasPreviousPageGroup, |
| 67 | + goToPage, |
| 68 | + goToNextPageGroup, |
| 69 | + goToPreviousPageGroup, |
| 70 | + } |
| 71 | +} |
0 commit comments