Skip to content

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

feat: show suggestions on successful submission (#1052)

Ayush Kumar Yadavb1b4d3a49434
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
index 37c3d867..ffe2967d 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
@@ -2,12 +2,13 @@ import { Button } from '@repo/ui/components/button';
import { Markdown } from '@repo/ui/components/markdown';
import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
import { toast } from '@repo/ui/components/use-toast';
-import { Copy, X } from '@repo/ui/icons';
+import { CheckCircle2, Copy, X, XCircle } from '@repo/ui/icons';
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';
+import { useParams, useSearchParams } from 'next/navigation';
+import { Suggestions } from './suggestions';
interface Props {
submissionId: string;
@@ -19,13 +20,18 @@ ${code}`;
export function SubmissionOverview({ submissionId }: Props) {
const { slug } = useParams();
+ const searchParams = useSearchParams();
+
+ const showSuggestions = searchParams.get('success') === 'true';
const { data: submission } = useQuery({
- queryKey: ['submission', submissionId],
+ queryKey: [`submission`, submissionId],
queryFn: () => getChallengeSubmissionById(submissionId),
});
const code = codifyForMarkdown(submission?.code.trimStart() ?? '');
+ const track = searchParams.get('slug');
+
const copyToClipboard = async () => {
if (navigator.clipboard) {
await navigator.clipboard.writeText(submission?.code ?? '').catch(console.error);
@@ -58,18 +64,30 @@ export function SubmissionOverview({ submissionId }: Props) {
<div className="p-2">
<div className="mb-5">
<div
- className={`inline-block rounded-xl px-4 py-1 ${
+ className={`flex items-center gap-1 py-1 ${
submission.isSuccessful
- ? 'bg-emerald-600/10 text-emerald-600 dark:bg-emerald-400/10 dark:text-emerald-400 '
- : 'bg-rose-600/10 text-rose-600 dark:bg-rose-400/10 dark:text-rose-400 '
+ ? ' text-emerald-600 dark:text-emerald-400 '
+ : ' text-rose-600 dark:text-rose-400 '
}`}
>
+ {submission.isSuccessful ? (
+ <CheckCircle2 size={17} className="mb-0.5" />
+ ) : (
+ <XCircle size={17} className="mb-0.5" />
+ )}
{submission.isSuccessful ? 'Accepted' : 'Rejected'}
</div>
- <div className="text-sm text-neutral-500">{getRelativeTime(submission.createdAt)}</div>
+ <div className="text-sm text-neutral-500">
+ Submitted {getRelativeTime(submission.createdAt)}
+ </div>
</div>
<Markdown>{code}</Markdown>
</div>
+ {showSuggestions ? (
+ <div className="flex h-full w-full items-start justify-center">
+ <Suggestions track={track} challengeId={submission.challengeId} />
+ </div>
+ ) : null}
</>
);
}
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/suggestions.tsx b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/suggestions.tsx
new file mode 100644
index 00000000..e67f86e1
--- /dev/null
+++ b/apps/web/src/app/[locale]/challenge/[slug]/submissions/[[...catchAll]]/_components/suggestions.tsx
@@ -0,0 +1,108 @@
+'use client';
+import { Button } from '@repo/ui/components/button';
+import type { ChallengeRouteData } from '../../../getChallengeRouteData';
+import { ChevronRight, Swords } from '@repo/ui/icons';
+import { useQuery } from '@tanstack/react-query';
+import { useMemo } from 'react';
+import { getTrackDetails } from '~/app/[locale]/tracks/_components/track.action';
+import { TrackChallenge } from '~/app/[locale]/tracks/_components/track-challenge-card';
+import { getSimilarChallenges } from '~/utils/server/get-similar-challenges';
+import Link from 'next/link';
+
+interface SuggestionsProps {
+ track: string | null;
+ challengeId: number;
+}
+
+export function Suggestions({ track, challengeId }: SuggestionsProps) {
+ // Get challenges in current track
+ const { data: trackDetails } = useQuery({
+ queryKey: ['track-details', track],
+ queryFn: () => {
+ return getTrackDetails(track!);
+ },
+ enabled: Boolean(track),
+ });
+
+ // Get suggested challenges
+ const { data: similarChallenges } = useQuery({
+ queryKey: ['similar-challenges', challengeId],
+ queryFn: () => {
+ return getSimilarChallenges(challengeId);
+ },
+ });
+
+ const currentIndex = useMemo(() => {
+ if (trackDetails === null || trackDetails === undefined) return null;
+
+ const index = trackDetails.trackChallenges.findIndex((x) => x.challengeId === challengeId);
+ return index === -1 ? null : index;
+ }, [trackDetails, challengeId]);
+
+ // Get next challenge in Track
+ const next = useMemo(() => {
+ if (currentIndex === null) return null;
+
+ const index = currentIndex + 1;
+ return index < trackDetails!.trackChallenges.length
+ ? trackDetails!.trackChallenges[index]
+ : null;
+ }, [currentIndex, trackDetails]);
+
+ return (
+ <div className="w-full max-w-[1000px] md:p-4 md:pb-8">
+ {trackDetails && next ? (
+ <>
+ <div className="flex items-center justify-between p-3">
+ <h2 className="text-foreground/70 flex items-center gap-2 text-xl font-bold md:text-2xl">
+ <Swords className="h-8 w-8" />
+ {`Next Up in ${trackDetails?.name}`}
+ </h2>
+ <Link href={`/tracks/${track}`}>
+ <Button size="sm" className="gap-1 rounded-full" variant="outline">
+ More <ChevronRight size={13} />
+ </Button>
+ </Link>
+ </div>
+ <div className="px-6">
+ <Link href={`/challenge/${next.challenge.slug}`}>
+ <TrackChallenge
+ challenge={next.challenge}
+ isInProgress={false}
+ hideSubmissionStatus
+ isCompleted={false}
+ />
+ </Link>
+ </div>
+ </>
+ ) : null}
+
+ {similarChallenges ? (
+ <>
+ <div className="mt-2 flex items-center justify-between p-3">
+ <h2 className="text-foreground/70 text-xl font-bold md:text-2xl">More Challenges</h2>
+ <Link href="/explore">
+ <Button size="sm" className="gap-1 rounded-full" variant="outline">
+ Explore <ChevronRight size={13} />
+ </Button>
+ </Link>
+ </div>
+ <div className="px-6">
+ {similarChallenges?.map((challenge, idx) => {
+ return (
+ <Link href={`/challenge/${challenge.slug}`} key={idx}>
+ <TrackChallenge
+ challenge={{ ...challenge, submission: [] }}
+ hideSubmissionStatus
+ isCompleted={false}
+ isInProgress={false}
+ />
+ </Link>
+ );
+ })}
+ </div>
+ </>
+ ) : null}
+ </div>
+ );
+}
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 a8acb054..76b6379b 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
@@ -23,7 +23,7 @@ interface Args {
isSuccessful: boolean;
}
export async function saveSubmission({ challenge, userId, code, isSuccessful }: Args) {
- await prisma.submission.create({
+ const submission = await prisma.submission.create({
data: {
challengeId: challenge.id,
userId,
@@ -35,4 +35,5 @@ export async function saveSubmission({ challenge, userId, code, isSuccessful }:
revalidateTag(createCacheKeyForSolutions(challenge.slug));
revalidateTag(createInProgressSubmissionCacheKey(userId));
revalidateTag(createCompletedSubmissionCacheKey(userId));
+ return submission;
}
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx b/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
index 7e9baf74..088b0aa7 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/wrapper.tsx
@@ -1,8 +1,8 @@
'use client';
import { useSession } from '@repo/auth/react';
import { CodePanel } from '@repo/monaco';
-import { track } from '@vercel/analytics';
-import { useSelectedLayoutSegments } from 'next/navigation';
+import { track as vercelTrack } from '@vercel/analytics';
+import { useRouter, useSelectedLayoutSegments } from 'next/navigation';
import { EditorShortcutsButton } from '../_components/editor-shortcuts/editor-shortcuts-button';
import { FullscreenButton } from '../_components/fullscreen';
import { ResetEditorButton } from '../_components/reset-editor-button';
@@ -13,9 +13,11 @@ import { saveSubmission } from './submissions/[[...catchAll]]/save-submission.ac
interface Props {
challenge: ChallengeRouteData['challenge'];
+ track: ChallengeRouteData['track'];
}
-export function Wrapper({ challenge }: Props) {
+export function Wrapper({ track, challenge }: Props) {
+ const router = useRouter();
const segments = useSelectedLayoutSegments();
const { data: session } = useSession();
@@ -25,20 +27,33 @@ export function Wrapper({ challenge }: Props) {
return <SubmissionOverview submissionId={segments[1]} />;
}
+ // Redirect to solution on successful submission and show suggestions
+ async function handleSuccessfulSubmission(
+ isSuccessful: boolean,
+ submissionId: number,
+ slug?: string,
+ ) {
+ const query = slug ? `&slug=${slug}` : '';
+ isSuccessful &&
+ router.push(`/challenge/${challenge.slug}/submissions/${submissionId}?success=true${query}`);
+ }
+
return (
<CodePanel
challenge={challenge}
- saveSubmission={(code, isSuccessful) => {
- track?.('challenge-submitted', {
+ saveSubmission={async (code, isSuccessful) => {
+ vercelTrack?.('challenge-submitted', {
success: !isSuccessful,
});
- return saveSubmission({
+ const submission = await saveSubmission({
challenge,
userId: session?.user.id!,
code,
isSuccessful,
});
+
+ return handleSuccessfulSubmission(submission.isSuccessful, submission.id, track?.slug);
}}
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 cc493022..ff50ae41 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
@@ -41,7 +41,7 @@ export function ChallengeLayoutWrapper({ challenge, track, children }: Props) {
{children}
</LeftWrapper>
}
- right={<Wrapper challenge={challenge} />}
+ right={<Wrapper track={track} challenge={challenge} />}
{...props}
/>
);
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 b82142d1..a1475c6e 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
@@ -18,6 +18,8 @@ interface TrackChallengeProps {
isSelected?: boolean;
/* Hide short description in a compact view like the in-challenge track overview */
isCompact?: boolean;
+ /* Hide submission status */
+ hideSubmissionStatus?: boolean;
}
const BGS_BY_DIFFICULTY = {
@@ -35,6 +37,7 @@ export function TrackChallenge({
isCompleted,
isSelected = false,
isCompact = false,
+ hideSubmissionStatus = false,
}: TrackChallengeProps) {
const isMobile = useIsMobile();
const backgroundColor = isCompleted
@@ -66,34 +69,36 @@ export function TrackChallenge({
<div className="w-full space-y-2">
<div className="flex w-full flex-row justify-between">
<div className="flex w-full flex-row gap-3">
- <Tooltip>
- <TooltipTrigger asChild>
- <div className="relative hidden gap-3 pr-1.5 pt-2 md:flex md:flex-row lg:items-center lg:pr-0 lg:pt-0">
- <input
- className="peer hidden appearance-none"
- type="checkbox"
- id={challenge.id.toString()}
- checked={isCompleted || isInProgress}
- readOnly
- />
- <div
- 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',
- backgroundColor,
- )}
- />
- {isCompleted ? (
- <Check className="absolute left-1 my-auto h-3.5 w-3.5 scale-0 stroke-[4] text-white duration-300 peer-checked:scale-100 dark:text-black" />
- ) : null}
- {isInProgress ? (
- <PieChart className="absolute left-1 my-auto h-3 w-3 scale-0 stroke-[4] text-white duration-300 peer-checked:scale-100 dark:text-black" />
- ) : null}
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>{isCompleted ? 'Completed' : isInProgress ? 'Attempted' : 'Todo'}</p>
- </TooltipContent>
- </Tooltip>
+ {!hideSubmissionStatus && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="relative hidden gap-3 pr-1.5 pt-2 md:flex md:flex-row lg:items-center lg:pr-0 lg:pt-0">
+ <input
+ className="peer hidden appearance-none"
+ type="checkbox"
+ id={challenge.id.toString()}
+ checked={isCompleted || isInProgress}
+ readOnly
+ />
+ <div
+ 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',
+ backgroundColor,
+ )}
+ />
+ {isCompleted ? (
+ <Check className="absolute left-1 my-auto h-3.5 w-3.5 scale-0 stroke-[4] text-white duration-300 peer-checked:scale-100 dark:text-black" />
+ ) : null}
+ {isInProgress ? (
+ <PieChart className="absolute left-1 my-auto h-3 w-3 scale-0 stroke-[4] text-white duration-300 peer-checked:scale-100 dark:text-black" />
+ ) : null}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{isCompleted ? 'Completed' : isInProgress ? 'Attempted' : 'Todo'}</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
<div className="flex w-full flex-col items-start gap-3 lg:flex-row">
<div className="flex w-full justify-between gap-2 text-lg font-bold lg:w-auto lg:text-base lg:font-normal">
<span className={cn({ 'font-bold': isSelected })}>{challenge.name}</span>
diff --git a/apps/web/src/utils/server/get-similar-challenges.ts b/apps/web/src/utils/server/get-similar-challenges.ts
new file mode 100644
index 00000000..f0e7ad5a
--- /dev/null
+++ b/apps/web/src/utils/server/get-similar-challenges.ts
@@ -0,0 +1,63 @@
+'use server';
+import { getServerAuthSession } from '@repo/auth/server';
+import { prisma } from '@repo/db';
+import type { Challenge } from '@repo/db/types';
+
+/**
+ * Get similar **unsolved** challenges for the given challengeId
+ * 1. Get challenges with same `difficulty` that are unsolved
+ * 2. Get random unsolved challenges if no problems exist for same `difficulty` that are unsolved
+ * @param {number} challengeId challengeId of the challenge
+ * @param {number} [maxChallenges=2] maximum number of similar challenges to return records to find
+ * @returns {Promise<Challenge[]>} challenge array promise
+ */
+export async function getSimilarChallenges(
+ challengeId: number,
+ maxChallenges = 2,
+): Promise<Challenge[]> {
+ try {
+ const session = await getServerAuthSession();
+ const { difficulty } = await prisma.challenge.findFirstOrThrow({
+ where: {
+ id: challengeId,
+ },
+ });
+
+ const solvedSolutions = await prisma.submission.findMany({
+ where: {
+ userId: session?.user.id,
+ isSuccessful: true,
+ },
+ select: {
+ challengeId: true,
+ },
+ });
+
+ const challengesByDifficulty = await prisma.challenge.findMany({
+ where: {
+ difficulty,
+ id: {
+ notIn: solvedSolutions.flatMap((solution) => solution.challengeId),
+ },
+ },
+ take: maxChallenges,
+ });
+
+ if (!challengesByDifficulty.length) {
+ const firstUnsolved = await prisma.challenge.findMany({
+ where: {
+ id: {
+ notIn: solvedSolutions.flatMap((solution) => solution.challengeId),
+ },
+ },
+ take: maxChallenges,
+ });
+ return firstUnsolved;
+ }
+
+ return challengesByDifficulty;
+ } catch (e) {
+ console.log(e);
+ return [];
+ }
+}