engelsystem/resources/assets/js/countdown.js

81 lines
1.9 KiB
JavaScript
Raw Normal View History

const lang = document.documentElement.getAttribute('lang');
const templateFuture = 'in %value %unit';
const templatePast = lang === 'en'
2022-11-26 14:50:59 +01:00
? '%value %unit ago'
: 'vor %value %unit';
const yearUnits = lang === 'en'
2022-11-26 14:50:59 +01:00
? ['year', 'years']
: ['Jahr', 'Jahren'];
const monthUnits = lang === 'en'
2022-11-26 14:50:59 +01:00
? ['month', 'months']
: ['Monat', 'Monaten'];
const dayUnits = lang === 'en'
2022-11-26 14:50:59 +01:00
? ['day', 'days']
: ['Tag', 'Tagen'];
const hourUnits = lang === 'en'
2022-11-26 14:50:59 +01:00
? ['hour', 'hours']
: ['Stunde', 'Stunden'];
const minuteUnits = lang === 'en'
2022-11-26 14:50:59 +01:00
? ['minute', 'minutes']
: ['Minute', 'Minuten'];
const secondUnits = lang === 'en'
2022-11-26 14:50:59 +01:00
? ['second', 'seconds']
: ['Sekunde', 'Sekunden'];
const nowString = lang === 'en' ? 'now' : 'jetzt';
const secondsHour = 60 * 60;
const timeFrames = [
2022-11-26 14:50:59 +01:00
[365 * 24 * 60 * 60, yearUnits],
[30 * 24 * 60 * 60, monthUnits],
[24 * 60 * 60, dayUnits],
[secondsHour, hourUnits],
[60, minuteUnits],
[1, secondUnits],
];
function formatFromNow(timestamp) {
2022-11-26 14:50:59 +01:00
const now = Date.now() / 1000;
const diff = Math.abs(timestamp - now);
const ago = now > timestamp;
2022-11-26 14:50:59 +01:00
for (const [duration, [singular, plural]] of timeFrames) {
const value = diff < secondsHour
? Math.floor(diff / duration)
: Math.round(diff / duration);
2022-11-26 14:50:59 +01:00
if (value) {
const template = ago ? templatePast : templateFuture;
const unit = value === 1 ? singular : plural;
return template
.replace('%value', value)
.replace('%unit', unit);
}
2022-11-26 14:50:59 +01:00
}
2022-11-26 14:50:59 +01:00
return nowString;
}
/**
* Initialises all countdown fields on the page.
*/
$(function () {
2022-11-26 14:50:59 +01:00
$.each($('[data-countdown-ts]'), function (i, e) {
const span = $(e);
const timestamp = span.data('countdown-ts');
const text = span.html();
span.html(text.replace('%c', formatFromNow(timestamp)));
setInterval(function () {
span.html(text.replace('%c', formatFromNow(timestamp)));
}, 1000);
});
});