import { h, Fragment, type FunctionComponent } from 'preact' import type { ForwardedRef } from 'preact/compat' import cn from 'classnames' import s from './pagination.module.scss' function getPages({ pathname, search, totalCount, limit, offset, }: { pathname: string search: string totalCount: number limit: number offset: number }) { const pages = [] const searchParams = new URLSearchParams(search) const last = Math.floor(totalCount / limit) const current = offset / limit for (let i = 0; i <= last; i++) { if (i === 0) searchParams.delete('offset') else searchParams.set('offset', (limit * i) as unknown as string) const query = searchParams.toString() // TODO should all pages have a rel attribute? pages.push({ path: pathname + (query ? '?' + query : ''), index: i, current: i === current, }) } return { current, firstItemCount: totalCount ? offset + 1 : 0, last, lastItemCount: Math.min(offset + limit, totalCount), next: pages[current + 1], pages, prev: pages[current - 1], totalCount, } } type PaginationProps = { className?: string forwardRef: ForwardedRef pathname: string search: string totalCount: number limit: number offset: number } const Pagination: FunctionComponent = (props) => { const { current, last, firstItemCount, lastItemCount, totalCount, pages, prev, next } = getPages(props) const start = current + 3 > last ? Math.max(last - 6, 0) : Math.max(current - 3, 0) const end = start + 7 return (
Showing {firstItemCount} to{' '} {lastItemCount || 0} of{' '} {totalCount || 0} entries
) } export default Pagination