import { ComponentChildren } from "preact"; import { Dispatch, StateUpdater, useEffect, useState } from "preact/hooks"; import FNote from "../../entities/fnote"; import froca from "../../services/froca"; import { useNoteLabelInt } from "../react/hooks"; import { t } from "../../services/i18n"; import ActionButton from "../react/ActionButton"; import Button from "../react/Button"; import "./Pagination.css"; import clsx from "clsx"; interface PaginationContext { page: number; setPage: Dispatch>; pageNotes?: FNote[]; pageCount: number; pageSize: number; totalNotes: number; } export function Pager({ page, pageSize, setPage, pageCount, totalNotes }: Omit) { if (pageCount < 2) return; const children = createPageButtons(page, setPage, pageCount); return (
{setPage(page - 1)}} />
{children}
{setPage(page + 1)}} /> ({t("pagination.total_notes", { count: totalNotes })})
) } function createPageButtons(page: number, setPage: Dispatch>, pageCount: number): ComponentChildren[] { const maxButtonCount = 9; const maxLeftRightSegmentLength = 2; // The left-side segment const leftLength = Math.min(pageCount, maxLeftRightSegmentLength); const leftStart = 1; // The middle segment const middleMaxLength = maxButtonCount - maxLeftRightSegmentLength * 2; const middleLength = Math.min(pageCount - leftLength, middleMaxLength); let middleStart = page - Math.floor(middleLength / 2); middleStart = Math.max(middleStart, leftLength + 1); // The right-side segment const rightLength = Math.min(pageCount - (middleLength + leftLength), maxLeftRightSegmentLength); const rightStart = pageCount - rightLength + 1; middleStart = Math.min(middleStart, rightStart - middleLength); return [ ...createSegment(leftStart, leftLength, page, setPage, false), ...createSegment(middleStart, middleLength, page, setPage, (middleStart - leftLength > 1)), ...createSegment(rightStart, rightLength, page, setPage, (rightStart - (middleStart + middleLength - 1) > 1)), ]; } function createSegment(start: number, length: number, currentPage: number, setPage: Dispatch>, prependEllipsis: boolean): ComponentChildren[] { const children: ComponentChildren[] = []; if (prependEllipsis) { children.push(...); } for (let i = 0; i < length; i++) { const pageNum = start + i; const isCurrent = (pageNum === currentPage); children.push((