web/_javascript/utils/timeago.js

74 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-09-30 15:38:41 +03:00
/*
2021-01-23 10:07:18 +03:00
* Calculate the Timeago
2019-09-30 15:38:41 +03:00
*/
$(function() {
2021-01-23 10:07:18 +03:00
const timeagoElem = $(".timeago");
2020-08-19 07:26:45 +03:00
2021-01-23 10:07:18 +03:00
let toRefresh = timeagoElem.length;
let intervalId = void 0;
2020-08-19 07:26:45 +03:00
2021-07-20 20:01:09 +03:00
const dPrompt = $("meta[name=day-prompt]").attr("content");
const hrPrompt = $("meta[name=hour-prompt]").attr("content");
const minPrompt = $("meta[name=minute-prompt]").attr("content");
const justnowPrompt = $("meta[name=justnow-prompt]").attr("content");
2020-07-23 10:33:42 +03:00
2021-07-20 20:01:09 +03:00
function timeago(isoDate, dateStr) {
let now = new Date();
let past = new Date(isoDate);
2019-09-30 15:38:41 +03:00
2021-07-20 20:01:09 +03:00
if (past.getFullYear() !== now.getFullYear()
|| past.getMonth() !== now.getMonth()) {
return dateStr;
2019-09-30 15:38:41 +03:00
}
2020-07-23 10:33:42 +03:00
let seconds = Math.floor((now - past) / 1000);
2019-09-30 15:38:41 +03:00
2020-07-23 10:33:42 +03:00
let day = Math.floor(seconds / 86400);
2019-09-30 15:38:41 +03:00
if (day >= 1) {
2020-07-23 10:33:42 +03:00
toRefresh -= 1;
2021-07-20 20:01:09 +03:00
return ` ${day} ${dPrompt}`;
2019-09-30 15:38:41 +03:00
}
2020-07-23 10:33:42 +03:00
let hour = Math.floor(seconds / 3600);
2019-09-30 15:38:41 +03:00
if (hour >= 1) {
2021-07-20 20:01:09 +03:00
return ` ${hour} ${hrPrompt}`;
2019-09-30 15:38:41 +03:00
}
2020-07-23 10:33:42 +03:00
let minute = Math.floor(seconds / 60);
2019-09-30 15:38:41 +03:00
if (minute >= 1) {
2021-07-20 20:01:09 +03:00
return ` ${minute} ${minPrompt}`;
2019-09-30 15:38:41 +03:00
}
2021-07-20 20:01:09 +03:00
return justnowPrompt;
2019-09-30 15:38:41 +03:00
}
function updateTimeago() {
$(".timeago").each(function() {
if ($(this).children("i").length > 0) {
2021-07-20 20:01:09 +03:00
let dateStr = $(this).clone().children().remove().end().text();
2021-01-23 10:07:18 +03:00
let node = $(this).children("i");
2021-07-20 20:01:09 +03:00
let iosDate = node.text(); /* ISO Date: "YYYY-MM-DDTHH:MM:SSZ" */
$(this).text(timeago(iosDate, dateStr));
2019-09-30 15:38:41 +03:00
$(this).append(node);
}
});
2020-08-19 07:26:45 +03:00
if (toRefresh === 0 && typeof intervalId !== "undefined") {
clearInterval(intervalId); /* stop interval */
2019-09-30 15:38:41 +03:00
}
2020-07-23 10:33:42 +03:00
return toRefresh;
2019-09-30 15:38:41 +03:00
}
2020-08-19 07:26:45 +03:00
if (toRefresh === 0) {
2019-09-30 15:38:41 +03:00
return;
}
2020-07-23 10:33:42 +03:00
if (updateTimeago() > 0) { /* run immediately */
2020-08-19 07:26:45 +03:00
intervalId = setInterval(updateTimeago, 60000); /* run every minute */
2019-09-30 15:38:41 +03:00
}
2020-08-19 07:26:45 +03:00
});