perf(admin): paginate responses on the server

This commit is contained in:
2026-08-09 21:58:19 +07:00 Unverified
parent 916aaf92ef
commit 78373b76cc
3 changed files with 183 additions and 175 deletions
-148
View File
@@ -1,148 +0,0 @@
"use client";
import Link from "next/link";
import { useMemo, useState } from "react";
import { Kbd } from "@/components/ui/kbd";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "@/components/ui/pagination";
import { DeleteAllSubmissionsButton, DeleteSubmissionButton } from "@/components/delete-buttons";
import { ResultsFilters } from "@/components/results-filters";
import type { DiscordMemberProfile } from "@/lib/discord/discord";
const RESULTS_PAGE_SIZE = 25;
type ResultFilters = {
q: string;
page: number;
sort: "submittedAt" | "respondent";
direction: "asc" | "desc";
edited: "all" | "edited" | "unedited";
dateFrom: string;
dateTo: string;
};
function resultFiltersToSearchParams(filters: ResultFilters) {
const params = new URLSearchParams();
if (filters.q) params.set("q", filters.q);
if (filters.page > 1) params.set("page", String(filters.page));
if (filters.sort !== "submittedAt") params.set("sort", filters.sort);
if (filters.direction !== "desc") params.set("direction", filters.direction);
if (filters.edited !== "all") params.set("edited", filters.edited);
if (filters.dateFrom) params.set("dateFrom", filters.dateFrom);
if (filters.dateTo) params.set("dateTo", filters.dateTo);
return params.toString();
}
type ResultRow = {
id: string;
userName: string | null;
userDiscordId: string | null;
submittedAt: string;
adminNote: string | null;
editHistory: unknown[];
};
function formatDate(value: string) {
return new Date(value).toLocaleString("en-GB", {
timeZone: "Asia/Bangkok",
hour12: false,
});
}
function bangkokDate(value: string) {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Bangkok",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(new Date(value));
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
return `${values.year}-${values.month}-${values.day}`;
}
function RespondentName({
row,
profile,
}: {
row: ResultRow;
profile: DiscordMemberProfile | null;
}) {
const displayName = profile?.globalName || profile?.username || row.userName || row.userDiscordId || "Anonymous";
const username = profile?.username || row.userName;
return (
<span className="inline-flex flex-wrap items-center gap-1.5">
<span>{displayName}</span>
{username && username !== displayName && <Kbd>({username})</Kbd>}
</span>
);
}
export default function ResultsClient({
formId,
initialFilters,
rows,
profiles,
}: {
formId: string;
initialFilters: ResultFilters;
rows: ResultRow[];
profiles: Record<string, DiscordMemberProfile | null>;
}) {
const [filters, setFilters] = useState(initialFilters);
const [page, setPage] = useState(initialFilters.page);
const filteredRows = useMemo(() => {
const query = filters.q.toLocaleLowerCase();
return rows
.filter((row) => {
const matchesQuery = !query || `${row.userName ?? ""} ${row.userDiscordId ?? ""}`.toLocaleLowerCase().includes(query);
const edited = row.editHistory.length > 0;
const matchesEdited = filters.edited === "all" || (filters.edited === "edited" ? edited : !edited);
const date = bangkokDate(row.submittedAt);
return matchesQuery && matchesEdited && (!filters.dateFrom || date >= filters.dateFrom) && (!filters.dateTo || date <= filters.dateTo);
})
.sort((a, b) => {
if (filters.sort === "respondent") {
const result = (a.userName || a.userDiscordId || "").localeCompare(b.userName || b.userDiscordId || "");
return filters.direction === "asc" ? result : -result;
}
const result = new Date(a.submittedAt).getTime() - new Date(b.submittedAt).getTime();
return filters.direction === "asc" ? result : -result;
});
}, [filters, rows]);
const pageCount = Math.max(1, Math.ceil(filteredRows.length / RESULTS_PAGE_SIZE));
const currentPage = Math.min(page, pageCount);
const visibleRows = filteredRows.slice((currentPage - 1) * RESULTS_PAGE_SIZE, currentPage * RESULTS_PAGE_SIZE);
const updateFilters = (next: ResultFilters) => {
const normalized = { ...next, page: 1 };
setFilters(normalized);
setPage(1);
const query = resultFiltersToSearchParams(normalized);
window.history.replaceState(null, "", `/admin/form/${formId}/result${query ? `?${query}` : ""}`);
};
return (
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-4 pb-12 md:p-6">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div>
<h2 className="text-2xl font-semibold">Responses</h2>
<p className="text-muted-foreground">{filteredRows.length} matching {filteredRows.length === 1 ? "response" : "responses"}</p>
</div>
{rows.length > 0 && <DeleteAllSubmissionsButton formId={formId} />}
</div>
<ResultsFilters formId={formId} filters={filters} onFiltersChange={updateFilters} />
{visibleRows.length === 0 ? (
<Card><CardHeader><CardTitle>No responses found</CardTitle><CardDescription>Try changing or clearing the current filters.</CardDescription></CardHeader></Card>
) : (
<>
<Card className="hidden md:block"><CardContent className="p-0"><Table><TableHeader><TableRow><TableHead>Respondent</TableHead><TableHead>Submitted</TableHead><TableHead>Note</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader><TableBody>
{visibleRows.map((row) => <TableRow key={row.id} className="relative cursor-pointer"><TableCell><Link href={`/admin/form/${formId}/result/${row.id}`} className="font-medium after:absolute after:inset-0 focus-visible:outline-none focus-visible:after:ring-2 focus-visible:after:ring-ring focus-visible:after:ring-inset"><RespondentName row={row} profile={row.userDiscordId ? profiles[row.userDiscordId] ?? null : null} /></Link>{row.userName && row.userDiscordId && <p className="text-xs text-muted-foreground">{row.userDiscordId}</p>}</TableCell><TableCell>{formatDate(row.submittedAt)}</TableCell><TableCell className="max-w-80">{row.adminNote ? <p className="line-clamp-2 whitespace-pre-wrap text-sm">{row.adminNote}</p> : <span className="text-sm italic text-muted-foreground">No note</span>}</TableCell><TableCell className="relative z-10 text-right"><DeleteSubmissionButton id={row.id} compact /></TableCell></TableRow>)}
</TableBody></Table></CardContent></Card>
<div className="flex flex-col gap-3 md:hidden">{visibleRows.map((row) => <Card key={row.id} className="relative transition-colors hover:bg-muted/50"><CardHeader><CardTitle className="text-base"><Link href={`/admin/form/${formId}/result/${row.id}`} className="after:absolute after:inset-0 focus-visible:outline-none focus-visible:after:ring-2 focus-visible:after:ring-ring focus-visible:after:ring-inset"><RespondentName row={row} profile={row.userDiscordId ? profiles[row.userDiscordId] ?? null : null} /></Link></CardTitle><CardDescription>{formatDate(row.submittedAt)}</CardDescription></CardHeader><CardContent className="flex items-start justify-between gap-4"><div className="min-w-0"><p className="text-xs font-medium text-muted-foreground">Note</p>{row.adminNote ? <p className="line-clamp-3 whitespace-pre-wrap text-sm">{row.adminNote}</p> : <p className="text-sm italic text-muted-foreground">No note</p>}</div><div className="relative z-10"><DeleteSubmissionButton id={row.id} compact /></div></CardContent></Card>)}</div>
</>
)}
{pageCount > 1 && <Pagination><PaginationContent><PaginationItem><PaginationPrevious href="#" onClick={(event) => { event.preventDefault(); setPage(Math.max(1, currentPage - 1)); }} aria-disabled={currentPage === 1} /></PaginationItem><PaginationItem><PaginationLink href="#" isActive onClick={(event) => event.preventDefault()}>{currentPage} / {pageCount}</PaginationLink></PaginationItem><PaginationItem><PaginationNext href="#" onClick={(event) => { event.preventDefault(); setPage(Math.min(pageCount, currentPage + 1)); }} aria-disabled={currentPage === pageCount} /></PaginationItem></PaginationContent></Pagination>}
</div>
);
}
+179 -25
View File
@@ -1,10 +1,54 @@
import { parseResultFilters, getFilteredSubmissions } from "@/lib/form/admin-form-results";
import { getDiscordMemberProfile } from "@/lib/discord/discord";
import Link from "next/link";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Kbd } from "@/components/ui/kbd";
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DeleteAllSubmissionsButton, DeleteSubmissionButton } from "@/components/delete-buttons";
import { RealtimeRefresh } from "@/components/realtime-refresh";
import ResultsClient from "./client";
import { ResultsFilters } from "@/components/results-filters";
import { getDiscordMemberProfile, type DiscordMemberProfile } from "@/lib/discord/discord";
import {
getFilteredSubmissions,
parseResultFilters,
resultFiltersToSearchParams,
type ResultFilters,
} from "@/lib/form/admin-form-results";
export const dynamic = "force-dynamic";
type ResultRow = Awaited<ReturnType<typeof getFilteredSubmissions>>["rows"][number];
function formatDate(value: Date) {
return value.toLocaleString("en-GB", {
timeZone: "Asia/Bangkok",
hour12: false,
});
}
function RespondentName({ row, profile }: { row: ResultRow; profile: DiscordMemberProfile | null }) {
const displayName = profile?.globalName || profile?.username || row.userName || row.userDiscordId || "Anonymous";
const username = profile?.username || row.userName;
return (
<span className="inline-flex flex-wrap items-center gap-1.5">
<span>{displayName}</span>
{username && username !== displayName && <Kbd>({username})</Kbd>}
</span>
);
}
function pageHref(formId: string, filters: ResultFilters, page: number) {
const query = resultFiltersToSearchParams(filters, { page });
return `/admin/form/${formId}/result${query ? `?${query}` : ""}`;
}
export default async function ResultsListPage({
params,
searchParams,
@@ -13,15 +57,13 @@ export default async function ResultsListPage({
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const [{ id }, rawFilters] = await Promise.all([params, searchParams]);
const initialFilters = parseResultFilters(rawFilters);
const { rows } = await getFilteredSubmissions(id, parseResultFilters({}), {
paginate: false,
});
const filters = parseResultFilters(rawFilters);
const { rows, total, page, pageCount } = await getFilteredSubmissions(id, filters);
const discordIds = [
...new Set(
rows
.map((row) => row.userDiscordId)
.filter((value): value is string => Boolean(value))
.filter((value): value is string => Boolean(value)),
),
];
const profiles = Object.fromEntries(
@@ -29,26 +71,138 @@ export default async function ResultsListPage({
discordIds.map(async (discordId) => [
discordId,
await getDiscordMemberProfile(discordId),
])
)
]),
),
);
const returnQuery = resultFiltersToSearchParams(filters, { page });
const detailHref = (submissionId: string) =>
`/admin/form/${id}/result/${submissionId}${returnQuery ? `?return=${encodeURIComponent(returnQuery)}` : ""}`;
return (
<>
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-4 pb-12 md:p-6">
<RealtimeRefresh topic="submissions" formId={id} />
<ResultsClient
formId={id}
initialFilters={initialFilters}
rows={rows.map((row) => ({
id: row.id,
userName: row.userName,
userDiscordId: row.userDiscordId,
submittedAt: row.submittedAt.toISOString(),
adminNote: row.adminNote,
editHistory: Array.isArray(row.editHistory) ? row.editHistory : [],
}))}
profiles={profiles}
/>
</>
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div>
<h2 className="text-2xl font-semibold">Responses</h2>
<p className="text-muted-foreground">
{total} matching {total === 1 ? "response" : "responses"}
</p>
</div>
{total > 0 && <DeleteAllSubmissionsButton formId={id} />}
</div>
<ResultsFilters formId={id} filters={filters} />
{rows.length === 0 ? (
<Card>
<CardHeader>
<CardTitle>No responses found</CardTitle>
<CardDescription>Try changing or clearing the current filters.</CardDescription>
</CardHeader>
</Card>
) : (
<>
<Card className="hidden md:block">
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Respondent</TableHead>
<TableHead>Submitted</TableHead>
<TableHead>Note</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row) => (
<TableRow key={row.id} className="relative cursor-pointer">
<TableCell>
<Link
href={detailHref(row.id)}
className="font-medium after:absolute after:inset-0 focus-visible:outline-none focus-visible:after:ring-2 focus-visible:after:ring-ring focus-visible:after:ring-inset"
>
<RespondentName row={row} profile={row.userDiscordId ? profiles[row.userDiscordId] ?? null : null} />
</Link>
{row.userName && row.userDiscordId && (
<p className="text-xs text-muted-foreground">{row.userDiscordId}</p>
)}
</TableCell>
<TableCell>{formatDate(row.submittedAt)}</TableCell>
<TableCell className="max-w-80">
{row.adminNote ? (
<p className="line-clamp-2 whitespace-pre-wrap text-sm">{row.adminNote}</p>
) : (
<span className="text-sm italic text-muted-foreground">No note</span>
)}
</TableCell>
<TableCell className="relative z-10 text-right">
<DeleteSubmissionButton id={row.id} compact />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
<div className="flex flex-col gap-3 md:hidden">
{rows.map((row) => (
<Card key={row.id} className="relative transition-colors hover:bg-muted/50">
<CardHeader>
<CardTitle className="text-base">
<Link
href={detailHref(row.id)}
className="after:absolute after:inset-0 focus-visible:outline-none focus-visible:after:ring-2 focus-visible:after:ring-ring focus-visible:after:ring-inset"
>
<RespondentName row={row} profile={row.userDiscordId ? profiles[row.userDiscordId] ?? null : null} />
</Link>
</CardTitle>
<CardDescription>{formatDate(row.submittedAt)}</CardDescription>
</CardHeader>
<CardContent className="flex items-start justify-between gap-4">
<div className="min-w-0">
<p className="text-xs font-medium text-muted-foreground">Note</p>
{row.adminNote ? (
<p className="line-clamp-3 whitespace-pre-wrap text-sm">{row.adminNote}</p>
) : (
<p className="text-sm italic text-muted-foreground">No note</p>
)}
</div>
<div className="relative z-10">
<DeleteSubmissionButton id={row.id} compact />
</div>
</CardContent>
</Card>
))}
</div>
</>
)}
{pageCount > 1 && (
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
href={pageHref(id, filters, Math.max(1, page - 1))}
aria-disabled={page === 1}
className={page === 1 ? "pointer-events-none opacity-50" : undefined}
/>
</PaginationItem>
<PaginationItem>
<PaginationLink href={pageHref(id, filters, page)} isActive>
{page} / {pageCount}
</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext
href={pageHref(id, filters, Math.min(pageCount, page + 1))}
aria-disabled={page === pageCount}
className={page === pageCount ? "pointer-events-none opacity-50" : undefined}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
)}
</div>
);
}