|
| 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: '; |
| 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 | +async function main() { |
| 20 | + const buffer = []; |
| 21 | + const {ccall} = await phpBinary({ |
| 22 | + print(data) { |
| 23 | + if (!data) { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + if (buffer.length) { |
| 28 | + buffer.push('\n'); |
| 29 | + } |
| 30 | + buffer.push(data); |
| 31 | + } |
| 32 | + }) |
| 33 | + |
| 34 | + console.log("PHP wasm %s loaded.", ccall("phpw_exec", "string", ["string"], ["phpversion();"])); |
| 35 | + let lastOutput = null |
| 36 | + |
| 37 | + document.querySelectorAll('.example').forEach((example) => { |
| 38 | + const button = document.createElement('button'); |
| 39 | + const phpcode = example.querySelector('.phpcode'); |
| 40 | + |
| 41 | + button.innerText = 'Run code'; |
| 42 | + button.onclick = function() { |
| 43 | + if (lastOutput && lastOutput.parentNode) { |
| 44 | + lastOutput.parentNode.removeChild(lastOutput) |
| 45 | + } |
| 46 | + |
| 47 | + ccall("phpw_run", null, ["string"], ['?>' + phpcode.innerText]); |
| 48 | + lastOutput = createOutput(buffer.join('')) |
| 49 | + phpcode.parentNode.appendChild(lastOutput); |
| 50 | + buffer.length = 0; |
| 51 | + }; |
| 52 | + |
| 53 | + phpcode.parentNode.insertBefore(button, phpcode); |
| 54 | + }); |
| 55 | + |
| 56 | +} |
| 57 | + |
| 58 | +main() |
0 commit comments