import { useEffect, useState } from 'react'; import { ChevronLeft, ChevronRight } from 'lucide-react'; import { cn } from '@/lib/utils'; interface Props { page: number; totalPages: number; postTotal: number; loading?: boolean; onPageChange: (page: number) => void; } /** 生成页码窗口:两端 + 当前邻页,中间用省略号 */ function buildPageItems(current: number, total: number): Array { if (total <= 7) { return Array.from({ length: total }, (_, i) => i + 1); } const set = new Set(); set.add(1); set.add(total); for (let i = current - 1; i <= current + 1; i++) { if (i >= 1 && i <= total) set.add(i); } // 靠近端点时多露出几页,避免 1 … 2 3 这种浪费 if (current <= 3) { set.add(2); set.add(3); set.add(4); } if (current >= total - 2) { set.add(total - 1); set.add(total - 2); set.add(total - 3); } const sorted = [...set].sort((a, b) => a - b); const items: Array = []; for (let i = 0; i < sorted.length; i++) { if (i > 0 && sorted[i] - sorted[i - 1] > 1) items.push('gap'); items.push(sorted[i]); } return items; } export default function FeedPagination({ page, totalPages, postTotal, loading = false, onPageChange, }: Props) { const [jumpInput, setJumpInput] = useState(String(page)); const pageItems = buildPageItems(page, totalPages); const showJump = totalPages > 5; useEffect(() => { setJumpInput(String(page)); }, [page]); const commitJump = () => { if (loading) return; const n = Number.parseInt(jumpInput, 10); if (!Number.isFinite(n)) { setJumpInput(String(page)); return; } const target = Math.min(totalPages, Math.max(1, n)); setJumpInput(String(target)); if (target !== page) onPageChange(target); }; return ( ); }