Files
knet/js/boxes.js
JurajKubrican c350501f29 live users
2025-08-04 20:05:08 +02:00

52 lines
1.8 KiB
JavaScript

"use strict";
(() => {
const socket = initSocket("/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;
}
if (instruction.startsWith("u:")) {
const items = instruction.split(":");
const el = document.getElementById("counter");
el.innerText = items[1];
const el2 = document.getElementById("ips");
el2.innerText = items[2].replaceAll(",", "\n");
return;
}
};
socket.addMessageListener((data) => {
const instructions = data.split("\n");
instructions.forEach(handleInstruction);
});
const handleBoxChange = (event) => {
const target = event.target;
const id = target?.id.split("-")[1];
const value = target.checked ? "+" : "-";
socket.send("b:" + id + ":" + value);
};
document.querySelectorAll(".boxes input").forEach((input) => {
input.addEventListener("change", handleBoxChange);
});
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);
})();