Mahdi Naser Moghadasi
Critical mobile improvements: Fix engagement tracking, improve code editor UX, add bottom navigation
0275695 Download components/CodeEditor.tsx from brightmind-ai/codepractice-ai: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/spaces/brightmind-ai/codepractice-ai/resolve/main/components/CodeEditor.tsx
- Command line
-
hf download hf://spaces/brightmind-ai/codepractice-ai/components/CodeEditor.tsx
-
curl -L -o CodeEditor.tsx https://huggingface.co/spaces/brightmind-ai/codepractice-ai/resolve/main/components/CodeEditor.tsx
17.1 kB
| '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: () => ( | |
| <div className="h-full flex items-center justify-center bg-[#1e1e1e] text-gray-400"> | |
| Loading editor... | |
| </div> | |
| ), | |
| }) | |
| // 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<CodeEditorRef, CodeEditorProps>(({ | |
| 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<editor.IStandaloneCodeEditor | null>(null) | |
| const codeMirrorViewRef = useRef<EditorView | null>(null) // Store CodeMirror view instance | |
| const codeMirrorRef = useRef<string>(code) // Track current CodeMirror value as fallback | |
| const [useMobileEditor, setUseMobileEditor] = useState(false) | |
| const [selectedLanguage, setSelectedLanguage] = useState<SupportedLanguage>(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<SupportedLanguage, string> = { | |
| 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<SupportedLanguage, string> = { | |
| python: 'Python', | |
| java: 'Java', | |
| } | |
| return names[lang] | |
| } | |
| const handleLanguageChange = (newLang: SupportedLanguage) => { | |
| setSelectedLanguage(newLang) | |
| if (onLanguageChange) { | |
| onLanguageChange(newLang) | |
| } | |
| } | |
| return ( | |
| <div className="flex flex-col h-full bg-gray-900 rounded-lg overflow-hidden border border-gray-700"> | |
| {/* Editor Toolbar */} | |
| <div className="flex items-center justify-between px-2 sm:px-4 py-1.5 sm:py-2 bg-gray-800 border-b border-gray-700 flex-shrink-0"> | |
| <div className="flex items-center gap-2"> | |
| <div className="w-3 h-3 rounded-full bg-red-500"></div> | |
| <div className="w-3 h-3 rounded-full bg-yellow-500"></div> | |
| <div className="w-3 h-3 rounded-full bg-green-500"></div> | |
| <select | |
| value={selectedLanguage} | |
| onChange={(e) => handleLanguageChange(e.target.value as SupportedLanguage)} | |
| className="ml-4 text-sm text-gray-300 bg-gray-700 border border-gray-600 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-primary-500" | |
| > | |
| <option value="python">Python</option> | |
| <option value="java">Java</option> | |
| </select> | |
| </div> | |
| <div id="tour-run-submit-buttons" className={`flex items-center gap-2 ${isMobile ? 'gap-3' : 'gap-2'}`}> | |
| <motion.button | |
| id="tour-run-button" | |
| whileHover={{ scale: isMobile ? 1 : 1.05 }} | |
| whileTap={{ scale: 0.95 }} | |
| onClick={onRun} | |
| disabled={isRunning || isSubmitting} | |
| className={`flex items-center justify-center gap-2 ${ | |
| isMobile | |
| ? 'px-6 py-3 text-base min-h-[48px] min-w-[100px]' | |
| : 'px-4 py-2 text-sm' | |
| } bg-green-600 hover:bg-green-700 active:bg-green-800 text-white rounded-lg font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed shadow-lg`} | |
| > | |
| {isRunning ? ( | |
| <> | |
| <Loader2 className={`${isMobile ? 'w-5 h-5' : 'w-4 h-4'} animate-spin`} /> | |
| <span>Running...</span> | |
| </> | |
| ) : ( | |
| <> | |
| <Play className={isMobile ? 'w-5 h-5' : 'w-4 h-4'} /> | |
| <span>Run</span> | |
| </> | |
| )} | |
| </motion.button> | |
| <motion.button | |
| id="tour-submit-button" | |
| whileHover={{ scale: isMobile ? 1 : 1.05 }} | |
| whileTap={{ scale: 0.95 }} | |
| onClick={onSubmit} | |
| disabled={isRunning || isSubmitting} | |
| className={`flex items-center justify-center gap-2 ${ | |
| isMobile | |
| ? 'px-6 py-3 text-base min-h-[48px] min-w-[100px]' | |
| : 'px-2 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm' | |
| } bg-primary-600 hover:bg-primary-700 active:bg-primary-800 text-white rounded-lg font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed shadow-lg`} | |
| > | |
| {isSubmitting ? ( | |
| <> | |
| <Loader2 className={`${isMobile ? 'w-5 h-5' : 'w-4 h-4'} animate-spin`} /> | |
| <span>Submitting...</span> | |
| </> | |
| ) : ( | |
| <> | |
| <Send className={isMobile ? 'w-5 h-5' : 'w-4 h-4'} /> | |
| <span>Submit</span> | |
| </> | |
| )} | |
| </motion.button> | |
| </div> | |
| </div> | |
| {/* Code Editor - CodeMirror for mobile, Monaco for desktop */} | |
| <div | |
| className="flex-1 min-h-[300px] sm:min-h-[400px] overflow-hidden" | |
| style={isMobile ? { | |
| height: '400px', | |
| flex: 'none', | |
| minHeight: '400px', | |
| maxHeight: '400px', | |
| position: 'relative', | |
| width: '100%' | |
| } : { | |
| display: 'flex', | |
| flexDirection: 'column', | |
| }} | |
| > | |
| {useMobileEditor ? ( | |
| // CodeMirror for mobile (better mobile support with syntax highlighting and autocomplete) | |
| <div className="h-full w-full [&_.cm-editor]:h-full [&_.cm-scroller]:h-full [&_.cm-editor]:bg-[#1e1e1e] [&_.cm-content]:bg-[#1e1e1e]"> | |
| <CodeMirror | |
| value={code ?? ''} | |
| height="400px" | |
| extensions={[ | |
| getCodeMirrorLanguage(), | |
| monacoDarkTheme, | |
| syntaxHighlighting(monacoHighlightStyle), | |
| autocompletion({ | |
| activateOnTyping: true, | |
| maxRenderedOptions: 10, | |
| }), | |
| captureViewExtension, // Capture view instance on focus | |
| captureViewOnUpdate, // Capture view instance on update | |
| ]} | |
| onChange={(value) => { | |
| 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, | |
| }} | |
| /> | |
| </div> | |
| ) : ( | |
| <div className="h-full w-full [&_.monaco-editor_.scroll-decoration]:hidden [&_.monaco-editor]:h-full [&_.monaco-scrollable-element]:h-full"> | |
| <MonacoEditor | |
| height="100%" | |
| language={selectedLanguage} | |
| value={code || ''} | |
| onChange={onChange} | |
| theme="vs-dark" | |
| onMount={(editor) => { | |
| 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, | |
| }, | |
| }} | |
| /> | |
| </div> | |
| )} | |
| </div> | |
| </div> | |
| ) | |
| }) | |
| CodeEditor.displayName = 'CodeEditor' | |
| export default CodeEditor | |