mirror of
https://github.com/php/web-php.git
synced 2026-03-23 23:02:13 +01:00
* Run examples with php wasm * make examples editable * load wasm only when running code * handle empty code Co-authored-by: lwlinux <1053317536@qq.com>
80 lines
2.0 KiB
JavaScript
80 lines
2.0 KiB
JavaScript
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.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();
|