67 lines
1.8 KiB
TypeScript
67 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;
|
|
// console.log(i,box,el)
|
|
});
|
|
return;
|
|
}
|
|
if (instruction.startsWith("u:")) {
|
|
const items = instruction.split(":");
|
|
|
|
const el = document.getElementById("counter") as CheckboxEl;
|
|
el.innerText = items[1];
|
|
const el2 = document.getElementById("ips") as CheckboxEl;
|
|
el2.innerText = items[2].replaceAll(",", "<br/>");
|
|
|
|
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);
|
|
})();
|