Skip to content

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

chore: use slugs for tracks + challenges (#870)

bautistaaa1ff604547fca
diff --git a/apps/admin/src/app/_components/tracks/add-track-form.tsx b/apps/admin/src/app/_components/tracks/add-track-form.tsx
index 382d5295..8a941664 100644
--- a/apps/admin/src/app/_components/tracks/add-track-form.tsx
+++ b/apps/admin/src/app/_components/tracks/add-track-form.tsx
@@ -18,7 +18,7 @@ import { DialogFooter } from '@repo/ui/components/dialog';
import { Button } from '@repo/ui/components/button';
const formSchema = z.object({
- title: z.string().min(3),
+ name: z.string().min(3),
description: z.string().min(10),
visible: z.boolean(),
});
@@ -35,7 +35,7 @@ export function AddTrackForm({ toggle }: Props) {
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
defaultValues: {
- title: '',
+ name: '',
description: '',
visible: false,
},
@@ -72,10 +72,10 @@ export function AddTrackForm({ toggle }: Props) {
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
- name="title"
+ name="name"
render={({ field }) => (
<FormItem>
- <FormLabel>Track Title:</FormLabel>
+ <FormLabel>Track Name:</FormLabel>
<FormControl>
<Input
className="rounded-xl bg-neutral-200 dark:bg-neutral-800"
diff --git a/apps/admin/src/app/_components/tracks/tracks.actions.ts b/apps/admin/src/app/_components/tracks/tracks.actions.ts
index 3c4a3a39..cbbbcd1b 100644
--- a/apps/admin/src/app/_components/tracks/tracks.actions.ts
+++ b/apps/admin/src/app/_components/tracks/tracks.actions.ts
@@ -11,11 +11,13 @@ export async function getTracks() {
});
}
-export async function createTrack(data: Prisma.TrackCreateInput) {
+export async function createTrack(data: Omit<Prisma.TrackCreateInput, 'slug'>) {
const { trackChallenges, ...rest } = data;
+ const slug = rest.name.toLowerCase().replace(/\s/g, '-');
return prisma.track.create({
data: {
...rest,
+ slug,
},
});
}
diff --git a/apps/admin/src/app/tracks/[trackId]/_components/update-track-form.tsx b/apps/admin/src/app/tracks/[trackId]/_components/update-track-form.tsx
index fde096c5..65b40ee6 100644
--- a/apps/admin/src/app/tracks/[trackId]/_components/update-track-form.tsx
+++ b/apps/admin/src/app/tracks/[trackId]/_components/update-track-form.tsx
@@ -31,7 +31,7 @@ const trackChallengeSchema = z.object({
});
const formSchema = z.object({
- title: z.string().min(3),
+ name: z.string().min(3),
description: z.string().min(10),
visible: z.boolean(),
trackChallenges: z.array(trackChallengeSchema),
@@ -56,7 +56,7 @@ export function UpdateTrackForm({ challenges, track }: Props) {
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
defaultValues: {
- title: track.title,
+ name: track.name,
description: track.description,
visible: track.visible,
trackChallenges: track.trackChallenges,
@@ -121,10 +121,10 @@ export function UpdateTrackForm({ challenges, track }: Props) {
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
- name="title"
+ name="name"
render={({ field }) => (
<FormItem>
- <FormLabel>Track Title:</FormLabel>
+ <FormLabel>Track Name:</FormLabel>
<FormControl>
<Input
className="rounded-xl bg-neutral-200 dark:bg-neutral-800"
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/challenge-playground-store.ts b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/challenge-playground-store.ts
index 1971b285..efa84730 100644
--- a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/challenge-playground-store.ts
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/challenge-playground-store.ts
@@ -6,6 +6,7 @@ export const DEFAULT_VALUES = {
challenge: {
id: 1,
code: 'type Foo = string;',
+ slug: 'some-slug',
tests: '// test cases go here',
},
};
diff --git a/apps/web/src/app/[locale]/[username]/_components/dashboard/in-progress-tab.tsx b/apps/web/src/app/[locale]/[username]/_components/dashboard/in-progress-tab.tsx
index 2d4c1ebf..c27c687a 100644
--- a/apps/web/src/app/[locale]/[username]/_components/dashboard/in-progress-tab.tsx
+++ b/apps/web/src/app/[locale]/[username]/_components/dashboard/in-progress-tab.tsx
@@ -41,20 +41,20 @@ export async function InProgressTab({ userId }: { userId: string }) {
);
}
-async function getInProgressChallenges(id: string) {
+async function getInProgressChallenges(userId: string) {
const challenges = await prisma.challenge.findMany({
where: {
AND: [
{
submission: {
none: {
- userId: id,
+ userId,
isSuccessful: true,
},
},
},
// Make sure there is at least one submission
- { submission: { some: { userId: id, isSuccessful: false } } },
+ { submission: { some: { userId, isSuccessful: false } } },
],
},
select: {
diff --git a/apps/web/src/app/[locale]/challenge/[id]/comments/[commentId]/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/comments/[commentId]/page.tsx
similarity index 78%
rename from apps/web/src/app/[locale]/challenge/[id]/comments/[commentId]/page.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/comments/[commentId]/page.tsx
index 82ecf018..13d0e2bb 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/comments/[commentId]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/comments/[commentId]/page.tsx
@@ -6,24 +6,24 @@ import { getChallengeRouteData } from '../../getChallengeRouteData';
interface Props {
params: {
- id: string;
+ slug: string;
commentId: string;
};
}
-export default async function CommentPage({ params: { id, commentId } }: Props) {
+export default async function CommentPage({ params: { slug, commentId } }: Props) {
const session = await getServerAuthSession();
+ const challenge = await getChallengeRouteData(slug, session);
const preselectedCommentMetadata = await getPreselectedCommentMetadata(
- Number(id),
+ challenge.id,
Number(commentId),
);
- const challenge = await getChallengeRouteData(id, session);
return (
<div className="relative h-full">
<Description challenge={challenge} />
<Comments
- rootId={Number(id)}
+ rootId={challenge.id}
preselectedCommentMetadata={preselectedCommentMetadata}
type="CHALLENGE"
expanded
diff --git a/apps/web/src/app/[locale]/challenge/[id]/getChallengeRouteData.ts b/apps/web/src/app/[locale]/challenge/[slug]/getChallengeRouteData.ts
similarity index 87%
rename from apps/web/src/app/[locale]/challenge/[id]/getChallengeRouteData.ts
rename to apps/web/src/app/[locale]/challenge/[slug]/getChallengeRouteData.ts
index 33dea3c5..e0889db7 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/getChallengeRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/[slug]/getChallengeRouteData.ts
@@ -5,10 +5,10 @@ import { cache } from 'react';
export type ChallengeRouteData = NonNullable<Awaited<ReturnType<typeof getChallengeRouteData>>>;
// this is to data to populate the description tab (default tab on challenge page)
-export const getChallengeRouteData = cache((id: string, session: Session | null) => {
+export const getChallengeRouteData = cache((slug: string, session: Session | null) => {
return prisma.challenge.findFirstOrThrow({
where: {
- id: Number(id),
+ slug,
status: 'ACTIVE',
},
include: {
diff --git a/apps/web/src/app/[locale]/challenge/[id]/layout.tsx b/apps/web/src/app/[locale]/challenge/[slug]/layout.tsx
similarity index 84%
rename from apps/web/src/app/[locale]/challenge/[id]/layout.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/layout.tsx
index b0e4f354..4e9c6d7b 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/layout.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/layout.tsx
@@ -5,13 +5,13 @@ import { ForceRenderUntilClient } from '@repo/ui/components/force-render-until-c
export default async function LayoutData({
children,
- params: { id },
+ params: { slug },
}: {
children: React.ReactNode;
- params: { id: string };
+ params: { slug: string };
}) {
const session = await getServerAuthSession();
- const challenge = await getChallengeRouteData(id, session);
+ const challenge = await getChallengeRouteData(slug, session);
return (
<ForceRenderUntilClient>
diff --git a/apps/web/src/app/[locale]/challenge/[id]/left-wrapper.tsx b/apps/web/src/app/[locale]/challenge/[slug]/left-wrapper.tsx
similarity index 94%
rename from apps/web/src/app/[locale]/challenge/[id]/left-wrapper.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/left-wrapper.tsx
index 1342b156..b9fe4a29 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/left-wrapper.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/left-wrapper.tsx
@@ -8,12 +8,12 @@ import { useMemo, type ReactNode, useRef, useState, useEffect } from 'react';
type Tab = 'description' | 'solutions' | 'submissions';
interface Props {
children: ReactNode;
- challengeId: number;
+ slug: string;
expandPanel: () => void;
isDesktop: boolean;
}
-export function LeftWrapper({ challengeId, children, expandPanel, isDesktop }: Props) {
+export function LeftWrapper({ slug, children, expandPanel, isDesktop }: Props) {
const pathname = usePathname();
const router = useRouter();
const [isCollapsed, setIsCollapsed] = useState(false);
@@ -102,7 +102,7 @@ export function LeftWrapper({ challengeId, children, expandPanel, isDesktop }: P
isCollapsed ? (isDesktop ? 'rounded-r-lg py-4' : 'rounded-bl-xl') : ''
}`}
onClick={() => {
- router.push(`/challenge/${challengeId}`);
+ router.push(`/challenge/${slug}`);
expandPanel();
}}
value="description"
@@ -114,7 +114,7 @@ export function LeftWrapper({ challengeId, children, expandPanel, isDesktop }: P
isCollapsed && isDesktop ? 'py-4' : ''
}`}
onClick={() => {
- router.push(`/challenge/${challengeId}/solutions`);
+ router.push(`/challenge/${slug}/solutions`);
expandPanel();
}}
value="solutions"
@@ -126,7 +126,7 @@ export function LeftWrapper({ challengeId, children, expandPanel, isDesktop }: P
isCollapsed ? (isDesktop ? 'rounded-md py-4' : 'rounded-br-xl') : ''
}`}
onClick={() => {
- router.push(`/challenge/${challengeId}/submissions`);
+ router.push(`/challenge/${slug}/submissions`);
expandPanel();
}}
value="submissions"
diff --git a/apps/web/src/app/[locale]/challenge/[id]/loading.tsx b/apps/web/src/app/[locale]/challenge/[slug]/loading.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/loading.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/loading.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/page.tsx
similarity index 77%
rename from apps/web/src/app/[locale]/challenge/[id]/page.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/page.tsx
index 6f19c587..361c7f3c 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/page.tsx
@@ -1,22 +1,20 @@
import { getServerAuthSession, type Session } from '@repo/auth/server';
-import { Description } from '../_components/description';
-import { Comments } from '../_components/comments';
-import { getChallengeRouteData } from './getChallengeRouteData';
+import { redirect } from 'next/navigation';
import { buildMetaForChallenge } from '~/app/metadata';
import { getRelativeTime } from '~/utils/relativeTime';
-import { getAllFlags } from '~/utils/feature-flags';
-import { redirect } from 'next/navigation';
-import { prisma } from '@repo/db';
import { isBetaUser } from '~/utils/server/is-beta-user';
+import { Comments } from '../_components/comments';
+import { Description } from '../_components/description';
+import { getChallengeRouteData } from './getChallengeRouteData';
interface Props {
params: {
- id: string;
+ slug: string;
};
}
-export async function generateMetadata({ params: { id } }: Props) {
- const challenge = await getChallengeRouteData(id, null);
+export async function generateMetadata({ params: { slug } }: Props) {
+ const challenge = await getChallengeRouteData(slug, null);
const description = `Unlock your TypeScript potential by solving the ${challenge.name} challenge on TypeHero.`;
return buildMetaForChallenge({
@@ -28,7 +26,7 @@ export async function generateMetadata({ params: { id } }: Props) {
});
}
-export default async function Challenges({ params: { id: challengeId } }: Props) {
+export default async function Challenges({ params: { slug } }: Props) {
// early acces you must be authorized
const session = await getServerAuthSession();
const isBeta = await isBetaUser(session);
@@ -37,7 +35,7 @@ export default async function Challenges({ params: { id: challengeId } }: Props)
return redirect('/claim');
}
- const challenge = await getChallengeRouteData(challengeId, session);
+ const challenge = await getChallengeRouteData(slug, session);
return (
<div className="relative h-full ">
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/comments/[commentId]/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/comments/[commentId]/page.tsx
similarity index 67%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/comments/[commentId]/page.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/comments/[commentId]/page.tsx
index 29436e11..f109b063 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/comments/[commentId]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/comments/[commentId]/page.tsx
@@ -1,26 +1,26 @@
-import { getServerAuthSession, type Session } from '@repo/auth/server';
+import { getServerAuthSession } from '@repo/auth/server';
+import { SolutionDetails } from '~/app/[locale]/challenge/[slug]/solutions/_components/solution-detail';
import { Comments } from '~/app/[locale]/challenge/_components/comments';
-import { SolutionDetails } from '~/app/[locale]/challenge/[id]/solutions/_components/solution-detail';
import { getPreselectedSolutionCommentMetadata } from '~/app/[locale]/challenge/_components/comments/getCommentRouteData';
import { getSolutionIdRouteData } from '../../getSolutionIdRouteData';
interface Props {
params: {
- id: string;
+ slug: string;
commentId: string;
solutionId: string;
};
}
-export default async function SolutionPage({
- params: { solutionId, commentId, id: challengeId },
+export default async function SolutionPageComments({
+ params: { solutionId, commentId, slug },
}: Props) {
const session = await getServerAuthSession();
- const solution = await getSolutionIdRouteData(challengeId, solutionId, session);
+ const solution = await getSolutionIdRouteData(slug, solutionId, session);
const preselectedCommentMetadata = await getPreselectedSolutionCommentMetadata(
Number(solutionId),
Number(commentId),
- Number(challengeId),
+ Number(solution.challengeId),
);
return (
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/error.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/error.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/error.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/error.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/getSolutionIdRouteData.ts b/apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/getSolutionIdRouteData.ts
similarity index 66%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/getSolutionIdRouteData.ts
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/getSolutionIdRouteData.ts
index 606b85fe..18bd41df 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/getSolutionIdRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/getSolutionIdRouteData.ts
@@ -4,11 +4,15 @@ import { type Session } from '@repo/auth/server';
import { redirect } from 'next/navigation';
export const getSolutionIdRouteData = cache(
- async (challengeId: string, solutionId: string, session: Session | null) => {
+ async (slug: string, solutionId: string, session: Session | null) => {
+ const challenge = await prisma.challenge.findFirstOrThrow({
+ where: { slug },
+ select: { id: true },
+ });
const solution = await prisma.sharedSolution.findFirst({
where: {
id: Number(solutionId),
- challengeId: Number(challengeId),
+ challengeId: challenge.id,
},
include: {
user: {
@@ -28,11 +32,16 @@ export const getSolutionIdRouteData = cache(
userId: true,
},
},
+ challenge: {
+ select: {
+ slug: true,
+ },
+ },
},
});
if (!solution) {
- redirect(`/challenge/${challengeId}/solutions`);
+ redirect(`/challenge/${challenge.id}/solutions`);
}
return solution;
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/page.tsx
similarity index 91%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/page.tsx
index 44359587..081d3f12 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/[solutionId]/page.tsx
@@ -8,13 +8,13 @@ import { redirect } from 'next/navigation';
interface Props {
params: {
- id: string;
+ slug: string;
solutionId: string;
};
}
export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionIdRouteData>>>;
-export default async function SolutionPage({ params: { solutionId, id: challengeId } }: Props) {
+export default async function SolutionPage({ params: { solutionId, slug } }: Props) {
const session = await getServerAuthSession();
const isBeta = await isBetaUser(session);
@@ -22,7 +22,7 @@ export default async function SolutionPage({ params: { solutionId, id: challenge
return redirect('/claim');
}
- const solution = await getSolutionIdRouteData(challengeId, solutionId, session);
+ const solution = await getSolutionIdRouteData(slug, solutionId, session);
return (
<div className="relative h-full">
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/_actions.ts
similarity index 62%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/_actions.ts
index 71628e82..16455ebb 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/_actions.ts
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/_actions.ts
@@ -3,18 +3,19 @@ import { getServerAuthSession } from '@repo/auth/server';
import { prisma } from '@repo/db';
import { revalidateTag } from 'next/cache';
import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';
+import type { ChallengeSolution } from '../[solutionId]/page';
interface Args {
challengeId: number;
description: string;
+ slug: string;
title: string;
userId: string;
}
-export const createCacheKeyForSolutions = (challengeId: number) =>
- `challenge-${challengeId}-solutions`;
+export const createCacheKeyForSolutions = (slug: string) => `challenge-${slug}-solutions`;
-export async function postSolution({ challengeId, description, title, userId }: Args) {
+export async function postSolution({ challengeId, description, slug, title, userId }: Args) {
const session = await getServerAuthSession();
if (!session) throw new Error('You must be logged in to submit a solution');
@@ -26,25 +27,23 @@ export async function postSolution({ challengeId, description, title, userId }:
userId,
},
});
- revalidateTag(createCacheKeyForSolutions(challengeId));
+ revalidateTag(createCacheKeyForSolutions(slug));
}
-export async function deleteSolution(id: number, challengeId: number) {
+export async function deleteSolution(solutionToDelete: ChallengeSolution) {
const session = await getServerAuthSession();
- const solution = await prisma.sharedSolution.findUnique({
- where: { id },
- });
- if (!isAuthor(session, solution?.userId)) {
+ if (!isAuthor(session, solutionToDelete?.userId)) {
throw new Error('Only author can delete their solution.');
}
await prisma.sharedSolution.delete({
- where: { id },
+ where: { id: solutionToDelete.id },
});
- revalidateTag(createCacheKeyForSolutions(challengeId));
+
+ revalidateTag(createCacheKeyForSolutions(solutionToDelete.challenge?.slug ?? ''));
}
-export async function pinOrUnpinSolution(id: number, isPinned: boolean, challengeId: number) {
+export async function pinOrUnpinSolution(id: number, isPinned: boolean, slug: string) {
const session = await getServerAuthSession();
if (!isAdminOrModerator(session))
@@ -54,5 +53,5 @@ export async function pinOrUnpinSolution(id: number, isPinned: boolean, challeng
where: { id },
data: { isPinned },
});
- revalidateTag(createCacheKeyForSolutions(challengeId));
+ revalidateTag(createCacheKeyForSolutions(slug));
}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/delete/index.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/delete/index.tsx
similarity index 97%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/delete/index.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/delete/index.tsx
index 9898bb02..522d00fa 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/delete/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/delete/index.tsx
@@ -2,7 +2,7 @@ import type { DialogTriggerProps } from '@radix-ui/react-dialog';
import { useState } from 'react';
import { Dialog, DialogContent, DialogTrigger } from '@repo/ui/components/dialog';
import { TypographyLarge } from '@repo/ui/components/typography/large';
-import type { ChallengeSolution } from '~/app/[locale]/challenge/[id]/solutions/[solutionId]/page';
+import type { ChallengeSolution } from '~/app/[locale]/challenge/[slug]/solutions/[solutionId]/page';
import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
import { getRelativeTime } from '~/utils/relativeTime';
import { Button } from '@repo/ui/components/button';
@@ -23,7 +23,7 @@ export function SolutionDeleteDialog({ children, solution, ...props }: SolutionD
async function handleDeleteSolution() {
try {
- await deleteSolution(solution.id, solution.challengeId ?? 0);
+ await deleteSolution(solution);
toast({
title: 'Solution Deleted',
variant: 'success',
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx
similarity index 95%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx
index 2df208c7..ec8806a5 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx
@@ -10,6 +10,7 @@ import type { ChallengeSolution } 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';
interface Props {
challenge: ChallengeSolution;
@@ -53,10 +54,11 @@ export function Solutions({ challenge }: Props) {
}
function SolutionRow({ solution }: { solution: ChallengeSolution['sharedSolution'][0] }) {
+ const { slug } = useParams();
return (
<Link
className="flex cursor-pointer flex-col gap-2 p-4 duration-300 hover:bg-neutral-100 dark:hover:bg-zinc-700/50"
- href={`/challenge/${solution.challengeId}/solutions/${solution.id}`}
+ href={`/challenge/${slug}/solutions/${solution.id}`}
>
<h3 className="truncate font-bold">{solution.title}</h3>
<div className="flex items-center gap-2">
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/nosolutions.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/nosolutions.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/nosolutions.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/nosolutions.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-detail.tsx
similarity index 96%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-detail.tsx
index c725b106..439f3df2 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-detail.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-detail.tsx
@@ -12,24 +12,26 @@ import { UserBadge } from '@repo/ui/components/user-badge';
import { Calendar, Flag, Pin, Share, X, Trash } 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 type { ChallengeSolution } from '~/app/[locale]/challenge/[slug]/solutions/[solutionId]/page';
import { ReportDialog } from '~/components/ReportDialog';
import { getRelativeTime } from '~/utils/relativeTime';
import { Vote } from '../../../_components/vote';
import { pinOrUnpinSolution } from './_actions';
import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';
import { SolutionDeleteDialog } from './delete';
+import { useParams } from 'next/navigation';
interface Props {
solution: ChallengeSolution;
}
export function SolutionDetails({ solution }: Props) {
+ const { slug } = useParams();
const { data: session } = useSession();
const showPin = isAdminOrModerator(session);
const handlePinClick = async () => {
- await pinOrUnpinSolution(solution.id, !solution.isPinned, solution.challengeId ?? 0);
+ await pinOrUnpinSolution(solution.id, !solution.isPinned, slug as string);
};
const handleShareClick = async () => {
if (navigator.clipboard) {
@@ -46,7 +48,7 @@ export function SolutionDetails({ solution }: Props) {
<div className="relative h-full">
<div className="relative flex h-full flex-col">
<div className="bg-background/90 dark:bg-muted/90 sticky right-0 top-0 flex w-full border-b border-zinc-300 p-2 backdrop-blur-sm dark:border-zinc-700">
- <Link href={`/challenge/${solution.challengeId}/solutions`}>
+ <Link href={`/challenge/${slug}/solutions`}>
<X className="stroke-gray-500 hover:stroke-gray-400" size={20} />
</Link>
</div>
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-editor.tsx
similarity index 96%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-editor.tsx
index d585fbc8..a779d945 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-editor.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-editor.tsx
@@ -5,13 +5,13 @@ import { Form, FormControl, FormField, FormItem, FormMessage } from '@repo/ui/co
import { Input } from '@repo/ui/components/input';
import { useToast } from '@repo/ui/components/use-toast';
import { useTheme } from 'next-themes';
-import { revalidateTag } from 'next/cache';
+import { useParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { RichMarkdownEditor } from '~/components/rich-markdown-editor';
import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';
import type { ChallengeSolution } from '../getSolutionRouteData';
-import { createCacheKeyForSolutions, postSolution } from './_actions';
+import { postSolution } from './_actions';
const getDefaultMarkdown = (solution: string) => `
## Thoughts
@@ -44,6 +44,7 @@ interface Props {
}
export function SolutionEditor({ dismiss, challenge }: Props) {
+ const { slug } = useParams();
const session = useSession();
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
@@ -59,6 +60,7 @@ export function SolutionEditor({ dismiss, challenge }: Props) {
await postSolution({
challengeId: challenge.id,
description: data.content ?? '',
+ slug: slug as string,
title: data.title ?? '',
userId: session.data?.user.id!,
});
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-skeleton.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-skeleton.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/solution-skeleton.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-skeleton.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/_components/submit-solution.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/submit-solution.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/_components/submit-solution.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/submit-solution.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts b/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts
similarity index 87%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts
index 7c6e3c49..3e27c62e 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/getSolutionRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts
@@ -3,9 +3,9 @@ import { prisma } from '@repo/db';
import type { Session } from '@repo/auth/server';
export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionsRouteData>>>;
-export const getSolutionsRouteData = cache(async (challengeId: string, session: Session | null) => {
+export const getSolutionsRouteData = cache(async (slug: string, session: Session | null) => {
const data = await prisma.challenge.findFirst({
- where: { id: Number(challengeId) },
+ where: { slug },
select: {
id: true,
submission: {
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/loading.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/loading.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/loading.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/loading.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
similarity index 75%
rename from apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
index b77e77ba..4b1be432 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
@@ -9,25 +9,25 @@ import { createCacheKeyForSolutions } from './_components/_actions';
interface Props {
params: {
- id: string;
+ slug: string;
};
}
-export async function generateMetadata({ params: { id } }: Props) {
- const challenge = await getChallengeRouteData(id, null);
+export async function generateMetadata({ params: { slug } }: Props) {
+ const challenge = await getChallengeRouteData(slug, null);
return buildMetaForDefault({
title: `Solutions to ${challenge.name} | TypeHero`,
description: challenge.shortDescription,
});
}
-export default async function SolutionPage({ params: { id } }: Props) {
+export default async function SolutionPage({ params: { slug } }: Props) {
const session = await getServerAuthSession();
const solutions = await withUnstableCache({
fn: getSolutionsRouteData,
- args: [id, session],
+ args: [slug, session],
keys: ['challenge-solutions'],
- tags: [createCacheKeyForSolutions(Number(id))],
+ tags: [createCacheKeyForSolutions(slug)],
});
if (!solutions) {
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/index.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/index.tsx
similarity index 89%
rename from apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/index.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/index.tsx
index 39d2df64..952359e3 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/index.tsx
@@ -8,6 +8,7 @@ import { useMemo, useState } from 'react';
import NoSubmissions from './nosubmissions';
import { getRelativeTime } from '~/utils/relativeTime';
import type { ChallengeSubmissions } from '../page';
+import { useParams } from 'next/navigation';
interface Props {
submissions: ChallengeSubmissions;
@@ -67,29 +68,18 @@ export function Submissions({ submissions }: Props) {
<ul className="custom-scrollable-element flex h-full flex-col overflow-y-auto pt-12">
{filteredSubmissions.map((submission) => {
- return (
- <SubmissionRow
- challengeId={submission.challengeId}
- key={submission.id}
- submission={submission}
- />
- );
+ return <SubmissionRow key={submission.id} submission={submission} />;
})}
</ul>
</div>
);
}
-function SubmissionRow({
- challengeId,
- submission,
-}: {
- challengeId: number;
- submission: Submission;
-}) {
+function SubmissionRow({ submission }: { submission: Submission }) {
+ const { slug } = useParams();
return (
<li className="flex cursor-pointer items-center justify-between px-4 py-2 duration-300 hover:bg-neutral-100 dark:rounded-none dark:hover:bg-zinc-700/50">
- <Link className="w-full" href={`/challenge/${challengeId}/submissions/${submission.id}`}>
+ <Link className="w-full" href={`/challenge/${slug}/submissions/${submission.id}`}>
<div
className={clsx({
'text-emerald-600 dark:text-emerald-400': submission.isSuccessful,
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/nosubmissions.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/nosubmissions.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/nosubmissions.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/nosubmissions.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/overview.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
similarity index 94%
rename from apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/overview.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
index f6203ae5..3e6fd516 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/overview.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
@@ -7,6 +7,7 @@ import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { getRelativeTime } from '~/utils/relativeTime';
import { getChallengeSubmissionById } from '../getChallengeSubmissions';
+import { useParams } from 'next/navigation';
interface Props {
submissionId: string;
@@ -17,6 +18,7 @@ ${code} \`\`\``;
};
export function SubmissionOverview({ submissionId }: Props) {
+ const { slug } = useParams();
const { data: submission } = useQuery({
queryKey: ['submission', submissionId],
queryFn: () => getChallengeSubmissionById(submissionId),
@@ -39,7 +41,7 @@ export function SubmissionOverview({ submissionId }: Props) {
return (
<>
<div className="sticky top-0 flex h-[40px] items-center justify-between border-b border-zinc-300 px-3 py-2 dark:border-zinc-700 dark:bg-[#1e1e1e]">
- <Link href={`/challenge/${submission.challengeId}/submissions`}>
+ <Link href={`/challenge/${slug}/submissions`}>
<X className="stroke-gray-500 hover:stroke-gray-400" size={20} />
</Link>
<Tooltip>
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/submissions-skeleton.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/submissions-skeleton.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/_components/submissions-skeleton.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/submissions-skeleton.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/getChallengeSubmissions.ts b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/getChallengeSubmissions.ts
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/getChallengeSubmissions.ts
rename to apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/getChallengeSubmissions.ts
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/page.tsx
similarity index 68%
rename from apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/page.tsx
index 1dcd1394..4df1833c 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/page.tsx
@@ -5,10 +5,11 @@ import { notFound, redirect } from 'next/navigation';
import { Submissions } from './_components';
import { withUnstableCache } from '~/utils/withUnstableCache';
import { isBetaUser } from '~/utils/server/is-beta-user';
+import { createChallengeSubmissionCacheKey } from './save-submission.action';
interface Props {
params: {
- id: string;
+ slug: string;
};
}
@@ -17,7 +18,7 @@ export const metadata = {
description: 'View your submissions to this challenge on TypeHero.',
};
-export default async function SubmissionPage({ params: { id } }: Props) {
+export default async function SubmissionPage({ params: { slug } }: Props) {
const session = await getServerAuthSession();
const isBeta = await isBetaUser(session);
@@ -27,9 +28,9 @@ export default async function SubmissionPage({ params: { id } }: Props) {
const submissions = await withUnstableCache({
fn: getChallengeSubmissions,
- args: [session?.user.id ?? '', id],
+ args: [session?.user.id ?? '', slug],
keys: ['all-challenge-submissions'],
- tags: [`${id}-challenge-submissions`],
+ tags: [createChallengeSubmissionCacheKey(slug)],
});
if (!submissions) {
@@ -40,9 +41,13 @@ export default async function SubmissionPage({ params: { id } }: Props) {
}
export type ChallengeSubmissions = NonNullable<Awaited<ReturnType<typeof getChallengeSubmissions>>>;
-const getChallengeSubmissions = cache((userId: string, challengeId: string) => {
+const getChallengeSubmissions = cache(async (userId: string, slug: string) => {
+ const challenge = await prisma.challenge.findFirstOrThrow({
+ where: { slug },
+ select: { id: true },
+ });
return prisma.submission.findMany({
- where: { challengeId: Number(challengeId), userId },
+ where: { challengeId: challenge.id, userId },
orderBy: [
{
createdAt: 'desc',
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/save-submission.action.ts b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/save-submission.action.ts
new file mode 100644
index 00000000..0c13d520
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/save-submission.action.ts
@@ -0,0 +1,27 @@
+'use server';
+import { prisma } from '@repo/db';
+import { revalidateTag } from 'next/cache';
+import type { ChallengeRouteData } from '../../getChallengeRouteData';
+import { createCacheKeyForSolutions } from '../../solutions/_components/_actions';
+
+export const createChallengeSubmissionCacheKey = (slug: string) => {
+ return `${slug}-challenge-submissions`;
+};
+interface Args {
+ challenge: ChallengeRouteData;
+ userId: string;
+ code: string;
+ isSuccessful: boolean;
+}
+export async function saveSubmission({ challenge, userId, code, isSuccessful }: Args) {
+ await prisma.submission.create({
+ data: {
+ challengeId: challenge.id,
+ userId,
+ code,
+ isSuccessful,
+ },
+ });
+ revalidateTag(createChallengeSubmissionCacheKey(challenge.slug));
+ revalidateTag(createCacheKeyForSolutions(challenge.slug));
+}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/loading.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/loading.tsx
similarity index 100%
rename from apps/web/src/app/[locale]/challenge/[id]/submissions/loading.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/submissions/loading.tsx
diff --git a/apps/web/src/app/[locale]/challenge/[id]/wrapper.tsx b/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
similarity index 91%
rename from apps/web/src/app/[locale]/challenge/[id]/wrapper.tsx
rename to apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
index 32b0bd4b..7f4bd558 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/wrapper.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
@@ -29,7 +29,12 @@ export function Wrapper({ challenge }: { challenge: ChallengeRouteData }) {
success: !isSuccessful,
});
- return saveSubmission(challenge.id, code, isSuccessful);
+ return saveSubmission({
+ challenge,
+ userId: session?.user.id!,
+ code,
+ isSuccessful,
+ });
}}
submissionDisabled={!session?.user}
settingsElement={<SettingsElements />}
diff --git a/apps/web/src/app/[locale]/challenge/_components/challenge-layout-wrapper.tsx b/apps/web/src/app/[locale]/challenge/_components/challenge-layout-wrapper.tsx
index b881429e..c3de98e7 100644
--- a/apps/web/src/app/[locale]/challenge/_components/challenge-layout-wrapper.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/challenge-layout-wrapper.tsx
@@ -1,10 +1,10 @@
'use client';
import { useState, type ReactNode } from 'react';
-import type { ChallengeRouteData } from '../[id]/getChallengeRouteData';
+import type { ChallengeRouteData } from '../[slug]/getChallengeRouteData';
import { ChallengeLayout, MOBILE_BREAKPOINT } from './challenge-layout';
import usePanelAdjustments from './usePanelAdjustments';
-import { LeftWrapper } from '../[id]/left-wrapper';
-import { Wrapper } from '../[id]/wrapper';
+import { LeftWrapper } from '../[slug]/left-wrapper';
+import { Wrapper } from '../[slug]/wrapper';
export function ChallengeLayoutWrapper({
challenge,
@@ -32,7 +32,7 @@ export function ChallengeLayoutWrapper({
return (
<ChallengeLayout
left={
- <LeftWrapper challengeId={challenge.id} expandPanel={expandPanel} isDesktop={isDesktop}>
+ <LeftWrapper slug={challenge.slug} expandPanel={expandPanel} isDesktop={isDesktop}>
{children}
</LeftWrapper>
}
diff --git a/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx b/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
index 6dbe6956..5a73fa3a 100644
--- a/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/comments/comment.tsx
@@ -264,8 +264,7 @@ function SingleComment({
replyQueryKey,
preselectedCommentMetadata,
}: SingleCommentProps) {
- const params = useParams();
- const challengeId = params.id as string;
+ const { slug } = useParams();
const searchParams = useSearchParams();
const replyId = searchParams.get('replyId');
const queryClient = useQueryClient();
@@ -303,9 +302,9 @@ function SingleComment({
}
}
- async function copyPathNotifyUser(isReply: boolean, challengeId: string) {
+ async function copyPathNotifyUser(isReply: boolean, slug: string) {
try {
- await copyCommentUrlToClipboard(isReply, challengeId);
+ await copyCommentUrlToClipboard(isReply, slug);
toast({
title: 'Success!',
variant: 'success',
@@ -321,13 +320,13 @@ function SingleComment({
}
}
- async function copyCommentUrlToClipboard(isReply: boolean, challengeId: string) {
+ async function copyCommentUrlToClipboard(isReply: boolean, slug: string) {
const commentId = isReply ? comment.parentId : comment.id;
const paramsObj = { replyId: String(comment.id) };
const searchParams = new URLSearchParams(paramsObj);
const { rootType, rootSolutionId } = comment;
- const baseURL = `${window.location.origin}/challenge/${challengeId}`;
+ const baseURL = `${window.location.origin}/challenge/${slug}`;
const hasGetParams = isReply ? `?${searchParams.toString()}` : '';
const shareUrl =
@@ -437,7 +436,7 @@ function SingleComment({
size="xs"
className="gap-2"
onClick={() => {
- copyPathNotifyUser(Boolean(isReply), challengeId);
+ copyPathNotifyUser(Boolean(isReply), slug as string);
}}
>
<Share className="h-3 w-3" />
diff --git a/apps/web/src/app/[locale]/challenge/_components/description/index.tsx b/apps/web/src/app/[locale]/challenge/_components/description/index.tsx
index 96930225..3d5ec7bf 100644
--- a/apps/web/src/app/[locale]/challenge/_components/description/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/description/index.tsx
@@ -6,7 +6,7 @@ import clsx from 'clsx';
import { debounce } from 'lodash';
import Link from 'next/link';
import { useRef, useState } from 'react';
-import { type ChallengeRouteData } from '~/app/[locale]/challenge/[id]/getChallengeRouteData';
+import { type ChallengeRouteData } from '~/app/[locale]/challenge/[slug]/getChallengeRouteData';
import { ReportDialog } from '~/components/ReportDialog';
import { getRelativeTime } from '~/utils/relativeTime';
import { addOrRemoveBookmark } from '../bookmark.action';
diff --git a/apps/web/src/app/[locale]/challenge/_components/share-form.tsx b/apps/web/src/app/[locale]/challenge/_components/share-form.tsx
index 93aaaf03..bf339173 100644
--- a/apps/web/src/app/[locale]/challenge/_components/share-form.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/share-form.tsx
@@ -8,14 +8,14 @@ import { useCallback, useState } from 'react';
import { useLocalStorage } from '~/utils/useLocalStorage';
export function ShareForm() {
- const { id: challengeId } = useParams();
+ const { slug } = useParams();
const [copied, setCopied] = useState(false);
const [copiedWithCode, setCopiedWithCode] = useState(false);
- const [codeToCompress] = useLocalStorage(`challenge-${challengeId}`, '');
- const url = `${window.location.origin}/challenge/${challengeId}`;
+ const [codeToCompress] = useLocalStorage(`challenge-${slug}`, '');
+ const url = `${window.location.origin}/challenge/${slug}`;
const copyToClipboard = useCallback(async () => {
- const url = `${window.location.origin}/challenge/${challengeId}`;
+ const url = `${window.location.origin}/challenge/${slug}`;
try {
if (navigator.clipboard && !copied) {
@@ -27,11 +27,11 @@ export function ShareForm() {
console.error('copyToClipboard', e);
setCopied(false);
}
- }, [challengeId, copied]);
+ }, [slug, copied]);
const copyToClipboardWithCode = useCallback(async () => {
const compressedCode = lzstring.compressToEncodedURIComponent(codeToCompress);
- const url = `${window.location.origin}/challenge/${challengeId}/?code=${compressedCode}`;
+ const url = `${window.location.origin}/challenge/${slug}/?code=${compressedCode}`;
try {
if (navigator.clipboard && !copiedWithCode) {
@@ -43,7 +43,7 @@ export function ShareForm() {
console.error('copyToClipboard', e);
setCopiedWithCode(false);
}
- }, [challengeId, copiedWithCode, codeToCompress]);
+ }, [slug, copiedWithCode, codeToCompress]);
return (
<div className="flex flex-col space-y-4">
diff --git a/apps/web/src/app/[locale]/explore/_components/explore-section.tsx b/apps/web/src/app/[locale]/explore/_components/explore-section.tsx
index abb4c4c5..27d5f7c4 100644
--- a/apps/web/src/app/[locale]/explore/_components/explore-section.tsx
+++ b/apps/web/src/app/[locale]/explore/_components/explore-section.tsx
@@ -73,7 +73,7 @@ export async function ExploreSection({ title, tag, redirectRoute }: SectionProps
.map((challenge) => (
<Link
className="group snap-center focus:outline-none sm:w-[330px] xl:w-[333px]"
- href={`/challenge/${challenge.id}`}
+ href={`/challenge/${challenge.slug}`}
key={challenge.id}
>
<ExploreCard challenge={challenge} key={`challenge-${challenge.id}`} />
diff --git a/apps/web/src/app/[locale]/tracks/[slug]/page.tsx b/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
index 507791c6..09d7990f 100644
--- a/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
+++ b/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
@@ -28,7 +28,7 @@ export default async function Page({ params }: Props) {
export async function generateMetadata({ params: { slug } }: Props) {
const track = await withUnstableCache({
fn: getTrackDetails,
- args: [parseInt(slug)],
+ args: [slug],
keys: [`track-${slug}-detail`],
tags: [`track-${slug}-detail`],
});
@@ -41,7 +41,7 @@ export async function generateMetadata({ params: { slug } }: Props) {
}
return {
- title: `${track.title} Track | TypeHero`,
- description: `View the details of the ${track.title} track on TypeHero. ${track.description}`,
+ title: `${track.name} Track | TypeHero`,
+ description: `View the details of the ${track.name} track on TypeHero. ${track.description}`,
};
}
diff --git a/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx b/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx
index 7d7ff1ce..cc2382f9 100644
--- a/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/enroll-button.tsx
@@ -13,7 +13,6 @@ interface EnrollButtonProps {
export function ActionButton({ action, text, trackId }: EnrollButtonProps) {
return (
<Button
- variant="secondary"
onClick={async () => {
try {
await action(trackId);
@@ -22,10 +21,7 @@ export function ActionButton({ action, text, trackId }: EnrollButtonProps) {
variant: 'success',
description: <p>You're now successfully {text.toLowerCase()}ed the track.</p>,
});
- } catch (e) {
- if (process.env.NODE_ENV === 'development') {
- console.log(e);
- }
+ } catch {
toast({
title: 'Error',
variant: 'destructive',
diff --git a/apps/web/src/app/[locale]/tracks/_components/personal-track-card.tsx b/apps/web/src/app/[locale]/tracks/_components/personal-track-card.tsx
index 4bcc48a3..6dee7456 100644
--- a/apps/web/src/app/[locale]/tracks/_components/personal-track-card.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/personal-track-card.tsx
@@ -32,7 +32,7 @@ export function PersonalTrackCard({ track }: PersonalTrackCardProps) {
)}
>
<CardHeader className="relative flex flex-col items-start gap-1 pb-0">
- <CardTitle className="max-w-[90%] truncate text-xl duration-300">{track.title}</CardTitle>
+ <CardTitle className="max-w-[90%] truncate text-xl duration-300">{track.name}</CardTitle>
</CardHeader>
<CardContent className="relative flex flex-col justify-between gap-2 rounded-xl p-6 pb-0 duration-300">
<CardDescription className="relative h-20 overflow-hidden pb-4">
diff --git a/apps/web/src/app/[locale]/tracks/_components/track-card.tsx b/apps/web/src/app/[locale]/tracks/_components/track-card.tsx
index ddeb87b6..065b9a40 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track-card.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/track-card.tsx
@@ -36,7 +36,7 @@ export function TrackCard({ track }: TrackProps) {
const isEnrolled = Boolean(track.enrolledUsers?.length);
return (
- <Link href={`/tracks/${track.id}`} className="group">
+ <Link href={`/tracks/${track.slug}`} className="group">
<Card
className={clsx(
'relative transition-colors duration-300',
@@ -63,7 +63,7 @@ export function TrackCard({ track }: TrackProps) {
)}
/>
</div>
- <div className="text-center font-semibold capitalize tracking-wide">{track.title}</div>
+ <div className="text-center font-semibold capitalize tracking-wide">{track.name}</div>
<div className="text-muted-foreground line-clamp-3 text-center text-sm tracking-wide">
{track.description}
</div>
diff --git a/apps/web/src/app/[locale]/tracks/_components/track-details.tsx b/apps/web/src/app/[locale]/tracks/_components/track-details.tsx
index f8ae55aa..6c2b8253 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track-details.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/track-details.tsx
@@ -1,4 +1,3 @@
-import { getServerAuthSession } from '@repo/auth/server';
import Link from 'next/link';
import { Swords } from '@repo/ui/icons';
@@ -23,11 +22,10 @@ export const BGS_BY_TRACK: Record<number, string> = {
export const bgsArray = Object.values(BGS_BY_TRACK);
export async function TrackDetail({ slug }: TrackDetailProps) {
- const trackId = parseInt(slug);
- const track = await getTrackDetails(trackId);
+ const track = await getTrackDetails(slug);
- const trackChallenges = track?.trackChallenges ?? [];
- const isEnrolled = Boolean(track?.enrolledUsers?.length);
+ const trackChallenges = track.trackChallenges ?? [];
+ const isEnrolled = Boolean(track.enrolledUsers?.length);
const completedTrackChallenges = trackChallenges
.filter((trackChallenge) => {
@@ -52,7 +50,7 @@ export async function TrackDetail({ slug }: TrackDetailProps) {
<div
className={clsx(
`bg-gradient-to-r from-neutral-500/10 from-10% ${
- BGS_BY_TRACK[trackId % bgsArray.length]
+ BGS_BY_TRACK[track.id % bgsArray.length]
} relative to-100% dark:from-neutral-500/20`,
'flex h-24 w-24 flex-none items-center justify-center rounded-2xl',
)}
@@ -67,16 +65,16 @@ export async function TrackDetail({ slug }: TrackDetailProps) {
</div>
<div className="flex flex-col items-center space-y-2">
<h1 className="text-center text-3xl font-bold tracking-tight text-neutral-900 dark:text-white">
- {track?.title}
+ {track.name}
</h1>
<p className="text-md max-w-[69ch] text-center text-neutral-600 dark:text-white/50">
- {track?.description}
+ {track.description}
</p>
</div>
{isEnrolled ? (
- <ActionButton action={unenrollUserFromTrack} trackId={trackId} text="Unenroll" />
+ <ActionButton action={unenrollUserFromTrack} trackId={track.id} text="Unenroll" />
) : (
- <ActionButton action={enrollUserInTrack} trackId={trackId} text="Enroll" />
+ <ActionButton action={enrollUserInTrack} trackId={track.id} text="Enroll" />
)}
</div>
{isEnrolled ? (
@@ -93,7 +91,7 @@ export async function TrackDetail({ slug }: TrackDetailProps) {
{trackChallenges.map((trackChallenge) => (
<Link
key={trackChallenge.challenge.id}
- href={`/challenge/${trackChallenge.challenge.id}`}
+ href={`/challenge/${trackChallenge.challenge.slug}`}
>
<TrackChallenge
challenge={trackChallenge.challenge}
diff --git a/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx b/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx
index 183ffafb..6936fdf1 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/track-enrolled-section.tsx
@@ -56,7 +56,7 @@ export async function EnrolledTrackSection() {
{tracks.map((t) => (
<Link
className="group w-[250px] flex-none snap-center focus:outline-none sm:w-[330px] xl:w-[333px]"
- href={`/tracks/${t.id}`}
+ href={`/tracks/${t.slug}`}
key={t.id}
>
<PersonalTrackCard track={t} />
@@ -125,7 +125,7 @@ async function getUserEnrolledTracks(session: Session) {
},
},
orderBy: {
- title: 'asc',
+ name: 'asc',
},
});
}
diff --git a/apps/web/src/app/[locale]/tracks/_components/track.action.ts b/apps/web/src/app/[locale]/tracks/_components/track.action.ts
index 85fb19fc..397bc728 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track.action.ts
+++ b/apps/web/src/app/[locale]/tracks/_components/track.action.ts
@@ -66,11 +66,11 @@ export async function unenrollUserFromTrack(id: number) {
* Fetches the track details given a track id.
* @param id The track id.
*/
-export const getTrackDetails = cache(async (id: number) => {
+export const getTrackDetails = cache(async (slug: string) => {
const session = await getServerAuthSession();
- return prisma.track.findUnique({
+ return prisma.track.findFirstOrThrow({
where: {
- id,
+ slug,
},
include: {
trackChallenges: {
diff --git a/apps/web/src/app/[locale]/wizard/_components/create.action.ts b/apps/web/src/app/[locale]/wizard/_components/create.action.ts
index 581da4b5..d87df845 100644
--- a/apps/web/src/app/[locale]/wizard/_components/create.action.ts
+++ b/apps/web/src/app/[locale]/wizard/_components/create.action.ts
@@ -14,6 +14,7 @@ export async function uploadChallenge(data: CreateChallengeSchema, isUserACreato
return prisma.challenge.create({
data: {
...data,
+ slug: data.name.toLowerCase().replace(/ /g, '-'),
userId: session.user.id,
// if a user has the creator role already then their challenges dont need to be approved anymore
...(isUserACreator ? { status: 'ACTIVE' } : {}),
diff --git a/apps/web/tests/e2e/authenticated/comment.test.ts b/apps/web/tests/e2e/authenticated/comment.test.ts
index ce50d6cb..dbc6fcf9 100644
--- a/apps/web/tests/e2e/authenticated/comment.test.ts
+++ b/apps/web/tests/e2e/authenticated/comment.test.ts
@@ -5,7 +5,7 @@ import { ctrlV, wrapTypescriptCode } from '../helpers';
test.describe('create, edit, and delete comments', () => {
test.beforeEach(async ({ page }) => {
- await page.goto('/challenge/5');
+ await page.goto('/challenge/pick');
await page.getByRole('button', { name: 'Comments' }).click();
});
@@ -108,13 +108,13 @@ test.describe('sharing comments', () => {
test('share comment and navigate to comment link', async ({ page, context }) => {
const comment = await prisma.comment.create({
data: {
- rootChallengeId: 6,
+ rootChallengeId: 3,
text: parentComment,
userId: USER.id,
},
});
- await page.goto('/challenge/6');
+ await page.goto('/challenge/omit');
await page.getByRole('button', { name: 'Comments' }).click();
const commentBlock = page.locator('div[id^=comment]', { hasText: parentComment });
@@ -150,7 +150,7 @@ test.describe('sharing comments', () => {
// delete comment A
await prisma.comment.delete({ where: { id: commentA.id } });
// but visit a deep link to it anyway
- await page.goto(`/challenge/6/comments/${commentA.id}`);
+ await page.goto(`/challenge/simple-vue/comments/${commentA.id}`);
// assert other comments, such as comment B, are still visible on page load
await expect(
page.locator('div[id^=comment]', { hasText: 'this comment is timeless' }),
diff --git a/apps/web/tests/e2e/unauthenticated/challenge.test.ts b/apps/web/tests/e2e/unauthenticated/challenge.test.ts
index fce4298e..020cdb0b 100644
--- a/apps/web/tests/e2e/unauthenticated/challenge.test.ts
+++ b/apps/web/tests/e2e/unauthenticated/challenge.test.ts
@@ -31,7 +31,7 @@ test('challenge page', async ({ page }) => {
},
});
- await page.goto(`/challenge/${challengeId}`);
+ await page.goto(`/challenge/pick`);
await expect(page.getByRole('heading', { name: 'Pick' })).toBeVisible();
await expect(
@@ -59,7 +59,7 @@ test('challenge page', async ({ page }) => {
});
test('reset challenge', async ({ page }) => {
- await page.goto('/challenge/4');
+ await page.goto('/challenge/pick');
await expect(page.getByText('type MyPick<T, K> = any')).toBeVisible();
diff --git a/packages/db/mocks/challenges.mock.ts b/packages/db/mocks/challenges.mock.ts
index e8cad912..8ec52f4a 100644
--- a/packages/db/mocks/challenges.mock.ts
+++ b/packages/db/mocks/challenges.mock.ts
@@ -1,12 +1,9 @@
-import url from 'node:url';
+import { ChallengeStatus, type Difficulty, type Prisma } from '@prisma/client';
import { readdir, readFile, rm } from 'node:fs/promises';
-import fs from 'node:fs';
import { resolve } from 'node:path';
-import { parse } from 'yaml';
-import { faker } from '@faker-js/faker';
import { simpleGit } from 'simple-git';
-import { ChallengeStatus, type Difficulty, type Prisma } from '@prisma/client';
-import { gId, trashId } from '../seed';
+import { parse } from 'yaml';
+import { slugify } from '../seed';
export interface InfoFile {
title: string;
@@ -65,6 +62,7 @@ export async function loadChallengesFromTypeChallenge() {
arr.push({
id: idNum,
name: title,
+ slug: slugify(title),
description: README,
status: ChallengeStatus.ACTIVE,
code: prompt,
@@ -83,77 +81,3 @@ export async function loadChallengesFromTypeChallenge() {
return arr;
}
-
-/**
- * Load markdown file synchronously from the __seed__
- */
-function loadChallengeSync(challengeSlug: string) {
- // read from the __seed__ folder all the markdown files
- const filePath = new URL(`../__seed__/${challengeSlug}.md`, import.meta.url);
- // return the file contents
- return fs.readFileSync(url.fileURLToPath(filePath), 'utf8');
-}
-
-export const CHALLENGE_MAP: Record<
- Difficulty,
- (v: number) => Prisma.ChallengeCreateWithoutUserInput
-> = {
- BEGINNER: () => ({
- name: faker.hacker.phrase(),
- createdAt: faker.date.between({ from: '2022-01-01', to: new Date() }),
- updatedAt: faker.date.between({ from: '2023-05-01', to: new Date() }),
- bookmark: faker.datatype.boolean()
- ? {
- create: {
- userId: faker.datatype.boolean() ? trashId : gId,
- },
- }
- : undefined,
- description: loadChallengeSync('beginner/desc'),
- shortDescription: faker.lorem.lines({ min: 1, max: 2 }),
- tests: '',
- code: '',
- difficulty: 'BEGINNER',
- }),
- EASY: () => ({
- name: faker.hacker.phrase(),
- createdAt: faker.date.between({ from: '2022-01-01', to: new Date() }),
- updatedAt: faker.date.between({ from: '2023-05-01', to: new Date() }),
- description: loadChallengeSync('easy/desc'),
- shortDescription: faker.lorem.lines({ min: 1, max: 2 }),
- tests: loadChallengeSync('easy/prompt'),
- code: '',
- difficulty: 'EASY',
- }),
- MEDIUM: () => ({
- name: faker.hacker.phrase(),
- createdAt: faker.date.between({ from: '2022-01-01', to: new Date() }),
- updatedAt: faker.date.between({ from: '2023-05-01', to: new Date() }),
- description: loadChallengeSync('medium/desc'),
- shortDescription: faker.lorem.lines({ min: 1, max: 2 }),
- prompt: loadChallengeSync('medium/prompt'),
- tests: '',
- code: '',
- difficulty: 'MEDIUM',
- }),
- HARD: () => ({
- name: faker.hacker.phrase(),
- createdAt: faker.date.between({ from: '2022-01-01', to: new Date() }),
- updatedAt: faker.date.between({ from: '2023-05-01', to: new Date() }),
- description: loadChallengeSync('hard/desc'),
- shortDescription: faker.lorem.lines({ min: 1, max: 2 }),
- tests: loadChallengeSync('hard/prompt'),
- code: '',
- difficulty: 'HARD',
- }),
- EXTREME: () => ({
- name: faker.hacker.phrase(),
- createdAt: faker.date.between({ from: '2022-01-01', to: new Date() }),
- updatedAt: faker.date.between({ from: '2023-05-01', to: new Date() }),
- description: loadChallengeSync('extreme/desc'),
- shortDescription: faker.lorem.lines({ min: 1, max: 2 }),
- tests: '',
- code: '',
- difficulty: 'EXTREME',
- }),
-};
diff --git a/packages/db/schema.prisma b/packages/db/schema.prisma
index d416cd01..2d26981c 100644
--- a/packages/db/schema.prisma
+++ b/packages/db/schema.prisma
@@ -152,7 +152,8 @@ model Challenge {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
difficulty Difficulty
- name String
+ name String @unique
+ slug String @unique
/// this is the description to describe the challenge on description panel
description String @db.MediumText
/// this is a short blue thats shown on the explore card
@@ -395,7 +396,8 @@ model TrackChallenge {
model Track {
id Int @id @default(autoincrement())
- title String
+ name String @unique
+ slug String @unique
description String @db.MediumText
visible Boolean @default(true)
trackChallenges TrackChallenge[]
diff --git a/packages/db/seed/index.ts b/packages/db/seed/index.ts
index fa89125d..bf4ff879 100644
--- a/packages/db/seed/index.ts
+++ b/packages/db/seed/index.ts
@@ -7,6 +7,7 @@ import UserMock from '../mocks/user.mock';
const prisma = new PrismaClient();
+export const slugify = (str: string) => str.toLowerCase().replace(/\s/g, '-');
const usersToBeMade = Array.from({ length: 15 }, () => UserMock());
const alotOfSharedSolutions = (challengeId: number) =>
Array.from({ length: 50 }, () => ({
@@ -72,7 +73,8 @@ for (const [index, track] of tracks.entries()) {
const createdTrack = await prisma.track.create({
data: {
- title: track.name,
+ name: track.name,
+ slug: slugify(track.name),
description: track.description,
visible: true,
},
diff --git a/packages/monaco/src/index.tsx b/packages/monaco/src/index.tsx
index ea86e8b6..e39a8533 100644
--- a/packages/monaco/src/index.tsx
+++ b/packages/monaco/src/index.tsx
@@ -20,6 +20,7 @@ export interface CodePanelProps {
challenge: {
id: number;
code: string;
+ slug: string;
tests: string;
};
saveSubmission: (code: string, isSuccessful: boolean) => Promise<void>;
@@ -36,6 +37,7 @@ export type TsErrors = [
];
export function CodePanel(props: CodePanelProps) {
+ console.log({ slug: props.challenge.slug });
const params = useSearchParams();
const router = useRouter();
const pathname = usePathname();
@@ -44,7 +46,7 @@ export function CodePanel(props: CodePanelProps) {
const [tsErrors, setTsErrors] = useState<TsErrors>();
const [isTestPanelExpanded, setIsTestPanelExpanded] = useState(false);
const [localStorageCode, setLocalStorageCode] = useLocalStorage(
- `challenge-${props.challenge.id}`,
+ `challenge-${props.challenge.slug}`,
'',
);