Skip to content

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

feat: adds a challenge playground (#788)

bautistaaa0b33d1affc61
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/challenge-playground-store.ts b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/challenge-playground-store.ts
new file mode 100644
index 00000000..1971b285
--- /dev/null
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/challenge-playground-store.ts
@@ -0,0 +1,30 @@
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
+
+export const DEFAULT_VALUES = {
+ prompt: '### Description',
+ challenge: {
+ id: 1,
+ code: 'type Foo = string;',
+ tests: '// test cases go here',
+ },
+};
+
+type Values = typeof DEFAULT_VALUES;
+
+interface State {
+ values: Values;
+ updateValues: (values: Values) => void;
+}
+
+export const useChallengePlaygroundStore = create<State>()(
+ persist(
+ (set, get) => ({
+ values: DEFAULT_VALUES,
+ updateValues: (values) => set({ values: { ...get().values, ...values } }),
+ }),
+ {
+ name: 'challenge-playground',
+ },
+ ),
+);
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/description.tsx b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/description.tsx
new file mode 100644
index 00000000..6bcc599f
--- /dev/null
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/description.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { RichMarkdownEditor } from '~/components/rich-markdown-editor';
+import { useChallengePlaygroundStore } from './challenge-playground-store';
+
+export function Description() {
+ const { values, updateValues } = useChallengePlaygroundStore();
+ return (
+ <RichMarkdownEditor
+ onChange={(v) => updateValues({ ...values, prompt: v as string })}
+ value={values.prompt}
+ />
+ );
+}
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/layout.tsx b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/layout.tsx
new file mode 100644
index 00000000..39f5975c
--- /dev/null
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/layout.tsx
@@ -0,0 +1,19 @@
+import { ForceRenderUntilClient } from '@repo/ui/components/force-render-until-client';
+import { ChallengeLayout } from '../../challenge/_components/challenge-layout';
+import { LeftWrapper } from './left-wrapper';
+import { Wrapper } from './wrapper';
+import { getServerAuthSession } from '@repo/auth/server';
+import { isAdminOrModerator } from '~/utils/auth-guards';
+import { redirect } from 'next/navigation';
+
+export default async function LayoutData({ children }: { children: React.ReactNode }) {
+ const session = await getServerAuthSession();
+ if (!isAdminOrModerator(session)) {
+ return redirect('/');
+ }
+ return (
+ <ForceRenderUntilClient>
+ <ChallengeLayout left={<LeftWrapper>{children}</LeftWrapper>} right={<Wrapper />} />
+ </ForceRenderUntilClient>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/left-wrapper.tsx b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/left-wrapper.tsx
new file mode 100644
index 00000000..8372c497
--- /dev/null
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/left-wrapper.tsx
@@ -0,0 +1,11 @@
+'use client';
+
+import { type ReactNode } from 'react';
+
+interface Props {
+ children: ReactNode;
+}
+
+export function LeftWrapper({ children }: Props) {
+ return <div className="flex h-full w-full flex-col">{children}</div>;
+}
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/page.tsx b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/page.tsx
new file mode 100644
index 00000000..779f37ca
--- /dev/null
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/page.tsx
@@ -0,0 +1,9 @@
+import { Description } from './description';
+
+export default async function ChallengePlaygroundPage() {
+ return (
+ <div className="relative h-full">
+ <Description />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/wrapper.tsx b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/wrapper.tsx
new file mode 100644
index 00000000..c77e82cd
--- /dev/null
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/wrapper.tsx
@@ -0,0 +1,38 @@
+'use client';
+import { CodePanel, type CodePanelProps } from '@repo/monaco';
+import { EditorShortcutsButton } from '../../challenge/_components/editor-shortcuts/editor-shortcuts-button';
+import { FullscreenButton } from '../../challenge/_components/fullscreen';
+import { ResetEditorButton } from '../../challenge/_components/reset-editor-button';
+import { SettingsButton } from '../../challenge/_components/settings/settings-button';
+import { useChallengePlaygroundStore } from './challenge-playground-store';
+
+export function Wrapper() {
+ const { values, updateValues } = useChallengePlaygroundStore();
+ const updatePlaygroundTestsLocalStorage = (code: string) => {
+ updateValues({ ...values, challenge: { ...values.challenge, tests: code } });
+ };
+ const updatePlaygroundCodeLocalStorage = (code: string) => {
+ updateValues({ ...values, challenge: { ...values.challenge, code } });
+ };
+ return (
+ <CodePanel
+ challenge={values.challenge}
+ saveSubmission={(() => {}) as unknown as CodePanelProps['saveSubmission']}
+ submissionDisabled={false}
+ settingsElement={<SettingsElements />}
+ updatePlaygroundTestsLocalStorage={updatePlaygroundTestsLocalStorage}
+ updatePlaygroundCodeLocalStorage={updatePlaygroundCodeLocalStorage}
+ />
+ );
+}
+
+function SettingsElements() {
+ return (
+ <>
+ <ResetEditorButton />
+ <EditorShortcutsButton />
+ <SettingsButton />
+ <FullscreenButton />
+ </>
+ );
+}
diff --git a/apps/web/src/components/navigation.tsx b/apps/web/src/components/navigation.tsx
index 48e1f7e1..2e70bbd0 100644
--- a/apps/web/src/components/navigation.tsx
+++ b/apps/web/src/components/navigation.tsx
@@ -2,13 +2,6 @@
import { signIn, signOut, useSession } from '@repo/auth/react';
import { type RoleTypes } from '@repo/db/types';
-import { Loader2, LogIn, Moon, Plus, Settings, Settings2, Sun, User } from '@repo/ui/icons';
-import clsx from 'clsx';
-import { useTheme } from 'next-themes';
-import Link from 'next/link';
-import { usePathname, useRouter } from 'next/navigation';
-import { useContext, useEffect, useState } from 'react';
-import { FeatureFlagContext } from '~/app/feature-flag-provider';
import { Button } from '@repo/ui/components/button';
import {
DropdownMenu,
@@ -17,7 +10,15 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@repo/ui/components/dropdown-menu';
+import { Loader2, LogIn, Moon, Play, Settings, Settings2, Sun, User } from '@repo/ui/icons';
+import clsx from 'clsx';
+import { useTheme } from 'next-themes';
+import Link from 'next/link';
+import { usePathname, useRouter } from 'next/navigation';
+import { useContext, useEffect, useState } from 'react';
import { useFullscreenSettingsStore } from '~/app/[locale]/challenge/_components/fullscreen';
+import { FeatureFlagContext } from '~/app/feature-flag-provider';
+import { isAdminOrModerator } from '~/utils/auth-guards';
export function getAdminUrl() {
// reference for vercel.com
@@ -39,6 +40,7 @@ const roleTypes: typeof RoleTypes = {
export function Navigation() {
const { fssettings } = useFullscreenSettingsStore();
const pathname = usePathname();
+ const { data } = useSession();
const featureFlags = useContext(FeatureFlagContext);
return (
@@ -148,9 +150,7 @@ function LoginButton() {
const { data: session, status } = useSession();
const router = useRouter();
- const isAdmin = session?.user.role.includes(roleTypes.ADMIN);
- const isMod = session?.user.role.includes(roleTypes.MODERATOR);
- const isAdminOrMod = isAdmin || isMod;
+ const isAdminOrMod = isAdminOrModerator(session);
// NOTE: 1. loading == true -> 2. signIn() -> 3. session status == 'loading' (loading == false)
const handleSignIn = async () => {
@@ -182,12 +182,6 @@ function LoginButton() {
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="/wizard">
- <DropdownMenuItem className="focus:bg-accent rounded-lg p-2 duration-300 focus:outline-none dark:hover:bg-neutral-700/50">
- <Plus className="mr-2 h-4 w-4" />
- <span>Create a Challenge</span>
- </DropdownMenuItem>
- </Link>
<Link className="block" href={`/@${session.user.name}`}>
<DropdownMenuItem className="focus:bg-accent rounded-lg p-2 duration-300 focus:outline-none dark:hover:bg-neutral-700/50">
<User className="mr-2 h-4 w-4" />
@@ -208,6 +202,14 @@ function LoginButton() {
</DropdownMenuItem>
</a>
) : null}
+ {isAdminOrMod ? (
+ <a className="block" href="/challenge-playground">
+ <DropdownMenuItem className="focus:bg-accent rounded-lg p-2 duration-300 focus:outline-none dark:hover:bg-neutral-700/50">
+ <Play className="mr-2 h-4 w-4" />
+ <span>Challenge Playground</span>
+ </DropdownMenuItem>
+ </a>
+ ) : null}
<DropdownMenuSeparator />
<Button
className="h-8 w-full justify-start rounded-b-lg rounded-t-sm bg-opacity-50 px-2 text-red-500 hover:bg-red-500/20 hover:text-red-500"
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
index ad5e0338..9bef28bc 100644
--- a/apps/web/src/middleware.ts
+++ b/apps/web/src/middleware.ts
@@ -21,6 +21,7 @@ export function middleware(req: NextRequest) {
if (
path === '/explore' ||
path.startsWith('/challenge') ||
+ path.startsWith('/challenge-playground') ||
path.startsWith('/challenge/') ||
path.startsWith('/tracks') ||
path.startsWith('/tracks/')
diff --git a/packages/monaco/src/index.tsx b/packages/monaco/src/index.tsx
index bbc00000..0830de9e 100644
--- a/packages/monaco/src/index.tsx
+++ b/packages/monaco/src/index.tsx
@@ -1,20 +1,20 @@
'use client';
+import { Button } from '@repo/ui/components/button';
+import { ToastAction } from '@repo/ui/components/toast';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
+import { useToast } from '@repo/ui/components/use-toast';
+import { CheckCircle2, ChevronUp, XCircle } from '@repo/ui/icons';
import clsx from 'clsx';
-import { ChevronUp, Loader2, XCircle, CheckCircle2 } from '@repo/ui/icons';
+import lzstring from 'lz-string';
import type * as monaco from 'monaco-editor';
-import { useRouter, useSearchParams } from 'next/navigation';
+import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import React, { useState } from 'react';
-import lzstring from 'lz-string';
-import { useLocalStorage } from './useLocalStorage';
+import { useResetEditor } from './editor-hooks';
+import { PrettierFormatProvider } from './prettier';
import SplitEditor, { TESTS_PATH, USER_CODE_PATH } from './split-editor';
import { createTwoslashInlayProvider } from './twoslash';
-import { PrettierFormatProvider } from './prettier';
-import { useResetEditor } from './editor-hooks';
-import { useToast } from '@repo/ui/components/use-toast';
-import { ToastAction } from '@repo/ui/components/toast';
-import { Button } from '@repo/ui/components/button';
-import { Tooltip, TooltipTrigger, TooltipContent } from '@repo/ui/components/tooltip';
+import { useLocalStorage } from './useLocalStorage';
export interface CodePanelProps {
challenge: {
@@ -25,6 +25,8 @@ export interface CodePanelProps {
saveSubmission: (code: string, isSuccessful: boolean) => Promise<void>;
submissionDisabled: boolean;
settingsElement: React.ReactNode;
+ updatePlaygroundTestsLocalStorage?: (code: string) => void;
+ updatePlaygroundCodeLocalStorage?: (code: string) => void;
}
export type TsErrors = [
@@ -36,6 +38,8 @@ export type TsErrors = [
export function CodePanel(props: CodePanelProps) {
const params = useSearchParams();
const router = useRouter();
+ const pathname = usePathname();
+ const isPlayground = pathname.includes('playground');
const { toast } = useToast();
const [tsErrors, setTsErrors] = useState<TsErrors>();
const [isTestPanelExpanded, setIsTestPanelExpanded] = useState(false);
@@ -96,6 +100,7 @@ export function CodePanel(props: CodePanelProps) {
{props.settingsElement}
</div>
<SplitEditor
+ isTestsReadonly={!isPlayground}
userEditorState={userEditorState}
monaco={monacoInstance}
expandTestPanel={isTestPanelExpanded}
@@ -159,8 +164,16 @@ export function CodePanel(props: CodePanelProps) {
},
}}
onChange={{
+ tests: (code) => {
+ if (isPlayground) {
+ props.updatePlaygroundTestsLocalStorage?.(code ?? '');
+ }
+ },
user: async (code) => {
if (!monacoInstance) return null;
+ if (isPlayground) {
+ props.updatePlaygroundCodeLocalStorage?.(code ?? '');
+ }
setCode(code ?? '');
setLocalStorageCode(code ?? '');
const getTsWorker = await monacoInstance.languages.typescript.getTypeScriptWorker();
diff --git a/packages/monaco/src/split-editor.tsx b/packages/monaco/src/split-editor.tsx
index d796c2f2..56d72308 100644
--- a/packages/monaco/src/split-editor.tsx
+++ b/packages/monaco/src/split-editor.tsx
@@ -46,21 +46,24 @@ export interface SplitEditorProps {
};
monaco: typeof import('monaco-editor') | undefined;
userEditorState?: monacoType.editor.IStandaloneCodeEditor;
+ isTestsReadonly?: boolean;
}
// million-ignore
export default function SplitEditor({
className,
- userEditorState,
+ isTestsReadonly = true,
expandTestPanel,
+ monaco,
+ onChange,
+ onMount,
+ onValidate,
setIsTestPanelExpanded,
tests,
userCode,
- onMount,
- onValidate,
- onChange,
- monaco,
+ userEditorState,
}: SplitEditorProps) {
+ console.log({ isTestsReadonly });
const { settings, updateSettings } = useEditorSettingsStore();
const { subscribe } = useResetEditor();
@@ -236,7 +239,7 @@ export default function SplitEditor({
}}
onMount={(editor, monaco) => {
editor.updateOptions({
- readOnly: true,
+ readOnly: isTestsReadonly,
renderValidationDecorations: 'on',
});
@@ -245,7 +248,10 @@ export default function SplitEditor({
defaultPath={TESTS_PATH}
value={tests}
defaultValue={tests}
- onChange={onChange?.tests}
+ onChange={async (e, a) => {
+ console.log({ e, a });
+ onChange?.tests?.(e, a);
+ }}
onValidate={onValidate?.tests}
/>
</div>