Skip to content

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

Add a `shortDescription` field to a challenge and use ESM (#66)

Sean Boult7bf736e062a8
diff --git a/package.json b/package.json
index 3337da97..b8ae438b 100644
--- a/package.json
+++ b/package.json
@@ -12,6 +12,7 @@
"refresh": "pnpm reset && pnpm prisma db seed",
"typecheck": "tsc --noEmit"
},
+ "type": "module",
"dependencies": {
"@clerk/nextjs": "^4.19.0",
"@hookform/resolvers": "^3.1.1",
diff --git a/prisma/challenges.mock.ts b/prisma/challenges.mock.ts
index 45e78a4c..dd6d791b 100644
--- a/prisma/challenges.mock.ts
+++ b/prisma/challenges.mock.ts
@@ -13,11 +13,15 @@ function randomTrueOrFalse() {
*/
function loadChallenegeSync(challengeSlug: string) {
// read from the __seed__ folder all the markdown files
- //
- const filePath = path.join(__dirname, `../__seed__/${challengeSlug}.md`);
+ const dirname = path.dirname(new URL(import.meta.url).pathname);
+ const filePath = path.join(dirname, `../__seed__/${challengeSlug}.md`);
return fs.readFileSync(filePath, 'utf8');
}
+const shortDescription = `This is a typescript challenge short description area in which we can place text.
+
+ In this challenge you will learn how to do something or at the least you learn how to use \`any\``;
+
export const CHALLENGE_MAP: Record<
Difficulty,
(v: number) => Prisma.ChallengeCreateWithoutUserInput
@@ -28,12 +32,13 @@ export const CHALLENGE_MAP: Record<
updatedAt: new Date(),
Bookmark: randomTrueOrFalse()
? {
- create: {
- userId: randomTrueOrFalse() ? trashId : gId,
- },
- }
+ create: {
+ userId: randomTrueOrFalse() ? trashId : gId,
+ },
+ }
: undefined,
description: loadChallenegeSync('beginner/desc'),
+ shortDescription,
prompt: loadChallenegeSync('beginner/prompt'),
difficulty: 'BEGINNER',
}),
@@ -42,6 +47,7 @@ export const CHALLENGE_MAP: Record<
createdAt: new Date(),
updatedAt: new Date(),
description: loadChallenegeSync('easy/desc'),
+ shortDescription,
prompt: loadChallenegeSync('easy/prompt'),
difficulty: 'EASY',
}),
@@ -50,6 +56,7 @@ export const CHALLENGE_MAP: Record<
createdAt: new Date(),
updatedAt: new Date(),
description: loadChallenegeSync('medium/desc'),
+ shortDescription,
prompt: loadChallenegeSync('medium/prompt'),
difficulty: 'MEDIUM',
}),
@@ -58,6 +65,7 @@ export const CHALLENGE_MAP: Record<
createdAt: new Date(),
updatedAt: new Date(),
description: loadChallenegeSync('hard/desc'),
+ shortDescription,
prompt: loadChallenegeSync('hard/prompt'),
difficulty: 'HARD',
}),
@@ -66,6 +74,7 @@ export const CHALLENGE_MAP: Record<
createdAt: new Date(),
updatedAt: new Date(),
description: loadChallenegeSync('extreme/desc'),
+ shortDescription,
prompt: loadChallenegeSync('extreme/prompt'),
difficulty: 'EXTREME',
}),
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 1f61592f..2acfa545 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -89,21 +89,22 @@ 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[]
- SharedSolution SharedSolution[]
+ id Int @id @default(autoincrement())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ difficulty Difficulty
+ name String
+ description Json
+ shortDescription String
+ 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])
}
diff --git a/prisma/seed.ts b/prisma/seed.ts
index 7d9a4b51..add4dcce 100644
--- a/prisma/seed.ts
+++ b/prisma/seed.ts
@@ -3,13 +3,13 @@ import uuidByString from 'uuid-by-string';
import { CHALLENGE_MAP } from './challenges.mock';
const prisma = new PrismaClient();
-const CHALLENGES_TO_CREATE = 50;
+const CHALLENGES_TO_CREATE = 20;
const DIFFICULTIES = ['BEGINNER', 'EASY', 'MEDIUM', 'HARD', 'EXTREME'];
const randomDifficulty = (): Difficulty => {
return DIFFICULTIES[Math.floor(Math.random() * DIFFICULTIES.length)] as Difficulty;
};
-// TODO: make this deterministic as the seed should always have the same difficulty
+// TODO: make this deterministic as the seed should always have the same difficulty
const challenges = (): Prisma.ChallengeCreateNestedManyWithoutUserInput => ({
create: Array.from({ length: CHALLENGES_TO_CREATE }, (_, challengeIndex) =>
CHALLENGE_MAP[randomDifficulty()](challengeIndex),
@@ -18,7 +18,9 @@ const challenges = (): Prisma.ChallengeCreateNestedManyWithoutUserInput => ({
export const trashId = uuidByString('trash');
export const gId = uuidByString('g');
-async function main() {
+
+// NOTE: we can use top-level await because we are in a module
+try {
await prisma.user.upsert({
where: { id: trashId },
update: {},
@@ -29,6 +31,7 @@ async function main() {
Challenge: challenges(),
},
});
+
await prisma.user.upsert({
where: { id: gId },
update: {},
@@ -39,13 +42,10 @@ async function main() {
Challenge: challenges(),
},
});
+
+ await prisma.$disconnect();
+} catch (e) {
+ console.error(e);
+ await prisma.$disconnect();
+ process.exit(1);
}
-main()
- .then(async () => {
- await prisma.$disconnect();
- })
- .catch(async (e) => {
- console.error(e);
- await prisma.$disconnect();
- process.exit(1);
- });
diff --git a/src/components/challenge/description-panel.tsx b/src/components/challenge/description-panel.tsx
index 697a35cf..ff72b731 100644
--- a/src/components/challenge/description-panel.tsx
+++ b/src/components/challenge/description-panel.tsx
@@ -24,6 +24,7 @@ import type { Challenge } from '.';
interface Props {
challenge: NonNullable<Challenge>;
}
+
export function DescriptionPanel({ challenge }: Props) {
const router = useRouter();
const [votes, setVotes] = useState(challenge._count.Vote);
diff --git a/src/components/explore/explore-card.tsx b/src/components/explore/explore-card.tsx
index 46468f56..238b0b49 100644
--- a/src/components/explore/explore-card.tsx
+++ b/src/components/explore/explore-card.tsx
@@ -1,8 +1,14 @@
+'use client';
+
import { ArrowBigUp } from 'lucide-react';
import { type Challenge } from '.';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card';
import { DifficultyBadge } from './difficulty-badge';
+import ReactMarkdown from 'react-markdown';
+import SyntaxHighlighter from 'react-syntax-highlighter';
+import remarkGfm from 'remark-gfm';
+import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
interface Props {
challenge: Awaited<Challenge>[0];
@@ -52,8 +58,9 @@ const getRelativeTime = (date: Date) => {
const elapsed = date - now;
// "Math.abs" accounts for both "past" & "future" scenarios
+ // @ts-ignore
for (const u in units)
- // @ts-ignore
+ // @ts-ignore
if (Math.abs(elapsed) > units[u] || u == 'second')
// @ts-ignore
return rtf.format(Math.round(elapsed / units[u]), u);
@@ -62,16 +69,42 @@ 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">
- <CardTitle>{challenge.name}</CardTitle>
+ <CardTitle className="pb-4">{challenge.name}</CardTitle>
<CardDescription className="relative h-48 overflow-hidden pb-4">
<div className="pointer-events-none absolute inset-0 h-full w-full shadow-[inset_0_-1.5rem_1rem_-0.5rem_hsl(var(--card))] duration-300 group-hover:shadow-[inset_0_-1.5rem_1rem_-0.5rem_hsl(var(--card-hovered))] group-focus:shadow-[inset_0_-1.5rem_1rem_-0.5rem_hsl(var(--card-hovered))]" />
- {challenge.description?.toString()}
+ {/* // TODO: we use this in two places and we should just make this shared */}
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={{
+ p: ({ ...props }) => <p className="mb-4" {...props} />,
+ code({ inline, className, children, ...props }) {
+ const match = /language-(\w+)/.exec(className || '');
+ return !inline && match ? (
+ <SyntaxHighlighter
+ // @ts-ignore
+ style={vscDarkPlus} // theme
+ className="rounded-xl dark:rounded-md"
+ language={match[1]}
+ PreTag="section" // parent tag
+ {...props}
+ >
+ {String(children).replace(/\n$/, '')}
+ </SyntaxHighlighter>
+ ) : (
+ <code className="rounded-md bg-neutral-200 p-1 font-mono dark:bg-black">
+ {children}
+ </code>
+ );
+ },
+ }}
+ >
+ {challenge?.shortDescription}
+ </ReactMarkdown>
</CardDescription>
</div>
</CardHeader>