Connect, collaborate, and grow with a community of TypeScript developers
feat: add sorting to solutions/pagination (#1079)
mecha4edc7fe02a37
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsxindex ec8806a5..6bd115a9 100644--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx@@ -1,26 +1,82 @@'use client';+import { Calendar, MessageCircle, ThumbsUp } from '@repo/ui/icons';import { useSession } from '@repo/auth/react';import Link from 'next/link';-import { useState } from 'react';+import { useRef, useState } from 'react';import { SolutionEditor } from './solution-editor';import { NoSolutions } from './nosolutions';import { SubmitSolution } from './submit-solution';-import type { ChallengeSolution } from '../getSolutionRouteData';+import { type ChallengeSolution, getPaginatedSolutions } from '../getSolutionRouteData';import { getRelativeTime } from '~/utils/relativeTime';import { Badge } from '@repo/ui/components/badge';import { UserBadge } from '@repo/ui/components/user-badge';import { useParams } from 'next/navigation';+import { Pagination } from '../../../_components/pagination';+import { useQuery } from '@tanstack/react-query';+import { SolutionsSkeleton } from './solution-skeleton';+import { SortSelect } from '../../../_components/sort-select';interface Props {challenge: ChallengeSolution;+ slug: string;}+type View = 'details' | 'editor' | 'list';-export function Solutions({ challenge }: Props) {++const sortKeys = [+ {+ label: 'Newest Solutions',+ value: 'newest',+ key: 'createdAt',+ order: 'desc',+ },+ {+ label: 'Most Votes',+ value: 'votes',+ key: 'vote',+ order: 'desc',+ },+ {+ label: 'Most Replies',+ value: 'solutionComment',+ key: 'solutionComment',+ order: 'desc',+ },+] as const;++export function Solutions({ challenge, slug }: Props) {const [view, setView] = useState<View>('list');- const loggedInUserHasSolution = challenge.submission.length;+ const commentContainerRef = useRef<HTMLDivElement>(null);+ const [sortKey, setSortKey] = useState<(typeof sortKeys)[number]>(sortKeys[0]);+ const [page, setPage] = useState(1);+ const queryKey = [`paginated-${challenge.id}-solutions`, sortKey.value, page];const session = useSession();+ const handleChangePage = (page: number) => {+ setPage(page);+ commentContainerRef.current?.scroll({+ top: 128,+ behavior: 'smooth',+ });+ };++ const handleValueChange = (value: string) => {+ setSortKey(sortKeys.find((sk) => sk.value === value) ?? sortKeys[0]);+ setPage(1);+ };++ const { status, data } = useQuery({+ queryKey,+ queryFn: () =>+ getPaginatedSolutions({ slug, page, sortKey: sortKey.key, sortOrder: sortKey.order }),+ keepPreviousData: true,+ staleTime: 60000, // one minute+ refetchOnWindowFocus: false,+ });++ const loggedInUserHasSolution = challenge.submission.length;+return (<div className="relative h-full">{view === 'editor' && (@@ -29,15 +85,42 @@ export function Solutions({ challenge }: Props) {{view === 'list' && (<>- {challenge.sharedSolution.length !== 0 ? (+ {data?.solutions.length !== 0 ? (<>- <div className="bg-background/70 dark:bg-muted/70 absolute right-0 top-0 flex w-full justify-end border-b border-zinc-300 p-2 backdrop-blur-sm dark:border-zinc-700">- <SubmitSolution disabled={Boolean(!loggedInUserHasSolution)} setView={setView} />- </div>- <div className="custom-scrollable-element h-full overflow-y-auto pt-12">- {challenge.sharedSolution.map((solution) => (- <SolutionRow key={solution.id} solution={solution} />- ))}+ {status === 'loading' && <SolutionsSkeleton />}+ {status === 'success' && (+ <div className="bg-background/70 dark:bg-muted/70 absolute right-0 top-0 flex w-full justify-end border-b border-zinc-300 p-2 backdrop-blur-sm dark:border-zinc-700">+ <SubmitSolution disabled={Boolean(!loggedInUserHasSolution)} setView={setView} />+ </div>+ )}+ <div+ className="custom-scrollable-element relative flex h-full flex-col overflow-y-auto pt-12"+ ref={commentContainerRef}+ >+ <div>+ {(data?.solutions.length ?? 0) > 0 && (+ <SortSelect+ currentSortKey={sortKey}+ totalSortKeys={sortKeys}+ onValueChange={handleValueChange}+ />+ )}+ </div>+ <div className="flex-1">+ {status === 'success' &&+ data?.solutions.map((solution) => (+ <SolutionRow key={solution.id} solution={solution} />+ ))}+ </div>+ {(data?.totalPages ?? 0) > 1 && (+ <div className="mb-2 flex justify-center">+ <Pagination+ currentPage={page}+ onClick={handleChangePage}+ totalPages={data?.totalPages ?? 0}+ />+ </div>+ )}</div></>) : (diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts b/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.tsindex 3e27c62e..0cd5ccc9 100644--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts@@ -1,6 +1,11 @@+'use server';import { cache } from 'react';import { prisma } from '@repo/db';-import type { Session } from '@repo/auth/server';+import { type Session } from '@repo/auth/server';+import type { SortKey, SortOrder } from '~/utils/sorting';+import { orderBy } from '~/utils/sorting';++const PAGESIZE = 10;export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionsRouteData>>>;export const getSolutionsRouteData = cache(async (slug: string, session: Session | null) => {@@ -45,3 +50,53 @@ export const getSolutionsRouteData = cache(async (slug: string, session: Sessionreturn data;});++export async function getPaginatedSolutions({+ slug,+ page,+ sortKey = 'createdAt',+ sortOrder = 'desc',+}: {+ slug: string;+ page: number;+ sortKey?: SortKey;+ sortOrder?: SortOrder;+}) {+ const challenge = await prisma.challenge.findFirst({+ where: { slug },+ });++ const solutions = await prisma.sharedSolution.findMany({+ where: { challengeId: challenge?.id },+ skip: (page - 1) * PAGESIZE,+ take: PAGESIZE,+ orderBy: [+ {+ isPinned: 'desc' as SortOrder,+ },+ orderBy(sortKey, sortOrder),+ ],+ include: {+ user: {+ select: {+ name: true,+ },+ },+ _count: {+ select: { vote: true, solutionComment: true },+ },+ },+ });++ const totalSolutions = await prisma.sharedSolution.count({+ where: { challengeId: challenge?.id },+ });++ const totalPages = Math.ceil(totalSolutions / PAGESIZE);++ return {+ totalPages,+ hasMore: page < totalPages,+ solutions,+ };+}diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsxindex 4bfb7d79..3929cfcd 100644--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx@@ -34,5 +34,5 @@ export default async function SolutionPage({ params: { slug } }: Props) {return notFound();}- return <Solutions challenge={solutions} />;+ return <Solutions challenge={solutions} slug={slug} />;}diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts b/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.tsindex 2dbec0d1..f4572169 100644--- a/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts+++ b/apps/web/src/app/[locale]/challenge/_components/comments/getCommentRouteData.ts@@ -2,36 +2,10 @@import { getServerAuthSession } from '@repo/auth/server';import { prisma } from '@repo/db';import type { CommentRoot } from '@repo/db/types';+import { orderBy, type SortKey, type SortOrder } from '~/utils/sorting';const PAGESIZE = 10;-const sortKeys = ['createdAt', 'vote', 'replies'] as const;-const sortOrders = ['asc', 'desc'] as const;--export type SortKey = (typeof sortKeys)[number];-export type SortOrder = (typeof sortOrders)[number];--function orderBy(sortKey: SortKey, sortOrder: SortOrder) {- switch (sortKey) {- case 'vote':- return {- vote: {- _count: sortOrder,- },- };- case 'replies':- return {- replies: {- _count: sortOrder,- },- };- case 'createdAt':- return {- [sortKey]: sortOrder,- };- }-}-export type PaginatedComments = NonNullable<Awaited<ReturnType<typeof getPaginatedComments>>>;export type PreselectedCommentMetadata =| NonNullable<Awaited<ReturnType<typeof getPreselectedCommentMetadata>>>diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/index.tsxindex 36d8e936..29c790bb 100644--- a/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx+++ b/apps/web/src/app/[locale]/challenge/_components/comments/index.tsx@@ -1,16 +1,8 @@'use client';import type { CommentRoot } from '@repo/db/types';-import { Button } from '@repo/ui/components/button';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@repo/ui/components/select';import { toast } from '@repo/ui/components/use-toast';-import { ChevronDown, ChevronLeft, ChevronRight, MessageCircle } from '@repo/ui/icons';+import { ChevronDown, MessageCircle } from '@repo/ui/icons';import { useQuery, useQueryClient } from '@tanstack/react-query';import clsx from 'clsx';import { useRef, useState } from 'react';@@ -20,6 +12,15 @@ import { CommentSkeleton } from './comment-skeleton';import { addComment } from './comment.action';import { getPaginatedComments, type PreselectedCommentMetadata } from './getCommentRouteData';import NoComments from './nocomments';+import { Pagination } from '../pagination';+import { SortSelect } from '../sort-select';++interface Props {+ preselectedCommentMetadata?: PreselectedCommentMetadata;+ expanded?: boolean;+ rootId: number;+ type: CommentRoot;+}const sortKeys = [{@@ -48,13 +49,6 @@ const sortKeys = [},] as const;-interface Props {- preselectedCommentMetadata?: PreselectedCommentMetadata;- expanded?: boolean;- rootId: number;- type: CommentRoot;-}-// million-ignoreexport function Comments({ preselectedCommentMetadata, rootId, type, expanded = false }: Props) {const [showComments, setShowComments] = useState(expanded);@@ -116,6 +110,11 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =});};+ const handleValueChange = (value: string) => {+ setSortKey(sortKeys.find((sk) => sk.value === value) ?? sortKeys[0]);+ setPage(1);+ };+return (<divclassName={clsx(@@ -163,27 +162,11 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =/></div>{(data?.comments.length ?? 0) > 0 && (- <div className="flex items-center gap-2 px-3 py-2">- <Select- value={sortKey.value}- defaultValue="newest"- onValueChange={(value) => {- setSortKey(sortKeys.find((sk) => sk.value === value) ?? sortKeys[0]);- setPage(1);- }}- >- <SelectTrigger className="w-[180px]">- <SelectValue placeholder="Sort Key" />- </SelectTrigger>- <SelectContent>- {sortKeys.map((sortKey, index) => (- <SelectItem key={index} value={sortKey.value}>- {sortKey.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>+ <SortSelect+ currentSortKey={sortKey}+ totalSortKeys={sortKeys}+ onValueChange={handleValueChange}+ />)}{status === 'loading' && <CommentSkeleton />}<div className="flex-1">@@ -217,62 +200,3 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =</div>);}--function Pagination({- currentPage,- totalPages,- onClick,-}: {- totalPages: number;- currentPage: number;- onClick: (page: number) => void;-}) {- const maxVisiblePages = 5;- const halfVisiblePages = Math.floor(maxVisiblePages / 2);-- let startPage = currentPage - halfVisiblePages;- let endPage = currentPage + halfVisiblePages;-- if (startPage <= 0) {- startPage = 1;- endPage = Math.min(totalPages, maxVisiblePages);- }-- if (endPage > totalPages) {- endPage = totalPages;- startPage = Math.max(1, totalPages - maxVisiblePages + 1);- }-- const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);-- return (- <nav className="justify-space-between flex items-center gap-2">- <Button- disabled={currentPage === 1}- onClick={() => onClick(Math.max(0, currentPage - 1))}- variant="ghost"- >- <ChevronLeft />- </Button>- {pages.map((page) => (- <Button- className={clsx('border-border dark:border-ring border', {- 'bg-border dark:bg-neutral-700': page === currentPage,- })}- key={`pagination-${page}`}- onClick={() => onClick(page)}- variant="ghost"- >- {page}- </Button>- ))}- <Button- disabled={currentPage === totalPages}- onClick={() => onClick(Math.min(totalPages, currentPage + 1))}- variant="ghost"- >- <ChevronRight />- </Button>- </nav>- );-}diff --git a/apps/web/src/app/[locale]/challenge/_components/pagination.tsx b/apps/web/src/app/[locale]/challenge/_components/pagination.tsxnew file mode 100644index 00000000..44a757cf--- /dev/null+++ b/apps/web/src/app/[locale]/challenge/_components/pagination.tsx@@ -0,0 +1,62 @@+import { Button } from '@repo/ui/components/button';+import { ChevronLeft, ChevronRight } from '@repo/ui/icons';+import clsx from 'clsx';++export function Pagination({+ currentPage,+ totalPages,+ onClick,+}: {+ totalPages: number;+ currentPage: number;+ onClick: (page: number) => void;+}) {+ const maxVisiblePages = 5;+ const halfVisiblePages = Math.floor(maxVisiblePages / 2);++ let startPage = currentPage - halfVisiblePages;+ let endPage = currentPage + halfVisiblePages;++ if (startPage <= 0) {+ startPage = 1;+ endPage = Math.min(totalPages, maxVisiblePages);+ }++ if (endPage > totalPages) {+ endPage = totalPages;+ startPage = Math.max(1, totalPages - maxVisiblePages + 1);+ }++ const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);++ return (+ <nav className="justify-space-between flex items-center gap-2">+ <Button+ disabled={currentPage === 1}+ onClick={() => onClick(Math.max(0, currentPage - 1))}+ variant="ghost"+ >+ <ChevronLeft />+ </Button>+ {pages.map((page) => (+ <Button+ className={clsx('border-border dark:border-ring border', {+ 'bg-border dark:bg-neutral-700': page === currentPage,+ })}+ key={`pagination-${page}`}+ onClick={() => onClick(page)}+ variant="ghost"+ >+ {page}+ </Button>+ ))}+ <Button+ disabled={currentPage === totalPages}+ onClick={() => onClick(Math.min(totalPages, currentPage + 1))}+ variant="ghost"+ >+ <ChevronRight />+ </Button>+ </nav>+ );+}diff --git a/apps/web/src/app/[locale]/challenge/_components/sort-select.tsx b/apps/web/src/app/[locale]/challenge/_components/sort-select.tsxnew file mode 100644index 00000000..3013f5e3--- /dev/null+++ b/apps/web/src/app/[locale]/challenge/_components/sort-select.tsx@@ -0,0 +1,39 @@+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@repo/ui/components/select';++interface SortKey {+ label: string;+ value: string;+ key: string;+ order: string;+}++interface Props {+ currentSortKey: SortKey;+ totalSortKeys: readonly SortKey[];+ onValueChange: (value: string) => void;+}++export function SortSelect({ currentSortKey, totalSortKeys, onValueChange }: Props) {+ return (+ <div className="flex items-center gap-2 px-3 py-2">+ <Select value={currentSortKey.value} defaultValue="newest" onValueChange={onValueChange}>+ <SelectTrigger className="w-[180px]">+ <SelectValue placeholder="Sort Key" />+ </SelectTrigger>+ <SelectContent>+ {totalSortKeys.map((sortKey, index) => (+ <SelectItem key={index} value={sortKey.value}>+ {sortKey.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}diff --git a/apps/web/src/utils/sorting.ts b/apps/web/src/utils/sorting.tsnew file mode 100644index 00000000..05ea3d03--- /dev/null+++ b/apps/web/src/utils/sorting.ts@@ -0,0 +1,32 @@+const sortingKeys = ['createdAt', 'vote', 'replies', 'solutionComment'] as const;+const sortingOrders = ['asc', 'desc'] as const;++export type SortKey = (typeof sortingKeys)[number];+export type SortOrder = (typeof sortingOrders)[number];++export function orderBy(sortKey: SortKey, sortOrder: SortOrder) {+ switch (sortKey) {+ case 'vote':+ return {+ vote: {+ _count: sortOrder,+ },+ };+ case 'replies':+ return {+ replies: {+ _count: sortOrder,+ },+ };+ case 'createdAt':+ return {+ [sortKey]: sortOrder,+ };+ case 'solutionComment':+ return {+ solutionComment: {+ _count: sortOrder,+ },+ };+ }+}