Skip to content

Commit 51dbc7b

Browse files
committed
Run examples with php wasm
1 parent 9ee511f commit 51dbc7b

File tree

4 files changed

+81
-0
lines changed

4 files changed

+81
-0
lines changed

include/footer.inc

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,13 @@ if (!empty($_SERVER['BASE_PAGE'])
105105
echo '<script src="/cached.php?t=' . @filemtime($path) . '&amp;f=/js/' . $filename . '"></script>' . "\n";
106106
}
107107
?>
108+
<?php
109+
$jsfiles = ["interactive-examples.js"];
110+
foreach ($jsfiles as $filename) {
111+
$path = dirname(__DIR__) . '/js/' . $filename;
112+
echo '<script type="module" src="/cached.php?t=' . @filemtime($path) . '&amp;f=/js/' . $filename . '"></script>' . "\n";
113+
}
114+
?>
108115

109116
<a id="toTop" href="javascript:;"><span id="toTopHover"></span><img width="40" height="40" alt="To Top" src="/images/to-top@2x.png"></a>
110117

js/interactive-examples.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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()

js/php-web.mjs

Lines changed: 16 additions & 0 deletions
Large diffs are not rendered by default.

js/php-web.wasm

3.56 MB
Binary file not shown.

0 commit comments

Comments
 (0)