File size: 17,069 Bytes
4623c17
 
0d3f3be
4623c17
 
 
 
f25bf7c
f5cda12
 
fe2a1b2
f5cda12
 
7ccd9fb
 
 
4623c17
 
 
 
 
 
 
 
 
 
16b584f
7ccd9fb
 
d9de1bc
7ccd9fb
 
d9de1bc
 
 
7ccd9fb
d9de1bc
7ccd9fb
16b584f
d9de1bc
7ccd9fb
 
 
16b584f
7ccd9fb
 
 
 
 
 
 
 
d9de1bc
7ccd9fb
16b584f
7ccd9fb
 
 
 
16b584f
7ccd9fb
 
 
 
16b584f
 
 
7ccd9fb
d9de1bc
16b584f
 
 
 
0275695
 
 
 
 
 
 
16b584f
 
d9de1bc
16b584f
 
 
7ccd9fb
 
 
16b584f
7ccd9fb
16b584f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8590f07
 
16b584f
 
7ccd9fb
 
ca10648
fe2a1b2
0d3f3be
 
 
 
4623c17
 
 
 
 
 
 
fe2a1b2
 
4623c17
 
0d3f3be
4623c17
 
 
 
 
 
fe2a1b2
 
0d3f3be
4623c17
ba131d1
f25bf7c
ba19790
 
f5cda12
fe2a1b2
0d3f3be
 
 
 
 
ba19790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d3f3be
 
 
 
 
 
 
 
 
 
 
ba131d1
 
 
f25bf7c
 
ba131d1
f25bf7c
0275695
f5cda12
 
ba131d1
 
f5cda12
ba131d1
 
 
4623c17
fe2a1b2
 
 
 
 
 
 
a51f27e
f25bf7c
a51f27e
f25bf7c
a51f27e
 
f25bf7c
 
f5cda12
f25bf7c
fe2a1b2
 
 
aaf3aaf
 
 
fe2a1b2
 
 
 
aaf3aaf
 
 
 
fe2a1b2
 
 
 
ba19790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe2a1b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4623c17
a6d6f01
4623c17
a7e3e0f
4623c17
 
 
 
fe2a1b2
 
 
 
 
 
 
 
4623c17
0275695
4623c17
988d1ad
0275695
4623c17
 
 
0275695
 
 
 
 
4623c17
 
 
0275695
 
4623c17
 
 
0275695
 
4623c17
 
 
 
988d1ad
0275695
4623c17
 
 
0275695
 
 
 
 
4623c17
 
 
0275695
 
4623c17
 
 
0275695
 
4623c17
 
 
 
 
 
f5cda12
dae6603
3dcfed4
dae6603
87d5cd8
dae6603
87d5cd8
 
dae6603
 
78bd015
 
 
 
dae6603
f5cda12
 
d9de1bc
5b2b0ac
 
 
 
fe2a1b2
7ccd9fb
 
5b2b0ac
 
 
 
ba19790
 
5b2b0ac
0d3f3be
ba19790
0d3f3be
 
5b2b0ac
 
 
 
 
 
 
 
 
 
 
 
 
dae6603
323d95b
3dcfed4
323d95b
94bc8a6
51fee5f
dae6603
 
f25bf7c
 
323d95b
 
 
 
f25bf7c
dae6603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd1829d
 
 
 
 
 
 
 
dae6603
 
3dcfed4
dae6603
4623c17
 
 
0d3f3be
 
 
 
 
4623c17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
'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