File size: 10,986 Bytes
9e5629a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect, useRef } from 'react'
import { FiPlay, FiSave, FiShare2, FiSettings, FiDownload, FiUpload } from 'react-icons/fi'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { atomDark } from 'react-syntax-highlighter/dist/cjs/styles/prism'
import dynamic from 'next/dynamic'

const MonacoEditor = dynamic(() => import('@monaco-editor/react'), {
  ssr: false,
  loading: () => <div className="h-full bg-gray-800 rounded-lg animate-pulse" />
})

export default function CodeEditor() {
  const [code, setCode] = useState('')
  const [language, setLanguage] = useState('javascript')
  const [output, setOutput] = useState('')
  const [isRunning, setIsRunning] = useState(false)
  const [error, setError] = useState(null)
  const [theme, setTheme] = useState('vs-dark')
  const [fontSize, setFontSize] = useState(14)
  const [showSettings, setShowSettings] = useState(false)
  const [savedSnippets, setSavedSnippets] = useState([])
  const [snippetName, setSnippetName] = useState('')
  const editorRef = useRef(null)

  const languages = [
    { value: 'javascript', label: 'JavaScript', icon: '🟑' },
    { value: 'python', label: 'Python', icon: '🐍' },
    { value: 'java', label: 'Java', icon: 'β˜•' },
    { value: 'csharp', label: 'C#', icon: 'πŸ”§' },
    { value: 'typescript', label: 'TypeScript', icon: 'πŸ”΅' },
    { value: 'go', label: 'Go', icon: '🐹' },
    { value: 'rust', label: 'Rust', icon: 'πŸ¦€' }
  ]

  const themes = [
    { value: 'vs-dark', label: 'Dark' },
    { value: 'vs-light', label: 'Light' },
    { value: 'hc-black', label: 'High Contrast' }
  ]

  useEffect(() => {
    const saved = localStorage.getItem('codeSnippets')
    if (saved) {
      setSavedSnippets(JSON.parse(saved))
    }
  }, [])

  const handleRunCode = async () => {
    if (!code.trim()) return

    setIsRunning(true)
    setError(null)
    setOutput('')

    try {
      const response = await fetch('/api/execute', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ code, language }),
      })

      const data = await response.json()

      if (response.ok) {
        setOutput(data.output)
      } else {
        throw new Error(data.error || 'Execution failed')
      }
    } catch (err) {
      setError(err.message)
    } finally {
      setIsRunning(false)
    }
  }

  const handleSaveSnippet = () => {
    if (!snippetName.trim()) return

    const newSnippet = {
      id: Date.now(),
      name: snippetName,
      code,
      language,
      createdAt: new Date().toISOString()
    }

    const updatedSnippets = [...savedSnippets, newSnippet]
    setSavedSnippets(updatedSnippets)
    localStorage.setItem('codeSnippets', JSON.stringify(updatedSnippets))
    setSnippetName('')
  }

  const handleLoadSnippet = (snippet) => {
    setCode(snippet.code)
    setLanguage(snippet.language)
  }

  const handleDownloadCode = () => {
    const blob = new Blob([code], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `code.${language === 'javascript' ? 'js' : language === 'python' ? 'py' : 'txt'}`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const handleUploadCode = (e) => {
    const file = e.target.files[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = (event) => {
      setCode(event.target.result)
    }
    reader.readAsText(file)
  }

  const handleEditorMount = (editor) => {
    editorRef.current = editor
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap justify-between items-center gap-4">
        <div className="flex items-center space-x-4">
          <select
            value={language}
            onChange={(e) => setLanguage(e.target.value)}
            className="bg-gray-700 text-white px-3 py-2 rounded-lg"
          >
            {languages.map((lang) => (
              <option key={lang.value} value={lang.value}>
                {lang.icon} {lang.label}
              </option>
            ))}
          </select>

          <button
            onClick={handleRunCode}
            disabled={isRunning}
            className={`px-4 py-2 rounded-lg flex items-center space-x-2 ${isRunning ? 'bg-gray-600' : 'bg-accent hover:bg-purple-600'} text-white transition-colors`}
          >
            <FiPlay />
            <span>{isRunning ? 'Running...' : 'Run Code'}</span>
          </button>

          <button
            onClick={() => setShowSettings(!showSettings)}
            className="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg flex items-center space-x-2 transition-colors"
          >
            <FiSettings />
            <span>Settings</span>
          </button>
        </div>

        <div className="flex items-center space-x-2">
          <label className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg cursor-pointer flex items-center space-x-2 transition-colors">
            <FiUpload />
            <span>Upload</span>
            <input type="file" className="hidden" onChange={handleUploadCode} accept=".js,.py,.java,.cs,.ts,.go,.rs" />
          </label>

          <button
            onClick={handleDownloadCode}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg flex items-center space-x-2 transition-colors"
          >
            <FiDownload />
            <span>Download</span>
          </button>

          <div className="flex items-center space-x-2">
            <input
              type="text"
              placeholder="Snippet name"
              value={snippetName}
              onChange={(e) => setSnippetName(e.target.value)}
              className="px-3 py-2 bg-gray-700 text-white rounded-lg text-sm"
            />
            <button
              onClick={handleSaveSnippet}
              disabled={!snippetName.trim()}
              className="px-4 py-2 bg-yellow-600 hover:bg-yellow-700 text-white rounded-lg flex items-center space-x-2 transition-colors disabled:opacity-50"
            >
              <FiSave />
              <span>Save</span>
            </button>
          </div>
        </div>
      </div>

      {showSettings && (
        <div className="bg-gray-800 rounded-lg p-4 mb-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-1">Theme</label>
              <select
                value={theme}
                onChange={(e) => setTheme(e.target.value)}
                className="w-full bg-gray-700 text-white px-3 py-2 rounded-lg"
              >
                {themes.map((t) => (
                  <option key={t.value} value={t.value}>{t.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-1">Font Size</label>
              <input
                type="range"
                min="12"
                max="24"
                value={fontSize}
                onChange={(e) => setFontSize(parseInt(e.target.value))}
                className="w-full"
              />
              <div className="text-center text-sm text-gray-300 mt-1">{fontSize}px</div>
            </div>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-250px)]">
        <div className="bg-gray-800 rounded-lg overflow-hidden">
          <div className="bg-gray-900 px-4 py-2 flex justify-between items-center">
            <span className="text-sm text-gray-300">Editor</span>
            {savedSnippets.length > 0 && (
              <select
                onChange={(e) => handleLoadSnippet(JSON.parse(e.target.value))}
                className="bg-gray-700 text-white px-2 py-1 rounded text-sm"
              >
                <option value="">Load Snippet</option>
                {savedSnippets.map((snippet) => (
                  <option key={snippet.id} value={JSON.stringify(snippet)}>
                    {snippet.name} ({snippet.language})
                  </option>
                ))}
              </select>
            )}
          </div>
          <div className="h-[calc(100%-40px)]">
            <MonacoEditor
              height="100%"
              language={language}
              theme={theme}
              value={code}
              onChange={setCode}
              onMount={handleEditorMount}
              options={{
                fontSize,
                minimap: { enabled: false },
                wordWrap: 'on',
                scrollBeyondLastLine: false,
                automaticLayout: true

            />
          </div>
        </div>

        <div className="bg-gray-100 rounded-lg p-4 overflow-auto">
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-bold text-gray-800">Output Console</h3>
            <button
              onClick={() => setOutput('')}
              className="text-sm text-gray-500 hover:text-gray-700"
            >
              Clear
            </button>
          </div>
          {error ? (
            <div className="text-red-600 p-3 bg-red-50 rounded-lg">
              <strong>Error:</strong> {error}
            </div>
          ) : (
            <div className="bg-white p-3 rounded-lg h-[calc(100%-50px)] overflow-auto">
              {output ? (
                <SyntaxHighlighter language={language} style={atomDark} customStyle={{ background: 'transparent' }}>
                  {output}
                </SyntaxHighlighter>
              ) : (
                <p className="text-gray-500">Code execution output will appear here...</p>
              )}
            </div>
          )}
        </div>
      </div>

      {savedSnippets.length > 0 && (
        <div className="mt-4 bg-gray-800 rounded-lg p-4">
          <h3 className="font-bold text-white mb-3">Saved Snippets</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            {savedSnippets.map((snippet) => (
              <div key={snippet.id} className="bg-gray-700 rounded-lg p-3 hover:bg-gray-600 transition-colors cursor-pointer" onClick={() => handleLoadSnippet(snippet)}>
                <div className="flex justify-between items-start">
                  <div>
                    <h4 className="font-medium text-white">{snippet.name}</h4>
                    <p className="text-xs text-gray-400">{snippet.language}</p>
                  </div>
                  <span className="text-xs text-gray-400">
                    {new Date(snippet.createdAt).toLocaleDateString()}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}