'use client' import { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react' import dynamic from 'next/dynamic' import { motion } from 'framer-motion' import { Play, Send, Loader2 } from 'lucide-react' import toast from 'react-hot-toast' import type { editor } from 'monaco-editor' import CodeMirror from '@uiw/react-codemirror' import { python } from '@codemirror/lang-python' import { java } from '@codemirror/lang-java' import { oneDark } from '@codemirror/theme-one-dark' import { autocompletion } from '@codemirror/autocomplete' import { EditorView } from '@codemirror/view' import { HighlightStyle, syntaxHighlighting } from '@codemirror/language' import { tags as t } from '@lezer/highlight' const MonacoEditor = dynamic(() => import('@monaco-editor/react'), { ssr: false, loading: () => (
Loading editor...
), }) // Custom theme to match Monaco Editor's vs-dark colors exactly const monacoDarkTheme = EditorView.theme({ '&': { backgroundColor: '#1e1e1e !important', color: '#d4d4d4', }, '.cm-editor': { backgroundColor: '#1e1e1e !important', }, '.cm-content': { backgroundColor: '#1e1e1e !important', caretColor: '#aeafad', padding: '0', color: '#d4d4d4', }, '.cm-cursor, .cm-dropCursor': { borderLeftColor: '#aeafad', borderLeftWidth: '2px', }, '.cm-selectionBackground, .cm-content ::selection': { backgroundColor: '#264f78', }, '.cm-focused .cm-selectionBackground': { backgroundColor: '#264f78', }, '.cm-gutters': { backgroundColor: '#1e1e1e !important', border: 'none', color: '#858585', }, '.cm-lineNumbers .cm-gutterElement': { color: '#858585', minWidth: '3ch', padding: '0 8px 0 16px', }, '.cm-activeLineGutter': { backgroundColor: 'transparent', }, '.cm-activeLine': { backgroundColor: 'transparent', }, '.cm-scroller': { backgroundColor: '#1e1e1e !important', fontFamily: '"Consolas", "Courier New", monospace', fontSize: '14px', lineHeight: '1.6', }, // Mobile-specific font size (larger for better readability) '@media (max-width: 640px)': { '.cm-scroller': { fontSize: '16px !important', // Minimum 16px prevents iOS zoom lineHeight: '1.8 !important', }, }, '.cm-line': { padding: '0 4px', backgroundColor: 'transparent', }, '.cm-focused': { outline: 'none', }, }, { dark: true }) // Syntax highlighting to match Monaco Editor vs-dark exactly const monacoHighlightStyle = HighlightStyle.define([ // Keywords (def, if, for, while, return, etc.) - Monaco: #569cd6 { tag: t.keyword, color: '#569cd6' }, // Function names - Monaco: #dcdcaa { tag: t.function(t.variableName), color: '#dcdcaa' }, { tag: [t.function(t.definition(t.variableName)), t.function(t.propertyName)], color: '#dcdcaa' }, // Variables - Monaco: #9cdcfe { tag: t.variableName, color: '#9cdcfe' }, // Strings - Monaco: #ce9178 { tag: t.string, color: '#ce9178' }, // Numbers - Monaco: #b5cea8 { tag: t.number, color: '#b5cea8' }, // Comments - Monaco: #6a9955 { tag: t.comment, color: '#6a9955' }, // Operators - Monaco: #d4d4d4 { tag: t.operator, color: '#d4d4d4' }, // Punctuation - Monaco: #d4d4d4 { tag: t.punctuation, color: '#d4d4d4' }, // Brackets - Monaco: #ffd700 (gold) { tag: t.bracket, color: '#ffd700' }, // Tags - Monaco: #569cd6 { tag: t.tagName, color: '#569cd6' }, // Attributes - Monaco: #92c5f7 { tag: t.attributeName, color: '#92c5f7' }, // Classes - Monaco: #4ec9b0 { tag: t.className, color: '#4ec9b0' }, // Properties - Monaco: #9cdcfe { tag: t.propertyName, color: '#9cdcfe' }, // Type names - Monaco: #4ec9b0 { tag: t.typeName, color: '#4ec9b0' }, // Namespace - Monaco: #569cd6 { tag: t.namespace, color: '#569cd6' }, // Literal values (constants) - Monaco: #4fc1ff { tag: t.literal, color: '#4fc1ff' }, // Default text color - Monaco: #d4d4d4 { tag: t.standard(t.variableName), color: '#d4d4d4' }, ]) import { type SupportedLanguage } from '@/lib/llmChecker' export interface CodeEditorRef { getCurrentCode: () => string } interface CodeEditorProps { code: string onChange: (value: string | undefined) => void onRun: () => void onSubmit: () => void isRunning?: boolean isSubmitting?: boolean language?: SupportedLanguage onLanguageChange?: (language: SupportedLanguage) => void } const CodeEditor = forwardRef(({ code, onChange, onRun, onSubmit, isRunning = false, isSubmitting = false, language = 'python', onLanguageChange, }, ref) => { const [editorHeight, setEditorHeight] = useState(500) const [isMobile, setIsMobile] = useState(false) const editorRef = useRef(null) const codeMirrorViewRef = useRef(null) // Store CodeMirror view instance const codeMirrorRef = useRef(code) // Track current CodeMirror value as fallback const [useMobileEditor, setUseMobileEditor] = useState(false) const [selectedLanguage, setSelectedLanguage] = useState(language) // Expose method to get current code directly from editor useImperativeHandle(ref, () => ({ getCurrentCode: () => { if (useMobileEditor) { // For CodeMirror, get value directly from view instance (most reliable) // Fallback to tracked ref if view not available if (codeMirrorViewRef.current) { try { const viewValue = codeMirrorViewRef.current.state.doc.toString() // Update ref to keep it in sync codeMirrorRef.current = viewValue return viewValue || code || '' } catch (error) { console.warn('[CodeEditor] Error reading from CodeMirror view:', error) // Fallback to tracked ref return codeMirrorRef.current || code || '' } } else { // Fallback to tracked value if view not available yet return codeMirrorRef.current || code || '' } } else { // For Monaco, get directly from editor return editorRef.current?.getValue() || code || '' } } })) // Update codeMirrorRef when code prop changes useEffect(() => { codeMirrorRef.current = code || '' }, [code]) useEffect(() => { if (typeof window !== 'undefined') { const mobile = window.innerWidth < 640 setIsMobile(mobile) // Set fixed height on mobile to prevent resize when keyboard appears if (mobile) { setEditorHeight(450) // Increased height on mobile for better visibility // Use CodeMirror for mobile (better mobile support than Monaco) setUseMobileEditor(true) } else { setEditorHeight(500) // Default height on desktop setUseMobileEditor(false) } } }, []) // Update selected language when prop changes useEffect(() => { if (language !== selectedLanguage) { setSelectedLanguage(language) } }, [language]) // Update editor value when code changes (for desktop Monaco only) useEffect(() => { if (editorRef.current && !useMobileEditor && code !== undefined) { const currentValue = editorRef.current.getValue() if (currentValue !== code) { editorRef.current.setValue(code || '') } } }, [code, useMobileEditor]) // Update Monaco editor language when selected language changes useEffect(() => { if (editorRef.current && !useMobileEditor) { // Type-safe check for Monaco const monaco = (window as any).monaco if (monaco && monaco.editor) { const languageMap: Record = { python: 'python', java: 'java', } const model = editorRef.current.getModel() if (model) { monaco.editor.setModelLanguage(model, languageMap[selectedLanguage]) } } } }, [selectedLanguage, useMobileEditor]) // Try to capture CodeMirror view after mount (fallback if extensions don't capture it) useEffect(() => { if (useMobileEditor && !codeMirrorViewRef.current) { // Small delay to ensure CodeMirror is fully initialized const timeout = setTimeout(() => { // Try to find the view from the DOM // CodeMirror stores the view in the editor element's data attribute or as a property const editorElement = document.querySelector('.cm-editor') if (editorElement) { // @uiw/react-codemirror might expose the view differently // This is a fallback - the extension should capture it first // If view is still not captured, we'll rely on codeMirrorRef.current } }, 100) return () => clearTimeout(timeout) } }, [useMobileEditor]) // Extension to capture CodeMirror view instance // Use a custom extension that runs when view is created const captureViewExtension = EditorView.domEventHandlers({ focus: (event, view) => { // Capture view on focus (first interaction) if (!codeMirrorViewRef.current) { codeMirrorViewRef.current = view } return false } }) // Also capture on any update to ensure we get the view const captureViewOnUpdate = EditorView.updateListener.of((update) => { if (update.view && !codeMirrorViewRef.current) { codeMirrorViewRef.current = update.view } }) // Get CodeMirror language extension const getCodeMirrorLanguage = () => { switch (selectedLanguage) { case 'python': return python() case 'java': return java() default: return python() } } // Get language display name const getLanguageName = (lang: SupportedLanguage) => { const names: Record = { python: 'Python', java: 'Java', } return names[lang] } const handleLanguageChange = (newLang: SupportedLanguage) => { setSelectedLanguage(newLang) if (onLanguageChange) { onLanguageChange(newLang) } } return (
{/* Editor Toolbar */}
{isRunning ? ( <> Running... ) : ( <> Run )} {isSubmitting ? ( <> Submitting... ) : ( <> Submit )}
{/* Code Editor - CodeMirror for mobile, Monaco for desktop */}
{useMobileEditor ? ( // CodeMirror for mobile (better mobile support with syntax highlighting and autocomplete)
{ codeMirrorRef.current = value // Track current value as fallback onChange(value) }} basicSetup={{ lineNumbers: false, foldGutter: false, dropCursor: false, allowMultipleSelections: false, indentOnInput: true, bracketMatching: true, closeBrackets: true, autocompletion: true, highlightSelectionMatches: false, }} />
) : (
{ editorRef.current = editor // Force layout to ensure proper sizing setTimeout(() => { editor.layout() }, 0) }} options={{ fontSize: 14, minimap: { enabled: false }, scrollBeyondLastLine: false, automaticLayout: true, tabSize: 4, wordWrap: 'on', lineNumbers: 'on', roundedSelection: false, cursorStyle: 'line', formatOnPaste: true, formatOnType: true, // Enable auto-complete quickSuggestions: true, suggestOnTriggerCharacters: true, acceptSuggestionOnEnter: 'on', tabCompletion: 'on', wordBasedSuggestions: 'allDocuments', // Enable IntelliSense features parameterHints: { enabled: true }, suggestSelection: 'first', snippetSuggestions: 'top', // Fix scroll decoration covering code scrollbar: { vertical: 'auto', horizontal: 'auto', useShadows: false, verticalHasArrows: false, horizontalHasArrows: false, }, }} />
)}
) }) CodeEditor.displayName = 'CodeEditor' export default CodeEditor