engelsystem/resources/assets/js/countdown.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

86 lines
2.0 KiB
JavaScript
Raw Normal View History

2022-11-29 19:19:30 +01:00
import { ready } from './ready';
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],
];
2022-12-10 15:23:37 +01:00
/**
* @param {number} timestamp
* @returns {string}
*/
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.
*/
2022-11-29 21:47:26 +01:00
ready(() => {
document.querySelectorAll('[data-countdown-ts]').forEach((element) => {
2022-12-10 15:28:13 +01:00
const timestamp = Number(element.dataset.countdownTs);
2022-11-29 21:47:26 +01:00
const template = element.innerHTML;
element.innerHTML = template.replace('%c', formatFromNow(timestamp));
setInterval(() => {
element.innerHTML = template.replace('%c', formatFromNow(timestamp));
2022-11-26 14:50:59 +01:00
}, 1000);
});
});