diff --git a/app/javascript/controllers/local_time_controller.js b/app/javascript/controllers/local_time_controller.js index 86d5e58e6..8151d6e40 100644 --- a/app/javascript/controllers/local_time_controller.js +++ b/app/javascript/controllers/local_time_controller.js @@ -3,6 +3,8 @@ import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["time", "date", "datetime", "shortdate", "ago"] + #timer + initialize() { this.timeFormatter = new Intl.DateTimeFormat(undefined, { timeStyle: "short" }) this.dateFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "long" }) @@ -11,6 +13,14 @@ export default class extends Controller { this.agoFormatter = new AgoFormatter() } + connect() { + this.#timer = setInterval(() => this.#refreshRelativeTimes(), 30_000) + } + + disconnect() { + clearInterval(this.#timer) + } + timeTargetConnected(target) { this.#formatTime(this.timeFormatter, target) } @@ -31,6 +41,12 @@ export default class extends Controller { this.#formatTime(this.agoFormatter, target) } + #refreshRelativeTimes() { + this.agoTargets.forEach(target => { + this.#formatTime(this.agoFormatter, target) + }) + } + #formatTime(formatter, target) { const dt = new Date(target.getAttribute("datetime")) target.textContent = formatter.format(dt)