|
| 1 | +import phpBinary from "/js/php-web.mjs"; |
| 2 | + |
| 3 | +function createOutput(output) { |
| 4 | + const container = document.createElement("div"); |
| 5 | + container.classList.add("screen", "example-contents"); |
| 6 | + const title = document.createElement("p"); |
| 7 | + title.innerText = "Output (PHP "+ PHP.version +"):"; |
| 8 | + container.appendChild(title); |
| 9 | + const div = document.createElement("div"); |
| 10 | + div.classList.add("examplescode"); |
| 11 | + container.appendChild(div); |
| 12 | + const pre = document.createElement("pre"); |
| 13 | + pre.classList.add("examplescode"); |
| 14 | + pre.innerText = output; |
| 15 | + div.appendChild(pre); |
| 16 | + return container; |
| 17 | +} |
| 18 | + |
| 19 | +class PHP { |
| 20 | + static buffer = []; |
| 21 | + static runPhp = null; |
| 22 | + static version = ''; |
| 23 | + static async loadPhp() { |
| 24 | + if (PHP.runPhp) { |
| 25 | + return PHP.runPhp; |
| 26 | + } |
| 27 | + |
| 28 | + const { ccall } = await phpBinary({ |
| 29 | + print(data) { |
| 30 | + if (!data) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + if (PHP.buffer.length) { |
| 35 | + PHP.buffer.push("\n"); |
| 36 | + } |
| 37 | + PHP.buffer.push(data); |
| 38 | + }, |
| 39 | + }); |
| 40 | + |
| 41 | + PHP.version = ccall("phpw_exec", "string", ["string"], ["phpversion();"]), |
| 42 | + console.log("PHP wasm %s loaded.", PHP.version); |
| 43 | + PHP.runPhp = (code) => ccall("phpw_run", null, ["string"], ["?>" + code]); |
| 44 | + return PHP.runPhp; |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +async function main() { |
| 49 | + let lastOutput = null; |
| 50 | + |
| 51 | + document.querySelectorAll(".example .example-contents").forEach((example) => { |
| 52 | + const button = document.createElement("button"); |
| 53 | + button.setAttribute("type", "button"); |
| 54 | + const phpcode = example.querySelector(".phpcode"); |
| 55 | + if (phpcode === null) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + const code = phpcode.querySelector("code"); |
| 60 | + code.setAttribute("contentEditable", true); |
| 61 | + |
| 62 | + button.innerText = "Run code"; |
| 63 | + button.onclick = async function () { |
| 64 | + if (lastOutput && lastOutput.parentNode) { |
| 65 | + lastOutput.remove(); |
| 66 | + } |
| 67 | + |
| 68 | + const runPhp = await PHP.loadPhp(); |
| 69 | + runPhp(phpcode.innerText); |
| 70 | + lastOutput = createOutput(PHP.buffer.join("")); |
| 71 | + phpcode.parentNode.appendChild(lastOutput); |
| 72 | + PHP.buffer.length = 0; |
| 73 | + }; |
| 74 | + |
| 75 | + phpcode.before(button); |
| 76 | + }); |
| 77 | +} |
| 78 | + |
| 79 | +main(); |
0 commit comments