forked from DhanushNehru/CustomCodeEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditorComponent.js
More file actions
427 lines (404 loc) · 12.3 KB
/
Copy pathEditorComponent.js
File metadata and controls
427 lines (404 loc) · 12.3 KB
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
import "@fortawesome/fontawesome-free/css/all.css";
import { Editor } from "@monaco-editor/react";
import { Avatar, Button, CircularProgress, styled } from "@mui/material";
import Box from "@mui/material/Box";
import { useSnackbar } from "notistack";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { FaPlay } from "react-icons/fa";
import GithubSignIn from "../components/GithubSignIn";
import GoogleSignIn from "../components/GoogleSignIn";
import "../components/css/EditorComponent.css";
import EditorThemeSelect from "../components/js/EditorThemeSelect";
import LanguageSelect from "../components/js/LanguageSelect";
import Stars from "../components/js/Stars";
import ToggleTheme from "../components/js/ToggleTheme";
import { defineEditorTheme } from "../components/js/defineEditorTheme";
import {
EDITOR_THEMES,
LANGUAGES,
judge0SubmitUrl,
rapidApiHost,
rapidApiKey,
} from "../constants/constants";
import { useAuth } from "../context/AuthContext";
import Footer from "../components/Footer";
const StyledButton = styled(Button)({
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "0.5rem",
});
const StyledLayout = styled("div")(({ theme }) => ({
display: "flex",
flexDirection: "column",
height: "80%",
margin: "0.5rem",
border: `2px solid ${theme.palette.divider}`,
borderRadius: "1rem",
"@media (min-width: 1024px)": {
flexDirection: "row",
padding: "1.5rem",
alignItems: "center",
},
}));
const OutputLayout = styled("div")(({ theme }) => ({
backgroundColor: theme.palette.background.paper,
height: "50vh",
margin: "1rem 0",
border: `2px solid ${theme.palette.divider}`,
borderRadius: "1rem",
"@media (min-width: 1024px)": {
height: "30vh",
padding: "1rem",
},
}));
const WelcomeText = styled("span")(({ theme }) => ({
color: theme.palette.text.primary,
fontWeight: "bold",
}));
function EditorComponent() {
const [code, setCode] = useState(null);
const [output, setOutput] = useState([]);
const [currentLanguage, setCurrentLanguage] = useState(
LANGUAGES[0].DEFAULT_LANGUAGE
);
const [languageDetails, setLanguageDetails] = useState(LANGUAGES[0]);
const [currentEditorTheme, setCurrentEditorTheme] = useState(
EDITOR_THEMES[1]
);
const [loading, setLoading] = useState(false);
const { enqueueSnackbar } = useSnackbar();
const editorRef = useRef(null);
const monacoRef = useRef(null);
const { currentUser, logOut } = useAuth();
const styles = {
flex: {
display: "flex",
flexDirection: "column",
alignItems: "center",
},
languageDropdown: {
marginTop: "1rem",
display: "flex",
alignItems: "center",
},
"@media (min-width: 576px)": {
flex: {
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
gap: "0.6em",
},
},
};
useEffect(() => {
const selectedLanguage = LANGUAGES.find(
(lang) => lang.DEFAULT_LANGUAGE === currentLanguage
);
setLanguageDetails({
ID: selectedLanguage.ID,
LANGUAGE_NAME: selectedLanguage.NAME,
DEFAULT_LANGUAGE: selectedLanguage.DEFAULT_LANGUAGE,
NAME: selectedLanguage.NAME,
});
setCode(selectedLanguage.HELLO_WORLD);
}, [currentLanguage]);
const handleEditorThemeChange = async (_, theme) => {
if (["light", "vs-dark"].includes(theme.ID)) {
setCurrentEditorTheme(theme);
} else {
setCurrentEditorTheme(theme);
defineEditorTheme(theme).then((_) => setCurrentEditorTheme(theme));
}
};
const getLanguageLogoById = (id) => {
const language = LANGUAGES.find(
(lang) => parseInt(lang.ID) === parseInt(id)
);
return language ? language.LOGO : null;
};
const submitCode = useCallback(async () => {
console.log("Submitting code..."); // Debug log
if (!editorRef.current) {
console.log("Editor reference not available");
return;
}
const codeToSubmit = editorRef.current.getValue();
if (codeToSubmit === "") {
enqueueSnackbar("Please enter valid code", { variant: "error" });
return;
}
setLoading(true);
try {
const encodedCode = btoa(codeToSubmit);
const response = await fetch(
`${judge0SubmitUrl}?base64_encoded=true&wait=false&fields=*`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-RapidAPI-Key": rapidApiKey,
"X-RapidAPI-Host": rapidApiHost,
},
body: JSON.stringify({
source_code: encodedCode,
language_id: languageDetails.ID,
stdin: "",
expected_output: "",
}),
}
);
if (!response.ok) {
enqueueSnackbar(
`Failed to create submission. Status code: ${response.status}`,
{ variant: "error" }
);
setLoading(false);
return;
}
const data = await response.json();
const submissionId = data["token"];
setTimeout(() => {
fetch(
`${judge0SubmitUrl}/${submissionId}?base64_encoded=true&fields=*`,
{
method: "GET",
headers: {
"X-RapidAPI-Key": rapidApiKey,
"X-RapidAPI-Host": rapidApiHost,
},
}
)
.then((response) => response.json())
.then((data) => {
if (!data.stdout) {
enqueueSnackbar("Please check the code", { variant: "error" });
setOutput(data.message);
return;
}
const decodedOutput = atob(data.stdout);
const formattedData = decodedOutput.split("\n");
setOutput(formattedData);
})
.catch((error) => {
enqueueSnackbar("Error retrieving output: " + error.message, {
variant: "error",
});
})
.finally(() => setLoading(false));
}, 2000);
} catch (error) {
enqueueSnackbar("Error: " + error.message, { variant: "error" });
}
}, [enqueueSnackbar, languageDetails]);
const handleEditorDidMount = useCallback(
(editor, monaco) => {
console.log("Editor mounted"); // Debug log
editorRef.current = editor;
monacoRef.current = monaco;
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () => {
console.log("Ctrl+Enter pressed in editor");
submitCode();
});
},
[submitCode]
);
useEffect(() => {
const handleKeyDown = (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === "Enter") {
console.log("Ctrl+Enter pressed globally");
event.preventDefault();
submitCode();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [submitCode]);
useEffect(() => {
if (editorRef.current && monacoRef.current) {
const editor = editorRef.current;
const monaco = monacoRef.current;
handleEditorDidMount(editor, monaco);
}
}, [handleEditorDidMount]);
function handleLanguageChange(_, value) {
setCurrentLanguage(value.DEFAULT_LANGUAGE);
setOutput("");
setCode(code ? code : value.HELLO_WORLD);
}
const handleSignOut = async () => {
try {
await logOut();
} catch (error) {
console.log(error);
}
};
const renderAuthenticatedContent = () => (
<>
<StyledLayout>
<Editor
className="editor"
theme={currentEditorTheme.NAME}
onMount={handleEditorDidMount}
value={code}
onChange={setCode}
language={languageDetails.DEFAULT_LANGUAGE}
options={{ minimap: { enabled: false } }}
/>
<div
className="sidebar"
style={{ display: "flex", flexDirection: "column" }}
>
{getLanguageLogoById(languageDetails.ID)}
<div style={{ fontWeight: "bold" }}>
{languageDetails.LANGUAGE_NAME}
</div>
<div style={styles.languageDropdown}>
<EditorThemeSelect
handleEditorThemeChange={handleEditorThemeChange}
defaultEditorTheme={currentEditorTheme}
/>
</div>
<div style={styles.languageDropdown}>
<LanguageSelect
handleLanguageChange={handleLanguageChange}
defaultLanguage={languageDetails}
/>
</div>
<StyledButton
sx={(theme) => ({
marginTop: "1rem",
padding: "10px 20px",
bgcolor: theme.palette.text.primary,
color: theme.palette.background.default,
border: "none",
borderRadius: "15px",
fontSize: "0.8em",
cursor: "pointer",
boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)",
width: "50%",
"@media (min-width: 1024px)": {
width: "100%",
},
})}
onClick={submitCode}
variant="contained"
color="primary"
disabled={loading}
>
<span>
{loading ? <CircularProgress size={13} /> : <FaPlay size="13" />}
</span>
Run {languageDetails.LANGUAGE_NAME}
</StyledButton>
</div>
</StyledLayout>
<OutputLayout>
{Array.isArray(output) &&
output.map((result, i) => <div key={i}>{result}</div>)}
</OutputLayout>
</>
);
const renderUnauthenticatedContent = () => (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "50vh",
flexDirection: "column",
}}
>
<h2>Please sign in to use the Code Editor</h2>
<GoogleSignIn />
<br />
<GithubSignIn />
</div>
);
return (
<div className="editor-container">
<Box
sx={[
(theme) => ({
height: "auto",
margin: "0.5rem",
paddingLeft: "0.5rem",
paddingRight: "0.5rem",
border: `2px solid ${theme.palette.divider}`,
borderRadius: "1rem",
}),
]}
>
<div style={styles.flex}>
<div style={{ display: "flex", alignItems: "center" }}>
<img
src="./images/custom-code-editor-rounded.svg"
alt="Custom Code Editor icon"
width={32}
style={{ marginLeft: "0.5rem" }}
/>
<span
style={{
backgroundClip: "text",
background: "linear-gradient(#2837BA 0%, #2F1888 100%)",
WebkitBackgroundClip: "text",
color: "transparent",
marginLeft: "0.5rem",
fontWeight: "bold",
fontSize: "1.5em",
}}
>
Custom Code Editor
</span>
</div>
<div className="flex-container">
<div className="flex items-center space-x-2">
{currentUser ? (
<>
<WelcomeText>
Welcome, {currentUser.displayName}
</WelcomeText>
<Avatar
src={currentUser.photoURL}
alt={currentUser.displayName}
sx={{
width: 32,
height: 32,
marginLeft: "0.5rem",
marginRight: "0.5rem",
}}
/>
<div className="signout-container">
<button
onClick={handleSignOut}
className="signout-button"
>
<span>Logout</span>
</button>
</div>
</>
) : (
<>
<GoogleSignIn />
<GithubSignIn />
</>
)}
</div>
<ToggleTheme />
<Stars />
</div>
</div>
</Box>
{currentUser
? renderAuthenticatedContent()
: renderUnauthenticatedContent()}
<div className="footer">
<Footer />
</div>
</div>
);
}
export default EditorComponent;