Files
knet/js/boxes.ts
2025-08-04 20:24:57 +02:00

66 lines
1.8 KiB
TypeScript

type CheckboxEl = HTMLInputElement & { checked: boolean; id: string };
type Box = {
id: number;
value: boolean;
};
(() => {
const socket = initSocket("/boxes/ws");
const deserializeBox = (msg: string): Box => {
msg = msg.replaceAll("b:", "");
const parts = msg.split(":");
return {
id: Number(parts[0]),
value: parts[1] === "+",
};
};
const handleInstruction = (instruction: string) => {
if (instruction.startsWith("b:")) {
const items = instruction.split(";");
items.forEach((i) => {
const box = deserializeBox(i);
const el = document.getElementById("box-" + box.id) as CheckboxEl;
el.checked = box.value;
});
return;
}
if (instruction.startsWith("u:")) {
const items = instruction.split(":");
const el = document.getElementById("counter") as CheckboxEl;
el.innerText = items[1];
const el2 = document.getElementById("users") as CheckboxEl;
el2.innerText = items[2].replaceAll(",,,", "\n");
return;
}
};
socket.addMessageListener((data) => {
const instructions = data.split("\n");
instructions.forEach(handleInstruction);
});
const handleBoxChange = (event: Event) => {
const target = event.target as CheckboxEl;
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") as HTMLDivElement;
const resizeObserver = new ResizeObserver((entries) => {
const entry = entries.at(0);
container.style.height = String(entry?.contentRect.width ?? 500) + "px";
});
resizeObserver.observe(container);
})();