///
///
///
import { getCodeFiles } from "./codeFile.ts";
import { bundle } from "./bundler.ts";
import {
eventName,
Scrapbox,
} from "https://raw.githubusercontent.com/scrapbox-jp/types/0.0.5/mod.ts";
declare const scrapbox: Scrapbox;
const callback = () => {
const files = getCodeFiles();
// ボタンを全部リセットする
document.querySelectorAll('[data-id="jupyter-button"]').forEach((div) =>
div.remove()
);
files.forEach((file) => {
// TS/JS以外は無視
if (
!["ts", "js", "tsx", "jsx", "mjs", "javascript", "typescript"].includes(
file.lang.toLowerCase(),
)
) {
return;
}
file.startIds.forEach((id) => {
const line = document.getElementById(`L${id}`);
line?.insertBefore(
createButton({
onClick: async ({ target }) => {
(target as HTMLDivElement).style.color = "red";
try {
const code = await bundle(file.lines.join("\n"));
console.log("execute:", code);
Function(`(async()=>{${code}})()`)();
} catch (e) {
console.error(e);
} finally {
(target as HTMLDivElement).style.removeProperty("color");
}
},
}),
line?.firstElementChild,
);
});
});
};
callback();
scrapbox.addListener("lines:changed" as eventName, callback);
function createButton(props: { onClick: (event: MouseEvent) => void }) {
const div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "-1em";
div.style.zIndex = "900";
div.textContent = "▶";
div.dataset.id = "jupyter-button";
div.addEventListener("click", props.onClick);
return div;
}