75 lines
2.1 KiB
TypeScript
75 lines
2.1 KiB
TypeScript
type CheckboxEl = HTMLInputElement & { checked: boolean; id: string };
|
|
type Box = {
|
|
id: number;
|
|
value: boolean;
|
|
};
|
|
|
|
(() => {
|
|
const socket = getSocket("/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;
|
|
}
|
|
};
|
|
|
|
socket.addEventListener("message", (event: MessageEvent<string>) => {
|
|
const instructions = event.data.split("\n");
|
|
instructions.forEach(handleInstruction);
|
|
});
|
|
|
|
document.querySelectorAll(".boxes input").forEach((input) => {
|
|
input.addEventListener("change", (event) => {
|
|
const target = event.target as CheckboxEl;
|
|
|
|
const id = target?.id.split("-")[1];
|
|
const value = target.checked ? "+" : "-";
|
|
socket.send("b:" + id + ":" + value);
|
|
});
|
|
});
|
|
|
|
const autoPlayEl = document.querySelector("#randomize") as CheckboxEl;
|
|
autoPlayEl?.addEventListener("click", (e) => socket.send("r:1000"));
|
|
|
|
var golTimer: number | undefined = undefined;
|
|
const handleGol = (el: CheckboxEl) => {
|
|
if (el.checked) {
|
|
golTimer = setInterval(() => {
|
|
socket.send("gol");
|
|
}, 500);
|
|
} else {
|
|
clearInterval(golTimer);
|
|
}
|
|
};
|
|
|
|
const golEl = document.querySelector("#game-of-life") as CheckboxEl;
|
|
handleGol(golEl);
|
|
golEl.addEventListener("change", (e) => handleGol(e.target as CheckboxEl));
|
|
|
|
|
|
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);
|
|
})();
|