Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/web/components/FeedSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { listMedia, type ListSort } from "@/lib/queries";
import { toClientCard } from "@/lib/serialize";
import { getCurrentUser, canParticipate } from "@/lib/session";
import { PAGE_SIZE } from "@/lib/queries";
import { pageCount } from "@/lib/pagination";
import { notFound } from "next/navigation";

const TABS: { label: string; href: string; sort?: ListSort }[] = [
{ label: "Newest", href: "/" },
Expand All @@ -21,6 +23,8 @@ export async function FeedSection({ page }: { page: number }) {
page,
userId: user?.id ?? null,
});
const totalPages = pageCount(total, PAGE_SIZE);
if (page > totalPages) notFound();

return (
<>
Expand Down
3 changes: 2 additions & 1 deletion apps/web/components/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Link from "next/link";
import { pageCount } from "@/lib/pagination";

export function Pagination({
page,
Expand All @@ -13,7 +14,7 @@ export function Pagination({
basePath: string; // e.g. "/page" or "/search"
query?: string; // extra query string without leading ?
}) {
const pages = Math.max(1, Math.ceil(total / pageSize));
const pages = pageCount(total, pageSize);
if (pages <= 1) return null;
const mk = (p: number) => {
if (basePath === "/page") return p <= 1 ? `/` : `/page/${p}`;
Expand Down
13 changes: 12 additions & 1 deletion apps/web/lib/pagination.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { normalizePage } from "./pagination";
import { normalizePage, pageCount } from "./pagination";

describe("normalizePage", () => {
it("accepts positive numeric page values", () => {
Expand All @@ -24,3 +24,14 @@ describe("normalizePage", () => {
expect(normalizePage("-2")).toBe(1);
});
});

describe("pageCount", () => {
it("keeps an empty feed on its first page", () => {
expect(pageCount(0, 24)).toBe(1);
});

it("rounds partial pages up", () => {
expect(pageCount(24, 24)).toBe(1);
expect(pageCount(25, 24)).toBe(2);
});
});
4 changes: 4 additions & 0 deletions apps/web/lib/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ export function normalizePage(value: unknown, fallback = 1): number {
return parsed >= 1 ? parsed : fallback;
}

export function pageCount(total: number, pageSize: number): number {
return Math.max(1, Math.ceil(total / pageSize));
}

export function parsePageInteger(value: unknown): number | null {
if (typeof value === "number") {
return Number.isSafeInteger(value) ? value : null;
Expand Down
Loading