Files
knet/js/boxes.js
2025-08-04 16:28:42 +02:00

59 lines
2.0 KiB
JavaScript

"use strict";
(() => {
const socket = getSocket("/boxes/ws");
const deserializeBox = (msg) => {
msg = msg.replaceAll("b:", "");
const parts = msg.split(":");
return {
id: Number(parts[0]),
value: parts[1] === "+",
};
};
const handleInstruction = (instruction) => {
if (instruction.startsWith("b:")) {
const items = instruction.split(";");
items.forEach((i) => {
const box = deserializeBox(i);
const el = document.getElementById("box-" + box.id);
el.checked = box.value;
// console.log(i,box,el)
});
return;
}
};
socket.addEventListener("message", (event) => {
const instructions = event.data.split("\n");
instructions.forEach(handleInstruction);
});
document.querySelectorAll(".boxes input").forEach((input) => {
input.addEventListener("change", (event) => {
const target = event.target;
const id = target?.id.split("-")[1];
const value = target.checked ? "+" : "-";
socket.send("b:" + id + ":" + value);
});
});
// const autoPlayEl = document.querySelector("#randomize");
// autoPlayEl?.addEventListener("click", (e) => socket.send("r:1000"));
// var golTimer = undefined;
// const handleGol = (el) => {
// if (el.checked) {
// golTimer = setInterval(() => {
// socket.send("gol");
// }, 500);
// }
// else {
// clearInterval(golTimer);
// }
// };
// const golEl = document.querySelector("#game-of-life");
// handleGol(golEl);
// golEl.addEventListener("change", (e) => handleGol(e.target));
const container = document.querySelector('.boxes');
const resizeObserver = new ResizeObserver((entries) => {
const entry = entries.at(0);
container.style.height = String(entry?.contentRect.width ?? 500) + 'px';
});
resizeObserver.observe(container);
})();