-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathPythonRunner.js
More file actions
321 lines (280 loc) · 10.5 KB
/
Copy pathPythonRunner.js
File metadata and controls
321 lines (280 loc) · 10.5 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
/* eslint-disable react-hooks/exhaustive-deps */
import './PythonRunner.scss';
import React, { useEffect, useRef, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import Sk from "skulpt"
import { setError, codeRunHandled, stopDraw } from '../../EditorSlice'
import ErrorMessage from '../../ErrorMessage/ErrorMessage'
import store from '../../../../app/store'
import AstroPiModel from '../../../AstroPiModel/AstroPiModel';
const PythonRunner = () => {
const projectCode = useSelector((state) => state.editor.project.components);
const projectImages = useSelector((state) => state.editor.project.image_list);
const codeRunTriggered = useSelector((state) => state.editor.codeRunTriggered);
const codeRunStopped = useSelector((state) => state.editor.codeRunStopped);
const drawTriggered = useSelector((state) => state.editor.drawTriggered);
const outputCanvas = useRef();
const output = useRef();
const pygalOutput = useRef();
const p5Output = useRef();
const senseHatContainer = useRef();
const dispatch = useDispatch();
const [senseHatEnabled, setSenseHatEnabled] = useState(false);
useEffect(() => {
if (codeRunTriggered) {
runCode();
}
}, [codeRunTriggered]);
useEffect(() => {
if (codeRunStopped && document.getElementById("input")) {
const input = document.getElementById("input")
input.removeAttribute("id")
input.removeAttribute("contentEditable")
dispatch(setError("Execution interrupted"));
dispatch(codeRunHandled())
}
}, [codeRunStopped]);
useEffect(() => {
if (!drawTriggered && p5Output.current && p5Output.current.innerHTML !== '') {
Sk.p5.stop();
if (document.getElementById("input")) {
const input = document.getElementById("input")
input.removeAttribute("id")
input.removeAttribute("contentEditable")
}
}
},
[drawTriggered]
)
const externalLibraries = {
"./pygal/__init__.js": {
path: `${process.env.PUBLIC_URL}/pygal.js`,
dependencies: [
'https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.2/highcharts.js',
'https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.2/js/highcharts-more.js'
],
},
"./p5/__init__.js": {
path: `${process.env.PUBLIC_URL}/p5-shim.js`,
dependencies: [
'https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js'
]
},
"./_internal_sense_hat/__init__.js": {
path: `${process.env.PUBLIC_URL}/_internal_sense_hat.js`
},
"./sense_hat.py": {
path: `${process.env.PUBLIC_URL}/sense_hat_blob.py`
}
};
const outf = (text) => {
if (text !== "") {
const node = output.current;
const div = document.createElement("span")
div.classList.add('pythonrunner-console-output-line')
div.innerHTML = new Option(text).innerHTML;
node.appendChild(div);
node.scrollTop = node.scrollHeight;
}
}
const builtinRead = (x) => {
if (x==="./_internal_sense_hat/__init__.js") {
setSenseHatEnabled(true)
senseHatContainer.current.hidden=false
}
let localProjectFiles = projectCode.filter((component) => component.name !== 'main').map((component) => `./${component.name}.py`);
if (localProjectFiles.includes(x)) {
let filename = x.slice(2, -3);
let component = projectCode.find((x) => x.name === filename);
if (component) {
return component.content;
}
}
if (Sk.builtinFiles !== undefined && Sk.builtinFiles["files"][x] !== undefined) {
return Sk.builtinFiles["files"][x];
}
if (externalLibraries[x]) {
var externalLibraryInfo = externalLibraries[x];
return Sk.misceval.promiseToSuspension(
new Promise(function (resolve, reject) {
// get the main skulpt extenstion
var request = new XMLHttpRequest();
request.open("GET", externalLibraryInfo.path);
request.onload = function () {
if (request.status === 200) {
resolve(request.responseText);
} else {
reject("File not found: '" + x + "'");
}
};
request.onerror = function () {
reject("File not found: '" + x + "'");
}
request.send();
}).then(function (code) {
if (!code) {
throw new Sk.builtin.ImportError("Failed to load remote module");
}
var promise;
function mapUrlToPromise(path) {
// If the script is already in the DOM don't add it again.
const existingScriptElement = document.querySelector(`script[src="${path}"]`)
if(!existingScriptElement) {
return new Promise(function (resolve, _reject) {
let scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.src = path;
scriptElement.async = true
scriptElement.onload = function () {
resolve(true);
}
document.body.appendChild(scriptElement);
});
}
}
if (externalLibraryInfo.loadDepsSynchronously) {
promise = (externalLibraryInfo.dependencies || []).reduce((p, url) => {
return p.then(() => mapUrlToPromise(url));
}, Promise.resolve()); // initial
} else {
promise = Promise.all((externalLibraryInfo.dependencies || []).map(mapUrlToPromise));
}
return promise.then(function () {
return code;
}).catch(function () {
throw new Sk.builtin.ImportError("Failed to load dependencies required");
});
})
);
}
throw new Error("File not found: '" + x + "'");
}
const inputSpan = () => {
const span = document.createElement("span");
span.setAttribute("id", "input");
span.setAttribute("spellCheck", "false");
span.setAttribute("class", "pythonrunner-input");
span.setAttribute("contentEditable", "true");
return span
}
const inf = function () {
if (Sk.sense_hat) {
Sk.sense_hat.mz_criteria.noInputEvents = false
}
const outputPane = output.current;
outputPane.appendChild(inputSpan());
const input = document.getElementById("input") || document.querySelector('editor-wc').shadowRoot.getElementById("input")
input.focus();
return new Promise(function (resolve, reject) {
input.addEventListener("keydown", function removeInput(e) {
if (e.key === "Enter") {
input.removeEventListener(e.type, removeInput)
// resolve the promise with the value of the input field
const answer = input.innerText;
input.removeAttribute("id");
input.removeAttribute("contentEditable");
input.innerText=answer+'\n';
document.addEventListener("keyup", function storeInput(e) {
if (e.key === "Enter") {
document.removeEventListener(e.type, storeInput);
resolve(answer);
}
})
}
})
})
}
const runCode = () => {
// clear previous output
dispatch(setError(""));
outputCanvas.current.innerHTML = '';
output.current.innerHTML = '';
pygalOutput.current.innerHTML = '';
p5Output.current.innerHTML = '';
senseHatContainer.current.hidden = true
var prog = projectCode[0].content;
Sk.configure({
inputfun: inf,
output: outf,
read: builtinRead,
debugging: true,
inputTakesPrompt: true
});
Sk.p5 = {}
Sk.p5.sketch = "p5Sketch";
Sk.p5.assets = projectImages;
(Sk.pygal || (Sk.pygal = {})).outputCanvas = pygalOutput.current;
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'outputCanvas';
Sk.TurtleGraphics.assets = Object.assign({}, ...projectImages.map((image) => ({[`${image.name}.${image.extension}`]: image.url})))
var myPromise = Sk.misceval.asyncToPromise(() =>
Sk.importMainWithBody("<stdin>", false, prog, true), {
"*": () => {
if (store.getState().editor.codeRunStopped) {
throw new Error("Execution interrupted");
}
}
},
).catch(err => {
const message = err.message || err.toString();
dispatch(setError(message));
if (document.getElementById("input")) {
const input = document.getElementById("input") || document.querySelector('editor-wc').shadowRoot.getElementById("input")
input.removeAttribute("id")
input.removeAttribute("contentEditable")
}
}).finally(()=>{
dispatch(codeRunHandled());
if (p5Output.current.innerHTML === '') {
dispatch(stopDraw());
}
}
);
myPromise.then(function (_mod) {
});
}
function shiftFocusToInput(e) {
if (document.getSelection().toString().length > 0) {
return;
}
const inputBox = document.getElementById("input") || document.querySelector('editor-wc').shadowRoot.getElementById("input");
if (inputBox && e.target !== inputBox) {
const input = document.getElementById("input") || document.querySelector('editor-wc').shadowRoot.getElementById("input")
const selection = window.getSelection();
selection.removeAllRanges();
if (input.innerText && input.innerText.length > 0){
const range = document.createRange();
range.setStart(input, 1);
range.collapse(true);
selection.addRange(range);
}
input.focus()
}
}
let tabIndex = projectCode[0] && projectCode[0].visualoutput ? 0 : 1;
return (
<div className="pythonrunner-container">
<Tabs forceRenderTabPanel={true} defaultIndex={tabIndex}>
<TabList>
<Tab key={0}>Visual Output</Tab>
<Tab key={1}>Text Output</Tab>
</TabList>
<ErrorMessage />
<TabPanel key={0}>
<div className='visual-output'>
<div id='p5Sketch' ref={p5Output} />
<div id='pygalOutput' ref={pygalOutput} />
<div className="pythonrunner-canvas-container">
<div id='outputCanvas' ref={outputCanvas} className="pythonrunner-graphic" />
</div>
<div id='senseHatCanvas' ref={senseHatContainer} hidden={true}>{senseHatEnabled?<AstroPiModel/>:null}</div>
</div>
</TabPanel>
<TabPanel key={1}>
<pre className="pythonrunner-console" onClick={shiftFocusToInput} ref={output}></pre>
</TabPanel>
</Tabs>
</div>
);
};
export default PythonRunner;