forked from php/web-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteractive-examples.js
80 lines (68 loc) · 2.05 KB
/
interactive-examples.js
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
import phpBinary from "/js/php-web.mjs";
function createOutput(output) {
const container = document.createElement("div");
container.classList.add("screen", "example-contents");
const title = document.createElement("p");
title.innerText = "Output (PHP "+ PHP.version +"):";
container.appendChild(title);
const div = document.createElement("div");
div.classList.add("examplescode");
container.appendChild(div);
const pre = document.createElement("pre");
pre.classList.add("examplescode");
pre.innerText = output;
div.appendChild(pre);
return container;
}
class PHP {
static buffer = [];
static runPhp = null;
static version = '';
static async loadPhp() {
if (PHP.runPhp) {
return PHP.runPhp;
}
const { ccall } = await phpBinary({
print(data) {
if (!data) {
return;
}
if (PHP.buffer.length) {
PHP.buffer.push("\n");
}
PHP.buffer.push(data);
},
});
PHP.version = ccall("phpw_exec", "string", ["string"], ["phpversion();"]),
console.log("PHP wasm %s loaded.", PHP.version);
PHP.runPhp = (code) => ccall("phpw_run", null, ["string"], ["?>" + code]);
return PHP.runPhp;
}
}
async function main() {
let lastOutput = null;
document.querySelectorAll(".example .example-contents").forEach((example) => {
const button = document.createElement("button");
button.setAttribute("type", "button");
const phpcode = example.querySelector(".phpcode");
if (phpcode === null) {
return;
}
const code = phpcode.querySelector("code");
code.spellcheck = false;
code.setAttribute("contentEditable", true);
button.innerText = "Run code";
button.onclick = async function () {
if (lastOutput && lastOutput.parentNode) {
lastOutput.remove();
}
const runPhp = await PHP.loadPhp();
runPhp(phpcode.innerText);
lastOutput = createOutput(PHP.buffer.join(""));
phpcode.parentNode.appendChild(lastOutput);
PHP.buffer.length = 0;
};
phpcode.before(button);
});
}
main();