window.addEventListener("DOMContentLoaded", () => { const websocket = new WebSocket("wss://lilac.thewisewolf.dev/tracker/timer/ws"); websocket.addEventListener("open", () => { communicate(websocket); }); }); class Timer { constructor(renderer, end_time, running) { this.renderer = renderer; this.end_time = end_time; this.running = running; this.destroying = false; } render_time() { // Render timer status to the document var timestr; // How many seconds to the end of time var dur_seconds = Math.floor( (this.end_time - new Date()) / 1000); if (dur_seconds < 0) { timestr = "00:00"; } else { var seconds = dur_seconds % 60; dur_seconds = dur_seconds - seconds; var minutes = Math.floor(dur_seconds / 60); var hours = Math.floor(minutes / 60); minutes = minutes - 60 * hours; // Change rendering mode based on hours or minutes left if (hours > 0) { timestr = String(hours).padStart(2, '0') + ':' + String(minutes).padStart(2, '0'); } else { timestr = String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0'); } } this.renderer.update_time(timestr); } tick() { // Recursive call run per second to update and change stage if (this.destroying) { return } this.render_time(); if (this.running) { setTimeout(this.tick.bind(this), 1000); } } } class TimerRenderer { constructor (){ this.background = document.getElementsByClassName("timer-bg")[0]; this.time_element = document.getElementsByClassName("timer-time")[0]; this.bg_width = parseInt( window.getComputedStyle( this.background, null ).getPropertyValue('width'), 10 ); this.bg_height = parseInt( window.getComputedStyle( this.background, null ).getPropertyValue('height'), 10 ) } update_time (timestr) { this.time_element.textContent = timestr; } } function communicate(websocket) { console.log("Communicating"); const params = new URLSearchParams(window.location.search); websocket.send(JSON.stringify({type: "init", channel: "SubTimer", community: params.get('community')})); var renderer = new TimerRenderer(); let timer; websocket.addEventListener("message", ({ data }) => { console.log("Rec Event " + data); const event = JSON.parse(data); switch (event.type) { case "DO": let args = event.args; // Call the specified method switch (event.method) { case "setTimer": if (timer != null) { timer.destroying = true; } timer = new Timer( renderer, new Date(args.end_at), args.running ) timer.tick(); break; case "noTimer": if (timer != null) { timer.renderer.update_time("--:--") timer.destroying = true; } case "endTimer": if (timer != null) { timer.renderer.update_time("00:00") timer.destroying = true; } default: throw new Error(`Unsupported method requested: ${event.method}.`) } break; default: throw new Error(`Unsupported event type: ${event.type}.`); } }); }