Skip to content

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

create challenge page (#96)

ggrandi4ea5580c7633
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 25fa6215..b7ad83d8 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,3 +1,4 @@
{
- "typescript.tsdk": "node_modules/typescript/lib"
+ "typescript.tsdk": "node_modules/typescript/lib",
+ "prettier.prettierPath": "./node_modules/prettier"
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a293ac2d..8ff1c142 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1,4 +1,4 @@
-lockfileVersion: '6.0'
+lockfileVersion: '6.1'
dependencies:
'@clerk/nextjs':
diff --git a/src/app/create/create-challenge-store.ts b/src/app/create/create-challenge-store.ts
new file mode 100644
index 00000000..37ea9e4c
--- /dev/null
+++ b/src/app/create/create-challenge-store.ts
@@ -0,0 +1,30 @@
+import type { Difficulty } from '@prisma/client';
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
+
+interface CreateState {
+ data:
+ | {
+ name: string;
+ difficulty: Difficulty;
+ shortDescription: string;
+ description: string;
+ prompt: string;
+ }
+ | undefined;
+ setData: (data: NonNullable<CreateState['data']>) => void;
+ clear: () => void;
+}
+
+export const useCreateChallengeStore = create<CreateState>()(
+ persist(
+ (set, _get) => ({
+ data: undefined,
+ clear: () => set({ data: undefined }),
+ setData: (data) => set({ data }),
+ }),
+ {
+ name: 'create-challenge-data',
+ },
+ ),
+);
diff --git a/src/app/create/loading.tsx b/src/app/create/loading.tsx
new file mode 100644
index 00000000..62269332
--- /dev/null
+++ b/src/app/create/loading.tsx
@@ -0,0 +1,2 @@
+// TODO actually make a skeleton
+export { default as default} from '../challenge/[id]/loading'
\ No newline at end of file
diff --git a/src/app/create/page.tsx b/src/app/create/page.tsx
new file mode 100644
index 00000000..e64141bc
--- /dev/null
+++ b/src/app/create/page.tsx
@@ -0,0 +1,223 @@
+'use client';
+
+import { ChallengeLayout } from '~/components/challenge/challenge-layout';
+import { Textarea } from '~/components/ui/textarea';
+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 { Input } from '~/components/ui/input';
+import { useToast } from '~/components/ui/use-toast';
+import { ToastAction } from '@radix-ui/react-toast';
+import { useRouter } from 'next/navigation';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '../../components/ui/select';
+import { type Difficulty } from '@prisma/client';
+
+export default function CreateChallenge() {
+ const createChallengeStore = useCreateChallengeStore();
+ const [isPreviewing, setIsPreviewing] = useState({
+ description: false,
+ shortDescription: false,
+ name: false,
+ });
+ const [description, setDescription] = useState(createChallengeStore.data?.description ?? '');
+ const [difficulty, setDifficulty] = useState<Difficulty | undefined>(
+ createChallengeStore.data?.difficulty,
+ );
+ const [shortDescription, setShortDescription] = useState(
+ createChallengeStore.data?.shortDescription ?? '',
+ );
+ const [name, setName] = useState(createChallengeStore.data?.name ?? '');
+
+ const router = useRouter();
+
+ const { toast } = useToast();
+
+ function onSubmit(prompt: string) {
+ if (name.length < 3) {
+ return void toast({
+ variant: 'destructive',
+ title: 'The title length should be longer than 3 character',
+ action: <ToastAction altText="Try again">Try again</ToastAction>,
+ });
+ }
+
+ if (shortDescription.length < 10) {
+ return void toast({
+ variant: 'destructive',
+ title: 'The short description should be longer than 10 character',
+ action: <ToastAction altText="Try again">Try again</ToastAction>,
+ });
+ }
+
+ if (description.length < 20) {
+ return void toast({
+ variant: 'destructive',
+ title: 'The description should be longer than 20 character',
+ action: <ToastAction altText="Try again">Try again</ToastAction>,
+ });
+ }
+
+ if (difficulty === undefined) {
+ return void toast({
+ variant: 'destructive',
+ title: 'Please select a difficulty',
+ action: <ToastAction altText="Try again">Try again</ToastAction>,
+ });
+ }
+
+ createChallengeStore.setData({
+ name,
+ description,
+ shortDescription,
+ difficulty,
+ prompt,
+ });
+
+ router.push('/create/preview');
+ }
+
+ return (
+ <ChallengeLayout
+ left={
+ <Tabs
+ defaultValue="short-description"
+ 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="short-description"
+ className="rounded-md rounded-tr-lg duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
+ >
+ Short Description
+ </TabsTrigger>
+ <TabsTrigger
+ value="long-description"
+ className="rounded-md rounded-tl-lg duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
+ >
+ Long Description
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent
+ value="short-description"
+ className="mt-0 flex flex-1 flex-col gap-3 p-4 dark:bg-muted [&[hidden]]:hidden"
+ >
+ <h1>Name:</h1>
+ {isPreviewing.name ? (
+ <h2 className="px-3 py-2">{name}</h2>
+ ) : (
+ <Input
+ className="resize-none dark:border-white"
+ value={name}
+ onChange={(ev) => setName(ev.currentTarget.value)}
+ />
+ )}
+ <div className="flex items-center justify-end space-x-2">
+ <Label
+ htmlFor="preview"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Preview:
+ </Label>
+ <Checkbox
+ id="preview"
+ checked={isPreviewing.name}
+ onCheckedChange={(checked) =>
+ setIsPreviewing((rest) => ({ ...rest, name: checked === true }))
+ }
+ />
+ </div>
+ <h1>Name:</h1>
+ <Select onValueChange={(value: Difficulty) => setDifficulty(value)} value={difficulty}>
+ <SelectTrigger className="dark:border-white">
+ <SelectValue placeholder="Select a Difficulty" />
+ </SelectTrigger>
+ <SelectContent className="dark:border-white">
+ <SelectItem value="BEGINNER">BEGINNER</SelectItem>
+ <SelectItem value="EASY">EASY</SelectItem>
+ <SelectItem value="MEDIUM">MEDIUM</SelectItem>
+ <SelectItem value="HARD">HARD</SelectItem>
+ <SelectItem value="EXTREME">EXTREME</SelectItem>
+ </SelectContent>
+ </Select>
+ <h1>Short Description:</h1>
+ {isPreviewing.shortDescription ? (
+ <div className="prose-invert flex-1 text-sm">
+ <Markdown>{shortDescription}</Markdown>
+ </div>
+ ) : (
+ <Textarea
+ className="flex-1 resize-none dark:border-white"
+ value={shortDescription}
+ onChange={(ev) => setShortDescription(ev.currentTarget.value)}
+ />
+ )}
+ <div className="flex items-center justify-end space-x-2">
+ <Label
+ htmlFor="preview"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Preview:
+ </Label>
+ <Checkbox
+ id="preview"
+ checked={isPreviewing.shortDescription}
+ onCheckedChange={(checked) =>
+ setIsPreviewing((rest) => ({ ...rest, shortDescription: checked === true }))
+ }
+ />
+ </div>
+ </TabsContent>
+ <TabsContent
+ value="long-description"
+ className="mt-0 flex flex-1 flex-col gap-3 p-4 dark:bg-muted [&[hidden]]:hidden"
+ >
+ {isPreviewing.description ? (
+ <div className="prose-invert flex-1 leading-8 prose-h3:text-xl">
+ <Markdown>{description}</Markdown>
+ </div>
+ ) : (
+ <Textarea
+ className="flex-1 resize-none dark:border-white"
+ value={description}
+ onChange={(ev) => setDescription(ev.currentTarget.value)}
+ />
+ )}
+ <div className="flex items-center justify-end space-x-2">
+ <Label
+ htmlFor="preview"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Preview:
+ </Label>
+ <Checkbox
+ id="preview"
+ checked={isPreviewing.description}
+ onCheckedChange={(checked) =>
+ setIsPreviewing((rest) => ({ ...rest, description: checked === true }))
+ }
+ />
+ </div>
+ </TabsContent>
+ </Tabs>
+ }
+ right={
+ <CodePanel
+ mode="create"
+ onSubmit={onSubmit}
+ submitText="Preview"
+ prompt={createChallengeStore.data?.prompt}
+ />
+ }
+ />
+ );
+}
diff --git a/src/app/create/preview/page.tsx b/src/app/create/preview/page.tsx
new file mode 100644
index 00000000..b2064680
--- /dev/null
+++ b/src/app/create/preview/page.tsx
@@ -0,0 +1,94 @@
+'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';
+
+export default function PreviewCreatedChallenge() {
+ const createChallengeStore = useCreateChallengeStore();
+
+ const router = useRouter();
+
+ if (createChallengeStore.data === undefined) {
+ return router.replace('/create');
+ }
+
+ function publishChallenge() {
+ console.log(createChallengeStore.data);
+
+ createChallengeStore.clear();
+
+ // router.push('/explore');
+ }
+
+ return (
+ <ChallengeLayout
+ left={
+ <Tabs
+ defaultValue="description"
+ 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="description"
+ className="rounded-md rounded-tr-lg duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
+ >
+ Description
+ </TabsTrigger>
+ <TabsTrigger
+ value="card"
+ className="rounded-md rounded-tl-lg duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"
+ >
+ Card
+ </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-muted [&[hidden]]:hidden"
+ >
+ <h1>Card Preview</h1>
+ <ExploreCard
+ challenge={{
+ ...createChallengeStore.data,
+ _count: { Vote: 420 },
+ updatedAt: new Date(),
+ difficulty: 'BEGINNER',
+ }}
+ />
+ </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"
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onClick={() => router.push('/create')}
+ >
+ Continue Editing
+ </Button>
+ }
+ />
+ }
+ />
+ );
+}
diff --git a/src/components/challenge/innerIndex.tsx b/src/components/challenge/challenge-layout.tsx
similarity index 57%
rename from src/components/challenge/innerIndex.tsx
rename to src/components/challenge/challenge-layout.tsx
index 75b6fd8a..fbdb6268 100644
--- a/src/components/challenge/innerIndex.tsx
+++ b/src/components/challenge/challenge-layout.tsx
@@ -1,26 +1,62 @@
'use client';
-import { CodePanel } from './editor';
-import { DescriptionPanel } from './description-panel';
-import { useRef, useEffect } from 'react';
-import { useLayoutSettingsStore } from './layout-store';
-
-import type { Challenge } from '.';
-interface Props {
- challenge: NonNullable<Challenge>;
+import clsx from 'clsx';
+import { useRef, useEffect, type ReactNode } from 'react';
+
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
+
+export const DEFAULT_SETTINGS = {
+ width: '500px',
+ height: '300px',
+};
+
+type Settings = typeof DEFAULT_SETTINGS;
+
+interface State {
+ settings: Settings;
+ updateSettings: (settings: Settings) => void;
}
-export function InnerIndex({ challenge }: Props) {
- const parent = useRef<HTMLDivElement | null>(null);
- const resizer = useRef<HTMLDivElement | null>(null);
- const leftSide = useRef<HTMLDivElement | null>(null);
- const rightSide = useRef<HTMLDivElement | null>(null);
+export const useLayoutSettingsStore = create<State>()(
+ persist(
+ (set, get) => ({
+ settings: DEFAULT_SETTINGS,
+ updateSettings: (settings) => set({ settings: { ...get().settings, ...settings } }),
+ }),
+ {
+ name: 'challenge-layout-settings',
+ },
+ ),
+);
+
+export interface ChallengeLayoutProps {
+ left: ReactNode;
+ right: ReactNode;
+ skeleton?: boolean;
+}
+
+export function ChallengeLayout({ left, right, skeleton = false }: ChallengeLayoutProps) {
+ const parent = useRef<HTMLDivElement>(null);
+ const resizer = useRef<HTMLDivElement>(null);
+ const leftSide = useRef<HTMLDivElement>(null);
+ const rightSide = useRef<HTMLDivElement>(null);
const { settings, updateSettings } = useLayoutSettingsStore();
useEffect(() => {
const ref = resizer.current as HTMLDivElement;
const leftRef = leftSide.current as HTMLDivElement;
const rightRef = rightSide.current as HTMLDivElement;
+ const parentRef = parent.current as HTMLDivElement;
+
+ if (skeleton) {
+ parentRef.classList.remove('opacity-0');
+ window.innerWidth > 1025
+ ? (leftRef.style.width = settings.width)
+ : (leftRef.style.height = settings.height);
+
+ return;
+ }
// resize width on desktop, height on mobile
window.innerWidth > 1025
@@ -53,8 +89,8 @@ export function InnerIndex({ challenge }: Props) {
const dx = e.clientX - x;
const dy = e.clientY - y;
- const divideByW = parent?.current?.getBoundingClientRect().width as number | 1;
- const divideByH = parent?.current?.getBoundingClientRect().height as number | 1;
+ const divideByW = parent.current?.getBoundingClientRect().width as number | 1;
+ const divideByH = parent.current?.getBoundingClientRect().height as number | 1;
const newLeftWidth = ((leftWidth + dx) * 100) / divideByW;
const newTopHeight = ((topHeight + dy) * 100) / divideByH;
@@ -106,32 +142,48 @@ export function InnerIndex({ challenge }: Props) {
return () => {
ref?.removeEventListener('mousedown', mouseDownHandler);
};
- }, [settings, updateSettings]);
+ }, [settings, updateSettings, skeleton]);
return (
<div
ref={parent}
- className="flex flex-col px-4 pb-4 lg:flex-row"
+ className={clsx('flex flex-col px-4 pb-4 lg:flex-row', skeleton && 'opacity-0')}
style={{ height: 'calc(100dvh - 3.5rem)' }}
>
<div
ref={leftSide}
- className="min-h-[42px] w-full overflow-y-auto rounded-xl border border-zinc-300 bg-white dark:border-zinc-700 dark:bg-zinc-800 lg:min-w-[500px]"
+ className={clsx(
+ 'min-h-[42px] w-full overflow-y-auto rounded-xl border border-zinc-300 bg-white dark:border-zinc-700 dark:bg-zinc-800 lg:min-w-[500px]',
+ skeleton && 'animate-pulse',
+ )}
>
- <DescriptionPanel challenge={challenge} />
+ {left}
</div>
<div
ref={resizer}
- className="resizer group relative cursor-row-resize p-2 lg:cursor-col-resize"
+ className={clsx(
+ 'resizer relative p-2',
+ !skeleton && 'group cursor-row-resize lg:cursor-col-resize',
+ )}
>
- <div className="absolute left-1/2 top-1/2 h-1 w-24 -translate-x-1/2 -translate-y-1/2 rounded-full bg-neutral-400 duration-300 group-hover:bg-neutral-600 group-active:bg-emerald-400 group-active:duration-75 dark:bg-neutral-700 group-hover:dark:bg-neutral-500 lg:h-24 lg:w-1" />
+ <div
+ className={clsx(
+ 'absolute left-1/2 top-1/2 h-1 w-24 -translate-x-1/2 -translate-y-1/2 rounded-full bg-neutral-400 lg:h-24 lg:w-1',
+ skeleton
+ ? 'dark:bg-neutral-700'
+ : 'duration-300 group-hover:bg-neutral-600 group-active:bg-emerald-400 group-active:duration-75 dark:bg-neutral-700 group-hover:dark:bg-neutral-500',
+ )}
+ />
</div>
<div
ref={rightSide}
style={{ flex: '1 1 0%' }}
- className="flex min-h-[90px] w-full flex-col overflow-hidden rounded-xl border border-zinc-300 dark:border-zinc-700 lg:min-w-[500px]"
+ className={clsx(
+ 'flex flex-col overflow-hidden rounded-xl border border-zinc-300 dark:border-zinc-700 lg:min-w-[500px]',
+ skeleton ? 'items-center justify-center pb-3 dark:bg-[#1e1e1e]' : 'min-h-[90px] w-full',
+ )}
>
- <CodePanel challenge={challenge} />
+ {right}
</div>
</div>
);
diff --git a/src/components/challenge/description-panel.tsx b/src/components/challenge/description-panel.tsx
index 60a01e30..c1a0913f 100644
--- a/src/components/challenge/description-panel.tsx
+++ b/src/components/challenge/description-panel.tsx
@@ -33,7 +33,7 @@ import { Checkbox } from '../ui/checkbox';
import { TypographyLarge } from '../ui/typography/large';
import { addReport } from './report.action';
import { toast } from '../ui/use-toast';
-import { Markdown } from './markdown';
+import { Markdown } from '../ui/markdown';
interface Props {
challenge: NonNullable<Challenge>;
diff --git a/src/components/challenge/editor/constants.ts b/src/components/challenge/editor/constants.ts
index ff2c69e2..55a9f241 100644
--- a/src/components/challenge/editor/constants.ts
+++ b/src/components/challenge/editor/constants.ts
@@ -8,3 +8,5 @@ export const TEST_CASE_START = '// TEST CASE START';
* This is the fence signifies where users code starts
*/
export const USER_CODE_START = '// CODE START';
+
+export const USER_CODE_START_REGEX = new RegExp(`\n${USER_CODE_START}`);
diff --git a/src/components/challenge/editor/editor-types.ts b/src/components/challenge/editor/editor-types.ts
index 65cbae88..9b4326fe 100644
--- a/src/components/challenge/editor/editor-types.ts
+++ b/src/components/challenge/editor/editor-types.ts
@@ -37,6 +37,16 @@ type IsUnion<T, U = T> = [T] extends [never]
*/
declare function Equal<A, B>(...args: Alike<A, B> extends true ? [] : [msg: "not equal"]): void;
+
+/**
+ * Helper function to test your code.
+ *
+ * Checks that two types aren't the same
+ *
+ * To check what it is failing, you can hover over \`NotEqual\` and see what the types failing are
+ */
+declare function NotEqual<A, B>(...args: Alike<A, B> extends true ? [msg: "equal"] : []): void;
+
/**
* Helper function to test your code.
*
diff --git a/src/components/challenge/editor/index.tsx b/src/components/challenge/editor/index.tsx
index 8dc9724a..a78a0716 100644
--- a/src/components/challenge/editor/index.tsx
+++ b/src/components/challenge/editor/index.tsx
@@ -23,12 +23,12 @@ import type { Challenge } from '..';
import { saveSubmission } from '../save-submission';
import { SettingsForm } from '../settings-form';
import { useEditorSettingsStore } from '../settings-store';
-import { USER_CODE_START } from './constants';
+import { USER_CODE_START, USER_CODE_START_REGEX } from './constants';
import { libSource } from './editor-types';
import { createTwoslashInlayProvider } from './twoslash';
import { VimStatusBar } from './vimMode';
-const DEFAULT_OPTIONS: monaco.editor.IStandaloneEditorConstructionOptions = {
+const DEFAULT_OPTIONS = {
lineNumbers: 'on',
tabSize: 2,
insertSpaces: false,
@@ -36,41 +36,73 @@ const DEFAULT_OPTIONS: monaco.editor.IStandaloneEditorConstructionOptions = {
enabled: false,
},
fontSize: 16,
-} as const;
+} as const satisfies monaco.editor.IStandaloneEditorConstructionOptions;
const LIB_URI = 'ts:filename/checking.d.ts';
type Monaco = typeof monaco;
-interface Props {
- challenge: NonNullable<Challenge>;
-}
+type Props = (
+ | {
+ mode: 'solve';
+ challenge: Pick<NonNullable<Challenge>, 'Solution' | 'prompt' | 'id'>;
+ 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 TsErrors = [
+ SemanticDiagnostics: monaco.languages.typescript.Diagnostic[],
+ SyntacticDiagnostics: monaco.languages.typescript.Diagnostic[],
+ SuggestionDiagnostics: monaco.languages.typescript.Diagnostic[],
+ CompilerOptionsDiagnostics: monaco.languages.typescript.Diagnostic[],
+];
const libCache = new Set<string>();
-export const CodePanel = ({ challenge }: Props) => {
+
+export const CodePanel = (props: Props) => {
const router = useRouter();
const { toast } = useToast();
const { theme } = useTheme();
const { data: session } = useSession();
const { settings } = useEditorSettingsStore();
- const [hasErrors, setHasErrors] = useState(false);
+ const [tsErrors, setTsErrors] = useState<TsErrors>([[], [], [], []]);
const [initialTypecheckDone, setInitialTypecheckDone] = useState(false);
+ // Prisma.JsonValue
const defaultCode = useMemo(() => {
+ if (props.mode !== 'solve') return props.prompt ?? '';
+
// if a user has an existing solution use that instead of prompt
- const usersExistingSolution = challenge.Solution?.[0];
+ const usersExistingSolution = props.challenge.Solution?.[0];
if (!usersExistingSolution) {
- return challenge.prompt;
+ return props.challenge.prompt;
}
- const [appendSolutionToThis, separator] = (challenge.prompt as string).split(
- /(\/\/ CODE START)/g,
+ const [appendSolutionToThis, separator] = (props.challenge.prompt as string).split(
+ USER_CODE_START_REGEX,
);
const parsedUserSolution = JSON.parse(usersExistingSolution?.code as string) as string;
return `${appendSolutionToThis ?? ''}${separator ?? ''}${parsedUserSolution}`;
- }, [challenge.Solution, challenge.prompt]);
+ }, [props.challenge?.Solution, props.challenge?.prompt, props.mode, props.prompt]);
+
const [code, setCode] = useState(defaultCode as string);
const editorTheme = theme === 'light' ? 'vs' : 'vs-dark';
@@ -89,33 +121,83 @@ export const CodePanel = ({ challenge }: Props) => {
};
}, [settings]);
- const handleSubmit = async () => {
- const [, solution] = code.split(USER_CODE_START);
+ const handleSubmit =
+ props.mode === 'solve'
+ ? async () => {
+ const [, solution] = code.split(USER_CODE_START);
- if (hasErrors) {
- toast({
- variant: 'destructive',
- title: 'Uh oh! You still have errors.',
- action: <ToastAction altText="Try again">Try again</ToastAction>,
- });
- } else {
- await saveSubmission(
- challenge?.id,
- session?.user?.id as string,
- JSON.stringify(solution) ?? '',
- );
- router.refresh();
- toast({
- variant: 'success',
- title: 'Good job!',
- description: 'You completed this challenge.',
- action: <ToastAction altText="Try again">Dismiss</ToastAction>,
- });
- }
- };
+ const hasErrors = tsErrors.some((e) => e.length);
+
+ if (hasErrors) {
+ toast({
+ variant: 'destructive',
+ title: 'Uh oh! You still have errors.',
+ action: <ToastAction altText="Try again">Try again</ToastAction>,
+ });
+ } else {
+ await saveSubmission(
+ props.challenge.id,
+ session?.user?.id as string,
+ JSON.stringify(solution) ?? '',
+ );
+ router.refresh();
+ 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)</.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;
+
+ 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 onMount =
- (value: string, onError: (v: boolean) => void) =>
+ (value: string, onError: (v: TsErrors) => void) =>
async (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => {
const lineWithUserCode = value
.split('\n')
@@ -151,18 +233,18 @@ export const CodePanel = ({ challenge }: Props) => {
ts.getCompilerOptionsDiagnostics(filename),
] as const);
- const hasErrors = errors.some((e) => e.length);
-
- onError(hasErrors);
+ onError(errors);
};
// 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) => {
- // 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);
+ 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);
@@ -194,13 +276,13 @@ export const CodePanel = ({ challenge }: Props) => {
</DialogContent>
</Dialog>
</div>
- <div className="flex-1">
+ <div className="w-full flex-1">
<Editor
theme={editorTheme}
options={editorOptions}
defaultLanguage="typescript"
// eslint-disable-next-line @typescript-eslint/no-misused-promises
- onMount={onMount(code, setHasErrors)}
+ onMount={onMount(code, setTsErrors)}
value={code}
onChange={(code) => setCode(code ?? '')}
/>
@@ -214,30 +296,31 @@ export const CodePanel = ({ challenge }: Props) => {
)}
>
{editorState && <VimStatusBar editor={editorState} />}
- <TooltipProvider>
- <Tooltip delayDuration={0.05} open={session?.user?.id ? false : undefined}>
- <TooltipTrigger asChild>
- <span>
- <Button
- size="sm"
- className="cursor-pointer 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>
- </span>
- </TooltipTrigger>
- <TooltipContent>
- <p>Login to Submit</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
+ <div className="flex items-center justify-center gap-4">
+ {props.extraButton}
+ <TooltipProvider>
+ <Tooltip delayDuration={0.05} open={session?.user?.id ? false : undefined}>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ size="sm"
+ className="cursor-pointer 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>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Login to Submit</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
</div>
</>
);
};
-
-CodePanel.displayName = 'CodePanel' as const;
diff --git a/src/components/challenge/index.tsx b/src/components/challenge/index.tsx
index 0850dc2f..694d6087 100644
--- a/src/components/challenge/index.tsx
+++ b/src/components/challenge/index.tsx
@@ -2,13 +2,16 @@ import { type Session, getServerSession } from 'next-auth';
import { notFound } from 'next/navigation';
import { prisma } from '~/server/db';
-import { InnerIndex } from './innerIndex';
+import { ChallengeLayout } from './challenge-layout';
+import { DescriptionPanel } from './description-panel';
+import { CodePanel } from './editor';
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);
@@ -17,7 +20,12 @@ export async function Challenge({ id }: Props) {
return notFound();
}
- return <InnerIndex challenge={challenge} />;
+ return (
+ <ChallengeLayout
+ left={<DescriptionPanel challenge={challenge} />}
+ right={<CodePanel mode="solve" challenge={challenge} />}
+ />
+ );
}
async function getChallenge(id: string, session: Session | null) {
diff --git a/src/components/challenge/layout-store.ts b/src/components/challenge/layout-store.ts
deleted file mode 100644
index 502844d3..00000000
--- a/src/components/challenge/layout-store.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { create } from 'zustand';
-import { persist } from 'zustand/middleware';
-
-export const DEFAULT_SETTINGS = {
- width: '500px',
- height: '300px',
-};
-
-type Settings = typeof DEFAULT_SETTINGS;
-
-interface State {
- settings: Settings;
- updateSettings: (settings: Settings) => void;
-}
-
-export const useLayoutSettingsStore = create<State>()(
- persist(
- (set, get) => ({
- settings: DEFAULT_SETTINGS,
- updateSettings: (settings) => set({ settings: { ...get().settings, ...settings } }),
- }),
- {
- name: 'challenge-layout-settings',
- },
- ),
-);
diff --git a/src/components/challenge/markdown.tsx b/src/components/challenge/markdown.tsx
deleted file mode 100644
index 115e37f5..00000000
--- a/src/components/challenge/markdown.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { ReactNode } from 'react';
-import ReactMarkdown from 'react-markdown';
-import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
-import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
-import remarkGfm from 'remark-gfm';
-
-interface Props {
- children: ReactNode;
-}
-export function Markdown({ children }: Props) {
- return (
- // @ts-ignore
- <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>
- );
- },
- }}
- >
- {children}
- </ReactMarkdown>
- );
-}
diff --git a/src/components/challenge/skeleton.tsx b/src/components/challenge/skeleton.tsx
index 54d31420..0966c2df 100644
--- a/src/components/challenge/skeleton.tsx
+++ b/src/components/challenge/skeleton.tsx
@@ -1,43 +1,8 @@
'use client';
+import { ChallengeLayout } from './challenge-layout';
import { DescriptionPanelSkeleton } from './description-panel-skeleton';
-import { useLayoutSettingsStore } from './layout-store';
-import { useRef, useEffect } from 'react';
export function ChallengeSkeleton() {
- const leftSide = useRef<HTMLDivElement | null>(null);
- const wholeThing = useRef<HTMLDivElement | null>(null);
- const { settings } = useLayoutSettingsStore();
-
- useEffect(() => {
- const wholeRef = wholeThing.current as HTMLDivElement;
- const leftRef = leftSide.current as HTMLDivElement;
- wholeRef.classList.remove('opacity-0');
- window.innerWidth > 1025
- ? (leftRef.style.width = settings.width)
- : (leftRef.style.height = settings.height);
- }, [settings]);
- return (
- <div
- ref={wholeThing}
- className="flex flex-col px-4 pb-4 opacity-0 lg:flex-row"
- style={{ height: 'calc(100dvh - 3.5rem)' }}
- >
- <div
- ref={leftSide}
- className="w-full min-w-full animate-pulse overflow-y-auto rounded-xl border border-zinc-300 bg-white dark:border-zinc-700 dark:bg-zinc-800 lg:min-w-[500px]"
- >
- <DescriptionPanelSkeleton />
- </div>
- <div className="resizer relative p-2">
- <div className="absolute left-1/2 top-1/2 h-1 w-24 -translate-x-1/2 -translate-y-1/2 rounded-full bg-neutral-400 dark:bg-neutral-700 lg:h-24 lg:w-1" />
- </div>
- <div
- style={{ flex: '1 1 0%' }}
- className="flex flex-col items-center justify-center overflow-hidden rounded-xl border border-zinc-300 pb-3 dark:border-zinc-700 dark:bg-[#1e1e1e] lg:min-w-[500px]"
- >
- Loading...
- </div>
- </div>
- );
+ return <ChallengeLayout skeleton left={<DescriptionPanelSkeleton />} right={'Loading...'} />;
}
diff --git a/src/components/explore/explore-card.tsx b/src/components/explore/explore-card.tsx
index d2be9000..be454b49 100644
--- a/src/components/explore/explore-card.tsx
+++ b/src/components/explore/explore-card.tsx
@@ -9,7 +9,10 @@ import { Markdown } from '../ui/markdown';
import getRelativeTime from '~/utils/relativeTime';
interface Props {
- challenge: Awaited<Challenge>[0];
+ challenge: Pick<
+ Awaited<Challenge>[0],
+ 'difficulty' | 'name' | 'shortDescription' | '_count' | 'updatedAt'
+ >;
}
const BORDERS_BY_DIFFICULTY = {
diff --git a/src/components/ui/markdown.tsx b/src/components/ui/markdown.tsx
index b16f5706..ad42c595 100644
--- a/src/components/ui/markdown.tsx
+++ b/src/components/ui/markdown.tsx
@@ -1,23 +1,23 @@
'use client';
import ReactMarkdown from 'react-markdown';
-import SyntaxHighlighter from 'react-syntax-highlighter';
+import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import remarkGfm from 'remark-gfm';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
+import clsx from 'clsx';
export function Markdown({ children }: { children: string }) {
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
- p: ({ ...props }) => <p className="mb-4" {...props} />,
- code({ inline, className, children, ...props }) {
+ p: ({ className, ...props }) => <p className={clsx(className, 'mb-4')} {...props} />,
+ code({ inline, className, children, style: _, ...props }) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter
- // @ts-ignore
style={vscDarkPlus} // theme
- className="rounded-xl dark:rounded-md"
+ className={clsx(className, 'rounded-xl dark:rounded-md')}
language={match[1]}
PreTag="section" // parent tag
{...props}
diff --git a/tailwind.config.ts b/tailwind.config.ts
index 3f945f7d..1831a78f 100644
--- a/tailwind.config.ts
+++ b/tailwind.config.ts
@@ -1,4 +1,5 @@
-const { fontFamily } = require('tailwindcss/defaultTheme');
+// eslint-disable-next-line
+const { fontFamily } = require('tailwindcss/defaultTheme') as typeof import('tailwindcss/defaultTheme');
/** @type {import('tailwindcss').Config} */
module.exports = {
@@ -54,8 +55,8 @@ module.exports = {
},
},
borderRadius: {
- lg: `var(--radius)`,
- md: `calc(var(--radius) - 2px)`,
+ lg: 'var(--radius)',
+ md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
},
fontFamily: {
diff --git a/tsconfig.json b/tsconfig.json
index bf347be7..92b25310 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -35,10 +35,11 @@
"include": [
".eslintrc.cjs",
"next-env.d.ts",
- "**/*.ts",
- "**/*.tsx",
- "**/*.cjs",
- "**/*.mjs",
+ "*.ts",
+ "./src/**/*.ts",
+ "./src/**/*.tsx",
+ "./src/**/*.cjs",
+ "./src/**/*.mjs",
".next/types/**/*.ts"
],
"exclude": [