mdbook-repl 0.2.1

A rust based mdbook preprocessor plugin that allows you to live code in your markdown book.
<!-- Custom REPL Script -->
<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 {
        // update the iframe height
        replElement.style.height = event.data.repl.dimensions.height + "px";
        // show the iframe and hide the pre element
        iframeElement.classList.remove("hide");
        replElement.nextElementSibling.style.display = "none";
      }
    });

    // listen to theme change
    document.querySelectorAll("button[role='menuitem'].theme").forEach((btn) => {
      btn.addEventListener("click", (event) => {
        theme = mapTheme(event.target.id);
        postmessage({ editor: { theme } });
      });
    });
  });
</script>