From b163db67a35a10e153a4fa88d1e1f1d8f9a21f8e Mon Sep 17 00:00:00 2001 From: tdro Date: Fri, 29 Jul 2022 21:24:09 -0400 Subject: static/js: Add relative dates --- static/js/index.ts | 3 ++- static/js/timeago.ts | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 static/js/timeago.ts (limited to 'static') diff --git a/static/js/index.ts b/static/js/index.ts index 6000441..52cc678 100644 --- a/static/js/index.ts +++ b/static/js/index.ts @@ -2,5 +2,6 @@ import "./pager.ts"; import "./plumber.ts"; import "./instantpage.ts"; import "./fixedsearch.ts"; +import "./timeago.ts"; -console.log("Surface Control: OK"); +console.log("Surface Control: Complete"); diff --git a/static/js/timeago.ts b/static/js/timeago.ts new file mode 100644 index 0000000..2cd72ca --- /dev/null +++ b/static/js/timeago.ts @@ -0,0 +1,47 @@ +(function () { + type second = number; + type millisecond = number; + + const relative = new Intl.RelativeTimeFormat("en", { + localeMatcher: "best fit", + numeric: "always", + style: "long", + }); + + const date = () => { + [...document.querySelectorAll("time")] + .forEach( + (element) => { + try { + const time: millisecond = new Date(element.dateTime) || new Date(); + const interval: second = ((new Date().getTime() - time.getTime()) / 1000); + + const seconds: number = Math.floor(interval); + const minutes: number = Math.floor(seconds / 60); + const hours: number = Math.floor(minutes / 60); + const days: number = Math.floor(hours / 24); + + if (seconds <= 60) { return element.textContent = relative.format(-1 * seconds, "second",); } + if (minutes <= 120) { return element.textContent = relative.format(-1 * minutes, "minute",); } + if (hours <= 48) { return element.textContent = relative.format(-1 * hours, "hour",); } + if (days <= 60) { return element.textContent = relative.format(-1 * days, "day",); } + + } catch (err) { + console.error( + "Error: Unable to resolve relative time format!", + err, + ); + } + }, + ); + } + + const substitution = setInterval(date, 4); + + self.addEventListener("load", () => { + setTimeout(() => { + clearInterval(substitution); + setInterval(date, 1000); + }, 1000); + }); +})(); -- cgit v1.2.3