Skip to content

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

[wizard] fix validation and bugs (#293)

bautistaaaec98ba7c5862
diff --git a/src/app/wizard/error.tsx b/src/app/wizard/error.tsx
new file mode 100644
index 00000000..4b0d0e4b
--- /dev/null
+++ b/src/app/wizard/error.tsx
@@ -0,0 +1,22 @@
+'use client'; // Error components must be Client Components
+
+import { Button } from '~/components/ui/button';
+import Text from '~/components/ui/typography/typography';
+
+export default function Error({ reset }: { reset: () => void }) {
+ return (
+ <div className="container flex h-full flex-col items-center justify-center">
+ <Text intent="h2" className="mb-6">
+ Something went wrong!
+ </Text>
+ <Button
+ onClick={
+ // Attempt to recover by trying to re-render the segment
+ () => reset()
+ }
+ >
+ Try again
+ </Button>
+ </div>
+ );
+}
diff --git a/src/app/wizard/page.tsx b/src/app/wizard/page.tsx
index 037ff93c..19ebfedf 100644
--- a/src/app/wizard/page.tsx
+++ b/src/app/wizard/page.tsx
@@ -1 +1,18 @@
-export { default as default } from '~/components/wizard';
+import { getServerSession } from 'next-auth';
+import { TypographyH2 } from '~/components/ui/typography/h2';
+import { Wizard } from '~/components/wizard';
+import { authOptions } from '~/server/auth';
+
+export default async function Page() {
+ const session = await getServerSession(authOptions);
+
+ if (!session?.user) {
+ return (
+ <div className="container flex h-full flex-col items-center justify-center">
+ <TypographyH2>You must be logged in to create a challenge.</TypographyH2>
+ </div>
+ );
+ }
+
+ return <Wizard />;
+}
diff --git a/src/components/ui/code-editor.tsx b/src/components/ui/code-editor.tsx
index 53f892bb..699da189 100644
--- a/src/components/ui/code-editor.tsx
+++ b/src/components/ui/code-editor.tsx
@@ -1,6 +1,6 @@
'use client';
-import Editor, { type OnChange, type OnMount } from '@monaco-editor/react';
+import Editor, { type EditorProps, type OnChange, type OnMount } from '@monaco-editor/react';
import type * as monaco from 'monaco-editor';
import { useTheme } from 'next-themes';
import { useMemo } from 'react';
@@ -16,13 +16,13 @@ const DEFAULT_OPTIONS = {
fontSize: 16,
} as const satisfies monaco.editor.IStandaloneEditorConstructionOptions;
-interface Props {
+interface Props extends EditorProps {
onChange?: OnChange;
onMount?: OnMount;
options?: monaco.editor.IStandaloneEditorConstructionOptions;
value: string;
}
-export function CodeEditor({ onChange, onMount, options, value }: Props) {
+export function CodeEditor({ onChange, onMount, options, value, ...props }: Props) {
const { theme } = useTheme();
const editorTheme = theme === 'light' ? 'vs' : 'vs-dark';
const { settings } = useEditorSettingsStore();
@@ -34,7 +34,9 @@ export function CodeEditor({ onChange, onMount, options, value }: Props) {
tabSize: parseInt(settings.tabSize),
...options,
};
- }, [settings]);
+ }, [options, settings]);
+
+ console.log({ value });
return (
<Editor
@@ -44,6 +46,7 @@ export function CodeEditor({ onChange, onMount, options, value }: Props) {
onMount={onMount}
value={value}
onChange={onChange}
+ {...props}
/>
);
}
diff --git a/src/components/ui/typography/h2.tsx b/src/components/ui/typography/h2.tsx
index 7a771c92..683d944f 100644
--- a/src/components/ui/typography/h2.tsx
+++ b/src/components/ui/typography/h2.tsx
@@ -8,7 +8,7 @@ export function TypographyH2({ children, className, ...props }: Props) {
return (
<h2
className={cn(
- 'scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight transition-colors first:mt-0',
+ 'scroll-m-20 pb-2 text-3xl font-semibold tracking-tight transition-colors first:mt-0',
className,
)}
{...props}
diff --git a/src/components/wizard/ChallengeCardEditor.tsx b/src/components/wizard/ChallengeCardEditor.tsx
index 52ff7f27..9e10b252 100644
--- a/src/components/wizard/ChallengeCardEditor.tsx
+++ b/src/components/wizard/ChallengeCardEditor.tsx
@@ -40,7 +40,7 @@ export function ChallengeCardEditor({ form }: Props) {
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 items-start gap-12">
<div className="flex w-1/3 flex-col gap-3">
<FormField
control={form.control}
diff --git a/src/components/wizard/Steps.tsx b/src/components/wizard/Steps.tsx
index 343c9c78..dc41cd34 100644
--- a/src/components/wizard/Steps.tsx
+++ b/src/components/wizard/Steps.tsx
@@ -1,31 +1,29 @@
import { Check } from 'lucide-react';
-
-interface Step {
- id: string;
- name: string;
- href?: string;
-}
+import { STEPS, type Step } from '.';
+import { Button } from '../ui/button';
interface Props<T extends Step> {
current: number;
steps: T[];
- onChange?: (step: T, index: number) => void;
+ onChange: (index: number) => void;
+ onNext: () => void;
+ onSubmit: () => Promise<void>;
}
-export function Steps<T extends Step>({ steps, current, onChange }: Props<T>) {
+export function Steps<T extends Step>({ steps, current, onChange, onNext, onSubmit }: Props<T>) {
return (
- <nav aria-label="Progress">
+ <nav className="items-center justify-between md:flex" 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"
+ className="mb-3 divide-y rounded-xl border border-zinc-300 dark:border-zinc-700 md:flex md:w-10/12 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 ?? '#'}
+ href={'#'}
className="group flex w-full items-center"
- onClick={() => onChange?.(step, stepIdx)}
+ onClick={() => onChange(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">
@@ -78,6 +76,24 @@ export function Steps<T extends Step>({ steps, current, onChange }: Props<T>) {
</li>
))}
</ol>
+ <div className="flex justify-end gap-3">
+ <>
+ {current > STEPS.ChallengeCard && (
+ <Button variant="ghost" onClick={() => onChange(current - 1)}>
+ Back
+ </Button>
+ )}
+ {current === STEPS.Summary ? (
+ <Button className="w-[79px]" onClick={onSubmit}>
+ Submit
+ </Button>
+ ) : (
+ <Button onClick={onNext} className="w-[79px]">
+ Next
+ </Button>
+ )}
+ </>
+ </div>
</nav>
);
}
diff --git a/src/components/wizard/Summary.tsx b/src/components/wizard/Summary.tsx
index 7adaf01b..49d89f2d 100644
--- a/src/components/wizard/Summary.tsx
+++ b/src/components/wizard/Summary.tsx
@@ -1,21 +1,9 @@
-import { WizardForm } from '.';
-import { Button } from '../ui/button';
-
-interface Props {
- goBack(): void;
-}
-export function Summary({ goBack }: Props) {
+export function Summary() {
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}>
- Back
- </Button>
- <Button type="submit">Submit</Button>
- </div>
</div>
);
}
diff --git a/src/components/wizard/TestCasesEditor.tsx b/src/components/wizard/TestCasesEditor.tsx
index daa90e08..2158500c 100644
--- a/src/components/wizard/TestCasesEditor.tsx
+++ b/src/components/wizard/TestCasesEditor.tsx
@@ -1,8 +1,9 @@
'use client';
+import type { OnChange } from '@monaco-editor/react';
import { Settings } from 'lucide-react';
import type * as monaco from 'monaco-editor';
-import { useState } from 'react';
+import { useCallback } from 'react';
import {
Dialog,
DialogContent,
@@ -18,51 +19,57 @@ 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;
+ hasTsErrors: boolean;
+ setTsErrors: (errors: TsErrors) => void;
}
-export function TestCasesEditor({ form }: Props) {
- const [, setTsErrors] = useState<TsErrors>([[], [], [], []]);
- const onMount =
+export function TestCasesEditor({ form, hasTsErrors, setTsErrors }: Props) {
+ const onMount = useCallback(
(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));
- }
+ // 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();
+ const model = editor.getModel();
- if (!model) {
- throw new Error();
- }
+ if (!model) {
+ throw new Error();
+ }
- const ts = await (await monaco.languages.typescript.getTypeScriptWorker())(model.uri);
+ const ts = await (await monaco.languages.typescript.getTypeScriptWorker())(model.uri);
- const filename = model.uri.toString();
+ 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);
+ // 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);
- };
+ onError(errors);
+ };
- model.onDidChangeContent(() => {
- typeCheck().catch(console.error);
- });
+ model.onDidChangeContent(() => {
+ typeCheck().catch(console.error);
+ });
+
+ await typeCheck();
+ },
+ [],
+ );
- await typeCheck();
- };
return (
<div className="flex h-full flex-col py-6">
<TypographyH3 className="mb-6">Create Test Cases</TypographyH3>
@@ -103,8 +110,11 @@ export function TestCasesEditor({ form }: Props) {
onChange={field.onChange as OnChange}
/>
</div>
+ <FormMessage />
+ {!hasTsErrors && (
+ <div className="text-sm text-destructive">You must have failing test cases</div>
+ )}
</div>
- <FormMessage />
</FormItem>
);
}}
@@ -112,21 +122,3 @@ export function TestCasesEditor({ form }: Props) {
</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/components/wizard/index.tsx b/src/components/wizard/index.tsx
index b00b12f7..1feac12e 100644
--- a/src/components/wizard/index.tsx
+++ b/src/components/wizard/index.tsx
@@ -1,70 +1,76 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
-import { useEffect, useState } from 'react';
-import { type UseFormReturn, useForm } from 'react-hook-form';
+import { useRouter } from 'next/navigation';
+import { useEffect, useMemo, useState } from 'react';
+import { useForm, type UseFormReturn } from 'react-hook-form';
import { z } from 'zod';
-import { Button } from '~/components/ui/button';
import { Form } from '~/components/ui/form';
+import { USER_CODE_START, USER_CODE_START_REGEX } from '../challenge/code-panel/constants';
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 { Steps } from './Steps';
import { Summary } from './Summary';
-import { useRouter } from 'next/navigation';
+import { TestCasesEditor } from './TestCasesEditor';
import { uploadChallenge } from './create.action';
+import DEFAULT_CHALLENGE_TEMPLATE from './default-challenge.md';
+import DEFAULT_DESCRIPTION from './default-description.md';
+import type { TsErrors } from '../challenge/code-panel';
-const steps = [
- { id: '1', name: 'Challenge Card' },
- { id: '2', name: 'Description' },
- { id: '3', name: 'Test Cases' },
- { id: '4', name: 'Summary' },
-];
-
-const createChallengeSchema = z.object({
+export const enum STEPS {
+ ChallengeCard,
+ Description,
+ TestCases,
+ Summary,
+}
+const testCaseRegex = new RegExp('(?:\n|^)s*(?:Equal|Extends|NotEqual|Expect)<');
+const createExploreCardSchema = z.object({
+ difficulty: z.enum(['BEGINNER', 'EASY', 'MEDIUM', 'HARD', 'EXTREME']),
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 createDescriptionSchema = z.object({
+ description: z.string().min(20, 'The description must be longer than 20 characters').max(65536),
+});
+const createTestCasesSchema = z.object({
+ prompt: z
+ .string()
+ .min(20, 'The test cases must be longer than 20 characters')
+ .max(65536)
+ .regex(testCaseRegex, 'You need to have test cases in your challenge')
+ .regex(
+ USER_CODE_START_REGEX,
+ `You need to have the line \`${USER_CODE_START}\` to signify the non-editable part`,
+ ),
+});
+const createChallengeSchema = createExploreCardSchema
+ .merge(createDescriptionSchema)
+ .merge(createTestCasesSchema);
+const steps = [
+ { id: '1', name: 'Challenge Card', schema: createExploreCardSchema },
+ { id: '2', name: 'Description', schema: createDescriptionSchema },
+ { id: '3', name: 'Test Cases', schema: createTestCasesSchema },
+ { id: '4', name: 'Summary', schema: z.any() },
+];
+export type Step = (typeof steps)[0];
-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() {
+export function Wizard() {
const router = useRouter();
const [step, setStep] = useState(0);
const [rendered, setRendered] = useState(false);
+ const [tsErrors, setTsErrors] = useState<TsErrors>([[], [], [], []]);
+
+ const hasTsErrors = useMemo(() => tsErrors.some((e) => e.length), [tsErrors]);
const form = useForm<CreateChallengeSchema>({
resolver: zodResolver(createChallengeSchema),
defaultValues: {
@@ -80,8 +86,13 @@ export default function Wizard() {
}, []);
const handleNextClick = async () => {
- const { success } = schemas[step as keyof Schemas]?.safeParse(form.getValues());
+ const { success } = steps[step]!.schema.safeParse(form.getValues());
if (success) {
+ // if they are currently on test cases do not let them go to next step
+ // until a type error exists
+ if (step === STEPS.TestCases) {
+ if (!hasTsErrors) return;
+ }
setStep((step) => step + 1);
} else {
await form.trigger();
@@ -90,6 +101,7 @@ export default function Wizard() {
};
async function onSubmit(data: CreateChallengeSchema) {
+ console.log({ data });
const { id } = await uploadChallenge(data);
router.push(`/challenge/${id}`);
@@ -98,33 +110,24 @@ export default function Wizard() {
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)} />
+ {/* we cant nest this in the form because it causes the editor to resize inifinitely hence the onSubmit(wtf..) */}
+ <Steps
+ steps={steps}
+ current={step}
+ onChange={(idx) => setStep(idx)}
+ onNext={handleNextClick}
+ onSubmit={form.handleSubmit(onSubmit)}
+ />
{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>
- </>
+ <form className="flex-1">
+ {step === STEPS.ChallengeCard && <ChallengeCardEditor form={form} />}
+ {step === STEPS.Description && <DescriptionEditor form={form} />}
+ {step === STEPS.TestCases && (
+ <TestCasesEditor form={form} hasTsErrors={hasTsErrors} setTsErrors={setTsErrors} />
)}
- </div>
+ {step === 3 && <Summary />}
+ </form>
</Form>
)}
</div>