Skip to content

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

reactify editor

bautistaaa5e91c9cf265b
diff --git a/src/components/challenge/description-panel.tsx b/src/components/challenge/description-panel.tsx
index 9897a000..e056cd26 100644
--- a/src/components/challenge/description-panel.tsx
+++ b/src/components/challenge/description-panel.tsx
@@ -161,7 +161,6 @@ export function DescriptionPanel({ challenge }: Props) {
components={{
p: ({ ...props }) => <p className="mb-4" {...props} />,
code({ inline, className, children, ...props }) {
- console.log(children);
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter
diff --git a/src/components/challenge/editor/editor-types.ts b/src/components/challenge/editor/editor-types.ts
new file mode 100644
index 00000000..65cbae88
--- /dev/null
+++ b/src/components/challenge/editor/editor-types.ts
@@ -0,0 +1,48 @@
+/**
+ * These types are used in the editor instance.
+ * Essentially, utility types to help test / debug code
+ * based on: https://github.com/type-challenges/type-challenges/blob/main/utils/index.d.ts
+ */
+export const libSource = `
+type Equal<X, Y> =
+ (<T>() => T extends X ? 1 : 2) extends
+ (<T>() => T extends Y ? 1 : 2) ? true : false
+
+type MergeInsertions<T> =
+ T extends object
+ ? { [K in keyof T]: MergeInsertions<T[K]> }
+ : T
+
+type Alike<X, Y> = Equal<MergeInsertions<X>, MergeInsertions<Y>>
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+
+type NoInfer<T> = [T][T extends any ? 0 : never];
+
+type IsUnion<T, U = T> = [T] extends [never]
+ ? false
+ : T extends unknown
+ ? [U] extends [T]
+ ? false
+ : true
+ : false;
+
+
+/**
+ * Helper function to test your code.
+ *
+ * Checks if two types have all the same properties and modifiers
+ *
+ * To check what it is failing, you can hover over \`Equal\` and see what the types failing are
+ */
+declare function Equal<A, B>(...args: Alike<A, B> extends true ? [] : [msg: "not equal"]): void;
+
+/**
+ * Helper function to test your code.
+ *
+ * Checks if type \`A\` extends \`B\`
+ *
+ * To check what it is failing, you can hover over \`Extends\` and see what the types failing are
+ */
+declare function Extends<A, B>(...args: A extends B ? [] : [msg: [A, "doesn't extend", B]]): void;
+`;
diff --git a/src/components/challenge/editor/index.tsx b/src/components/challenge/editor/index.tsx
index b0c2bcc8..a21ea738 100644
--- a/src/components/challenge/editor/index.tsx
+++ b/src/components/challenge/editor/index.tsx
@@ -1,9 +1,11 @@
'use client';
+
import Editor from '@monaco-editor/react';
import { Settings } from 'lucide-react';
import type * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { useTheme } from 'next-themes';
-import { useMemo, useState } from 'react';
+import { useMemo, useRef, useState } from 'react';
+import { Button } from '~/components/ui/button';
import {
Dialog,
DialogContent,
@@ -11,22 +13,15 @@ import {
DialogTitle,
DialogTrigger,
} from '~/components/ui/dialog';
+import { ToastAction } from '~/components/ui/toast';
+import { useToast } from '~/components/ui/use-toast';
+import { SettingsForm } from '../settings-form';
import { useEditorSettingsStore } from '../settings-store';
+import { libSource } from './editor-types';
import { createTwoslashInlayProvider } from './twoslash';
-import { VimStatusBar, loadVim } from './vimMode';
-import { SettingsForm } from '../settings-form';
-import { Button } from '~/components/ui/button';
-import { useToast } from '~/components/ui/use-toast';
-import { ToastAction } from '~/components/ui/toast';
-
-declare global {
- // eslint-disable-next-line no-var
- var editor: monaco.editor.IStandaloneCodeEditor;
- // eslint-disable-next-line no-var
- var model: monaco.editor.ITextModel;
-}
+import { VimStatusBar } from './vimMode';
-const defaultOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
+const DEFAULT_OPTIONS: monaco.editor.IStandaloneEditorConstructionOptions = {
lineNumbers: 'on',
tabSize: 2,
insertSpaces: false,
@@ -34,124 +29,16 @@ const defaultOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
enabled: false,
},
fontSize: 16,
-};
-
-type Monaco = typeof monaco;
-
-/// based on: https://github.com/type-challenges/type-challenges/blob/main/utils/index.d.ts
-const libSource = `
-type Equal<X, Y> =
- (<T>() => T extends X ? 1 : 2) extends
- (<T>() => T extends Y ? 1 : 2) ? true : false
-
-type MergeInsertions<T> =
- T extends object
- ? { [K in keyof T]: MergeInsertions<T[K]> }
- : T
-
-type Alike<X, Y> = Equal<MergeInsertions<X>, MergeInsertions<Y>>
-
-type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
-
-type NoInfer<T> = [T][T extends any ? 0 : never];
-
-type IsUnion<T, U = T> = [T] extends [never]
- ? false
- : T extends unknown
- ? [U] extends [T]
- ? false
- : true
- : false;
-
-
-/**
- * Helper function to test your code.
- *
- * Checks if two types have all the same properties and modifiers
- *
- * To check what it is failing, you can hover over \`Equal\` and see what the types failing are
- */
-declare function Equal<A, B>(...args: Alike<A, B> extends true ? [] : [msg: "not equal"]): void;
-
-/**
- * Helper function to test your code.
- *
- * Checks if type \`A\` extends \`B\`
- *
- * To check what it is failing, you can hover over \`Extends\` and see what the types failing are
- */
-declare function Extends<A, B>(...args: A extends B ? [] : [msg: [A, "doesn't extend", B]]): void;
-`;
-
-const libUri = 'ts:filename/checking.d.ts';
-
-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;
-
- monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, libUri);
- monaco.editor.createModel(libSource, 'typescript', monaco.Uri.parse(libUri));
-
- const model = editor.getModel();
-
- if (!model) {
- throw new Error();
- }
-
- globalThis.model = model;
- globalThis.editor = editor;
-
- loadVim(editor);
-
- const ts = await (await monaco.languages.typescript.getTypeScriptWorker())(model.uri);
-
- const filename = model.uri.toString();
-
- // what actually runs when checking errors
- const _runCommand = 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);
-
- 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);
- }
-
- fixingStart = !fixingStart;
- }
- });
+} as const;
- editor.getModel()?.onDidChangeContent(() => void _runCommand());
+const LIB_URI = 'ts:filename/checking.d.ts';
- monaco.languages.registerInlayHintsProvider(
- 'typescript',
- createTwoslashInlayProvider(monaco, ts),
- );
- };
+type Monaco = typeof monaco;
interface Props {
prompt: string;
}
+
export const CodePanel = ({ prompt }: Props) => {
const { toast } = useToast();
const { theme } = useTheme();
@@ -160,9 +47,12 @@ export const CodePanel = ({ prompt }: Props) => {
const [hasErrors, setHasErrors] = useState(false);
const [code, setCode] = useState(prompt);
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(() => {
const options = {
- ...defaultOptions,
+ ...DEFAULT_OPTIONS,
...settings,
fontSize: parseInt(settings.fontSize),
tabSize: parseInt(settings.tabSize),
@@ -189,6 +79,68 @@ export const CodePanel = ({ prompt }: 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;
+
+ 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();
+ }
+
+ modelRef.current = model;
+ setEditorState(editor);
+
+ const ts = await (await monaco.languages.typescript.getTypeScriptWorker())(model.uri);
+
+ const filename = model.uri.toString();
+
+ // what actually runs when checking errors
+ const _runCommand = 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);
+
+ 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);
+ }
+
+ fixingStart = !fixingStart;
+ }
+ });
+
+ editor.getModel()?.onDidChangeContent(() => void _runCommand());
+
+ monaco.languages.registerInlayHintsProvider(
+ 'typescript',
+ createTwoslashInlayProvider(monaco, ts),
+ );
+ };
+
return (
<div className="flex flex-1 flex-col overflow-hidden rounded-md">
<div className="container flex h-[40px] flex-row-reverse items-center space-y-2 border border-b-zinc-300 bg-muted dark:border-b-zinc-700">
@@ -218,7 +170,7 @@ export const CodePanel = ({ prompt }: Props) => {
/>
</div>
<div className="flex items-center justify-between bg-muted p-2">
- <VimStatusBar />
+ {editorState && <VimStatusBar editor={editorState} />}
<Button
size="sm"
className="bg-green-300 hover:bg-green-400 dark:hover:bg-green-200"
diff --git a/src/components/challenge/editor/vimMode.tsx b/src/components/challenge/editor/vimMode.tsx
index f61851b5..c78a71b9 100644
--- a/src/components/challenge/editor/vimMode.tsx
+++ b/src/components/challenge/editor/vimMode.tsx
@@ -1,66 +1,35 @@
+'use client';
+
import type * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
-import { type VimMode, initVimMode } from 'monaco-vim';
+import { initVimMode, type VimMode } from 'monaco-vim';
+import { useEffect, useRef } from 'react';
import { useEditorSettingsStore } from '../settings-store';
-const STATUS_BAR_ID = 'vim-status-bar';
-
-export const VimStatusBar = () => {
+interface Props {
+ editor: monaco.editor.IStandaloneCodeEditor;
+}
+export const VimStatusBar = ({ editor }: Props) => {
+ const statusBarRef = useRef<HTMLDivElement | null>(null);
+ const vimModeRef = useRef<VimMode>();
const { settings } = useEditorSettingsStore();
- if (settings.bindings === 'vim' && globalThis.editor) {
- activateVimMode(globalThis.editor);
- } else {
- deactivateVimMode();
- }
+
+ useEffect(() => {
+ if (settings.bindings === 'vim') {
+ if (!vimModeRef.current) {
+ vimModeRef.current = initVimMode(editor, statusBarRef.current);
+ }
+ } else {
+ vimModeRef.current?.dispose();
+ vimModeRef.current = undefined;
+ if (statusBarRef.current) {
+ statusBarRef.current.textContent = '';
+ }
+ }
+ }, [editor, settings.bindings]);
+
return (
<div className="flex w-full">
- <div id={STATUS_BAR_ID} className="font-mono" />
+ <div ref={statusBarRef} className="font-mono" />
</div>
);
};
-
-export function loadVim(editor: monaco.editor.IStandaloneCodeEditor) {
- // eslint-disable-next-line
- const settings = localStorage.getItem('editor-settings');
- if (!settings) return;
-
- // eslint-disable-next-line
- const parsedSettings = JSON.parse(settings);
-
- // eslint-disable-next-line
- if (parsedSettings?.state?.settings?.bindings === 'vim') {
- activateVimMode(editor);
- }
-}
-
-declare global {
- // eslint-disable-next-line no-var
- var vimMode: VimMode | undefined;
-}
-
-export function activateVimMode(editor: monaco.editor.IStandaloneCodeEditor) {
- if (globalThis.vimMode === undefined) {
- const statusBar = document.getElementById(STATUS_BAR_ID);
-
- if (statusBar === null) {
- return;
- }
-
- globalThis.vimMode = initVimMode(editor, statusBar);
- }
-}
-
-export function deactivateVimMode() {
- if (globalThis.vimMode !== undefined) {
- const statusBar = document.getElementById(STATUS_BAR_ID);
-
- if (statusBar === null) {
- return;
- }
-
- globalThis.vimMode.dispose();
-
- delete globalThis.vimMode;
-
- statusBar.textContent = '';
- }
-}
diff --git a/src/components/challenge/index.tsx b/src/components/challenge/index.tsx
index 1bd55309..10570b77 100644
--- a/src/components/challenge/index.tsx
+++ b/src/components/challenge/index.tsx
@@ -9,9 +9,6 @@ interface Props {
}
export async function Challenge({ id }: Props) {
const session = await getServerSession();
- // query a challenge by id
- // include the count of votes
- // include if I voted for this challenge
const challenge = await prisma.challenge.findFirst({
where: { id: +id },
include: {