engelsystem/resources/assets/js/countdown.js

48 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-11-29 19:19:30 +01:00
import { ready } from './ready';
2022-12-10 15:23:37 +01:00
/**
* Initialises all countdown fields on the page.
2022-12-10 15:23:37 +01:00
*/
ready(() => {
const lang = document.documentElement.getAttribute('lang');
2023-04-01 15:14:32 +02:00
const rtf = new Intl.RelativeTimeFormat(lang ?? [], { numeric: 'auto' });
const timeFrames = [
[60 * 60 * 24 * 365, 'year'],
[60 * 60 * 24 * 30, 'month'],
[60 * 60 * 24 * 7, 'week'],
[60 * 60 * 24, 'day'],
[60 * 60, 'hour'],
[60, 'minute'],
[1, 'second'],
];
/**
* @param {number} timestamp
* @returns {string}
*/
function formatFromNow(timestamp) {
const now = Date.now() / 1000;
const diff = Math.round(timestamp - now);
const absValue = Math.abs(diff);
for (const [duration, unit] of timeFrames) {
if (absValue >= duration) {
return rtf.format(Math.round(diff / duration), unit);
}
}
return rtf.format(0, 'second');
}
2022-11-29 21:47:26 +01:00
document.querySelectorAll('[data-countdown-ts]').forEach((element) => {
2022-12-10 15:28:13 +01:00
const timestamp = Number(element.dataset.countdownTs);
const template = element.textContent;
element.textContent = template.replace('%c', formatFromNow(timestamp));
2022-11-29 21:47:26 +01:00
setInterval(() => {
element.textContent = template.replace('%c', formatFromNow(timestamp));
2022-11-26 14:50:59 +01:00
}, 1000);
});
});