From c3b66fc95102b36bf21eacdc960183216683c270 Mon Sep 17 00:00:00 2001 From: Steven Le Rouzic Date: Sat, 13 Apr 2024 23:48:00 +0200 Subject: Show timer, set time on create --- static/ui-components.js | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 static/ui-components.js (limited to 'static/ui-components.js') diff --git a/static/ui-components.js b/static/ui-components.js new file mode 100644 index 0000000..b825f23 --- /dev/null +++ b/static/ui-components.js @@ -0,0 +1,65 @@ +class LocalDate extends HTMLElement { + connectedCallback() { + let utcDate = new Date(this.innerText); + this.innerText = utcDate.toLocaleString(); + } +} +customElements.define("local-date", LocalDate); + +class TimerCountdown extends HTMLElement { + startTime; + endTime; + refreshInterval = null; + + refreshCountdown() { + let diff = Math.floor((this.endTime - this.startTime) / 1000); + if (diff <= 0) { + this.innerText = "Finished"; + return; + } + + let days = Math.floor(diff / (24 * 60 * 60)); + diff -= days * 24 * 60 * 60; + let hours = Math.floor(diff / (60 * 60)); + diff -= hours * 60 * 60; + let minutes = Math.floor(diff / 60); + diff -= minutes * 60; + let seconds = diff; + + let newText = ""; + if (days > 0) { + newText += `${days} days, `; + } + newText += `${hours.toFixed(0).padStart(2, "0")}:` + + `${minutes.toFixed(0).padStart(2, "0")}:` + + `${seconds.toFixed(0).padStart(2, "0")}`; + + this.innerText = newText; + } + + refreshCountdownNow() { + this.startTime = (new Date()).getTime(); + this.refreshCountdown(); + } + + connectedCallback() { + this.endTime = (new Date(this.getAttribute("end"))).getTime(); + if (this.hasAttribute("start")) { + this.startTime = (new Date(this.getAttribute("start"))).getTime(); + this.refreshCountdown(); + } + else { + this.startTime = (new Date()).getTime(); + this.refreshCountdown(); + this.refreshInterval = setInterval(this.refreshCountdownNow.bind(this), 1000); + } + } + + disconnectedCallback() { + if (this.refreshInterval !== null) { + clearInterval(this.refreshInterval); + } + } +} +customElements.define("timer-countdown", TimerCountdown); + -- cgit