Skip to content

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

feat: add in-challenge track overview (#806)

Eric Leef23b45407fe7
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts
deleted file mode 100644
index 0995d494..00000000
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/save-submission.action.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-'use server';
-import { getServerAuthSession } from '@repo/auth/server';
-import { prisma } from '@repo/db';
-import { revalidateTag } from 'next/cache';
-import { z } from 'zod';
-
-const submissionSchema = z.object({
- challengeId: z.number(),
- code: z.string(),
- isSuccessful: z.boolean(),
-});
-
-export async function saveSubmission(challengeId: number, code: string, isSuccessful: boolean) {
- submissionSchema.parse({ challengeId, code, isSuccessful });
-
- const session = await getServerAuthSession();
- if (!session) {
- throw new Error('User not authenticated');
- }
-
- await prisma.submission.create({
- data: {
- challengeId,
- userId: session.user.id,
- code,
- isSuccessful,
- },
- });
- revalidateTag(`${challengeId}-challenge-submissions`);
- revalidateTag(`challenge-${challengeId}-solutions`);
-}
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/comments/[commentId]/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/comments/[commentId]/page.tsx
index 13d0e2bb..45e87251 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/comments/[commentId]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/comments/[commentId]/page.tsx
@@ -13,7 +13,7 @@ interface Props {
export default async function CommentPage({ params: { slug, commentId } }: Props) {
const session = await getServerAuthSession();
- const challenge = await getChallengeRouteData(slug, session);
+ const { challenge } = await getChallengeRouteData(slug, session);
const preselectedCommentMetadata = await getPreselectedCommentMetadata(
challenge.id,
Number(commentId),
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/getChallengeRouteData.ts b/apps/web/src/app/[locale]/challenge/[slug]/getChallengeRouteData.ts
index e0889db7..5b8871a2 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/getChallengeRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/[slug]/getChallengeRouteData.ts
@@ -1,12 +1,15 @@
import { type Session } from '@repo/auth/server';
import { prisma } from '@repo/db';
import { cache } from 'react';
+import { getAllFlags } from '~/utils/feature-flags';
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((slug: string, session: Session | null) => {
- return prisma.challenge.findFirstOrThrow({
+export const getChallengeRouteData = cache(async (slug: string, session: Session | null) => {
+ const featureFlags = await getAllFlags();
+
+ const challenge = await prisma.challenge.findFirstOrThrow({
where: {
slug,
status: 'ACTIVE',
@@ -34,4 +37,29 @@ export const getChallengeRouteData = cache((slug: string, session: Session | nul
},
},
});
+
+ /**
+ * Select the first track that the user is enrolled in for this challenge.
+ */
+ const track =
+ featureFlags?.enableInChallengeTrack && session
+ ? await prisma.track.findFirst({
+ where: {
+ trackChallenges: {
+ some: {
+ challengeId: challenge.id,
+ track: {
+ enrolledUsers: {
+ some: {
+ id: session.user.id,
+ },
+ },
+ },
+ },
+ },
+ },
+ })
+ : null;
+
+ return { challenge, track };
});
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/layout.tsx b/apps/web/src/app/[locale]/challenge/[slug]/layout.tsx
index 4e9c6d7b..7f7139b7 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/layout.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/layout.tsx
@@ -1,8 +1,10 @@
+import { ChallengeLayoutWrapper } from '~/app/[locale]/challenge/_components/challenge-layout-wrapper';
+
import { getServerAuthSession } from '@repo/auth/server';
-import { ChallengeLayoutWrapper } from '../_components/challenge-layout-wrapper';
-import { getChallengeRouteData } from './getChallengeRouteData';
import { ForceRenderUntilClient } from '@repo/ui/components/force-render-until-client';
+import { getChallengeRouteData } from './getChallengeRouteData';
+
export default async function LayoutData({
children,
params: { slug },
@@ -11,11 +13,13 @@ export default async function LayoutData({
params: { slug: string };
}) {
const session = await getServerAuthSession();
- const challenge = await getChallengeRouteData(slug, session);
+ const { challenge, track } = await getChallengeRouteData(slug, session);
return (
<ForceRenderUntilClient>
- <ChallengeLayoutWrapper challenge={challenge}>{children}</ChallengeLayoutWrapper>
+ <ChallengeLayoutWrapper challenge={challenge} track={track}>
+ {children}
+ </ChallengeLayoutWrapper>
</ForceRenderUntilClient>
);
}
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/left-wrapper.tsx b/apps/web/src/app/[locale]/challenge/[slug]/left-wrapper.tsx
index b9fe4a29..03d980a5 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/left-wrapper.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/left-wrapper.tsx
@@ -1,23 +1,33 @@
'use client';
+import { usePathname, useRouter } from 'next/navigation';
+import { useMemo, type ReactNode, useRef, useState, useEffect, useContext } from 'react';
+
+import { FeatureFlagContext } from '~/app/feature-flag-provider';
+import { ChallengeTrackNavigation } from '~/app/[locale]/challenge/_components/challenge-track-navigation';
+
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@repo/ui/components/tabs';
+import { cn } from '@repo/ui/cn';
import { FlaskConical, History, Text } from '@repo/ui/icons';
-import { usePathname, useRouter } from 'next/navigation';
-import { useMemo, type ReactNode, useRef, useState, useEffect } from 'react';
+
+import type { ChallengeRouteData } from './getChallengeRouteData';
type Tab = 'description' | 'solutions' | 'submissions';
interface Props {
children: ReactNode;
- slug: string;
+ challenge: ChallengeRouteData['challenge'];
+ track: ChallengeRouteData['track'];
expandPanel: () => void;
isDesktop: boolean;
}
-export function LeftWrapper({ slug, children, expandPanel, isDesktop }: Props) {
+export function LeftWrapper({ children, challenge, track, expandPanel, isDesktop }: Props) {
const pathname = usePathname();
const router = useRouter();
const [isCollapsed, setIsCollapsed] = useState(false);
+ const featureFlags = useContext(FeatureFlagContext);
+
const isCollapsedRef = useRef(isCollapsed);
const isDesktopRef = useRef(isDesktop);
isDesktopRef.current = isDesktop;
@@ -81,62 +91,92 @@ export function LeftWrapper({ slug, children, expandPanel, isDesktop }: Props) {
return 'description';
}, [pathname]);
+ // Hide the enrolled track when in collapsed mobile view.
+ const isTrackFeatureEnabled = featureFlags?.enableInChallengeTrack;
+ const hasEnrolledTrackForChallenge = track !== null;
+ const isTrackVisible =
+ isTrackFeatureEnabled && hasEnrolledTrackForChallenge && (!isCollapsed || isDesktop);
+
+ const isIconOnly = isCollapsed && isDesktop;
+
return (
- <Tabs
- ref={tabsRef}
- className="flex h-full w-full flex-col overflow-hidden"
- defaultValue={selectedTab}
- >
- <TabsList
- className={`bg-background/90 dark:bg-muted/90 sticky top-0 z-10 grid h-auto w-full rounded-none rounded-tl-2xl rounded-tr-xl border-b border-zinc-300 backdrop-blur-sm dark:border-zinc-700 ${
- isCollapsed
- ? isDesktop
- ? 'grid-rows-3 gap-2'
- : 'grid-cols-3 gap-0.5'
- : 'grid-cols-3 gap-0.5'
- }`}
- ref={tabsListRef}
+ <div className="flex h-full w-full flex-col">
+ {Boolean(isTrackVisible) && (
+ <ChallengeTrackNavigation
+ challenge={challenge}
+ track={track}
+ isCollapsed={isCollapsed}
+ className={cn('border-b border-zinc-300 p-1 dark:border-zinc-700')}
+ />
+ )}
+ <Tabs
+ ref={tabsRef}
+ className="flex h-full w-full flex-col overflow-hidden"
+ defaultValue={selectedTab}
>
- <TabsTrigger
- className={`rounded-md rounded-tl-xl duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700 ${
- isCollapsed ? (isDesktop ? 'rounded-r-lg py-4' : 'rounded-bl-xl') : ''
- }`}
- onClick={() => {
- router.push(`/challenge/${slug}`);
- expandPanel();
- }}
- value="description"
- >
- {isCollapsed && isDesktop ? <Text className="h-4 w-4" /> : 'Description'}
- </TabsTrigger>
- <TabsTrigger
- className={`rounded-md duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700 ${
- isCollapsed && isDesktop ? 'py-4' : ''
- }`}
- onClick={() => {
- router.push(`/challenge/${slug}/solutions`);
- expandPanel();
- }}
- value="solutions"
+ <TabsList
+ className={cn(
+ 'bg-background/90 dark:bg-muted/90 sticky top-0 z-10 grid h-auto w-full rounded-none rounded-tl-2xl rounded-tr-xl border-b border-zinc-300 backdrop-blur-sm dark:border-zinc-700',
+ {
+ 'grid-rows-3 gap-2': isIconOnly,
+ 'grid-cols-3 gap-0.5': !isIconOnly,
+ 'rounded-tl-xl': !isTrackVisible,
+ },
+ )}
+ ref={tabsListRef}
>
- {isCollapsed && isDesktop ? <FlaskConical className="h-4 w-4" /> : 'Solutions'}
- </TabsTrigger>
- <TabsTrigger
- className={`rounded-md rounded-tr-lg duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700 ${
- isCollapsed ? (isDesktop ? 'rounded-md py-4' : 'rounded-br-xl') : ''
- }`}
- onClick={() => {
- router.push(`/challenge/${slug}/submissions`);
- expandPanel();
- }}
- value="submissions"
+ <TabsTrigger
+ className={cn(
+ 'rounded-md duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700',
+ {
+ 'p-4': isIconOnly,
+ 'rounded-tl-xl': !isTrackVisible,
+ 'rounded-bl-xl': isCollapsed && !isDesktop,
+ },
+ )}
+ onClick={() => {
+ router.push(`/challenge/${challenge.slug}`);
+ expandPanel();
+ }}
+ value="description"
+ >
+ {isIconOnly ? <Text className="h-4 w-4" /> : 'Description'}
+ </TabsTrigger>
+ <TabsTrigger
+ className={cn(
+ 'rounded-md duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700',
+ { 'p-4': isIconOnly },
+ )}
+ onClick={() => {
+ router.push(`/challenge/${challenge.slug}/solutions`);
+ expandPanel();
+ }}
+ value="solutions"
+ >
+ {isIconOnly ? <FlaskConical className="h-4 w-4" /> : 'Solutions'}
+ </TabsTrigger>
+ <TabsTrigger
+ className={cn(
+ 'rounded-md rounded-tr-lg duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700',
+ { 'p-4': isIconOnly },
+ )}
+ onClick={() => {
+ router.push(`/challenge/${challenge.slug}/submissions`);
+ expandPanel();
+ }}
+ value="submissions"
+ >
+ {isIconOnly ? <History className="h-4 w-4" /> : 'Submissions'}
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent
+ className="mt-0 h-[calc(100%_-_44px)]"
+ value={selectedTab}
+ ref={tabsContentRef}
>
- {isCollapsed && isDesktop ? <History className="h-4 w-4" /> : 'Submissions'}
- </TabsTrigger>
- </TabsList>
- <TabsContent className="mt-0 h-[calc(100%_-_41px)]" value={selectedTab} ref={tabsContentRef}>
- {children}
- </TabsContent>
- </Tabs>
+ {children}
+ </TabsContent>
+ </Tabs>
+ </div>
);
}
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/page.tsx
index 361c7f3c..f52955bb 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/page.tsx
@@ -14,7 +14,7 @@ interface Props {
}
export async function generateMetadata({ params: { slug } }: Props) {
- const challenge = await getChallengeRouteData(slug, null);
+ const { challenge } = await getChallengeRouteData(slug, null);
const description = `Unlock your TypeScript potential by solving the ${challenge.name} challenge on TypeHero.`;
return buildMetaForChallenge({
@@ -27,7 +27,7 @@ export async function generateMetadata({ params: { slug } }: Props) {
}
export default async function Challenges({ params: { slug } }: Props) {
- // early acces you must be authorized
+ // early access you must be authorized
const session = await getServerAuthSession();
const isBeta = await isBetaUser(session);
@@ -35,7 +35,7 @@ export default async function Challenges({ params: { slug } }: Props) {
return redirect('/claim');
}
- const challenge = await getChallengeRouteData(slug, session);
+ const { challenge } = await getChallengeRouteData(slug, session);
return (
<div className="relative h-full ">
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
index 4b1be432..4bfb7d79 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
@@ -14,7 +14,7 @@ interface Props {
}
export async function generateMetadata({ params: { slug } }: Props) {
- const challenge = await getChallengeRouteData(slug, null);
+ const { challenge } = await getChallengeRouteData(slug, null);
return buildMetaForDefault({
title: `Solutions to ${challenge.name} | TypeHero`,
description: challenge.shortDescription,
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
index 0c13d520..5e7f40fa 100644
--- 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
@@ -8,7 +8,7 @@ export const createChallengeSubmissionCacheKey = (slug: string) => {
return `${slug}-challenge-submissions`;
};
interface Args {
- challenge: ChallengeRouteData;
+ challenge: ChallengeRouteData['challenge'];
userId: string;
code: string;
isSuccessful: boolean;
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx b/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
index 7f4bd558..7e9baf74 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
@@ -11,7 +11,11 @@ import type { ChallengeRouteData } from './getChallengeRouteData';
import { SubmissionOverview } from './submissions/[[...catchAll]]/_components/overview';
import { saveSubmission } from './submissions/[[...catchAll]]/save-submission.action';
-export function Wrapper({ challenge }: { challenge: ChallengeRouteData }) {
+interface Props {
+ challenge: ChallengeRouteData['challenge'];
+}
+
+export function Wrapper({ challenge }: Props) {
const segments = useSelectedLayoutSegments();
const { data: session } = useSession();
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 c3de98e7..cc493022 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
@@ -6,13 +6,13 @@ import usePanelAdjustments from './usePanelAdjustments';
import { LeftWrapper } from '../[slug]/left-wrapper';
import { Wrapper } from '../[slug]/wrapper';
-export function ChallengeLayoutWrapper({
- challenge,
- children,
-}: {
- challenge: ChallengeRouteData;
+interface Props {
+ challenge: ChallengeRouteData['challenge'];
+ track: ChallengeRouteData['track'];
children: ReactNode;
-}) {
+}
+
+export function ChallengeLayoutWrapper({ challenge, track, children }: Props) {
const [isDesktop, setIsDesktop] = useState(window.innerWidth > MOBILE_BREAKPOINT);
const LEFT_PANEL_BREAKPOINT = isDesktop ? 500 : 318;
const DEFAULT_DESKTOP_WIDTH_PX = `${LEFT_PANEL_BREAKPOINT}px`;
@@ -32,7 +32,12 @@ export function ChallengeLayoutWrapper({
return (
<ChallengeLayout
left={
- <LeftWrapper slug={challenge.slug} expandPanel={expandPanel} isDesktop={isDesktop}>
+ <LeftWrapper
+ challenge={challenge}
+ track={track}
+ expandPanel={expandPanel}
+ isDesktop={isDesktop}
+ >
{children}
</LeftWrapper>
}
diff --git a/apps/web/src/app/[locale]/challenge/_components/challenge-track-navigation.tsx b/apps/web/src/app/[locale]/challenge/_components/challenge-track-navigation.tsx
new file mode 100644
index 00000000..185d166b
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/_components/challenge-track-navigation.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { useQuery } from '@tanstack/react-query';
+import { useRouter } from 'next/navigation';
+import { useMemo } from 'react';
+
+import { type ChallengeRouteData } from '~/app/[locale]/challenge/[slug]/getChallengeRouteData';
+import { getTrackDetails } from '~/app/[locale]/tracks/_components/track.action';
+
+import { Button } from '@repo/ui/components/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
+import { cn } from '@repo/ui/cn';
+import { Swords, ChevronLeft, ChevronRight } from '@repo/ui/icons';
+
+import { ChallengeTrackOutline } from './challenge-track-outline';
+
+interface Props {
+ challenge: ChallengeRouteData['challenge'];
+ track: ChallengeRouteData['track'];
+ isCollapsed: boolean;
+ className?: string;
+}
+
+export function ChallengeTrackNavigation({ challenge, track, isCollapsed, className }: Props) {
+ const router = useRouter();
+
+ const { data: trackDetails, isLoading } = useQuery({
+ queryKey: ['track-details', track?.slug],
+ queryFn: () => {
+ return getTrackDetails(track!.slug);
+ },
+ enabled: Boolean(track?.slug),
+ });
+
+ const currentIndex = useMemo(() => {
+ if (trackDetails === null || trackDetails === undefined) return null;
+
+ const index = trackDetails.trackChallenges.findIndex((x) => x.challengeId === challenge.id);
+ return index === -1 ? null : index;
+ }, [trackDetails, challenge]);
+
+ const next = useMemo(() => {
+ if (currentIndex === null) return null;
+
+ const index = currentIndex + 1;
+ return index < trackDetails!.trackChallenges.length
+ ? trackDetails!.trackChallenges[index]
+ : null;
+ }, [currentIndex, trackDetails]);
+
+ const previous = useMemo(() => {
+ if (currentIndex === null) return null;
+
+ const index = currentIndex - 1;
+ return index > 0 ? trackDetails!.trackChallenges[index] : null;
+ }, [currentIndex, trackDetails]);
+
+ if (isLoading || track === null || trackDetails === null || trackDetails === undefined)
+ return null;
+
+ return (
+ <div
+ className={cn(
+ {
+ 'flex h-[44px] items-center gap-1': !isCollapsed,
+ 'text-muted-foreground inline-flex h-auto': isCollapsed,
+ },
+ className,
+ )}
+ >
+ <ChallengeTrackOutline challenge={challenge} track={trackDetails} asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn('inline-flex flex-1 gap-2 overflow-hidden rounded-tl-xl', {
+ 'justify-start': !isCollapsed,
+ 'h-full items-center justify-center p-4 hover:bg-neutral-200/50 dark:hover:bg-neutral-700/50':
+ isCollapsed,
+ })}
+ >
+ <Swords className="h-4 w-4 shrink-0" />
+ {Boolean(!isCollapsed) && (
+ <span className="overflow-hidden text-ellipsis whitespace-nowrap">{track.name}</span>
+ )}
+ </Button>
+ </ChallengeTrackOutline>
+ {Boolean(!isCollapsed) && (
+ <>
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={Boolean(!previous)}
+ onClick={() => router.push(`/challenge/${previous!.challenge.slug}`)}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Previous</TooltipContent>
+ </Tooltip>
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={Boolean(!next)}
+ onClick={() => router.push(`/challenge/${next!.challenge.slug}`)}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Next</TooltipContent>
+ </Tooltip>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/app/[locale]/challenge/_components/challenge-track-outline.tsx b/apps/web/src/app/[locale]/challenge/_components/challenge-track-outline.tsx
new file mode 100644
index 00000000..3378e22c
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/_components/challenge-track-outline.tsx
@@ -0,0 +1,94 @@
+'use client';
+
+import Link from 'next/link';
+import { useRouter } from 'next/navigation';
+import { type ReactNode } from 'react';
+
+import type { getTrackDetails } from '~/app/[locale]/tracks/_components/track.action';
+import { TrackChallenge } from '~/app/[locale]/tracks/_components/track-challenge-card';
+import { TrackProgress } from '~/app/[locale]/tracks/_components/track-progress';
+
+import { Button } from '@repo/ui/components/button';
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetTrigger,
+} from '@repo/ui/components/sheet';
+import type { Challenge } from '@repo/db/types';
+import { ChevronRight } from '@repo/ui/icons';
+
+interface Props {
+ children: ReactNode;
+ challenge: Challenge;
+ track: NonNullable<Awaited<ReturnType<typeof getTrackDetails>>>;
+ asChild?: boolean;
+}
+
+export function ChallengeTrackOutline({ children, challenge, track, asChild = false }: Props) {
+ const router = useRouter();
+
+ const trackChallenges = track?.trackChallenges ?? [];
+ const completedTrackChallenges = track.trackChallenges
+ .filter((trackChallenge) => {
+ return (
+ trackChallenge.challenge.submission.length &&
+ trackChallenge.challenge.submission.some((submission) => submission.isSuccessful)
+ );
+ })
+ .map((trackChallenge) => trackChallenge.id);
+ const inProgressTrackChallenges = track.trackChallenges
+ .filter((trackChallenge) => {
+ return (
+ trackChallenge.challenge.submission.length &&
+ trackChallenge.challenge.submission.every((submission) => !submission.isSuccessful)
+ );
+ })
+ .map((trackChallenge) => trackChallenge.id);
+
+ return (
+ <Sheet>
+ <SheetTrigger asChild={asChild}>{children}</SheetTrigger>
+ <SheetContent
+ className="flex w-full flex-col gap-8 overflow-y-scroll sm:max-w-[400px] md:max-w-[540px]"
+ side="left"
+ >
+ <SheetHeader>
+ <SheetTitle>
+ <Button
+ variant="ghost"
+ className="text-foreground flex max-w-full justify-start gap-4 text-lg font-semibold"
+ onClick={() => router.push(`/tracks/${track.slug}`)}
+ >
+ <span className="overflow-hidden text-ellipsis whitespace-nowrap">{track.name}</span>
+ <ChevronRight className="h-4 w-4 shrink-0" />
+ </Button>
+ </SheetTitle>
+ </SheetHeader>
+ <TrackProgress
+ completedChallenges={completedTrackChallenges.length}
+ totalChallenges={trackChallenges.length}
+ />
+ <div className="flex flex-col">
+ {track.trackChallenges.map((trackChallenge) => {
+ return (
+ <Link
+ key={trackChallenge.challenge.id}
+ href={`/challenge/${trackChallenge.challenge.slug}`}
+ >
+ <TrackChallenge
+ challenge={trackChallenge.challenge}
+ isCompleted={completedTrackChallenges.includes(trackChallenge.id)}
+ isInProgress={inProgressTrackChallenges.includes(trackChallenge.id)}
+ isSelected={trackChallenge.challengeId === challenge.id}
+ isCompact
+ />
+ </Link>
+ );
+ })}
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
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 3d5ec7bf..e3868deb 100644
--- a/apps/web/src/app/[locale]/challenge/_components/description/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/_components/description/index.tsx
@@ -28,7 +28,7 @@ import { Markdown } from '@repo/ui/components/markdown';
import { Button } from '@repo/ui/components/button';
interface Props {
- challenge: ChallengeRouteData;
+ challenge: ChallengeRouteData['challenge'];
}
export interface FormValues {
diff --git a/apps/web/src/app/[locale]/tracks/_components/track-challenge-card.tsx b/apps/web/src/app/[locale]/tracks/_components/track-challenge-card.tsx
index c793f573..3cf8b530 100644
--- a/apps/web/src/app/[locale]/tracks/_components/track-challenge-card.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/track-challenge-card.tsx
@@ -1,13 +1,13 @@
'use client';
import { Check, PieChart } from '@repo/ui/icons';
-import clsx from 'clsx';
import { useIsMobile } from '~/utils/useIsMobile';
import type { Challenge, Submission } from '@repo/db/types';
import { Badge } from '@repo/ui/components/badge';
import { DifficultyBadge } from '@repo/ui/components/difficulty-badge';
import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
+import { cn } from '@repo/ui/cn';
interface TrackChallengeProps {
challenge: Challenge & {
@@ -15,6 +15,9 @@ interface TrackChallengeProps {
};
isInProgress: boolean;
isCompleted: boolean;
+ isSelected?: boolean;
+ /* Hide short description in a compact view like the in-challenge track overview */
+ isCompact?: boolean;
}
const BGS_BY_DIFFICULTY = {
@@ -26,7 +29,13 @@ const BGS_BY_DIFFICULTY = {
} as const;
// million-ignore
-export function TrackChallenge({ challenge, isInProgress, isCompleted }: TrackChallengeProps) {
+export function TrackChallenge({
+ challenge,
+ isInProgress,
+ isCompleted,
+ isSelected = false,
+ isCompact = false,
+}: TrackChallengeProps) {
const isMobile = useIsMobile();
return (
@@ -35,14 +44,15 @@ export function TrackChallenge({ challenge, isInProgress, isCompleted }: TrackCh
className="group/challenge flex cursor-pointer flex-col items-center pt-2"
>
<div
- className={clsx(
- `flex w-full items-center justify-between gap-3 rounded-lg`,
- `bg-gradient-to-r from-neutral-500/10 from-70% ${
- BGS_BY_DIFFICULTY[challenge.difficulty]
- } to-100% dark:from-neutral-500/20`,
- ` p-4 py-2 text-black/90 duration-300 group-active/challenge:bg-neutral-500/40 group-active/challenge:duration-75 dark:text-white/90 sm:py-4`,
- !isMobile &&
- 'group-hover/challenge:scale-105 group-hover/challenge:rounded-xl group-hover/challenge:bg-neutral-500/20',
+ className={cn(
+ BGS_BY_DIFFICULTY[challenge.difficulty],
+ 'flex w-full items-center justify-between gap-3 rounded-lg',
+ 'bg-gradient-to-r from-neutral-500/10 from-70% to-100% dark:from-neutral-500/20',
+ 'p-4 py-2 text-black/90 duration-300 group-active/challenge:bg-neutral-500/40 group-active/challenge:duration-75 dark:text-white/90 sm:py-4',
+ {
+ 'group-hover/challenge:scale-105 group-hover/challenge:rounded-xl group-hover/challenge:bg-neutral-500/20':
+ !isMobile,
+ },
)}
>
<div className="w-full flex-col space-y-2">
@@ -59,12 +69,14 @@ export function TrackChallenge({ challenge, isInProgress, isCompleted }: TrackCh
readOnly
/>
<div
- className={clsx(
- 'h-5 w-5 rounded-full border border-black/70 bg-black/10 duration-75 peer-checked:border-transparent dark:border-white/50 dark:bg-white/10 ',
- isCompleted &&
- 'peer-checked:bg-green-600/80 peer-checked:dark:bg-green-300/80',
- isInProgress &&
- 'peer-checked:bg-orange-600/80 peer-checked:dark:bg-orange-300/80',
+ className={cn(
+ 'h-5 w-5 rounded-full border border-black/70 bg-black/10 duration-75 peer-checked:border-transparent dark:border-white/50 dark:bg-white/10',
+ {
+ 'peer-checked:bg-green-600/80 peer-checked:dark:bg-green-300/80':
+ isCompleted,
+ 'peer-checked:bg-orange-600/80 peer-checked:dark:bg-orange-300/80':
+ isInProgress,
+ },
)}
/>
{isCompleted ? (
@@ -81,15 +93,17 @@ export function TrackChallenge({ challenge, isInProgress, isCompleted }: TrackCh
</Tooltip>
<div className="flex flex-col items-start gap-3 md:flex-row">
<div className="flex flex-col gap-2">
- {challenge.name}
+ <span className={cn({ 'text-primary': isSelected })}>{challenge.name}</span>
<div className="flex flex-row gap-3 md:hidden">
<DifficultyBadge difficulty={challenge.difficulty} />
{isCompleted && isMobile ? <Badge variant="outline">Completed</Badge> : null}
</div>
</div>
- <span className="text-muted-foreground">
- {challenge.shortDescription.substring(0, 60).concat('...')}
- </span>
+ {Boolean(!isCompact) && (
+ <span className="text-muted-foreground">
+ {challenge.shortDescription.substring(0, 60).concat('...')}
+ </span>
+ )}
</div>
</div>
<div className="hidden md:block">
@@ -111,14 +125,15 @@ export function MockTrackChallenge({ challenge }: { challenge: Challenge }) {
className="group/challenge flex cursor-pointer flex-col items-center pt-2"
>
<div
- className={clsx(
- `flex w-full items-center justify-between gap-3 overflow-hidden rounded-lg`,
- `bg-gradient-to-r from-neutral-500/10 from-70% ${
- BGS_BY_DIFFICULTY[challenge.difficulty]
- } to-100% dark:from-neutral-500/20`,
- `p-4 py-2 text-black/90 duration-300 group-active/challenge:bg-neutral-500/40 group-active/challenge:duration-75 dark:text-white/90 sm:py-4`,
- !isMobile &&
- 'group-hover/challenge:scale-105 group-hover/challenge:rounded-xl group-hover/challenge:bg-neutral-500/20',
+ className={cn(
+ BGS_BY_DIFFICULTY[challenge.difficulty],
+ 'flex w-full items-center justify-between gap-3 overflow-hidden rounded-lg',
+ 'bg-gradient-to-r from-neutral-500/10 from-70% to-100% dark:from-neutral-500/20',
+ 'p-4 py-2 text-black/90 duration-300 group-active/challenge:bg-neutral-500/40 group-active/challenge:duration-75 dark:text-white/90 sm:py-4',
+ {
+ 'group-hover/challenge:scale-105 group-hover/challenge:rounded-xl group-hover/challenge:bg-neutral-500/20':
+ !isMobile,
+ },
)}
>
<div className="relative flex flex-row items-center gap-3">
diff --git a/apps/web/src/utils/feature-flags.ts b/apps/web/src/utils/feature-flags.ts
index f79cd4cf..da9f1aec 100644
--- a/apps/web/src/utils/feature-flags.ts
+++ b/apps/web/src/utils/feature-flags.ts
@@ -5,6 +5,7 @@ export const mockFlags = {
enableExplore: true,
enableTracks: true,
enableEarlyAccess: false,
+ enableInChallengeTrack: true,
};
export async function getAllFlags() {
diff --git a/packages/db/schema.prisma b/packages/db/schema.prisma
index 2d26981c..acdeff9d 100644
--- a/packages/db/schema.prisma
+++ b/packages/db/schema.prisma
@@ -386,7 +386,7 @@ model TrackChallenge {
orderId Int
challengeId Int
challenge Challenge @relation(fields: [challengeId], references: [id])
- Track Track? @relation(fields: [trackId], references: [id])
+ track Track? @relation(fields: [trackId], references: [id])
trackId Int?
@@unique([challengeId, orderId])
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 65ea0d9d..0233f565 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -5,6 +5,7 @@
"exports": {
"./types": "./src/types.ts",
"./icons": "./src/icons.ts",
+ "./cn": "./src/cn.ts",
"./components/*": "./src/components/*"
},
"typesVersions": {
@@ -15,6 +16,9 @@
"icons": [
"./src/icons.ts"
],
+ "cn": [
+ "./src/cn.ts"
+ ],
"components/*": [
"./src/components/*"
]
diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsx
new file mode 100644
index 00000000..d2951ce6
--- /dev/null
+++ b/packages/ui/src/components/sheet.tsx
@@ -0,0 +1,124 @@
+'use client';
+
+import * as React from 'react';
+import * as SheetPrimitive from '@radix-ui/react-dialog';
+import { cva, type VariantProps } from 'class-variance-authority';
+import { X } from 'lucide-react';
+
+import { cn } from '../cn';
+
+const Sheet = SheetPrimitive.Root;
+
+const SheetTrigger = SheetPrimitive.Trigger;
+
+const SheetClose = SheetPrimitive.Close;
+
+const SheetPortal = ({ className, ...props }: SheetPrimitive.DialogPortalProps) => (
+ <SheetPrimitive.Portal className={cn(className)} {...props} />
+);
+SheetPortal.displayName = SheetPrimitive.Portal.displayName;
+
+const SheetOverlay = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Overlay
+ className={cn(
+ 'bg-background/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 backdrop-blur-sm',
+ className,
+ )}
+ {...props}
+ ref={ref}
+ />
+));
+SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
+
+const sheetVariants = cva(
+ 'fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500',
+ {
+ variants: {
+ side: {
+ top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',
+ bottom:
+ 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
+ left: 'inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm',
+ right:
+ 'inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm',
+ },
+ },
+ defaultVariants: {
+ side: 'right',
+ },
+ },
+);
+
+interface SheetContentProps
+ extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
+ VariantProps<typeof sheetVariants> {}
+
+const SheetContent = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Content>,
+ SheetContentProps
+>(({ side = 'right', className, children, ...props }, ref) => (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
+ {children}
+ <SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none">
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ </SheetPrimitive.Content>
+ </SheetPortal>
+));
+SheetContent.displayName = SheetPrimitive.Content.displayName;
+
+const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div className={cn('flex flex-col space-y-2 text-center sm:text-left', className)} {...props} />
+);
+SheetHeader.displayName = 'SheetHeader';
+
+const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)}
+ {...props}
+ />
+);
+SheetFooter.displayName = 'SheetFooter';
+
+const SheetTitle = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Title
+ ref={ref}
+ className={cn('text-foreground text-lg font-semibold', className)}
+ {...props}
+ />
+));
+SheetTitle.displayName = SheetPrimitive.Title.displayName;
+
+const SheetDescription = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Description
+ ref={ref}
+ className={cn('text-muted-foreground text-sm', className)}
+ {...props}
+ />
+));
+SheetDescription.displayName = SheetPrimitive.Description.displayName;
+
+export {
+ Sheet,
+ SheetPortal,
+ SheetOverlay,
+ SheetTrigger,
+ SheetClose,
+ SheetContent,
+ SheetHeader,
+ SheetFooter,
+ SheetTitle,
+ SheetDescription,
+};