-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
62 lines (52 loc) · 1.81 KB
/
Copy pathscript.js
File metadata and controls
62 lines (52 loc) · 1.81 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
// 1. Initialize the Ace Editor
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/python");
editor.setOptions({
fontSize: "14px",
showPrintMargin: false,
enableBasicAutocompletion: true,
enableLiveAutocompletion: true
});
// 2. Global variable to hold the MicroPython instance
let mp = null;
// 3. Initialize MicroPython and override input()
async function initMicroPython() {
try {
const stdoutWriter = (line) => {
const outputElement = document.getElementById("output");
outputElement.innerText += line + "\n";
outputElement.scrollTop = outputElement.scrollHeight;
};
// Load MicroPython runtime with stdout mapping
mp = await loadMicroPython({ stdout: stdoutWriter });
// Override Python's built-in input() to use browser's window.prompt()
await mp.runPythonAsync(`
import js
def input(prompt_str=""):
res = js.window.prompt(prompt_str)
return "" if res is None else res
__builtins__.input = input
`);
console.log("MicroPython WASM initialized with input() support.");
} catch (error) {
console.error("Failed to load MicroPython:", error);
}
}
initMicroPython();
// 4. Extract and execute code when the button is clicked
window.runCode = async function() {
if (!mp) {
alert("MicroPython is still loading. Please wait a moment.");
return;
}
// Clear previous output
document.getElementById("output").innerText = "";
// Get code from Ace Editor
var pythonCode = editor.getValue();
try {
await mp.runPythonAsync(pythonCode);
} catch (error) {
document.getElementById("output").innerText += "Error: " + error + "\n";
}
};