Jacksuyu commited on
Commit
e22b981
·
1 Parent(s): 4e6ece3

feat: add numbered pagination to idea list

Browse files
Files changed (2) hide show
  1. app/api/ideas/route.ts +36 -20
  2. components/HomeList.tsx +95 -3
app/api/ideas/route.ts CHANGED
@@ -102,16 +102,11 @@ export async function GET(request: NextRequest) {
102
  const normalizedQuery = normalizeSearchText(query);
103
  const rawLimit = Number(request.nextUrl.searchParams.get("limit") || 20);
104
  const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 50) : 20;
105
- const cursor = request.nextUrl.searchParams.get("cursor");
106
- const cursorDate = cursor ? new Date(cursor) : null;
107
-
108
- const where = cursorDate && !Number.isNaN(cursorDate.getTime()) ? { createdAt: { lt: cursorDate } } : undefined;
109
  const isSearching = Boolean(normalizedQuery) && queryTokens.length > 0;
110
- const totalIdeasPromise = isSearching ? Promise.resolve(null) : prisma.idea.count();
111
 
112
  const ideas = await prisma.idea.findMany({
113
- take: isSearching ? Math.max(limit * 10, 250) : limit + 1,
114
- where,
115
  include: {
116
  createdByUser: {
117
  select: { name: true, developerProfile: { select: { displayName: true } } },
@@ -196,22 +191,43 @@ export async function GET(request: NextRequest) {
196
  filtered = scored.filter((entry) => entry.score >= fallbackThreshold);
197
  }
198
 
199
- const items = filtered.slice(0, limit).map((entry) => entry.idea);
200
- return NextResponse.json({ items, nextCursor: null, totalCount: filtered.length });
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  }
202
 
203
- const totalCount = (await totalIdeasPromise) ?? mapped.length;
204
-
205
- const hasMore = mapped.length > limit;
206
- const page = hasMore ? mapped.slice(0, limit) : mapped;
207
-
208
- const items =
209
  sort === "new"
210
- ? page
211
- : [...page].sort((a, b) => scoreHot(b.upvotesCount, b.createdAt) - scoreHot(a.upvotesCount, a.createdAt));
212
-
213
- const nextCursor = hasMore ? page[page.length - 1]?.createdAt.toISOString() ?? null : null;
214
- return NextResponse.json({ items, nextCursor, totalCount });
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  }
216
 
217
  export async function POST(request: NextRequest) {
 
102
  const normalizedQuery = normalizeSearchText(query);
103
  const rawLimit = Number(request.nextUrl.searchParams.get("limit") || 20);
104
  const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 50) : 20;
105
+ const rawPage = Number(request.nextUrl.searchParams.get("page") || 1);
106
+ const requestedPage = Number.isFinite(rawPage) ? Math.max(Math.floor(rawPage), 1) : 1;
 
 
107
  const isSearching = Boolean(normalizedQuery) && queryTokens.length > 0;
 
108
 
109
  const ideas = await prisma.idea.findMany({
 
 
110
  include: {
111
  createdByUser: {
112
  select: { name: true, developerProfile: { select: { displayName: true } } },
 
191
  filtered = scored.filter((entry) => entry.score >= fallbackThreshold);
192
  }
193
 
194
+ const totalCount = filtered.length;
195
+ const totalPages = totalCount === 0 ? 0 : Math.ceil(totalCount / limit);
196
+ const currentPage = totalPages === 0 ? 1 : Math.min(requestedPage, totalPages);
197
+ const offset = (currentPage - 1) * limit;
198
+ const items = filtered.slice(offset, offset + limit).map((entry) => entry.idea);
199
+
200
+ return NextResponse.json({
201
+ items,
202
+ nextCursor: null,
203
+ totalCount,
204
+ currentPage,
205
+ totalPages,
206
+ hasNextPage: currentPage < totalPages,
207
+ hasPreviousPage: currentPage > 1,
208
+ });
209
  }
210
 
211
+ const ranked =
 
 
 
 
 
212
  sort === "new"
213
+ ? mapped
214
+ : [...mapped].sort((a, b) => scoreHot(b.upvotesCount, b.createdAt) - scoreHot(a.upvotesCount, a.createdAt));
215
+
216
+ const totalCount = ranked.length;
217
+ const totalPages = totalCount === 0 ? 0 : Math.ceil(totalCount / limit);
218
+ const currentPage = totalPages === 0 ? 1 : Math.min(requestedPage, totalPages);
219
+ const offset = (currentPage - 1) * limit;
220
+ const items = ranked.slice(offset, offset + limit);
221
+
222
+ return NextResponse.json({
223
+ items,
224
+ nextCursor: null,
225
+ totalCount,
226
+ currentPage,
227
+ totalPages,
228
+ hasNextPage: currentPage < totalPages,
229
+ hasPreviousPage: currentPage > 1,
230
+ });
231
  }
232
 
233
  export async function POST(request: NextRequest) {
components/HomeList.tsx CHANGED
@@ -3,6 +3,8 @@
3
  import Link from "next/link";
4
  import { useEffect, useMemo, useState } from "react";
5
 
 
 
6
  type IdeaCard = {
7
  id: string;
8
  title: string;
@@ -16,16 +18,48 @@ type IdeaCard = {
16
  working_developers?: string[];
17
  };
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  export function HomeList() {
20
  const [sort, setSort] = useState<"hot" | "new">("hot");
21
  const [loading, setLoading] = useState(true);
22
  const [items, setItems] = useState<IdeaCard[]>([]);
23
  const [totalCount, setTotalCount] = useState<number | null>(null);
 
 
24
  const [error, setError] = useState("");
25
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
26
  const [queryInput, setQueryInput] = useState("");
27
  const [query, setQuery] = useState("");
28
 
 
 
 
 
 
29
  useEffect(() => {
30
  const timer = setTimeout(() => {
31
  setQuery(queryInput.trim());
@@ -34,12 +68,18 @@ export function HomeList() {
34
  return () => clearTimeout(timer);
35
  }, [queryInput]);
36
 
 
 
 
 
37
  useEffect(() => {
38
  let active = true;
39
  setLoading(true);
40
  setError("");
41
 
42
  const params = new URLSearchParams({ sort });
 
 
43
  if (query) {
44
  params.set("q", query);
45
  }
@@ -57,12 +97,17 @@ export function HomeList() {
57
  const nextItems = data.items || [];
58
  setItems(nextItems);
59
  setTotalCount(typeof data.totalCount === "number" ? data.totalCount : nextItems.length);
 
 
 
 
60
  }
61
  })
62
  .catch((err) => {
63
  if (active) {
64
  setItems([]);
65
  setTotalCount(0);
 
66
  setError(err instanceof Error ? err.message : "Failed to load ideas");
67
  }
68
  })
@@ -73,14 +118,17 @@ export function HomeList() {
73
  return () => {
74
  active = false;
75
  };
76
- }, [sort, query]);
77
 
78
  const empty = useMemo(() => !loading && !error && items.length === 0, [loading, error, items.length]);
79
  const visibleCount = items.length;
 
 
80
  const summaryLabel =
81
- totalCount !== null && visibleCount < totalCount
82
- ? `Showing ${visibleCount} of ${totalCount} ideas`
83
  : `${totalCount ?? visibleCount} ideas`;
 
84
 
85
  return (
86
  <div className="space-y-4">
@@ -197,6 +245,50 @@ export function HomeList() {
197
  );
198
  })}
199
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  </div>
201
  );
202
  }
 
3
  import Link from "next/link";
4
  import { useEffect, useMemo, useState } from "react";
5
 
6
+ const PAGE_SIZE = 20;
7
+
8
  type IdeaCard = {
9
  id: string;
10
  title: string;
 
18
  working_developers?: string[];
19
  };
20
 
21
+ function buildPageItems(currentPage: number, totalPages: number): Array<number | string> {
22
+ if (totalPages <= 7) {
23
+ return Array.from({ length: totalPages }, (_, index) => index + 1);
24
+ }
25
+
26
+ const items: Array<number | string> = [1];
27
+ const windowStart = Math.max(2, currentPage - 1);
28
+ const windowEnd = Math.min(totalPages - 1, currentPage + 1);
29
+
30
+ if (windowStart > 2) {
31
+ items.push("left-ellipsis");
32
+ }
33
+
34
+ for (let page = windowStart; page <= windowEnd; page += 1) {
35
+ items.push(page);
36
+ }
37
+
38
+ if (windowEnd < totalPages - 1) {
39
+ items.push("right-ellipsis");
40
+ }
41
+
42
+ items.push(totalPages);
43
+ return items;
44
+ }
45
+
46
  export function HomeList() {
47
  const [sort, setSort] = useState<"hot" | "new">("hot");
48
  const [loading, setLoading] = useState(true);
49
  const [items, setItems] = useState<IdeaCard[]>([]);
50
  const [totalCount, setTotalCount] = useState<number | null>(null);
51
+ const [page, setPage] = useState(1);
52
+ const [totalPages, setTotalPages] = useState(0);
53
  const [error, setError] = useState("");
54
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
55
  const [queryInput, setQueryInput] = useState("");
56
  const [query, setQuery] = useState("");
57
 
58
+ function changePage(nextPage: number) {
59
+ setPage(nextPage);
60
+ window.scrollTo({ top: 0, behavior: "smooth" });
61
+ }
62
+
63
  useEffect(() => {
64
  const timer = setTimeout(() => {
65
  setQuery(queryInput.trim());
 
68
  return () => clearTimeout(timer);
69
  }, [queryInput]);
70
 
71
+ useEffect(() => {
72
+ setPage(1);
73
+ }, [sort, query]);
74
+
75
  useEffect(() => {
76
  let active = true;
77
  setLoading(true);
78
  setError("");
79
 
80
  const params = new URLSearchParams({ sort });
81
+ params.set("page", String(page));
82
+ params.set("limit", String(PAGE_SIZE));
83
  if (query) {
84
  params.set("q", query);
85
  }
 
97
  const nextItems = data.items || [];
98
  setItems(nextItems);
99
  setTotalCount(typeof data.totalCount === "number" ? data.totalCount : nextItems.length);
100
+ setTotalPages(typeof data.totalPages === "number" ? data.totalPages : 0);
101
+ if (typeof data.currentPage === "number") {
102
+ setPage(data.currentPage);
103
+ }
104
  }
105
  })
106
  .catch((err) => {
107
  if (active) {
108
  setItems([]);
109
  setTotalCount(0);
110
+ setTotalPages(0);
111
  setError(err instanceof Error ? err.message : "Failed to load ideas");
112
  }
113
  })
 
118
  return () => {
119
  active = false;
120
  };
121
+ }, [page, sort, query]);
122
 
123
  const empty = useMemo(() => !loading && !error && items.length === 0, [loading, error, items.length]);
124
  const visibleCount = items.length;
125
+ const startItem = visibleCount > 0 ? (page - 1) * PAGE_SIZE + 1 : 0;
126
+ const endItem = visibleCount > 0 ? startItem + visibleCount - 1 : 0;
127
  const summaryLabel =
128
+ totalCount !== null && visibleCount > 0 && visibleCount < totalCount
129
+ ? `Showing ${startItem}-${endItem} of ${totalCount} ideas`
130
  : `${totalCount ?? visibleCount} ideas`;
131
+ const pageItems = buildPageItems(page, totalPages);
132
 
133
  return (
134
  <div className="space-y-4">
 
245
  );
246
  })}
247
  </div>
248
+
249
+ {totalPages > 1 ? (
250
+ <div className="flex flex-wrap items-center justify-between gap-3">
251
+ <p className="subtle text-sm">
252
+ Page {page} of {totalPages}
253
+ </p>
254
+ <nav className="flex flex-wrap items-center gap-2" aria-label="Ideas pagination">
255
+ <button
256
+ type="button"
257
+ className="btn rounded-full px-4"
258
+ onClick={() => changePage(page - 1)}
259
+ disabled={page <= 1 || loading}
260
+ >
261
+ Previous
262
+ </button>
263
+ {pageItems.map((item) =>
264
+ typeof item === "number" ? (
265
+ <button
266
+ key={item}
267
+ type="button"
268
+ className={`btn min-w-10 rounded-full px-4 ${item === page ? "btn-primary" : ""}`}
269
+ onClick={() => changePage(item)}
270
+ aria-current={item === page ? "page" : undefined}
271
+ disabled={loading}
272
+ >
273
+ {item}
274
+ </button>
275
+ ) : (
276
+ <span key={item} className="subtle px-1 text-sm" aria-hidden="true">
277
+ ...
278
+ </span>
279
+ )
280
+ )}
281
+ <button
282
+ type="button"
283
+ className="btn rounded-full px-4"
284
+ onClick={() => changePage(page + 1)}
285
+ disabled={page >= totalPages || loading}
286
+ >
287
+ Next
288
+ </button>
289
+ </nav>
290
+ </div>
291
+ ) : null}
292
  </div>
293
  );
294
  }