<script>
document.querySelectorAll(".repl").forEach((replElement) => {
const iframeElement = replElement.querySelector("iframe");
const id = replElement.getAttribute("data-id");
const lang = replElement.getAttribute("data-lang");
const code = replElement.nextElementSibling.innerText.trim();
const readonly = replElement.getAttribute("data-readonly") === "true";
let theme = mapTheme(localStorage.getItem("mdbook-theme"));
const message = { id, editor: { theme, lang, code, defaultCode: code, readonly } };
const postmessage = () => iframeElement.contentWindow.postMessage({ repl: message }, "*");
function mapTheme(bookTheme) {
if (bookTheme === "coal" || bookTheme === "navy" || bookTheme === "ayu") return "dark";
else return "light";
}
window.addEventListener("message", (event) => {
if (event.source === window || !event.data.repl) return;
if (
event.data.repl.id !== id ||
event.data.repl.editor.theme !== theme ||
event.data.repl.editor.lang !== lang ||
event.data.repl.editor.readonly !== readonly ||
event.data.repl.editor.defaultCode !== code
)
postmessage();
else {
replElement.style.height = event.data.repl.dimensions.height + "px";
iframeElement.classList.remove("hide");
replElement.nextElementSibling.style.display = "none";
}
});
document.querySelectorAll("button[role='menuitem'].theme").forEach((btn) => {
btn.addEventListener("click", (event) => {
theme = mapTheme(event.target.id);
postmessage({ editor: { theme } });
});
});
});
</script>