Connect, collaborate, and grow with a community of TypeScript developers
code submissions (#53)
bautistaaa7433aa148c5a
diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 37393569..1f61592f 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -62,21 +62,22 @@ model Session {}model User {- id String @id @default(uuid())- name String?- email String? @unique- role Role @default(USER)- status Status @default(PENDING)- emailVerified DateTime?- image String?- accounts Account[]- sessions Session[]- Challenge Challenge[]- Vote Vote[]- Solution Solution[]- Comment Comment[]- Report Report[]- Bookmark Bookmark[]+ id String @id @default(uuid())+ name String?+ email String? @unique+ role Role @default(USER)+ status Status @default(PENDING)+ emailVerified DateTime?+ image String?+ accounts Account[]+ sessions Session[]+ Challenge Challenge[]+ Vote Vote[]+ Solution Solution[]+ Comment Comment[]+ Report Report[]+ Bookmark Bookmark[]+ SharedSolution SharedSolution[]}model VerificationToken {@@ -88,47 +89,68 @@ model VerificationToken {}model Challenge {- id Int @id @default(autoincrement())- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- difficulty Difficulty- name String- description Json- prompt Json- user User @relation(fields: [userId], references: [id])- userId String- Vote Vote[]- Solution Solution[]- Comment Comment[]- Report Report[]- Bookmark Bookmark[]+ id Int @id @default(autoincrement())+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ difficulty Difficulty+ name String+ description Json+ prompt Json+ user User @relation(fields: [userId], references: [id])+ userId String+ Vote Vote[]+ Solution Solution[]+ Comment Comment[]+ Report Report[]+ Bookmark Bookmark[]+ SharedSolution SharedSolution[]@@index([userId])}model Vote {- id Int @id @default(autoincrement())- user User @relation(fields: [userId], references: [id])- userId String- challenge Challenge? @relation(fields: [challengeId], references: [id])- challengeId Int?- solution Solution? @relation(fields: [solutionId], references: [id])- solutionId Int?+ id Int @id @default(autoincrement())+ user User @relation(fields: [userId], references: [id])+ userId String+ challenge Challenge? @relation(fields: [challengeId], references: [id])+ challengeId Int?+ solution Solution? @relation(fields: [solutionId], references: [id])+ solutionId Int?+ SharedSolution SharedSolution? @relation(fields: [sharedSolutionId], references: [id])+ sharedSolutionId Int?@@index([userId])@@index([challengeId])@@index([solutionId])}-model Solution {- id Int @id @default(autoincrement())- content String- user User @relation(fields: [userId], references: [id])- userId String- challenge Challenge @relation(fields: [challengeId], references: [id])- challengeId Int+model SharedSolution {+ id Int @id @default(autoincrement())+ description Json+ solution Solution @relation(fields: [solutionId], references: [id])+ solutionId IntVote Vote[]+ User User? @relation(fields: [userId], references: [id])+ userId String?+ Challenge Challenge? @relation(fields: [challengeId], references: [id])+ challengeId Int?+ @@index([solutionId])+ @@index([userId])+ @@index([challengeId])+}++model Solution {+ id Int @id @default(autoincrement())+ code Json+ user User @relation(fields: [userId], references: [id])+ userId String+ challenge Challenge @relation(fields: [challengeId], references: [id])+ challengeId Int+ Vote Vote[]+ SharedSolution SharedSolution[]++ @@unique([challengeId, userId])@@index([userId])@@index([challengeId])}diff --git a/src/components/challenge/description-panel.tsx b/src/components/challenge/description-panel.tsxindex d7ab0a5b..4a039031 100644--- a/src/components/challenge/description-panel.tsx+++ b/src/components/challenge/description-panel.tsx@@ -1,33 +1,28 @@'use client';-import type { Bookmark, Challenge, Vote } from '@prisma/client';import { clsx } from 'clsx';-import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';-import remarkGfm from 'remark-gfm';-import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';import { debounce } from 'lodash';import { Bookmark as BookmarkIcon, Share, ThumbsUp } from 'lucide-react';import { useSession } from 'next-auth/react';+import { useRouter } from 'next/navigation';import { useRef, useState } from 'react';import ReactMarkdown from 'react-markdown';-import { useRouter } from 'next/navigation';-import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';-import { incrementOrDecrementUpvote } from './increment.action';-import { TypographyH3 } from '../ui/typography/h3';+import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';+import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';+import remarkGfm from 'remark-gfm';import { DifficultyBadge } from '../explore/difficulty-badge';import { Button } from '../ui/button';import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '../ui/dialog';-import { ShareForm } from './share-form';+import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';+import { TypographyH3 } from '../ui/typography/h3';import { addOrRemoveBookmark } from './bookmark.action';+import { incrementOrDecrementUpvote } from './increment.action';+import { ShareForm } from './share-form';+import { Solutions } from './solutions';+import type { Challenge } from '.';interface Props {- challenge: Challenge & {- Vote: Vote[];- Bookmark: Bookmark[];- _count: {- Vote: number;- };- };+ challenge: NonNullable<Challenge>;}export function DescriptionPanel({ challenge }: Props) {const router = useRouter();@@ -199,13 +194,13 @@ export function DescriptionPanel({ challenge }: Props) {},}}>- {challenge.description}+ {challenge?.description}</ReactMarkdown></div></div></TabsContent><TabsContent value="solutions">- <div className="p-4">solutions</div>+ <Solutions challenge={challenge} /></TabsContent></Tabs></div>diff --git a/src/components/challenge/editor/index.tsx b/src/components/challenge/editor/index.tsxindex 9b88df1b..eea726b5 100644--- a/src/components/challenge/editor/index.tsx+++ b/src/components/challenge/editor/index.tsx@@ -3,6 +3,7 @@import Editor from '@monaco-editor/react';import { Loader2, Settings } from 'lucide-react';import type * as monaco from 'monaco-editor/esm/vs/editor/editor.api';+import { useSession } from 'next-auth/react';import { useTheme } from 'next-themes';import { useMemo, useRef, useState } from 'react';import { Button } from '~/components/ui/button';@@ -15,11 +16,13 @@ import {} from '~/components/ui/dialog';import { ToastAction } from '~/components/ui/toast';import { useToast } from '~/components/ui/use-toast';+import { saveSubmission } from '../save-submission';import { SettingsForm } from '../settings-form';import { useEditorSettingsStore } from '../settings-store';import { libSource } from './editor-types';import { createTwoslashInlayProvider } from './twoslash';import { VimStatusBar } from './vimMode';+import type { Challenge } from '..';const DEFAULT_OPTIONS: monaco.editor.IStandaloneEditorConstructionOptions = {lineNumbers: 'on',@@ -36,18 +39,19 @@ const LIB_URI = 'ts:filename/checking.d.ts';type Monaco = typeof monaco;interface Props {- prompt: string;+ challenge: NonNullable<Challenge>;}const libCache = new Set<string>();-export const CodePanel = ({ prompt }: Props) => {+export const CodePanel = ({ challenge }: Props) => {const { toast } = useToast();const { theme } = useTheme();+ const { data: session } = useSession();const { settings } = useEditorSettingsStore();const [hasErrors, setHasErrors] = useState(false);const [initialTypecheckDone, setInitialTypecheckDone] = useState(false);- const [code, setCode] = useState(prompt);+ const [code, setCode] = useState<string>(challenge?.prompt as string);const editorTheme = theme === 'light' ? 'vs' : 'vs-dark';const modelRef = useRef<monaco.editor.ITextModel>();// ref doesnt cause a rerender@@ -64,7 +68,9 @@ export const CodePanel = ({ prompt }: Props) => {};}, [settings]);- const handleSubmit = () => {+ const handleSubmit = async () => {+ const [, solution] = code.split('/* _____________ Your Code Here _____________ */');+if (hasErrors) {toast({variant: 'destructive',@@ -72,6 +78,11 @@ export const CodePanel = ({ prompt }: Props) => {action: <ToastAction altText="Try again">Try again</ToastAction>,});} else {+ await saveSubmission(+ challenge?.id,+ session?.user?.id as string,+ JSON.stringify(solution) ?? '',+ );toast({variant: 'success',title: 'Good job!',@@ -139,8 +150,6 @@ export const CodePanel = ({ prompt }: Props) => {fixingStart = !fixingStart;}- // @TODO: race condition exists. you can click submit before this is done- // how to gaurd this?typeCheck().catch(console.error);});@@ -155,7 +164,7 @@ export const CodePanel = ({ prompt }: Props) => {return (<div className="col-span-2 flex flex-1 flex-col overflow-hidden rounded-xl border border-zinc-300 dark:border-zinc-700">- <div className="container sticky top-0 flex h-[40px] flex-row-reverse items-center border-b border-zinc-300 py-2 dark:border-zinc-700 dark:bg-[#1e1e1e]">+ <div className="sticky top-0 flex h-[40px] flex-row-reverse items-center border-b border-zinc-300 py-2 dark:border-zinc-700 dark:bg-[#1e1e1e]"><Dialog><DialogTrigger><Settings size={20} className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400" />@@ -176,7 +185,7 @@ export const CodePanel = ({ prompt }: Props) => {options={editorOptions}defaultLanguage="typescript"// eslint-disable-next-line @typescript-eslint/no-misused-promises- onMount={onMount(prompt, setHasErrors)}+ onMount={onMount(code, setHasErrors)}value={code}onChange={(code) => setCode(code ?? '')}/>@@ -188,8 +197,9 @@ export const CodePanel = ({ prompt }: Props) => {<Buttonsize="sm"className="bg-emerald-600 duration-300 hover:bg-emerald-500 dark:bg-emerald-300 dark:hover:bg-emerald-400"+ // eslint-disable-next-line @typescript-eslint/no-misused-promisesonClick={handleSubmit}- disabled={!initialTypecheckDone}+ disabled={!initialTypecheckDone || !session?.user}>{!initialTypecheckDone && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}Submitdiff --git a/src/components/challenge/index.tsx b/src/components/challenge/index.tsxindex 442f7163..465c2c23 100644--- a/src/components/challenge/index.tsx+++ b/src/components/challenge/index.tsx@@ -1,14 +1,34 @@+import { type Session, getServerSession } from 'next-auth';import { notFound } from 'next/navigation';import { prisma } from '~/server/db';import { DescriptionPanel } from './description-panel';import { CodePanel } from './editor';-import { getServerSession } from 'next-auth';interface Props {id: string;}++export type Challenge = Awaited<ReturnType<typeof getChallenge>>;export async function Challenge({ id }: Props) {const session = await getServerSession();+ const challenge = await getChallenge(id, session);+ if (!challenge || typeof challenge.prompt !== 'string') {+ notFound();+ }++ return (+ <div+ className="flex flex-col gap-2 px-4 pb-4 lg:flex-row 2xl:grid 2xl:grid-cols-3"+ style={{ height: 'calc(100dvh - 3.5rem)' }}+ >+ <DescriptionPanel challenge={challenge} />++ <CodePanel challenge={challenge} />+ </div>+ );+}++async function getChallenge(id: string, session: Session | null) {const challenge = await prisma.challenge.findFirst({where: { id: +id },include: {@@ -27,21 +47,19 @@ export async function Challenge({ id }: Props) {challengeId: +id,},},+ Solution: {+ where: {+ userId: session?.user.id,+ challengeId: +id,+ },+ },+ SharedSolution: {+ where: {+ challengeId: +id,+ },+ },},});- if (!challenge || typeof challenge.prompt !== 'string') {- notFound();- }-- return (- <div- className="flex flex-col gap-2 px-4 pb-4 lg:flex-row 2xl:grid 2xl:grid-cols-3"- style={{ height: 'calc(100dvh - 3.5rem)' }}- >- <DescriptionPanel challenge={challenge} />-- <CodePanel prompt={challenge.prompt} />- </div>- );+ return challenge;}diff --git a/src/components/challenge/save-submission.ts b/src/components/challenge/save-submission.tsnew file mode 100644index 00000000..09e2d10b--- /dev/null+++ b/src/components/challenge/save-submission.ts@@ -0,0 +1,21 @@+'use server';+import { prisma } from '~/server/db';++export async function saveSubmission(challengeId: number, userId: string, code: string) {+ await prisma.solution.upsert({+ where: {+ challengeId_userId: {+ challengeId,+ userId,+ },+ },+ update: {+ code,+ },+ create: {+ challengeId,+ userId,+ code,+ },+ });+}diff --git a/src/components/challenge/solutions.tsx b/src/components/challenge/solutions.tsxnew file mode 100644index 00000000..38f9f826--- /dev/null+++ b/src/components/challenge/solutions.tsx@@ -0,0 +1,49 @@+'use client';+import { ArrowUp, MessageCircle, Plus } from 'lucide-react';++import { Button } from '~/components/ui/button';+import { TypographyH3 } from '../ui/typography/h3';+import type { Challenge } from '.';++interface Props {+ challenge: NonNullable<Challenge>;+}+export function Solutions({ challenge }: Props) {+ const hasSolution = challenge.Solution?.length > 0;++ const handleClick = () => {+ console.log('do stuff');+ };++ return (+ <div className="p-4">+ <div className="flex items-center justify-end">+ <Button className="bg-green-400" onClick={handleClick} disabled={!hasSolution}>+ <Plus className="mr-2 h-4 w-4" /> Solution+ </Button>+ </div>+ <div>{/* <SolutionRow /> */}</div>+ </div>+ );+}++function SolutionRow() {+ const date = new Date();+ return (+ <div className="p-4 hover:bg-gray-600">+ <TypographyH3>Some Title</TypographyH3>+ <div className="flex gap-2">+ <div>username goes here</div>+ <div>{date.toLocaleString()}</div>+ </div>+ <div className="flex gap-2">+ <div className="flex">+ <ArrowUp /> 69+ </div>+ <div className="flex">+ <MessageCircle /> 69+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/explore/explore-card.tsx b/src/components/explore/explore-card.tsxindex 2cfd75c6..46468f56 100644--- a/src/components/explore/explore-card.tsx+++ b/src/components/explore/explore-card.tsx@@ -1,11 +1,11 @@import { ArrowBigUp } from 'lucide-react';-import { type Challenges } from '.';+import { type Challenge } from '.';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card';import { DifficultyBadge } from './difficulty-badge';interface Props {- challenge: Awaited<Challenges>[0];+ challenge: Awaited<Challenge>[0];}const BORDERS_BY_DIFFICULTY = {@@ -62,8 +62,9 @@ const getRelativeTime = (date: Date) => {export function ExploreCard({ challenge }: Props) {return (<Card- className={`group duration-300 hover:bg-card-hovered group-focus:bg-card-hovered ${SHADOWS_BY_DIFFICULTY[challenge.difficulty]- } ${BORDERS_BY_DIFFICULTY[challenge.difficulty]}`}+ className={`group duration-300 hover:bg-card-hovered group-focus:bg-card-hovered ${+ SHADOWS_BY_DIFFICULTY[challenge.difficulty]+ } ${BORDERS_BY_DIFFICULTY[challenge.difficulty]}`}><CardHeader className="grid items-start gap-4 space-y-0"><div className="space-y-1">diff --git a/src/components/explore/index.tsx b/src/components/explore/index.tsxindex 858fbab2..1d63c8a6 100644--- a/src/components/explore/index.tsx+++ b/src/components/explore/index.tsx@@ -23,14 +23,14 @@ export function Explore() {</section><Suspense fallback={<ExploreSectionSkeleton />}>- <ExploreSection data={getChallenges} />+ <ExploreSection data={getChallenge} /></Suspense></div>);}-export type Challenges = ReturnType<typeof getChallenges>;-async function getChallenges() {+export type Challenge = ReturnType<typeof getChallenge>;+async function getChallenge() {return prisma.challenge.findMany({include: {_count: {diff --git a/src/components/explore/section.tsx b/src/components/explore/section.tsxindex 9cc005b9..f74103fd 100644--- a/src/components/explore/section.tsx+++ b/src/components/explore/section.tsx@@ -1,9 +1,9 @@import Link from 'next/link';-import type { Challenges } from '.';+import type { Challenge } from '.';import { ExploreCard } from './explore-card';interface Props {- data(): Challenges;+ data(): Challenge;}export async function ExploreSection({ data }: Props) {diff --git a/src/components/ui/table.tsx b/src/components/ui/table.tsxnew file mode 100644index 00000000..152c22d1--- /dev/null+++ b/src/components/ui/table.tsx@@ -0,0 +1,91 @@+import * as React from 'react';++import { cn } from '~/utils/cn';++const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(+ ({ className, ...props }, ref) => (+ <div className="w-full overflow-auto">+ <table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} />+ </div>+ ),+);+Table.displayName = 'Table';++const TableHeader = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />+));+TableHeader.displayName = 'TableHeader';++const TableBody = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />+));+TableBody.displayName = 'TableBody';++const TableFooter = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <tfoot+ ref={ref}+ className={cn('bg-primary font-medium text-primary-foreground', className)}+ {...props}+ />+));+TableFooter.displayName = 'TableFooter';++const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(+ ({ className, ...props }, ref) => (+ <tr+ ref={ref}+ className={cn(+ 'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',+ className,+ )}+ {...props}+ />+ ),+);+TableRow.displayName = 'TableRow';++const TableHead = React.forwardRef<+ HTMLTableCellElement,+ React.ThHTMLAttributes<HTMLTableCellElement>+>(({ className, ...props }, ref) => (+ <th+ ref={ref}+ className={cn(+ 'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',+ className,+ )}+ {...props}+ />+));+TableHead.displayName = 'TableHead';++const TableCell = React.forwardRef<+ HTMLTableCellElement,+ React.TdHTMLAttributes<HTMLTableCellElement>+>(({ className, ...props }, ref) => (+ <td+ ref={ref}+ className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)}+ {...props}+ />+));+TableCell.displayName = 'TableCell';++const TableCaption = React.forwardRef<+ HTMLTableCaptionElement,+ React.HTMLAttributes<HTMLTableCaptionElement>+>(({ className, ...props }, ref) => (+ <caption ref={ref} className={cn('mt-4 text-sm text-muted-foreground', className)} {...props} />+));+TableCaption.displayName = 'TableCaption';++export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };