forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.js
More file actions
89 lines (80 loc) · 2.16 KB
/
process.js
File metadata and controls
89 lines (80 loc) · 2.16 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
// MarkedJs: renders Markdown
// https://github.com/markedjs/marked
import marked from 'marked';
// KaTex: renders Math
// https://github.com/KaTeX/KaTeX
import katex from 'katex';
import 'katex/dist/katex.min.css';
// Render Markdown with imported marked compiler
function renderMarkdown(md) {
// TODO: add error handling and output sanitization
let settings = {
headerIds: true,
breaks: true,
};
return marked(md, settings);
}
// Render Math with Katex
function renderMath(math) {
// TODO: definetly add error handling.
return katex.renderToString(math, {
macros: { '\\f': '#1f(#2)' },
});
}
function runPython(pyvm, code, error) {
try {
pyvm.exec(code);
} catch (err) {
handlePythonError(error, err);
}
}
function handlePythonError(errorElem, err) {
if (err instanceof WebAssembly.RuntimeError) {
err = window.__RUSTPYTHON_ERROR || err;
}
errorElem.textContent = err;
}
function addCSS(code) {
let style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = code;
// add a data attribute to check if css already loaded
style.dataset.status = 'loaded';
document.getElementsByTagName('head')[0].appendChild(style);
}
function checkCssStatus() {
let style = document.getElementsByTagName('style')[0];
if (!style) {
return 'none';
} else {
return style.dataset.status;
}
}
async function runJS(code) {
const script = document.createElement('script');
const doc = document.body || document.documentElement;
const blob = new Blob([code], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
script.src = url;
const scriptLoaded = new Promise((resolve) => {
script.addEventListener('load', resolve);
});
doc.appendChild(script);
try {
URL.revokeObjectURL(url);
doc.removeChild(script);
await scriptLoaded;
} catch (e) {
// ignore if body is changed and script is detached
console.log(e);
}
}
export {
runPython,
handlePythonError,
runJS,
renderMarkdown,
renderMath,
addCSS,
checkCssStatus,
};