-
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathEditorComponent.js
More file actions
636 lines (595 loc) · 19 KB
/
EditorComponent.js
File metadata and controls
636 lines (595 loc) · 19 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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
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, FaFileUpload, FaFileDownload } from "react-icons/fa";
// import { FaFileUpload } 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";
// import FileUploadIcon from "@mui/icons-material/FileUpload";
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",
},
overflow: "auto",
}));
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: "row",
alignItems: "center",
justifyContent: "space-between",
},
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(() => {
if (isImportingRef.current) return;
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"];
const decodeFormat = (data) => {
return atob(data).split("\n");
}
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) {
if(data.stderr) {
enqueueSnackbar("Please check the code", { variant: "error" });
setOutput(decodeFormat(data.stderr));
return;
}
else {
enqueueSnackbar("Please check the code", { variant: "error" });
setOutput(decodeFormat(data.compile_output));
return;
}
}
setOutput(decodeFormat(data.stdout));
})
.catch((error) => {
enqueueSnackbar("Error retrieving output: " + error.message, {
variant: "error",
});
})
.finally(() => setLoading(false));
}, 2000);
} catch (error) {
enqueueSnackbar("Error: " + error.message, { variant: "error" });
}
}, [enqueueSnackbar, languageDetails]);
// import file
const [isImporting, setIsImporting] = React.useState(false);
const isImportingRef = useRef(false);
const fileInputRef = React.useRef(null);
const handleFileImport = (e) => {
const file = e.target.files[0];
if (!file) return;
setCode("");
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
isImportingRef.current = true;
setIsImporting(true);
const extension = file.name.split(".").pop().toLowerCase();
const languageMap = {
js: "Javascript",
py: "Python3",
cpp: "C++",
java: "Java",
};
const languageName = languageMap[extension];
const selectedLanguage = LANGUAGES.find(
(lang) => lang.NAME === languageName
);
if (!selectedLanguage) {
console.error("Unsupported file type");
enqueueSnackbar("Unsupported file type", { variant: "error" });
isImportingRef.current = false;
setIsImporting(false);
return;
}
const reader = new FileReader();
reader.onload = (event) => {
setCurrentLanguage(selectedLanguage.DEFAULT_LANGUAGE);
setLanguageDetails({
ID: selectedLanguage.ID,
NAME: selectedLanguage.NAME,
DEFAULT_LANGUAGE: selectedLanguage.DEFAULT_LANGUAGE,
LANGUAGE_NAME: selectedLanguage.NAME,
});
setCode(event.target.result);
// console.log("file code ", event.target.result);
setOutput("");
setIsImporting(false);
};
reader.onerror = () => {
console.error("Error reading file");
isImportingRef.current = false;
setIsImporting(false);
};
reader.readAsText(file);
};
// download file
const [isDownloading, setDownloading] = React.useState(false);
const exportFile = () => {
if (!code) return;
setDownloading(true);
const fileContent = code;
const extensionMap = {
javascript: "js",
python: "py",
cpp: "cpp",
java: "java",
};
const extension = extensionMap[languageDetails.DEFAULT_LANGUAGE] || "txt";
const blob = new Blob([fileContent], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `code.${extension}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
setDownloading(false);
};
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) {
if (isImporting) return;
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" }}
>
{/* import and export btn */}
<div style={{ display: "flex", flexDirection: "row", gap: "0.5rem" }}>
<StyledButton
onClick={() => fileInputRef.current.click()}
disabled={isImporting}
sx={(theme) => ({
padding: "8px 10px",
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
border: `1px solid ${theme.palette.primary.dark}`,
borderRadius: "8px",
fontSize: "0.875rem",
fontWeight: 500,
cursor: "pointer",
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.08)",
transition: "all 0.2s ease",
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "8px",
"&:hover": {
backgroundColor: theme.palette.primary.dark,
boxShadow: "0 4px 8px rgba(0, 0, 0, 0.12)",
transform: "translateY(-1px)",
},
"&:active": {
transform: "translateY(0)",
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
},
"&:disabled": {
backgroundColor: theme.palette.action.disabled,
color: theme.palette.action.disabledBackground,
cursor: "not-allowed",
transform: "none",
},
"@media (max-width: 768px)": {
padding: "8px 12px",
fontSize: "0.8125rem",
},
})}
>
{isImporting ? (
<>
<CircularProgress size={16} color="inherit" />
Importing...
</>
) : (
<>
<FaFileUpload fontSize="small" />
Import
</>
)}
</StyledButton>
<input
type="file"
ref={fileInputRef}
style={{ display: "none" }}
accept=".java,.js,.py,.cpp"
onChange={handleFileImport}
/>
<StyledButton
onClick={exportFile}
sx={(theme) => ({
padding: "8px 10px",
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
border: `1px solid ${theme.palette.primary.dark}`,
borderRadius: "8px",
fontSize: "0.875rem",
fontWeight: 500,
cursor: "pointer",
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.08)",
transition: "all 0.2s ease",
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "8px",
"&:hover": {
backgroundColor: theme.palette.primary.dark,
boxShadow: "0 4px 8px rgba(0, 0, 0, 0.12)",
transform: "translateY(-1px)",
},
"&:active": {
transform: "translateY(0)",
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
},
"&:disabled": {
backgroundColor: theme.palette.action.disabled,
color: theme.palette.action.disabledBackground,
cursor: "not-allowed",
transform: "none",
},
"@media (max-width: 768px)": {
padding: "8px 12px",
fontSize: "0.8125rem",
},
})}
>
{isDownloading ? (
<>
<CircularProgress size={16} color="inherit" />
Exporting...
</>
) : (
<>
<FaFileDownload fontSize="small" />
Export
</>
)}
</StyledButton>
</div>
{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>
<Stars />
<ToggleTheme />
{currentUser && (
<div className="flex-container">
<div className="flex items-center space-x-2">
<>
<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>
</>
</div>
</div>
)}
</div>
</Box>
{currentUser
? renderAuthenticatedContent()
: renderUnauthenticatedContent()}
<div className="footer">
<Footer />
</div>
</div>
);
}
export default EditorComponent;