Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

feat: ability to pin solutions (#774)

bautistaaacbf4b787e411
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts
new file mode 100644
index 00000000..c2e02652
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts
@@ -0,0 +1,39 @@
+'use server';
+import { getServerAuthSession } from '@repo/auth/server';
+import { prisma } from '@repo/db';
+import { revalidateTag } from 'next/cache';
+import { isAdminOrModerator } from '~/utils/auth-guards';
+
+interface Args {
+ challengeId: number;
+ description: string;
+ title: string;
+ userId: string;
+}
+
+export async function postSolution({ challengeId, description, title, userId }: Args) {
+ const session = await getServerAuthSession();
+ if (!session) throw new Error('You must be logged in to submit a solution');
+
+ await prisma.sharedSolution.create({
+ data: {
+ challengeId,
+ description,
+ title,
+ userId,
+ },
+ });
+}
+
+export async function pinOrUnpinSolution(id: number, isPinned: boolean) {
+ const session = await getServerAuthSession();
+
+ if (!isAdminOrModerator(session))
+ throw new Error('You are not authorized to pin/unpin solutions');
+
+ await prisma.sharedSolution.update({
+ where: { id },
+ data: { isPinned },
+ });
+ revalidateTag(`challenge-${id}-submissions`);
+}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
index ef0a33ff..2df208c7 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
@@ -35,13 +35,7 @@ export function Solutions({ challenge }: Props) {
</div>
<div className="custom-scrollable-element h-full overflow-y-auto pt-12">
{challenge.sharedSolution.map((solution) => (
- <SolutionRow
- handleClick={() => {
- setView('details');
- }}
- key={solution.id}
- solution={solution}
- />
+ <SolutionRow key={solution.id} solution={solution} />
))}
</div>
</>
@@ -54,18 +48,11 @@ export function Solutions({ challenge }: Props) {
)}
</>
)}
-
- {view === 'details' && <div>show some details</div>}
</div>
);
}
-function SolutionRow({
- solution,
-}: {
- handleClick: (id: string) => void;
- solution: ChallengeSolution['sharedSolution'][0];
-}) {
+function SolutionRow({ solution }: { solution: ChallengeSolution['sharedSolution'][0] }) {
return (
<Link
className="flex cursor-pointer flex-col gap-2 p-4 duration-300 hover:bg-neutral-100 dark:hover:bg-zinc-700/50"
@@ -78,7 +65,11 @@ function SolutionRow({
<Calendar className=" h-4 w-4" />
<span className="text-xs">{getRelativeTime(solution.createdAt)}</span>
</div>
- {/* TODO: Use `Vote` component here instead which handles voted state */}
+ {solution.isPinned ? (
+ <Badge className="dark:bg-difficulty-beginner-dark bg-difficulty-beginner text-white duration-300 dark:text-black">
+ Pinned
+ </Badge>
+ ) : null}
<Badge variant="secondary" size="xs" className="gap-1">
<ThumbsUp className="h-4 w-4" />
<span>{solution._count.vote}</span>
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/post-solution.action.ts b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/post-solution.action.ts
deleted file mode 100644
index 167d7d60..00000000
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/post-solution.action.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-'use server';
-import { prisma } from '@repo/db';
-
-interface Args {
- challengeId: number;
- description: string;
- title: string;
- userId: string;
-}
-
-export async function postSolution({ challengeId, description, title, userId }: Args) {
- await prisma.sharedSolution.create({
- data: {
- challengeId,
- description,
- title,
- userId,
- },
- });
-}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx
index 919f3818..f518b8cf 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx
@@ -1,26 +1,36 @@
'use client';
-import { Calendar, Flag, Share, X } from '@repo/ui/icons';
-import Link from 'next/link';
-import type { ChallengeSolution } from '~/app/[locale]/challenge/[id]/solutions/[solutionId]/page';
-import { ReportDialog } from '~/components/ReportDialog';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { useSession } from '@repo/auth/react';
import { ActionMenu } from '@repo/ui/components/action-menu';
-import { Avatar, AvatarImage, AvatarFallback } from '@repo/ui/components/avatar';
+import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/avatar';
import { Button } from '@repo/ui/components/button';
-import { toast } from '@repo/ui/components/use-toast';
-import { TypographyLarge } from '@repo/ui/components/typography/large';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
import { Markdown } from '@repo/ui/components/markdown';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
+import { TypographyLarge } from '@repo/ui/components/typography/large';
+import { toast } from '@repo/ui/components/use-toast';
import { UserBadge } from '@repo/ui/components/user-badge';
+import { Calendar, Flag, Pin, Share, X } from '@repo/ui/icons';
+import clsx from 'clsx';
+import Link from 'next/link';
+import type { ChallengeSolution } from '~/app/[locale]/challenge/[id]/solutions/[solutionId]/page';
+import { ReportDialog } from '~/components/ReportDialog';
+import { getRelativeTime } from '~/utils/relativeTime';
import { Vote } from '../../../_components/vote';
-import { useSession } from '@repo/auth/react';
+import { pinOrUnpinSolution } from './_actions';
+import { isAdminOrModerator } from '~/utils/auth-guards';
interface Props {
solution: ChallengeSolution;
}
+
export function SolutionDetails({ solution }: Props) {
const { data: session } = useSession();
+
+ const showPin = isAdminOrModerator(session);
+
+ const handlePinClick = async () => {
+ await pinOrUnpinSolution(solution.id, !solution.isPinned);
+ };
const handleShareClick = async () => {
if (navigator.clipboard) {
const url = window.location.href;
@@ -103,6 +113,21 @@ export function SolutionDetails({ solution }: Props) {
<p>Share</p>
</TooltipContent>
</Tooltip>
+ {showPin ? (
+ <Button
+ onClick={handlePinClick}
+ variant="secondary"
+ size="xs"
+ className={clsx(
+ 'gap-2 border border-transparent [&:not(:disabled)]:hover:border-emerald-600 [&:not(:disabled)]:hover:text-emerald-600',
+ {
+ 'border-emerald-600 text-emerald-600': solution.isPinned,
+ },
+ )}
+ >
+ <Pin className={clsx('h-4 w-4')} />
+ </Button>
+ ) : null}
</div>
</div>
<Markdown>{solution.description || ''}</Markdown>
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
index 76b2d6f8..664da4d1 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
@@ -4,7 +4,7 @@ import { useTheme } from 'next-themes';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
-import { postSolution } from './post-solution.action';
+import { postSolution } from './_actions';
import { RichMarkdownEditor } from '~/components/rich-markdown-editor';
import type { ChallengeSolution } from '../getSolutionRouteData';
import { Button } from '@repo/ui/components/button';
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts b/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts
index ac28705e..7c6e3c49 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts
@@ -8,10 +8,10 @@ export const getSolutionsRouteData = cache(async (challengeId: string, session:
where: { id: Number(challengeId) },
select: {
id: true,
- // we just want their most recent solution
submission: {
where: {
userId: session?.user.id || '',
+ isSuccessful: true,
},
orderBy: [
{
@@ -22,6 +22,9 @@ export const getSolutionsRouteData = cache(async (challengeId: string, session:
},
sharedSolution: {
orderBy: [
+ {
+ isPinned: 'desc',
+ },
{
createdAt: 'desc',
},
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
index dddb58b8..1afc6e1f 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
@@ -1,8 +1,9 @@
import { getServerAuthSession } from '@repo/auth/server';
import { notFound } from 'next/navigation';
-import { Solutions } from './_components';
-import { getChallengeRouteData } from '../getChallengeRouteData';
import { buildMetaForDefault } from '~/app/metadata';
+import { withUnstableCache } from '~/utils/withUnstableCache';
+import { getChallengeRouteData } from '../getChallengeRouteData';
+import { Solutions } from './_components';
import { getSolutionsRouteData } from './getSolutionRouteData';
interface Props {
@@ -21,7 +22,12 @@ export async function generateMetadata({ params: { id } }: Props) {
export default async function SolutionPage({ params: { id } }: Props) {
const session = await getServerAuthSession();
- const solutions = await getSolutionsRouteData(id, session);
+ const solutions = await withUnstableCache({
+ fn: getSolutionsRouteData,
+ args: [id, session],
+ keys: ['challenge-submissions'],
+ tags: [`challenge-${id}-submissions`],
+ });
if (!solutions) {
return notFound();
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/index.tsx b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/index.tsx
index 55c80c03..39d2df64 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/index.tsx
@@ -6,8 +6,8 @@ import clsx from 'clsx';
import Link from 'next/link';
import { useMemo, useState } from 'react';
import NoSubmissions from './nosubmissions';
-import type { ChallengeSubmissions } from '~/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/getChallengeSubmissions';
import { getRelativeTime } from '~/utils/relativeTime';
+import type { ChallengeSubmissions } from '../page';
interface Props {
submissions: ChallengeSubmissions;
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/getChallengeSubmissions.ts b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/getChallengeSubmissions.ts
index 6636c2bb..90c55c10 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/getChallengeSubmissions.ts
+++ b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/getChallengeSubmissions.ts
@@ -3,18 +3,6 @@
import { cache } from 'react';
import { prisma } from '@repo/db';
-export type ChallengeSubmissions = NonNullable<Awaited<ReturnType<typeof getChallengeSubmissions>>>;
-export const getChallengeSubmissions = cache((userId: string, challengeId: string) => {
- return prisma.submission.findMany({
- where: { challengeId: Number(challengeId), userId },
- orderBy: [
- {
- createdAt: 'desc',
- },
- ],
- });
-});
-
export const getChallengeSubmissionById = cache((id: string) => {
return prisma.submission.findFirst({
where: {
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
index 170d63a8..f818256b 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
@@ -1,7 +1,8 @@
+import { cache } from 'react';
+import { prisma } from '@repo/db';
import { getServerAuthSession } from '@repo/auth/server';
import { notFound } from 'next/navigation';
import { Submissions } from './_components';
-import { getChallengeSubmissions } from './getChallengeSubmissions';
import { withUnstableCache } from '~/utils/withUnstableCache';
interface Props {
@@ -30,3 +31,15 @@ export default async function SubmissionPage({ params: { id } }: Props) {
return <Submissions submissions={submissions} />;
}
+
+export type ChallengeSubmissions = NonNullable<Awaited<ReturnType<typeof getChallengeSubmissions>>>;
+export const getChallengeSubmissions = cache((userId: string, challengeId: string) => {
+ return prisma.submission.findMany({
+ where: { challengeId: Number(challengeId), userId },
+ orderBy: [
+ {
+ createdAt: 'desc',
+ },
+ ],
+ });
+});
diff --git a/apps/web/src/utils/auth-guards.ts b/apps/web/src/utils/auth-guards.ts
new file mode 100644
index 00000000..f9c97b5a
--- /dev/null
+++ b/apps/web/src/utils/auth-guards.ts
@@ -0,0 +1,6 @@
+import type { Session } from '@repo/auth/server';
+import { RoleTypes } from '@repo/db/types';
+
+export function isAdminOrModerator(session: Session | null) {
+ return [RoleTypes.ADMIN, RoleTypes.MODERATOR].some((i) => session?.user.role.includes(i));
+}
diff --git a/packages/db/schema.prisma b/packages/db/schema.prisma
index 3ad12ca3..71adbcfe 100644
--- a/packages/db/schema.prisma
+++ b/packages/db/schema.prisma
@@ -213,6 +213,7 @@ model Vote {
model SharedSolution {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
+ isPinned Boolean @default(false)
title String
description String @db.MediumText
vote Vote[]
diff --git a/packages/ui/src/icons.ts b/packages/ui/src/icons.ts
index 753880fc..79e349b6 100644
--- a/packages/ui/src/icons.ts
+++ b/packages/ui/src/icons.ts
@@ -38,6 +38,7 @@ export {
MoreHorizontal,
Pencil,
PieChart,
+ Pin,
Play,
Plus,
Reply,