Skip to content

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

Wizard (#286)

bautistaaacc547df68e88
diff --git a/src/app/admin/report/[id]/page.tsx b/src/app/admin/report/[id]/page.tsx
index 280a8ab9..ec458dbd 100644
--- a/src/app/admin/report/[id]/page.tsx
+++ b/src/app/admin/report/[id]/page.tsx
@@ -1,13 +1,13 @@
-import { redirect } from 'next/navigation';
-import Text from '~/components/ui/typography/typography';
+import { AlertCircle, ThumbsUp } from 'lucide-react';
import Link from 'next/link';
+import { redirect } from 'next/navigation';
+import { getChallenge } from '~/components/admin/admin.actions';
+import { Alert, AlertDescription, AlertTitle } from '~/components/ui/alert';
+import { CodeEditor } from '~/components/ui/code-editor';
import { Markdown } from '~/components/ui/markdown';
-import Editor from '~/components/ui/editor';
+import Text from '~/components/ui/typography/typography';
import { UserBadge } from '~/components/ui/user-badge';
-import { AlertCircle, ThumbsUp } from 'lucide-react';
-import { Alert, AlertDescription, AlertTitle } from '~/components/ui/alert';
import ReportActions from './actions';
-import { getChallenge } from '~/components/admin/admin.actions';
export interface Props {
params: {
@@ -105,7 +105,7 @@ const Report = async function (props: Props) {
<Markdown className="mt-4">{challenge.description}</Markdown>
</div>
<div className="w-full md:w-1/2">
- <Editor value={challenge.prompt} />
+ <CodeEditor value={challenge.prompt} />
</div>
</section>
</div>
diff --git a/src/app/challenge/[id]/wrapper.tsx b/src/app/challenge/[id]/wrapper.tsx
index d205dee0..7aa87f23 100644
--- a/src/app/challenge/[id]/wrapper.tsx
+++ b/src/app/challenge/[id]/wrapper.tsx
@@ -1,6 +1,6 @@
'use client';
import { useSelectedLayoutSegments } from 'next/navigation';
-import { CodePanel } from '~/components/challenge/editor';
+import { CodePanel } from '~/components/challenge/code-panel';
import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';
import { SubmissionOverview } from '~/components/challenge/submissions/overview';
@@ -13,5 +13,5 @@ export function Wrapper({ challenge }: { challenge: ChallengeRouteData }) {
return <SubmissionOverview submissionId={segments[1]} />;
}
- return <CodePanel mode="solve" challenge={challenge} />;
+ return <CodePanel challenge={challenge} />;
}
diff --git a/src/app/create/create-challenge-store.ts b/src/app/create/create-challenge-store.ts
deleted file mode 100644
index 535428b9..00000000
--- a/src/app/create/create-challenge-store.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import type { Prisma } from '@prisma/client';
-import { create } from 'zustand';
-import { persist } from 'zustand/middleware';
-
-export type CreateChallengeInputData = Pick<
- Prisma.ChallengeCreateInput,
- 'name' | 'difficulty' | 'shortDescription' | 'description' | 'prompt'
->;
-
-export type CreateChallengeState = {
- data: CreateChallengeInputData | undefined;
- setData: (data: CreateChallengeInputData) => void;
- clear: () => void;
-};
-
-export const useCreateChallengeStore = create<CreateChallengeState>()(
- persist(
- (set, _get) => ({
- data: undefined,
- clear: () => set({ data: undefined }),
- setData: (data) => set({ data }),
- }),
- {
- name: 'create-challenge-data',
- },
- ),
-);
diff --git a/src/app/create/create-validator.ts b/src/app/create/create-validator.ts
deleted file mode 100644
index 487c6b45..00000000
--- a/src/app/create/create-validator.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { z } from 'zod';
-import { type CreateChallengeState } from './create-challenge-store';
-
-type MapToZod<T> = {
- [K in keyof T]: z.ZodType<T[K]>;
-};
-
-// TODO: Select better `.min(...).max(...)`
-export const createChallengeValidator = z.object<
- MapToZod<NonNullable<CreateChallengeState['data']>>
->({
- name: z
- .string()
- .min(3, 'The name must be longer than 3 characters')
- .max(30, 'The name must be shorter than 30 characters'),
- prompt: z.string().max(65536),
- difficulty: z.enum(['BEGINNER', 'EASY', 'MEDIUM', 'HARD', 'EXTREME']),
- description: z.string().min(20, 'The description must be longer than 20 characters').max(65536),
- shortDescription: z
- .string()
- .min(10, 'The short description must be longer than 10 characters')
- .max(191, 'The short description must be shorter than 191 characters'),
-});
diff --git a/src/app/create/default-challenge.md b/src/app/create/default-challenge.md
deleted file mode 100644
index 4ea7eea2..00000000
--- a/src/app/create/default-challenge.md
+++ /dev/null
@@ -1,27 +0,0 @@
-// TEST CASE START (code in test cases are not editable)
-type cases = [
- Expect<Equal<Expected1, MyPick<Todo, 'title'>>>,
- Expect<Equal<Expected2, MyPick<Todo, 'title' | 'completed'>>>
-]
-
-
-// @ts-expect-error
-MyPick<Todo, 'title' | 'completed' | 'invalid'>
-
-interface Todo {
- title: string
- description: string
- completed: boolean
-}
-
-interface Expected1 {
- title: string
-}
-
-interface Expected2 {
- title: string
- completed: boolean
-}
-
-// CODE START (code below this line is editable)
-type MyPick<T, K> = any;
diff --git a/src/app/create/default-description.md b/src/app/create/default-description.md
deleted file mode 100644
index 911fa026..00000000
--- a/src/app/create/default-description.md
+++ /dev/null
@@ -1,21 +0,0 @@
-### Description
-Implement the built-in `Pick<T, K>` generic without using it.
-
-Constructs a type by picking the set of properties `K` from `T`
-
-For example:
-
-```ts
- interface Todo {
- title: string
- description: string
- completed: boolean
- }
-
- type TodoPreview = MyPick<Todo, 'title' | 'completed'>
-
- const todo: TodoPreview = {
- title: 'Clean room',
- completed: false,
- }
-```
diff --git a/src/app/create/page.tsx b/src/app/create/page.tsx
deleted file mode 100644
index a973ce0f..00000000
--- a/src/app/create/page.tsx
+++ /dev/null
@@ -1,149 +0,0 @@
-'use client';
-
-import { ChallengeLayout } from '~/components/challenge/challenge-layout';
-import { CodePanel } from '~/components/challenge/editor';
-import { useState } from 'react';
-import { Checkbox } from '~/components/ui/checkbox';
-import { Label } from '~/components/ui/label';
-import { Markdown } from '~/components/ui/markdown';
-import { useCreateChallengeStore } from './create-challenge-store';
-import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';
-import { useToast } from '~/components/ui/use-toast';
-import { ToastAction } from '@radix-ui/react-toast';
-import { useRouter } from 'next/navigation';
-import DEFAULT_DESCRIPTION from './default-description.md';
-import DEFAULT_CHALLENGE_TEMPLATE from './default-challenge.md';
-
-import { type Difficulty } from '@prisma/client';
-import ExploreCardInputs from '~/components/create/explore-card-inputs';
-
-import { useTheme } from 'next-themes';
-import { RichMarkdownEditor } from '~/components/ui/rich-markdown-editor';
-import { createChallengeValidator } from './create-validator';
-
-export default function CreateChallenge() {
- const createChallengeStore = useCreateChallengeStore();
- const [isPreviewing, setIsPreviewing] = useState({
- description: false,
- });
- const [description, setDescription] = useState(
- createChallengeStore.data?.description ?? DEFAULT_DESCRIPTION,
- );
- const [difficulty, setDifficulty] = useState<Difficulty | 'BEGINNER'>(
- createChallengeStore.data?.difficulty || 'BEGINNER',
- );
- const [shortDescription, setShortDescription] = useState(
- createChallengeStore.data?.shortDescription ?? '',
- );
- const [name, setName] = useState(createChallengeStore.data?.name ?? '');
-
- const router = useRouter();
-
- const { toast } = useToast();
-
- function onSubmit(prompt: string) {
- const parseResult = createChallengeValidator.safeParse({
- name,
- description,
- shortDescription,
- difficulty,
- prompt,
- });
-
- if (!parseResult.success) {
- for (const error of parseResult.error.errors) {
- toast({
- title: error.message,
- variant: 'destructive',
- action: <ToastAction altText="dismiss">Dismiss</ToastAction>,
- });
- }
-
- return;
- }
-
- createChallengeStore.setData(parseResult.data);
-
- router.push('/create/preview');
- }
-
- const { theme } = useTheme();
- theme == 'dark'
- ? document.documentElement.setAttribute('data-color-mode', 'dark')
- : document.documentElement.setAttribute('data-color-mode', 'light');
-
- return (
- <ChallengeLayout
- left={
- <Tabs
- defaultValue="card-editor"
- className="flex h-full w-full flex-col border-zinc-300 dark:border-zinc-700"
- >
- <TabsList className="sticky top-0 z-10 grid h-auto w-full grid-cols-2 rounded-none border-b border-zinc-300 bg-background/90 backdrop-blur-sm dark:border-zinc-700 dark:bg-muted/90">
- <TabsTrigger
- value="card-editor"
- className="rounded-md rounded-tl-xl duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
- >
- Card Editor
- </TabsTrigger>
- <TabsTrigger
- value="challenge-description"
- className="rounded-md rounded-tr-lg duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
- >
- Challenge Description
- </TabsTrigger>
- </TabsList>
- <TabsContent
- value="card-editor"
- className="mt-0 flex flex-1 flex-col p-4 dark:bg-muted [&[hidden]]:hidden"
- >
- <ExploreCardInputs
- name={name}
- setName={setName}
- difficulty={difficulty}
- setDifficulty={setDifficulty}
- shortDescription={shortDescription}
- setShortDescription={setShortDescription}
- />
- </TabsContent>
- <TabsContent
- value="challenge-description"
- className="relative mt-0 flex flex-1 flex-col dark:bg-muted [&[hidden]]:hidden"
- >
- <div className="absolute bottom-4 right-4 z-10 flex items-center justify-end">
- <Label
- htmlFor="previewLong"
- className="flex cursor-pointer gap-2 text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
- >
- Preview:
- <Checkbox
- id="previewLong"
- className="border-zinc-500"
- checked={isPreviewing.description}
- onCheckedChange={(checked) =>
- setIsPreviewing((rest) => ({ ...rest, description: checked === true }))
- }
- />
- </Label>
- </div>
- {isPreviewing.description ? (
- <div className="prose-invert flex-1 px-3 py-1 leading-8 prose-h3:text-xl">
- <Markdown>{description}</Markdown>
- </div>
- ) : (
- <RichMarkdownEditor onChange={(val) => setDescription(val)} value={description} />
- )}
- </TabsContent>
- </Tabs>
- }
- right={
- <CodePanel
- mode="create"
- onSubmit={onSubmit}
- submitText="Preview"
- prompt={createChallengeStore.data?.prompt ?? DEFAULT_CHALLENGE_TEMPLATE}
- />
- }
- />
- );
-}
diff --git a/src/app/create/preview/page.tsx b/src/app/create/preview/page.tsx
deleted file mode 100644
index 1cecf3b6..00000000
--- a/src/app/create/preview/page.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-'use client';
-
-import { ChallengeLayout } from '~/components/challenge/challenge-layout';
-import { useCreateChallengeStore } from '../create-challenge-store';
-import { useRouter } from 'next/navigation';
-import { CodePanel } from '~/components/challenge/editor';
-import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';
-import { Markdown } from '~/components/ui/markdown';
-import ExploreCard from '~/components/explore/explore-card';
-import { Button } from '~/components/ui/button';
-import { uploadChallenge } from '../create.action';
-import { useState } from 'react';
-import { useSession } from 'next-auth/react';
-
-export default function PreviewCreatedChallenge() {
- const createChallengeStore = useCreateChallengeStore();
- const router = useRouter();
- const user = useSession();
- const [isRedirecting, setIsRedirecting] = useState(false);
-
- if (createChallengeStore.data === undefined) {
- if (!isRedirecting) {
- router.replace('/create');
- }
-
- // TODO: show some ui when isRedirecting
- return;
- }
-
- async function publishChallenge() {
- console.log(createChallengeStore.data);
-
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- const { id } = await uploadChallenge(createChallengeStore.data!);
-
- // TODO: add guard in case the upload fails
- createChallengeStore.clear();
-
- router.push(`/challenge/${id}`);
-
- setIsRedirecting(true);
- }
-
- return (
- <ChallengeLayout
- left={
- <Tabs
- defaultValue="card"
- className="flex h-full w-full flex-col border-zinc-300 dark:border-zinc-700"
- >
- <TabsList className="sticky top-0 z-10 grid h-auto w-full grid-cols-2 rounded-none border-b border-zinc-300 bg-background/90 backdrop-blur-sm dark:border-zinc-700 dark:bg-muted/90">
- <TabsTrigger
- value="card"
- className="rounded-md rounded-tl-xl duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
- >
- Card
- </TabsTrigger>
- <TabsTrigger
- value="description"
- className="rounded-md rounded-tr-lg duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
- >
- Description
- </TabsTrigger>
- </TabsList>
- <TabsContent
- value="description"
- className="mt-0 flex flex-1 flex-col gap-3 p-4 dark:bg-muted [&[hidden]]:hidden"
- >
- <div className="prose-invert flex-1 leading-8 prose-h3:text-xl">
- <Markdown>{createChallengeStore.data.description}</Markdown>
- </div>
- </TabsContent>
- <TabsContent
- value="card"
- className="mt-0 flex flex-1 flex-col gap-3 p-4 dark:bg-background [&[hidden]]:hidden"
- >
- <ExploreCard
- challenge={{
- ...createChallengeStore.data,
- _count: {
- vote: 420,
- comment: 0,
- },
- // @ts-ignore
- user: user?.data?.user || { name: 'you' },
- updatedAt: new Date(),
- difficulty: createChallengeStore.data.difficulty,
- }}
- />
- </TabsContent>
- </Tabs>
- }
- right={
- <CodePanel
- mode="check-created"
- prompt={createChallengeStore.data.prompt}
- onSubmit={publishChallenge}
- submitText="Publish"
- extraButton={
- <Button
- size="sm"
- className="cursor-pointer whitespace-nowrap bg-red-600 duration-300 hover:bg-red-500 dark:bg-red-400 dark:hover:bg-red-300"
- onClick={() => router.push('/create/')}
- >
- Continue Editing
- </Button>
- }
- />
- }
- />
- );
-}
diff --git a/src/app/wizard/page.tsx b/src/app/wizard/page.tsx
new file mode 100644
index 00000000..037ff93c
--- /dev/null
+++ b/src/app/wizard/page.tsx
@@ -0,0 +1 @@
+export { default as default } from '~/components/wizard';
diff --git a/src/components/card/index.tsx b/src/components/card/index.tsx
deleted file mode 100644
index 2ae2448f..00000000
--- a/src/components/card/index.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-'use client';
-import { cva, type VariantProps } from 'class-variance-authority';
-import { MessageCircle, Play } from 'lucide-react';
-import * as React from 'react';
-import { cn } from '~/utils/cn';
-import { TypographyP } from '../ui/paragraph';
-import { TypographyH3 } from '../ui/typography/h3';
-import type { Challenge } from '@prisma/client';
-import { useRouter } from 'next/navigation';
-import { getRelativeTime } from '~/utils/relativeTime';
-
-const cardVariants = cva('card border-2 rounded-xl @container/card dark:bg-gray-900', {
- variants: {
- variant: {
- BEGINNER: 'border-pink-300 hover:shadow-lg dark:hover:shadow-pink-400/30',
- EASY: 'border-green-500 hover:shadow-lg dark:hover:shadow-green-500/40',
- MEDIUM: 'border-yellow-400 hover:shadow-lg dark:hover:shadow-yellow-300/50',
- HARD: 'border-red-600 hover:shadow-lg dark:hover:shadow-red-500/40',
- EXTREME: 'border-orange-400 hover:shadow-lg dark:hover:shadow-orange-300/50',
- },
- },
- defaultVariants: {
- variant: 'BEGINNER',
- },
-});
-
-const headerVariants = cva('relative rounded-t-xl bg-gradient-to-b p-6 pb-12', {
- variants: {
- variant: {
- BEGINNER: 'dark:bg-pink-400 dark:text-gray-800 dark:from-pink-700/40 dark:to-pink-300/50',
- EASY: 'dark:bg-green-500 dark:from-green-800/60 dark:to-green-600',
- MEDIUM: 'dark:bg-yellow-400 dark:text-gray-800 dark:from-yellow-700/60 dark:to-yellow-400',
- EXTREME: 'dark:bg-orange-400 dark:from-orange-700/60 dark:to-orange-400',
- HARD: 'dark:bg-red-600 dark:from-red-800/50 dark:to-red-500',
- },
- },
- defaultVariants: {
- variant: 'BEGINNER',
- },
-});
-
-const actionButton = cva('rounded-full p-4 hover:shadow hover:outline', {
- variants: {
- variant: {
- BEGINNER: 'dark:bg-pink-400 dark:shadow-pink-300',
- EASY: 'dark:bg-green-600 dark:shadow-green-400 dark:hover:outline-green-800',
- MEDIUM: 'dark:bg-yellow-400',
- HARD: 'dark:bg-red-500 dark:shadow-red-300 dark:hover:outline-red-800',
- EXTREME:
- 'dark:bg-orange-400 dark:hover:outline-orange-700/70 dark:hover:shadow-orange-800/70',
- },
- },
- defaultVariants: {
- variant: 'BEGINNER',
- },
-});
-
-export interface CardProps extends VariantProps<typeof cardVariants> {
- title: string;
- content: React.ReactNode;
- // children: React.ReactNode | React.ReactNode[] | undefined;
- challenge: Challenge & {
- _count: {
- vote: number;
- comment: number;
- solution: number;
- };
- };
-}
-
-export default function Card({ challenge, variant }: CardProps) {
- const router = useRouter();
-
- return (
- <div className={cn(cardVariants({ variant: variant }), '')}>
- <header className={headerVariants({ variant: variant })}>
- <TypographyH3>{challenge.name}</TypographyH3>
- <p className="capitalize">{challenge.difficulty.toLowerCase()}</p>
- <p>{getRelativeTime(challenge.updatedAt)}</p>
- <section className="absolute bottom-0 right-6 translate-y-1/2 ">
- <button
- className={actionButton({ variant: variant })}
- type="button"
- onClick={(e) => {
- e.preventDefault();
- router.push(`/challenge/${challenge.id}`);
- }}
- >
- <Play size={36} />
- </button>
- </section>
- </header>
- <section className="flex flex-col gap-6 px-6 pb-6 pt-8 shadow-inner">
- <div className="flex justify-start gap-6">
- <div className="flex flex-col items-center">
- <TypographyH3>{challenge._count.solution}</TypographyH3>
- <TypographyP>Solutions</TypographyP>
- </div>
- <div className="flex flex-col items-center">
- <TypographyH3>
- <div className="flex items-center gap-4">
- <MessageCircle size={28} />
- <TypographyH3>{challenge._count.comment}</TypographyH3>
- </div>
- </TypographyH3>
- <TypographyP>Comments</TypographyP>
- </div>
- </div>
- <p>{challenge.shortDescription}</p>
- </section>
- </div>
- );
-}
diff --git a/src/components/challenge/editor/constants.ts b/src/components/challenge/code-panel/constants.ts
similarity index 100%
rename from src/components/challenge/editor/constants.ts
rename to src/components/challenge/code-panel/constants.ts
diff --git a/src/components/challenge/editor/editor-types.ts b/src/components/challenge/code-panel/editor-types.ts
similarity index 100%
rename from src/components/challenge/editor/editor-types.ts
rename to src/components/challenge/code-panel/editor-types.ts
diff --git a/src/components/challenge/editor/index.tsx b/src/components/challenge/code-panel/index.tsx
similarity index 52%
rename from src/components/challenge/editor/index.tsx
rename to src/components/challenge/code-panel/index.tsx
index 75d568b6..37e89efc 100644
--- a/src/components/challenge/editor/index.tsx
+++ b/src/components/challenge/code-panel/index.tsx
@@ -1,15 +1,17 @@
'use client';
-import Editor, { loader } from '@monaco-editor/react';
+import { loader } from '@monaco-editor/react';
import clsx from 'clsx';
import { Loader2, Settings } from 'lucide-react';
-import { initVimMode } from 'monaco-vim';
import type * as monaco from 'monaco-editor';
+import { initVimMode } from 'monaco-vim';
import { useSession } from 'next-auth/react';
-import { useTheme } from 'next-themes';
+import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
-import { useMemo, useRef, useState } from 'react';
+import { useRef, useState } from 'react';
+import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';
import { Button } from '~/components/ui/button';
+import { CodeEditor } from '~/components/ui/code-editor';
import {
Dialog,
DialogContent,
@@ -18,17 +20,14 @@ import {
DialogTrigger,
} from '~/components/ui/dialog';
import { ToastAction } from '~/components/ui/toast';
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '~/components/ui/tooltip';
+import { Tooltip, TooltipContent, TooltipTrigger } from '~/components/ui/tooltip';
import { useToast } from '~/components/ui/use-toast';
+import { useLocalStorage } from '~/utils/useLocalStorage';
import { saveSubmission } from '../save-submission.action';
import { SettingsForm } from '../settings-form';
-import { useEditorSettingsStore } from '../settings-store';
import { USER_CODE_START, USER_CODE_START_REGEX } from './constants';
import { libSource } from './editor-types';
import { createTwoslashInlayProvider } from './twoslash';
-import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';
-import dynamic from 'next/dynamic';
-import { useLocalStorage } from '~/utils/useLocalStorage';
const VimStatusBar = dynamic(() => import('./vimMode').then((v) => v.VimStatusBar), {
ssr: false,
@@ -40,43 +39,13 @@ loader.config({
},
});
-const DEFAULT_OPTIONS = {
- lineNumbers: 'on',
- tabSize: 2,
- insertSpaces: false,
- minimap: {
- enabled: false,
- },
- fontSize: 16,
-} as const satisfies monaco.editor.IStandaloneEditorConstructionOptions;
-
-const LIB_URI = 'ts:filename/checking.d.ts';
+export const LIB_URI = 'ts:filename/checking.d.ts';
-type Props = (
- | {
- mode: 'solve';
- challenge: ChallengeRouteData;
- prompt?: never;
- }
- | {
- mode: 'create';
- challenge?: never;
- onSubmit: (code: string) => void;
- prompt: string | undefined;
- }
- | {
- mode: 'check-created';
- challenge?: never;
- prompt: string;
- onSubmit: () => void;
- }
-) & {
- /** @default "Submit" */
- submitText?: string;
- extraButton?: React.ReactNode;
+type Props = {
+ challenge: ChallengeRouteData;
};
-type TsErrors = [
+export type TsErrors = [
SemanticDiagnostics: monaco.languages.typescript.Diagnostic[],
SyntacticDiagnostics: monaco.languages.typescript.Diagnostic[],
SuggestionDiagnostics: monaco.languages.typescript.Diagnostic[],
@@ -86,9 +55,7 @@ type TsErrors = [
export const CodePanel = (props: Props) => {
const router = useRouter();
const { toast } = useToast();
- const { theme } = useTheme();
const { data: session } = useSession();
- const { settings } = useEditorSettingsStore();
const [tsErrors, setTsErrors] = useState<TsErrors>([[], [], [], []]);
const [initialTypecheckDone, setInitialTypecheckDone] = useState(false);
const [localStorageCode, setLocalStorageCode] = useLocalStorage(
@@ -97,8 +64,6 @@ export const CodePanel = (props: Props) => {
);
const getDefaultCode = () => {
- if (props.mode !== 'solve') return props.prompt ?? '';
-
if (!localStorageCode) {
return props.challenge.prompt;
}
@@ -110,104 +75,42 @@ export const CodePanel = (props: Props) => {
const [code, setCode] = useState(() => getDefaultCode());
- const editorTheme = theme === 'light' ? 'vs' : 'vs-dark';
const modelRef = useRef<monaco.editor.ITextModel>();
// ref doesnt cause a rerender
const [editorState, setEditorState] = useState<monaco.editor.IStandaloneCodeEditor>();
- const editorOptions = useMemo(() => {
- return {
- ...DEFAULT_OPTIONS,
- ...settings,
- fontSize: parseInt(settings.fontSize),
- tabSize: parseInt(settings.tabSize),
- };
- }, [settings]);
-
- const handleSubmit =
- props.mode === 'solve'
- ? async () => {
- const [, solution] = code.split(USER_CODE_START);
- const hasErrors = tsErrors.some((e) => e.length);
- await saveSubmission(
- props.challenge.id,
- session?.user?.id as string,
- solution ?? '',
- !hasErrors,
- );
- router.refresh();
-
- if (hasErrors) {
- toast({
- variant: 'destructive',
- title: 'Uh oh! You still have errors.',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
- } else {
- toast({
- variant: 'success',
- title: 'Good job!',
- description: 'You completed this challenge.',
- action: <ToastAction altText="Try again">Dismiss</ToastAction>,
- });
- }
- }
- : props.mode === 'create'
- ? () => {
- // check that it has some test cases
- // checks that there is a line that starts with Equal or Extends or NotEqual
- if (!/(?:\n|^)\s*(?:Equal|Extends|NotEqual|Expect)</.test(code)) {
- toast({
- variant: 'destructive',
- title: 'You need to have test cases in your challenge',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
-
- return Promise.resolve();
- }
-
- const hasErrors = !!tsErrors[0].length;
- console.info(tsErrors);
-
- if (!hasErrors) {
- toast({
- variant: 'destructive',
- title: 'You need to have failing test cases in your challenge',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
-
- return Promise.resolve();
- }
-
- if (!USER_CODE_START_REGEX.test(code)) {
- toast({
- variant: 'destructive',
- title: `You need to have the line \`${USER_CODE_START}\` to signify the non-editable part`,
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
-
- return Promise.resolve();
- }
-
- props.onSubmit(code);
-
- return Promise.resolve();
- }
- : props.mode === 'check-created'
- ? () => {
- props.onSubmit();
- return Promise.resolve();
- }
- : () => Promise.reject('not finished');
+ const handleSubmit = async () => {
+ const [, solution] = code.split(USER_CODE_START);
+ const hasErrors = tsErrors.some((e) => e.length);
+
+ await saveSubmission(
+ props.challenge.id,
+ session?.user?.id as string,
+ solution ?? '',
+ !hasErrors,
+ );
+ router.refresh();
+
+ if (hasErrors) {
+ toast({
+ variant: 'destructive',
+ title: 'Uh oh! You still have errors.',
+ action: <ToastAction altText="Try again">Try again</ToastAction>,
+ });
+ } else {
+ toast({
+ variant: 'success',
+ title: 'Good job!',
+ description: 'You completed this challenge.',
+ action: <ToastAction altText="Try again">Dismiss</ToastAction>,
+ });
+ }
+ };
const onMount =
(value: string, onError: (v: TsErrors) => void) =>
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
async (editor: monaco.editor.IStandaloneCodeEditor, monaco: typeof import('monaco-editor')) => {
- const lineWithUserCode = value
- .split('\n')
- .findIndex((line) => line.includes(USER_CODE_START));
-
if (!monaco.editor.getModel(monaco.Uri.parse(LIB_URI))) {
monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, LIB_URI);
monaco.editor.createModel(libSource, 'typescript', monaco.Uri.parse(LIB_URI));
@@ -241,14 +144,6 @@ export const CodePanel = (props: Props) => {
// TODO: we prolly should use this for blocking ranges as it might not be as janky
// https://github.com/Pranomvignesh/constrained-editor-plugin
model.onDidChangeContent((e) => {
- if (props.mode !== 'create') {
- // in monaco editor, the first line is e1e1e
- // do net let them type if they are editing before lineWithUserCode
- if (e.changes.some((c) => c.range.startLineNumber <= lineWithUserCode + 1)) {
- editor.trigger('someIdString', 'undo', null);
- }
- }
-
typeCheck().catch(console.error);
});
@@ -267,7 +162,7 @@ export const CodePanel = (props: Props) => {
<Dialog>
<DialogTrigger>
<Tooltip>
- <TooltipTrigger>
+ <TooltipTrigger asChild>
<Settings size={20} className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400" />
</TooltipTrigger>
<TooltipContent className="px-2 py-1">Settings</TooltipContent>
@@ -284,11 +179,7 @@ export const CodePanel = (props: Props) => {
</Dialog>
</div>
<div className="w-full flex-1">
- <Editor
- theme={editorTheme}
- options={editorOptions}
- defaultLanguage="typescript"
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ <CodeEditor
onMount={onMount(code, setTsErrors)}
value={code}
onChange={(code) => {
@@ -309,21 +200,18 @@ export const CodePanel = (props: Props) => {
>
{editorState && <VimStatusBar editor={editorState} initVimMode={initVimMode} />}
<div className="flex items-center justify-center gap-4">
- {props.extraButton}
<Tooltip>
<TooltipTrigger asChild>
- <span>
- <Button
- size="sm"
- className="cursor-pointer rounded-lg bg-emerald-600 duration-300 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
- onClick={handleSubmit}
- disabled={!initialTypecheckDone || !session?.user}
- >
- {!initialTypecheckDone && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
- {props.submitText ?? 'Submit'}
- </Button>
- </span>
+ <Button
+ size="sm"
+ className="cursor-pointer rounded-lg bg-emerald-600 duration-300 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onClick={handleSubmit}
+ disabled={!initialTypecheckDone || !session?.user}
+ >
+ {!initialTypecheckDone && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ Submit
+ </Button>
</TooltipTrigger>
<TooltipContent>
<p>Login to Submit</p>
diff --git a/src/components/challenge/editor/twoslash.ts b/src/components/challenge/code-panel/twoslash.ts
similarity index 100%
rename from src/components/challenge/editor/twoslash.ts
rename to src/components/challenge/code-panel/twoslash.ts
diff --git a/src/components/challenge/editor/vimMode.tsx b/src/components/challenge/code-panel/vimMode.tsx
similarity index 100%
rename from src/components/challenge/editor/vimMode.tsx
rename to src/components/challenge/code-panel/vimMode.tsx
diff --git a/src/components/challenge/description/index.tsx b/src/components/challenge/description/index.tsx
index 9c40bc08..0c5209b0 100644
--- a/src/components/challenge/description/index.tsx
+++ b/src/components/challenge/description/index.tsx
@@ -82,40 +82,38 @@ export function Description({ challenge }: Props) {
{/* TODO: split this mess into components, make buttons have bigger horizontal padding and decrease the gap value on container above */}
<Tooltip>
<TooltipTrigger asChild>
- <span>
- <Button
- variant="ghost"
- className="p-1"
- disabled={!session?.data?.user?.id}
- onClick={() => {
- let shouldBookmark = false;
- if (hasBookmarked) {
- shouldBookmark = false;
- setHasBookmarked(false);
- } else {
- shouldBookmark = true;
- setHasBookmarked(true);
- }
- debouncedBookmark(
- challenge.id,
- session?.data?.user?.id as string,
- shouldBookmark,
- )?.catch((e) => {
- console.error(e);
- });
- }}
- >
- <BookmarkIcon
- className={clsx(
- {
- 'fill-blue-500 stroke-blue-500': hasBookmarked,
- 'stroke-zinc-500': !hasBookmarked,
- },
- 'h-4 w-4 hover:stroke-zinc-400',
- )}
- />
- </Button>
- </span>
+ <Button
+ variant="ghost"
+ className="p-1"
+ disabled={!session?.data?.user?.id}
+ onClick={() => {
+ let shouldBookmark = false;
+ if (hasBookmarked) {
+ shouldBookmark = false;
+ setHasBookmarked(false);
+ } else {
+ shouldBookmark = true;
+ setHasBookmarked(true);
+ }
+ debouncedBookmark(
+ challenge.id,
+ session?.data?.user?.id as string,
+ shouldBookmark,
+ )?.catch((e) => {
+ console.error(e);
+ });
+ }}
+ >
+ <BookmarkIcon
+ className={clsx(
+ {
+ 'fill-blue-500 stroke-blue-500': hasBookmarked,
+ 'stroke-zinc-500': !hasBookmarked,
+ },
+ 'h-4 w-4 hover:stroke-zinc-400',
+ )}
+ />
+ </Button>
</TooltipTrigger>
<TooltipContent>
<p>{session?.data?.user?.id ? 'Bookmark' : 'Login to Bookmark'}</p>
@@ -143,54 +141,52 @@ export function Description({ challenge }: Props) {
</Dialog>
<Tooltip>
<TooltipTrigger asChild>
- <span>
- <Button
- className="group gap-2 rounded-xl px-2 py-1"
- variant="ghost"
- disabled={!session?.data?.user?.id}
- onClick={() => {
- let shouldIncrement = false;
- if (hasVoted) {
- setVotes((v) => v - 1);
- shouldIncrement = false;
- setHasVoted(false);
- } else {
- setVotes((v) => v + 1);
- shouldIncrement = true;
- setHasVoted(true);
- }
- debouncedSearch(
- challenge.id,
- session?.data?.user?.id as string,
- shouldIncrement,
- )?.catch((e) => {
- console.error(e);
- });
- }}
+ <Button
+ className="group gap-2 rounded-xl px-2 py-1"
+ variant="ghost"
+ disabled={!session?.data?.user?.id}
+ onClick={() => {
+ let shouldIncrement = false;
+ if (hasVoted) {
+ setVotes((v) => v - 1);
+ shouldIncrement = false;
+ setHasVoted(false);
+ } else {
+ setVotes((v) => v + 1);
+ shouldIncrement = true;
+ setHasVoted(true);
+ }
+ debouncedSearch(
+ challenge.id,
+ session?.data?.user?.id as string,
+ shouldIncrement,
+ )?.catch((e) => {
+ console.error(e);
+ });
+ }}
+ >
+ <ThumbsUp
+ className={clsx(
+ {
+ 'fill-emerald-600 stroke-emerald-600 group-hover:stroke-emerald-400 dark:fill-emerald-400 dark:stroke-emerald-400':
+ hasVoted,
+ 'stroke-zinc-500 group-hover:stroke-zinc-400': !hasVoted,
+ },
+ 'h-4 w-4 duration-200 group-hover:scale-105 group-active:scale-95 group-active:duration-75',
+ )}
+ />
+ <span
+ className={clsx(
+ {
+ 'text-emerald-600 dark:text-emerald-400': hasVoted,
+ 'text-zinc-500 group-hover:text-zinc-400': !hasVoted,
+ },
+ 'my-auto w-4 self-end duration-300',
+ )}
>
- <ThumbsUp
- className={clsx(
- {
- 'fill-emerald-600 stroke-emerald-600 group-hover:stroke-emerald-400 dark:fill-emerald-400 dark:stroke-emerald-400':
- hasVoted,
- 'stroke-zinc-500 group-hover:stroke-zinc-400': !hasVoted,
- },
- 'h-4 w-4 duration-200 group-hover:scale-105 group-active:scale-95 group-active:duration-75',
- )}
- />
- <span
- className={clsx(
- {
- 'text-emerald-600 dark:text-emerald-400': hasVoted,
- 'text-zinc-500 group-hover:text-zinc-400': !hasVoted,
- },
- 'my-auto w-4 self-end duration-300',
- )}
- >
- {votes}
- </span>
- </Button>
- </span>
+ {votes}
+ </span>
+ </Button>
</TooltipTrigger>
<TooltipContent>
<p>{session?.data?.user?.id ? 'Upvote' : 'Login to Upvote'}</p>
diff --git a/src/components/challenge/solutions/index.tsx b/src/components/challenge/solutions/index.tsx
index a79bcfdd..1abfecdf 100644
--- a/src/components/challenge/solutions/index.tsx
+++ b/src/components/challenge/solutions/index.tsx
@@ -30,11 +30,9 @@ export function Solutions({ challenge }: Props) {
<>
{challenge.sharedSolution.length !== 0 ? (
<>
- {(loggedInUserHasSolution || !session?.data?.user) && (
- <div className="absolute right-0 top-0 flex w-full justify-end border-b border-zinc-300 bg-background/70 p-2 backdrop-blur-sm dark:border-zinc-700 dark:bg-muted/70">
- <SubmitSolution setView={setView} />
- </div>
- )}
+ <div className="absolute right-0 top-0 flex w-full justify-end border-b border-zinc-300 bg-background/70 p-2 backdrop-blur-sm dark:border-zinc-700 dark:bg-muted/70">
+ <SubmitSolution disabled={Boolean(!loggedInUserHasSolution)} setView={setView} />
+ </div>
<div className="custom-scrollable-element h-full overflow-y-auto pt-12">
{challenge?.sharedSolution.map((solution) => (
<SolutionRow
diff --git a/src/components/challenge/solutions/nosolutions.tsx b/src/components/challenge/solutions/nosolutions.tsx
index 27698e9c..273ffb2e 100644
--- a/src/components/challenge/solutions/nosolutions.tsx
+++ b/src/components/challenge/solutions/nosolutions.tsx
@@ -54,7 +54,7 @@ const NoSolutions = ({ setView, loggedInUser, loggedInUserHasSolution }: Props)
No solutions yet, <br />
{loggedInUser && loggedInUserHasSolution ? (
<>
- be the first to submit one! <SubmitSolution setView={setView} />
+ be the first to submit one! <SubmitSolution disabled={false} setView={setView} />
</>
) : (
'complete the challenge to submit one!'
diff --git a/src/components/challenge/solutions/solution-editor.tsx b/src/components/challenge/solutions/solution-editor.tsx
index bf3c70d8..11846d67 100644
--- a/src/components/challenge/solutions/solution-editor.tsx
+++ b/src/components/challenge/solutions/solution-editor.tsx
@@ -54,8 +54,8 @@ export function SolutionEditor({ dismiss, challenge }: Props) {
try {
await postSolution({
challengeId: challenge.id,
- description: data.content,
- title: data.title,
+ description: data.content ?? '',
+ title: data.title ?? '',
userId: session?.data?.user?.id as string,
});
diff --git a/src/components/challenge/solutions/submit-solution.tsx b/src/components/challenge/solutions/submit-solution.tsx
index 9d018284..18067684 100644
--- a/src/components/challenge/solutions/submit-solution.tsx
+++ b/src/components/challenge/solutions/submit-solution.tsx
@@ -2,14 +2,16 @@ import { Plus } from 'lucide-react';
import { Button } from '~/components/ui/button';
interface Props {
+ disabled: boolean
setView: (view: 'editor' | 'list') => void;
}
-const SubmitSolution = ({ setView }: Props) => {
+const SubmitSolution = ({ disabled, setView }: Props) => {
return (
<Button
className="h-8 rounded-lg bg-emerald-600 px-3 py-2 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"
onClick={() => setView('editor')}
+ disabled={disabled}
>
<Plus className="mr-2 h-4 w-4" /> Solution
</Button>
diff --git a/src/components/explore/explore-card.tsx b/src/components/explore/explore-card.tsx
index d2485fc7..ab624e46 100644
--- a/src/components/explore/explore-card.tsx
+++ b/src/components/explore/explore-card.tsx
@@ -44,7 +44,7 @@ const GRADIENTS_BY_DIFFICULTY = {
'bg-gradient-to-br hover:bg-[right_-2px_bottom] bg-[length:200%_200%] bg-left-top dark:from-orange-950 dark:via-orange-500 dark:to-orange-300 dark:via-30% from-orange-400 via-orange-600 via-30% to-orange-600',
};
-const ExploreCard = ({ challenge }: ExploreCardProps) => {
+export const ExploreCard = ({ challenge }: ExploreCardProps) => {
return (
<Card
className={`group relative overflow-hidden duration-300
diff --git a/src/components/explore/section.tsx b/src/components/explore/section.tsx
index 49d7666e..ed2e5b48 100644
--- a/src/components/explore/section.tsx
+++ b/src/components/explore/section.tsx
@@ -1,6 +1,6 @@
import Link from 'next/link';
-import Card from './explore-card';
+import { ExploreCard } from './explore-card';
import type { ExploreChallengeData } from '.';
import type { Difficulty } from '@prisma/client';
@@ -59,7 +59,7 @@ export async function ExploreSection({ title, fetcher }: Props) {
href={`/challenge/${challenge.id}`}
key={challenge.id}
>
- <Card key={`challenge-${challenge.id}`} challenge={challenge} />
+ <ExploreCard key={`challenge-${challenge.id}`} challenge={challenge} />
</Link>
))}
</div>
diff --git a/src/components/ui/code-editor.tsx b/src/components/ui/code-editor.tsx
new file mode 100644
index 00000000..53f892bb
--- /dev/null
+++ b/src/components/ui/code-editor.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import Editor, { type OnChange, type OnMount } from '@monaco-editor/react';
+import type * as monaco from 'monaco-editor';
+import { useTheme } from 'next-themes';
+import { useMemo } from 'react';
+import { useEditorSettingsStore } from '../challenge/settings-store';
+
+const DEFAULT_OPTIONS = {
+ lineNumbers: 'on',
+ tabSize: 2,
+ insertSpaces: false,
+ minimap: {
+ enabled: false,
+ },
+ fontSize: 16,
+} as const satisfies monaco.editor.IStandaloneEditorConstructionOptions;
+
+interface Props {
+ onChange?: OnChange;
+ onMount?: OnMount;
+ options?: monaco.editor.IStandaloneEditorConstructionOptions;
+ value: string;
+}
+export function CodeEditor({ onChange, onMount, options, value }: Props) {
+ const { theme } = useTheme();
+ const editorTheme = theme === 'light' ? 'vs' : 'vs-dark';
+ const { settings } = useEditorSettingsStore();
+ const editorOptions = useMemo(() => {
+ return {
+ ...DEFAULT_OPTIONS,
+ ...settings,
+ fontSize: parseInt(settings.fontSize),
+ tabSize: parseInt(settings.tabSize),
+ ...options,
+ };
+ }, [settings]);
+
+ return (
+ <Editor
+ theme={editorTheme}
+ options={editorOptions}
+ defaultLanguage="typescript"
+ onMount={onMount}
+ value={value}
+ onChange={onChange}
+ />
+ );
+}
diff --git a/src/components/ui/editor.tsx b/src/components/ui/editor.tsx
deleted file mode 100644
index f62e4a9c..00000000
--- a/src/components/ui/editor.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-'use client';
-import Editor, { loader } from '@monaco-editor/react';
-import { useTheme } from 'next-themes';
-
-export interface EditorProps {
- value: string;
-}
-
-loader.config({
- paths: {
- vs: '/vs',
- },
-});
-/**
- * @description Used as a read-only monaco editor. Respects theme values, disables minimap.
- */
-export default function ReadOnlyEditor({ value }: EditorProps) {
- const { theme } = useTheme();
- return (
- <Editor
- value={value}
- theme={theme === 'light' ? 'vs' : 'vs-dark'}
- defaultLanguage="typescript"
- options={{
- readOnly: true,
- minimap: {
- enabled: false,
- },
- }}
- />
- );
-}
diff --git a/src/components/ui/markdown.tsx b/src/components/ui/markdown.tsx
index aa664ae2..bdbc9dce 100644
--- a/src/components/ui/markdown.tsx
+++ b/src/components/ui/markdown.tsx
@@ -46,6 +46,9 @@ export function Markdown({ children, className }: { children: string; className?
className={className}
remarkPlugins={[removeHtmlComments, remarkGfm]}
components={{
+ ul: ({ className, ...props }) => (
+ <ul className={clsx(className, 'list-disc ps-10')} {...props} />
+ ),
h1: ({ className, ...props }) => (
<h1 className={clsx(className, 'mb-2 pb-2 text-3xl font-bold')} {...props} />
),
diff --git a/src/components/ui/navigation.tsx b/src/components/ui/navigation.tsx
index c049781a..be1f48bb 100644
--- a/src/components/ui/navigation.tsx
+++ b/src/components/ui/navigation.tsx
@@ -73,7 +73,7 @@ export function Navigation() {
align="end"
className="mt-[0.33rem] w-56 rounded-xl bg-white/50 backdrop-blur-sm dark:bg-neutral-950/50"
>
- <Link className="block" href="/create">
+ <Link className="block" href="/wizard">
<DropdownMenuItem className="rounded-lg p-2 duration-300 focus:bg-accent focus:outline-none dark:hover:bg-neutral-700/50">
<Plus className="mr-2 h-4 w-4" />
<span>Create a Challange</span>
@@ -132,7 +132,7 @@ export function Navigation() {
<header className="w-full">
<nav
className={`flex h-14 items-center ${
- pathname.includes('/challenge') || pathname.includes('/create') ? 'px-4' : 'container '
+ pathname.includes('/challenge') ? 'px-4' : 'container '
}`}
>
<div className="flex w-full items-center justify-between">
diff --git a/src/components/ui/rich-markdown-editor.tsx b/src/components/ui/rich-markdown-editor.tsx
index 9117173e..65e24577 100644
--- a/src/components/ui/rich-markdown-editor.tsx
+++ b/src/components/ui/rich-markdown-editor.tsx
@@ -55,9 +55,10 @@ const codePreview: ICommand = {
interface Props {
value: string;
onChange: (v: string) => void;
+ dismissPreview?: boolean;
}
-export function RichMarkdownEditor({ value, onChange }: Props) {
+export function RichMarkdownEditor({ dismissPreview, value, onChange }: Props) {
const { theme } = useTheme();
useEffect(() => {
theme == 'dark'
@@ -65,6 +66,8 @@ export function RichMarkdownEditor({ value, onChange }: Props) {
: document.documentElement.setAttribute('data-color-mode', 'light');
}, [theme]);
+ const extraCommands = [...(dismissPreview ? [] : [codePreview, commands.fullscreen])];
+
return (
<div className="h-full flex-1">
<MDEditor
@@ -73,7 +76,7 @@ export function RichMarkdownEditor({ value, onChange }: Props) {
// non-split-screen by default
preview="edit"
visibleDragbar={false}
- extraCommands={[codePreview, commands.fullscreen]}
+ extraCommands={extraCommands}
// @ts-ignore
onChange={onChange}
components={{
diff --git a/src/components/wizard/ChallengeCardEditor.tsx b/src/components/wizard/ChallengeCardEditor.tsx
new file mode 100644
index 00000000..52ff7f27
--- /dev/null
+++ b/src/components/wizard/ChallengeCardEditor.tsx
@@ -0,0 +1,110 @@
+'use client';
+
+import { useWatch } from 'react-hook-form';
+import type { WizardForm } from '.';
+import type { ExploreChallengeData } from '../explore';
+import { ExploreCard } from '../explore/explore-card';
+import { FormControl, FormField, FormItem, FormLabel, FormMessage } from '../ui/form';
+import { Input } from '../ui/input';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
+import { Textarea } from '../ui/textarea';
+import { TypographyH3 } from '../ui/typography/h3';
+
+interface Props {
+ form: WizardForm;
+}
+
+export function ChallengeCardEditor({ form }: Props) {
+ const difficulty = useWatch({ control: form.control, name: 'difficulty' });
+ const title = useWatch({ control: form.control, name: 'name' });
+ const shortDescription = useWatch({ control: form.control, name: 'shortDescription' });
+
+ const data: Pick<
+ ExploreChallengeData[0],
+ 'difficulty' | 'name' | 'shortDescription' | 'user' | '_count' | 'updatedAt'
+ > = {
+ difficulty,
+ name: title || 'Your Title Here',
+ shortDescription: shortDescription || 'Your Short Description Here',
+ user: {
+ name: 'You',
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any,
+ _count: {
+ vote: 100,
+ comment: 50,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any,
+ updatedAt: new Date(),
+ };
+ return (
+ <div className="h-full py-6">
+ <TypographyH3 className="mb-6">Create Challenge Card</TypographyH3>
+ <div className="flex items-center gap-12">
+ <div className="flex w-1/3 flex-col gap-3">
+ <FormField
+ control={form.control}
+ name="difficulty"
+ render={({ field }) => {
+ return (
+ <FormItem>
+ <FormLabel>Email</FormLabel>
+ <Select
+ onValueChange={field.onChange as (value: string) => void}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a difficulty for your challenge" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ <SelectItem value="BEGINNER">BEGINNER</SelectItem>
+ <SelectItem value="MEDIUM">MEDIUM</SelectItem>
+ <SelectItem value="HARD">HARD</SelectItem>
+ <SelectItem value="EXTREME">EXTREME</SelectItem>
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Challenge Title</FormLabel>
+ <FormControl>
+ <Input placeholder="Enter a Challenge Title" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="shortDescription"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Short Description</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="Enter a Short Description"
+ className="resize-none"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ <div className="w-[392px]">
+ <ExploreCard challenge={data} />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/wizard/DescriptionEditor.tsx b/src/components/wizard/DescriptionEditor.tsx
new file mode 100644
index 00000000..0987d545
--- /dev/null
+++ b/src/components/wizard/DescriptionEditor.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import { useWatch } from 'react-hook-form';
+import { WizardForm } from '.';
+import { FormField, FormItem, FormMessage } from '../ui/form';
+import { Markdown } from '../ui/markdown';
+import { RichMarkdownEditor } from '../ui/rich-markdown-editor';
+import { TypographyH3 } from '../ui/typography/h3';
+
+interface Props {
+ form: WizardForm;
+}
+
+export function DescriptionEditor({ form }: Props) {
+ const description = useWatch({ control: form.control, name: 'description' });
+ return (
+ <div className="flex h-full flex-col py-6">
+ <TypographyH3 className="mb-6">Create Challenge Description</TypographyH3>
+ <div className="flex flex-1 gap-6">
+ <div className="flex w-[500px] flex-col gap-3">
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <FormItem className="h-full">
+ <RichMarkdownEditor
+ value={field.value as string}
+ onChange={field.onChange}
+ dismissPreview
+ />
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ </div>
+ <div className="h-full w-full rounded-md border border-zinc-300 bg-white p-3 dark:border-zinc-700 dark:bg-zinc-800">
+ <Markdown>{description}</Markdown>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/wizard/Steps.tsx b/src/components/wizard/Steps.tsx
new file mode 100644
index 00000000..343c9c78
--- /dev/null
+++ b/src/components/wizard/Steps.tsx
@@ -0,0 +1,83 @@
+import { Check } from 'lucide-react';
+
+interface Step {
+ id: string;
+ name: string;
+ href?: string;
+}
+
+interface Props<T extends Step> {
+ current: number;
+ steps: T[];
+ onChange?: (step: T, index: number) => void;
+}
+
+export function Steps<T extends Step>({ steps, current, onChange }: Props<T>) {
+ return (
+ <nav aria-label="Progress">
+ <ol
+ role="list"
+ className="divide-y rounded-xl border border-zinc-300 dark:border-zinc-700 md:flex md:divide-y-0"
+ >
+ {steps.map((step, stepIdx) => (
+ <li key={step.name} className="relative md:flex md:flex-1">
+ {current > stepIdx ? (
+ <a
+ href={step.href ?? '#'}
+ className="group flex w-full items-center"
+ onClick={() => onChange?.(step, stepIdx)}
+ >
+ <span className="flex items-center px-6 py-4 text-sm font-medium">
+ <span className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-green-300 text-white dark:bg-green-800">
+ <Check className="stroke-black dark:stroke-white" size={20} />
+ </span>
+ <span className="ml-4 text-sm font-medium">{step.name}</span>
+ </span>
+ </a>
+ ) : current === stepIdx ? (
+ <span className="flex items-center px-6 py-4 text-sm font-medium" aria-current="step">
+ <span className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border-2 border-zinc-300 dark:border-zinc-700">
+ <span>{step.id}</span>
+ </span>
+ <span className="ml-4 text-sm font-medium">{step.name}</span>
+ </span>
+ ) : (
+ <span className="group flex items-center">
+ <span className="flex items-center px-6 py-4 text-sm font-medium">
+ <span className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border-2">
+ <span className="text-gray-500">{step.id}</span>
+ </span>
+ <span className="ml-4 text-sm font-medium text-gray-500 ">{step.name}</span>
+ </span>
+ </span>
+ )}
+
+ {stepIdx !== steps.length - 1 ? (
+ <>
+ {/* Arrow separator for lg screens and up */}
+ <div
+ className="absolute right-0 top-0 hidden h-full w-5 md:block"
+ aria-hidden="true"
+ >
+ <svg
+ className="h-full w-full text-zinc-300 dark:text-zinc-700"
+ viewBox="0 0 22 80"
+ fill="none"
+ preserveAspectRatio="none"
+ >
+ <path
+ d="M0 -2L20 40L0 82"
+ vectorEffect="non-scaling-stroke"
+ stroke="currentcolor"
+ strokeLinejoin="round"
+ />
+ </svg>
+ </div>
+ </>
+ ) : null}
+ </li>
+ ))}
+ </ol>
+ </nav>
+ );
+}
diff --git a/src/components/wizard/Summary.tsx b/src/components/wizard/Summary.tsx
new file mode 100644
index 00000000..e74f2e8e
--- /dev/null
+++ b/src/components/wizard/Summary.tsx
@@ -0,0 +1,21 @@
+import { WizardForm } from '.';
+import { Button } from '../ui/button';
+
+interface Props {
+ goBack(): void;
+}
+export function Summary({ goBack }: Props) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center">
+ <div className="mb-5 text-center text-5xl font-bold text-gray-900 dark:text-gray-100">
+ Thanks for creating a challenge! Submit it to the community for review.
+ </div>
+ <div className="flex gap-3">
+ <Button variant="secondary" onClick={goBack}>
+ Review
+ </Button>
+ <Button type="submit">Submit</Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/wizard/TestCasesEditor.tsx b/src/components/wizard/TestCasesEditor.tsx
new file mode 100644
index 00000000..4d73addf
--- /dev/null
+++ b/src/components/wizard/TestCasesEditor.tsx
@@ -0,0 +1,132 @@
+'use client';
+
+import { Settings } from 'lucide-react';
+import type * as monaco from 'monaco-editor';
+import { useState } from 'react';
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '~/components/ui/dialog';
+import { Tooltip, TooltipContent, TooltipTrigger } from '~/components/ui/tooltip';
+import type { WizardForm } from '.';
+import { LIB_URI, type TsErrors } from '../challenge/code-panel';
+import { libSource } from '../challenge/code-panel/editor-types';
+import { SettingsForm } from '../challenge/settings-form';
+import { CodeEditor } from '../ui/code-editor';
+import { FormField, FormItem, FormMessage } from '../ui/form';
+import { TypographyH3 } from '../ui/typography/h3';
+import type { OnChange } from '@monaco-editor/react';
+
+interface Props {
+ form: WizardForm;
+}
+
+export function TestCasesEditor({ form }: Props) {
+ const [, setTsErrors] = useState<TsErrors>([[], [], [], []]);
+ const onMount =
+ (onError: (v: TsErrors) => void) =>
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ async (editor: monaco.editor.IStandaloneCodeEditor, monaco: typeof import('monaco-editor')) => {
+ if (!monaco.editor.getModel(monaco.Uri.parse(LIB_URI))) {
+ monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, LIB_URI);
+ monaco.editor.createModel(libSource, 'typescript', monaco.Uri.parse(LIB_URI));
+ }
+
+ const model = editor.getModel();
+
+ if (!model) {
+ throw new Error();
+ }
+
+ const ts = await (await monaco.languages.typescript.getTypeScriptWorker())(model.uri);
+
+ const filename = model.uri.toString();
+
+ // what actually runs when checking errors
+ const typeCheck = async () => {
+ const errors = await Promise.all([
+ ts.getSemanticDiagnostics(filename),
+ ts.getSyntacticDiagnostics(filename),
+ ts.getSuggestionDiagnostics(filename),
+ ts.getCompilerOptionsDiagnostics(filename),
+ ] as const);
+
+ onError(errors);
+ };
+
+ model.onDidChangeContent(() => {
+ typeCheck().catch(console.error);
+ });
+
+ await typeCheck();
+ };
+ return (
+ <div className="flex h-full flex-col py-6">
+ <TypographyH3 className="mb-6">Create Test Cases</TypographyH3>
+ <FormField
+ control={form.control}
+ name="prompt"
+ render={({ field }) => {
+ return (
+ <FormItem className="h-full">
+ <div className="flex h-full flex-col">
+ <div className="sticky top-0 flex h-[40px] flex-row-reverse items-center border-b border-zinc-300 px-3 py-2 dark:border-zinc-700 dark:bg-[#1e1e1e]">
+ <Dialog>
+ <DialogTrigger>
+ <Tooltip>
+ <TooltipTrigger>
+ <Settings
+ size={20}
+ className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400"
+ />
+ </TooltipTrigger>
+ <TooltipContent className="px-2 py-1">Settings</TooltipContent>
+ </Tooltip>
+ </DialogTrigger>
+ <DialogContent className="w-[200px]">
+ <DialogHeader>
+ <DialogTitle>Settings</DialogTitle>
+ </DialogHeader>
+ <div className="pt-4">
+ <SettingsForm />
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ <div className="w-full flex-1">
+ <CodeEditor
+ onMount={onMount(setTsErrors)}
+ value={field.value}
+ onChange={field.onChange as OnChange}
+ />
+ </div>
+ </div>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
+ />
+ </div>
+ );
+}
+// Add these extra validations
+// if (!/(?:\n|^)\s*(?:Equal|Extends|NotEqual|Expect)</.test(code)) {
+// toast({
+// variant: 'destructive',
+// title: 'You need to have test cases in your challenge',
+// action: <ToastAction altText="Try again">Try again</ToastAction>,
+// });
+//
+// const hasErrors = !!tsErrors[0].length;
+//
+// if (!USER_CODE_START_REGEX.test(code)) {
+// toast({
+// variant: 'destructive',
+// title: `You need to have the line \`${USER_CODE_START}\` to signify the non-editable part`,
+// action: <ToastAction altText="Try again">Try again</ToastAction>,
+// });
+//
+//
diff --git a/src/app/create/create.action.ts b/src/components/wizard/create.action.ts
similarity index 54%
rename from src/app/create/create.action.ts
rename to src/components/wizard/create.action.ts
index da9e3e8f..67fb25aa 100644
--- a/src/app/create/create.action.ts
+++ b/src/components/wizard/create.action.ts
@@ -1,13 +1,10 @@
'use server';
import { prisma } from '~/server/db';
-import { createChallengeValidator } from './create-validator';
import { getServerAuthSession } from '~/server/auth';
-import { type CreateChallengeInputData } from './create-challenge-store';
-
-export async function uploadChallenge(data: CreateChallengeInputData) {
- const parsedData = createChallengeValidator.parse(data);
+import { CreateChallengeSchema } from '.';
+export async function uploadChallenge(data: CreateChallengeSchema) {
const session = await getServerAuthSession();
if (!session) {
@@ -16,7 +13,7 @@ export async function uploadChallenge(data: CreateChallengeInputData) {
return prisma.challenge.create({
data: {
- ...parsedData,
+ ...data,
userId: session.user.id,
},
select: {
diff --git a/src/components/wizard/default-challenge.md b/src/components/wizard/default-challenge.md
new file mode 100644
index 00000000..cd9417e8
--- /dev/null
+++ b/src/components/wizard/default-challenge.md
@@ -0,0 +1,7 @@
+// TEST CASE START (code in test cases are not editable)
+Extends<HelloWorld, `Hello, ${string}`>()
+
+Extends<HelloWorld, `${string}!`>()
+
+// CODE START (code below this line is editable)
+type HelloWorld = ""
diff --git a/src/components/wizard/default-description.md b/src/components/wizard/default-description.md
new file mode 100644
index 00000000..6e2188cd
--- /dev/null
+++ b/src/components/wizard/default-description.md
@@ -0,0 +1,12 @@
+### Description
+Please enter a well written description of your challenge.
+
+We find that including code snippets in your description is extremely helpful.
+
+```ts
+ interface Todo {
+ title: string
+ description: string
+ completed: boolean
+ }
+```
diff --git a/src/components/wizard/index.tsx b/src/components/wizard/index.tsx
new file mode 100644
index 00000000..b00b12f7
--- /dev/null
+++ b/src/components/wizard/index.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { zodResolver } from '@hookform/resolvers/zod';
+import { useEffect, useState } from 'react';
+import { type UseFormReturn, useForm } from 'react-hook-form';
+import { z } from 'zod';
+import { Button } from '~/components/ui/button';
+import { Form } from '~/components/ui/form';
+import { ChallengeCardEditor } from './ChallengeCardEditor';
+import { Steps } from './Steps';
+import { TestCasesEditor } from './TestCasesEditor';
+import DEFAULT_DESCRIPTION from './default-description.md';
+import DEFAULT_CHALLENGE_TEMPLATE from './default-challenge.md';
+import { DescriptionEditor } from './DescriptionEditor';
+import { Summary } from './Summary';
+import { useRouter } from 'next/navigation';
+import { uploadChallenge } from './create.action';
+
+const steps = [
+ { id: '1', name: 'Challenge Card' },
+ { id: '2', name: 'Description' },
+ { id: '3', name: 'Test Cases' },
+ { id: '4', name: 'Summary' },
+];
+
+const createChallengeSchema = z.object({
+ name: z
+ .string()
+ .min(3, 'The name must be longer than 3 characters')
+ .max(30, 'The name must be shorter than 30 characters'),
+ prompt: z.string().min(20, 'The test cases must be longer than 20 characters').max(65536),
+ difficulty: z.enum(['BEGINNER', 'EASY', 'MEDIUM', 'HARD', 'EXTREME']),
+ description: z.string().min(20, 'The description must be longer than 20 characters').max(65536),
+ shortDescription: z
+ .string()
+ .min(10, 'The short description must be longer than 10 characters')
+ .max(191, 'The short description must be shorter than 191 characters'),
+});
+
+const schemas = {
+ 0: z.object({
+ name: z
+ .string()
+ .min(3, 'The name must be longer than 3 characters')
+ .max(30, 'The name must be shorter than 30 characters'),
+ shortDescription: z
+ .string()
+ .min(10, 'The short description must be longer than 10 characters')
+ .max(191, 'The short description must be shorter than 191 characters'),
+ }),
+ 1: z.object({
+ description: z.string().min(20, 'The description must be longer than 20 characters').max(65536),
+ }),
+ 2: z.object({
+ prompt: z.string().max(65536),
+ }),
+};
+
+type Schemas = typeof schemas;
+export type CreateChallengeSchema = z.infer<typeof createChallengeSchema>;
+
+export type WizardForm = UseFormReturn<CreateChallengeSchema>;
+
+export default function Wizard() {
+ const router = useRouter();
+ const [step, setStep] = useState(0);
+ const [rendered, setRendered] = useState(false);
+ const form = useForm<CreateChallengeSchema>({
+ resolver: zodResolver(createChallengeSchema),
+ defaultValues: {
+ name: '',
+ difficulty: 'BEGINNER',
+ description: DEFAULT_DESCRIPTION,
+ prompt: DEFAULT_CHALLENGE_TEMPLATE,
+ },
+ });
+
+ useEffect(() => {
+ setRendered(true);
+ }, []);
+
+ const handleNextClick = async () => {
+ const { success } = schemas[step as keyof Schemas]?.safeParse(form.getValues());
+ if (success) {
+ setStep((step) => step + 1);
+ } else {
+ await form.trigger();
+ console.error(success);
+ }
+ };
+
+ async function onSubmit(data: CreateChallengeSchema) {
+ const { id } = await uploadChallenge(data);
+
+ router.push(`/challenge/${id}`);
+ }
+
+ return (
+ <div className="container h-full pb-6">
+ <div className="flex h-full flex-col">
+ <Steps steps={steps} current={step} onChange={(step, idx) => setStep(idx)} />
+ {rendered && (
+ <Form {...form}>
+ <form className="flex-1" onSubmit={form.handleSubmit(onSubmit)}>
+ {step === 0 && <ChallengeCardEditor form={form} />}
+ {step === 1 && <DescriptionEditor form={form} />}
+ {step === 2 && <TestCasesEditor form={form} />}
+ {step === 3 && <Summary goBack={() => setStep((step) => step - 1)} />}
+ </form>
+ <div className="flex justify-end gap-3">
+ {step !== 3 && (
+ <>
+ {step > 0 && (
+ <Button
+ variant="ghost"
+ type="button"
+ onClick={() => setStep((step) => step - 1)}
+ >
+ Prev
+ </Button>
+ )}
+ <Button type="button" onClick={handleNextClick}>
+ Next
+ </Button>
+ </>
+ )}
+ </div>
+ </Form>
+ )}
+ </div>
+ </div>
+ );
+}