From 7189e7a39ea278d55b6180068bee03cec037e6cb Mon Sep 17 00:00:00 2001 From: Kevin McConnell Date: Wed, 5 Feb 2025 15:18:40 +0000 Subject: [PATCH] Periodically refresh relative times Otherwise the text will get out of date. For example, a new notification will say "Less than a minute ago", which is not true for very long if the page isn't refreshed. --- .../controllers/local_time_controller.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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)