treehouse/template/sandbox.hbs
2024-02-18 12:10:02 +01:00

67 lines
2 KiB
Handlebars

<!DOCTYPE html>
<html>
<head>
<title>treehouse iframe sandbox</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
<script type="importmap">{ "imports": { "treehouse/": "{{ config.site }}/static/js/" } }</script>
<script type="module">
import { evaluate } from "treehouse/components/literate-programming/eval.js";
import { internals as sandboxInternals } from "treehouse/sandbox.js";
// I'm aware there's also ResizeObserver but it didn't seem to fire off any events when a
// canvas was added, rendering it pretty much useless.
let mutationObserver = new MutationObserver(() => {
postMessage({
kind: "resize",
width: document.body.scrollWidth,
height: document.body.scrollHeight,
});
});
mutationObserver.observe(document.body, { subtree: true, childList: true });
addEventListener("message", async event => {
let message = event.data;
if (message.action == "eval") {
evaluate(message.input, {
success() {
// A double buffered approach for flickerless code modifications.
document.body.replaceChildren(...sandboxInternals.body.childNodes);
sandboxInternals.body.replaceChildren();
requestAnimationFrame(() => {
postMessage({
kind: "resize",
width: document.body.scrollWidth,
height: document.body.scrollHeight,
});
});
},
error() {
sandboxInternals.body.replaceChildren();
},
});
}
});
postMessage({ kind: "ready" });
</script>
</head>
<body></body>
</html>