aboutsummaryrefslogtreecommitdiff
path: root/static/js/timeago.ts
blob: f7567ed4fd0ada336a73807358cd74612eb436fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
(function () {
  type second = number;
  type millisecond = number;

  const relative = new Intl.RelativeTimeFormat("en", {
    localeMatcher: "best fit",
    numeric: "always",
    style: "long",
  });

  const date = function () {
    const elements = document.querySelectorAll("time");
    for (let i = 0; i < elements.length; ++i) {
      (function (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 (Math.sign(seconds) === 1) {
            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",);    }
          }

          if (Math.sign(seconds) === -1) {
            if (-1 * days    >= 60)  { return element.textContent = relative.format(-1 * days,    "day",);    }
            if (-1 * hours   >= 48)  { return element.textContent = relative.format(-1 * hours,   "hour",);   }
            if (-1 * minutes >= 120) { return element.textContent = relative.format(-1 * minutes, "minute",); }
            if (-1 * seconds >= 0)   { return element.textContent = relative.format(-1 * seconds, "second",); }
          }

        } catch (error) {
          console.error(
            "Error: Unable to resolve relative time format!",
            error,
          );
        }
      })(elements[i]);
    }
  };

  const substitution = setInterval(date, 4);

  self.addEventListener("load", function () {
    setTimeout(function () {
      clearInterval(substitution);
      setInterval(date, 1000);
    }, 1000);
  });
})();