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.
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user