bytebeat-composer/src/embed.ts
2024-08-09 15:07:45 -04:00

82 lines
2.1 KiB
TypeScript

import { isPlainObject } from "./common.ts";
import elements from "./elements.ts";
import { setCanvasWidth, autoSizeCanvas, getSong, setSong } from "./interface.ts";
const nameids: [string, (show: boolean) => void, ...string[]][] = [
["codeEditor", () => {}, "code-editor-container"],
[
"timeControls",
show => {
elements.controls.dataset["timeControlsDisabled"] = !show as unknown as string;
elements.canvasContainer.dataset["disabled"] = !show as unknown as string;
},
"canvas-toggleplay",
],
[
"playbackControls",
show => {
elements.controls.dataset["playbackControlsDisabled"] = !show as unknown as string;
},
],
[
"viewControls",
show => {
elements.controls.dataset["viewControlsDisabled"] = !show as unknown as string;
},
],
[
"songControls",
show => {
elements.controls.dataset["songControlsDisabled"] = !show as unknown as string;
},
],
["error", () => {}, "error"],
["scope", () => {}, "canvas-container"],
];
window.addEventListener(
"message",
e => {
console.info("recieved message", e);
if (isPlainObject(e.data)) {
const data: { [index: string]: unknown } = e.data;
// show/hide elements
if (isPlainObject(data["show"])) {
for (const [name, fn, ...ids] of nameids) {
const show: { [index: string]: unknown } = data["show"];
if (show[name] !== undefined) {
if (show[name]) {
fn(true);
for (const id of ids) {
document.getElementById(id)!.classList.remove("disabled");
}
} else {
fn(false);
for (const id of ids) {
document.getElementById(id)!.classList.add("disabled");
}
}
}
}
}
if (data["forceScopeWidth"] !== undefined && elements.canvas) {
if (typeof data["forceScopeWidth"] === "number") {
elements.canvas.dataset["forcedWidth"] = true as unknown as string;
setCanvasWidth(data["forceScopeWidth"]);
} else {
delete elements.canvas.dataset["forcedWidth"];
autoSizeCanvas();
}
}
if (data["getSong"]) {
window.parent.postMessage({ song: getSong() }, "*");
}
if (isPlainObject(data["setSong"])) {
setSong(data["setSong"], false);
}
}
},
false,
);