-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEditor.js
More file actions
109 lines (88 loc) · 3.17 KB
/
Copy pathEditor.js
File metadata and controls
109 lines (88 loc) · 3.17 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
import React, { useEffect, useState, useRef } from 'react';
import Codemirror from 'codemirror';
import 'codemirror/lib/codemirror.css';
//import 'codemirror/theme/dracula.css';
import 'codemirror/theme/isotope.css';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/python/python';
import 'codemirror/addon/edit/closetag';
import 'codemirror/addon/edit/closebrackets';
import ACTIONS from '../Actions';
import Axios from 'axios';
import toast from 'react-hot-toast';
import { useParams } from 'react-router-dom';
import { Button } from 'bootstrap';
const Editor = ({ socketRef, roomId, onCodeChange }) => {
const editorRef = useRef(null);
const [code, setCode] = useState("");
const [output, setOutput] = useState("");
useEffect(() => {
async function init() {
editorRef.current = Codemirror.fromTextArea(
document.getElementById('realtimeEditor'),
{
mode: { name: 'javascript', json: true },
mode: { name: 'python', json: true },
theme: 'isotope',
autoCloseTags: true,
autoCloseBrackets: true,
lineNumbers: true,
}
);
editorRef.current.on('change', (instance, changes) => {
const { origin } = changes;
const code = instance.getValue();
onCodeChange(code);
if (origin !== 'setValue') {
socketRef.current.emit(ACTIONS.CODE_CHANGE, {
roomId,
code,
});
}
});
}
init();
}, []);
const handleSubmit = async () => {
const payload = {
language: "cpp",
code,
};
try {
const { data } = await Axios.post("http://localhost:5000/run", payload)
setOutput(data.output);
} catch (err) {
console.log(err.response);
}
};
async function copyCode() {
try {
await navigator.clipboard.writeText(editorRef.current.getValue());
toast.success('Code has been copied to your clipboard');
} catch (err) {
toast.error('Could not copy the Code');
console.error(err);
}
}
useEffect(() => {
if (socketRef.current) {
socketRef.current.on(ACTIONS.CODE_CHANGE, ({ code }) => {
if (code !== null) {
editorRef.current.setValue(code);
}
});
}
return () => {
socketRef.current.off(ACTIONS.CODE_CHANGE);
};
}, [socketRef.current]);
return <div>
<div className='copyHeader'>
<button className="copyCode" onClick={copyCode}>Copy Code</button>
</div>
<div>
<textarea id="realtimeEditor" value={code} onChange={(e)=>{setCode(e.target.value)}} rows="20" cols="75"></textarea>
</div>
</div>;
};
export default Editor;