Connect, collaborate, and grow with a community of TypeScript developers
Refactor the fences and update seeding (#59)
Sean Boult9bd841a88f22
diff --git a/__seed__/beginner/prompt.md b/__seed__/beginner/prompt.mdindex 51f7591f..fd5ccd92 100644--- a/__seed__/beginner/prompt.md+++ b/__seed__/beginner/prompt.md@@ -1,7 +1,6 @@-/* _____________ Test Cases _____________ */+// TEST CASE STARTExtends<HelloWorld, `Hello, ${string}`>()Extends<HelloWorld, `${string}!`>()-/* _____________ Your Code Here _____________ */-type HelloWorld = ""+// CODE STARTdiff --git a/__seed__/easy/desc.md b/__seed__/easy/desc.mdindex d9365684..d89071a7 100644--- a/__seed__/easy/desc.md+++ b/__seed__/easy/desc.md@@ -6,15 +6,15 @@ For example:```tsinterface Todo {- title: string- description: string- completed: boolean+ title: string;+ description: string;+ completed: boolean;}-type TodoPreview = MyPick<Todo, 'title' | 'completed'>+type TodoPreview = MyPick<Todo, 'title' | 'completed'>;const todo: TodoPreview = {- title: 'Clean room',- completed: false,-}+ title: 'Clean room',+ completed: false,+};```diff --git a/__seed__/easy/prompt.md b/__seed__/easy/prompt.mdindex cef2cc13..bf70b2c7 100644--- a/__seed__/easy/prompt.md+++ b/__seed__/easy/prompt.md@@ -1,8 +1,8 @@-/* _____________ Test Cases _____________ */-Extends<HelloWorld, `Hello, \${string}`>()+// TEST CASE START+Extends<HelloWorld, `Hello, ${string}`>()Extends<HelloWorld, `${string}!`>()-/* _____________ Your Code Here _____________ */-type HelloWorld = ""+// CODE START+type HelloWorld = ""diff --git a/__seed__/extreme/desc.md b/__seed__/extreme/desc.mdindex 722a1021..0ca9a58f 100644--- a/__seed__/extreme/desc.md+++ b/__seed__/extreme/desc.md@@ -1,5 +1,5 @@Implement a generic `GetReadonlyKeys<T>` that returns a union of the readonly keys of an Object.-# THIS IS A TEST+For example```tsdiff --git a/__seed__/extreme/prompt.md b/__seed__/extreme/prompt.mdindex b48fffa4..3e23a101 100644--- a/__seed__/extreme/prompt.md+++ b/__seed__/extreme/prompt.md@@ -1,7 +1,7 @@-/* _____________ Test Cases _____________ */+// TEST CASE STARTExtends<HelloWorld, `Hello, \${string}\`>()Extends<HelloWorld, `\${string}!\`>()-/* _____________ Your Code Here _____________ */+// CODE STARTtype HelloWorld = ""diff --git a/__seed__/hard/desc.md b/__seed__/hard/desc.mdindex 5cf52573..f345250c 100644--- a/__seed__/hard/desc.md+++ b/__seed__/hard/desc.md@@ -1,4 +1,4 @@-Implement a simpiled version of a Vue-like typing support.+Implement a simple version of a Vue-like typing support.By providing a function name `SimpleVue` (similar to `Vue.extend` or `defineComponent`), it should properly infer the `this` type inside computed and methods.diff --git a/__seed__/hard/prompt.md b/__seed__/hard/prompt.mdindex b48fffa4..3e23a101 100644--- a/__seed__/hard/prompt.md+++ b/__seed__/hard/prompt.md@@ -1,7 +1,7 @@-/* _____________ Test Cases _____________ */+// TEST CASE STARTExtends<HelloWorld, `Hello, \${string}\`>()Extends<HelloWorld, `\${string}!\`>()-/* _____________ Your Code Here _____________ */+// CODE STARTtype HelloWorld = ""diff --git a/__seed__/medium/prompt.md b/__seed__/medium/prompt.mdindex b48fffa4..3e23a101 100644--- a/__seed__/medium/prompt.md+++ b/__seed__/medium/prompt.md@@ -1,7 +1,7 @@-/* _____________ Test Cases _____________ */+// TEST CASE STARTExtends<HelloWorld, `Hello, \${string}\`>()Extends<HelloWorld, `\${string}!\`>()-/* _____________ Your Code Here _____________ */+// CODE STARTtype HelloWorld = ""diff --git a/prisma/seed.ts b/prisma/seed.tsindex c4d29498..7d9a4b51 100644--- a/prisma/seed.ts+++ b/prisma/seed.ts@@ -9,6 +9,7 @@ const randomDifficulty = (): Difficulty => {return DIFFICULTIES[Math.floor(Math.random() * DIFFICULTIES.length)] as Difficulty;};+// TODO: make this deterministic as the seed should always have the same difficultyconst challenges = (): Prisma.ChallengeCreateNestedManyWithoutUserInput => ({create: Array.from({ length: CHALLENGES_TO_CREATE }, (_, challengeIndex) =>CHALLENGE_MAP[randomDifficulty()](challengeIndex),diff --git a/src/components/challenge/editor/constants.ts b/src/components/challenge/editor/constants.tsnew file mode 100644index 00000000..ff2c69e2--- /dev/null+++ b/src/components/challenge/editor/constants.ts@@ -0,0 +1,10 @@+/**+ * This is the fence that a challenge starts with+ * @deprecated this doesn't even make sense because it's probably always 0+ */+export const TEST_CASE_START = '// TEST CASE START';++/**+ * This is the fence signifies where users code starts+ */+export const USER_CODE_START = '// CODE START';diff --git a/src/components/challenge/editor/index.tsx b/src/components/challenge/editor/index.tsxindex eea726b5..9b7d75d1 100644--- a/src/components/challenge/editor/index.tsx+++ b/src/components/challenge/editor/index.tsx@@ -23,6 +23,7 @@ import { libSource } from './editor-types';import { createTwoslashInlayProvider } from './twoslash';import { VimStatusBar } from './vimMode';import type { Challenge } from '..';+import { USER_CODE_START } from './constants';const DEFAULT_OPTIONS: monaco.editor.IStandaloneEditorConstructionOptions = {lineNumbers: 'on',@@ -42,7 +43,7 @@ interface Props {challenge: NonNullable<Challenge>;}-const libCache = new Set<string>();+const libCache = new Set < string > ();export const CodePanel = ({ challenge }: Props) => {const { toast } = useToast();const { theme } = useTheme();@@ -51,11 +52,11 @@ export const CodePanel = ({ challenge }: Props) => {const { settings } = useEditorSettingsStore();const [hasErrors, setHasErrors] = useState(false);const [initialTypecheckDone, setInitialTypecheckDone] = useState(false);- const [code, setCode] = useState<string>(challenge?.prompt as string);+ const [code, setCode] = useState < string > (challenge?.prompt as string);const editorTheme = theme === 'light' ? 'vs' : 'vs-dark';- const modelRef = useRef<monaco.editor.ITextModel>();+ const modelRef = useRef < monaco.editor.ITextModel > ();// ref doesnt cause a rerender- const [editorState, setEditorState] = useState<monaco.editor.IStandaloneCodeEditor>();+ const [editorState, setEditorState] = useState < monaco.editor.IStandaloneCodeEditor > ();const editorOptions = useMemo(() => {const options = {...DEFAULT_OPTIONS,@@ -69,7 +70,7 @@ export const CodePanel = ({ challenge }: Props) => {}, [settings]);const handleSubmit = async () => {- const [, solution] = code.split('/* _____________ Your Code Here _____________ */');+ const [, solution] = code.split(USER_CODE_START);if (hasErrors) {toast({@@ -94,73 +95,63 @@ export const CodePanel = ({ challenge }: Props) => {const onMount =(value: string, onError: (v: boolean) => void) =>- async (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => {- const numLines = value.split('\n').length;- const lastLineLength = value.split('\n').at(-1)?.length || 1;+ async (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => {+ const lineWithUserCode =+ value.split('\n').findIndex((line) => line.includes(USER_CODE_START));++ // once you register a lib you cant unregister it (idk how to unregister it)+ // so when editor mounts again it tries to add the lib again and throws an error+ if (!libCache.has(libSource)) {+ monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, LIB_URI);+ monaco.editor.createModel(libSource, 'typescript', monaco.Uri.parse(LIB_URI));+ libCache.add(libSource);+ }- // once you register a lib you cant unregister it (idk how to unregister it)- // so when editor mounts again it tries to add the lib again and throws an error- if (!libCache.has(libSource)) {- monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, LIB_URI);- monaco.editor.createModel(libSource, 'typescript', monaco.Uri.parse(LIB_URI));- libCache.add(libSource);- }+ const model = editor.getModel();- const model = editor.getModel();+ if (!model) {+ throw new Error();+ }- if (!model) {- throw new Error();- }+ modelRef.current = model;+ setEditorState(editor);- modelRef.current = model;- setEditorState(editor);+ 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);+ const hasErrors = errors.some((e) => e.length);- const hasErrors = errors.some((e) => e.length);+ onError(hasErrors);+ };- onError(hasErrors);- };-- let fixingStart = false;-- model.onDidChangeContent((e) => {- if (- e.changes.some(- (c) =>- c.range.startLineNumber < numLines ||- (c.range.startLineNumber === numLines && c.range.startColumn <= lastLineLength),- )- ) {- if (!fixingStart && !e.isUndoing && !e.isRedoing) {- editor.trigger('someIdString', e.isUndoing ? 'redo' : 'undo', null);+ 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);}- fixingStart = !fixingStart;- }-- typeCheck().catch(console.error);- });+ typeCheck().catch(console.error);+ });- await typeCheck();- setInitialTypecheckDone(true);+ await typeCheck();+ setInitialTypecheckDone(true);- monaco.languages.registerInlayHintsProvider(- 'typescript',- createTwoslashInlayProvider(monaco, ts),- );- };+ monaco.languages.registerInlayHintsProvider(+ 'typescript',+ createTwoslashInlayProvider(monaco, ts),+ );+ };return (<div className="col-span-2 flex flex-1 flex-col overflow-hidden rounded-xl border border-zinc-300 dark:border-zinc-700">diff --git a/src/components/challenge/solutions.tsx b/src/components/challenge/solutions.tsxindex 38f9f826..0c1d8b1a 100644--- a/src/components/challenge/solutions.tsx+++ b/src/components/challenge/solutions.tsx@@ -27,6 +27,7 @@ export function Solutions({ challenge }: Props) {);}+// eslint-disable-next-line @typescript-eslint/no-unused-varsfunction SolutionRow() {const date = new Date();return (