krata/_javascript/utils/timeago.js

81 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-09-30 14:38:41 +02:00
/*
2021-01-23 08:07:18 +01:00
* Calculate the Timeago
2019-09-30 14:38:41 +02:00
*/
$(function() {
2021-01-23 08:07:18 +01:00
const timeagoElem = $(".timeago");
2020-08-19 06:26:45 +02:00
2021-01-23 08:07:18 +01:00
let toRefresh = timeagoElem.length;
let intervalId = void 0;
2020-08-19 06:26:45 +02:00
function timeago(iso, preposition) {
2020-07-23 09:33:42 +02:00
let now = new Date();
let past = new Date(iso);
let prep = (typeof preposition !== "undefined" ? `${preposition} ` : "");
2020-07-23 09:33:42 +02:00
2020-08-19 06:26:45 +02:00
if (past.getFullYear() !== now.getFullYear()) {
2020-07-23 09:33:42 +02:00
toRefresh -= 1;
return prep + past.toLocaleString("en-US", {
2020-08-19 06:26:45 +02:00
year: "numeric",
month: "short",
day: "numeric"
2020-07-23 09:33:42 +02:00
});
2019-09-30 14:38:41 +02:00
}
2020-08-19 06:26:45 +02:00
if (past.getMonth() !== now.getMonth()) {
2020-07-23 09:33:42 +02:00
toRefresh -= 1;
return prep + past.toLocaleString("en-US", {
2020-08-19 06:26:45 +02:00
month: "short",
day: "numeric"
2020-07-23 09:33:42 +02:00
});
2019-09-30 14:38:41 +02:00
}
2020-07-23 09:33:42 +02:00
let seconds = Math.floor((now - past) / 1000);
2019-09-30 14:38:41 +02:00
2020-07-23 09:33:42 +02:00
let day = Math.floor(seconds / 86400);
2019-09-30 14:38:41 +02:00
if (day >= 1) {
2020-07-23 09:33:42 +02:00
toRefresh -= 1;
2019-09-30 14:38:41 +02:00
return day + " day" + (day > 1 ? "s" : "") + " ago";
}
2020-07-23 09:33:42 +02:00
let hour = Math.floor(seconds / 3600);
2019-09-30 14:38:41 +02:00
if (hour >= 1) {
return hour + " hour" + (hour > 1 ? "s" : "") + " ago";
}
2020-07-23 09:33:42 +02:00
let minute = Math.floor(seconds / 60);
2019-09-30 14:38:41 +02:00
if (minute >= 1) {
return minute + " minute" + (minute > 1 ? "s" : "") + " ago";
}
return "just now";
2019-09-30 14:38:41 +02:00
}
function updateTimeago() {
$(".timeago").each(function() {
if ($(this).children("i").length > 0) {
2021-01-23 08:07:18 +01:00
let node = $(this).children("i");
let date = node.text(); /* ISO Date: "YYYY-MM-DDTHH:MM:SSZ" */
$(this).text(timeago(date, $(this).attr("prep")));
2019-09-30 14:38:41 +02:00
$(this).append(node);
}
});
2020-08-19 06:26:45 +02:00
if (toRefresh === 0 && typeof intervalId !== "undefined") {
clearInterval(intervalId); /* stop interval */
2019-09-30 14:38:41 +02:00
}
2020-07-23 09:33:42 +02:00
return toRefresh;
2019-09-30 14:38:41 +02:00
}
2020-08-19 06:26:45 +02:00
if (toRefresh === 0) {
2019-09-30 14:38:41 +02:00
return;
}
2020-07-23 09:33:42 +02:00
if (updateTimeago() > 0) { /* run immediately */
2020-08-19 06:26:45 +02:00
intervalId = setInterval(updateTimeago, 60000); /* run every minute */
2019-09-30 14:38:41 +02:00
}
2020-08-19 06:26:45 +02:00
});