2022-11-29 19:19:30 +01:00
|
|
|
import { ready } from './ready';
|
|
|
|
|
2022-12-10 15:23:37 +01:00
|
|
|
/**
|
2022-12-21 14:18:21 +01:00
|
|
|
* Initialises all countdown fields on the page.
|
2022-12-10 15:23:37 +01:00
|
|
|
*/
|
2022-12-21 14:18:21 +01:00
|
|
|
ready(() => {
|
|
|
|
const lang = document.documentElement.getAttribute('lang');
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
2022-10-18 22:34:53 +02:00
|
|
|
}
|
|
|
|
|
2022-12-21 14:18:21 +01:00
|
|
|
return rtf.format(0, 'second');
|
|
|
|
}
|
2022-10-18 22:34:53 +02:00
|
|
|
|
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);
|
2022-12-21 14:18:21 +01:00
|
|
|
const template = element.textContent;
|
|
|
|
element.textContent = template.replace('%c', formatFromNow(timestamp));
|
2022-11-29 21:47:26 +01:00
|
|
|
setInterval(() => {
|
2022-12-21 14:18:21 +01:00
|
|
|
element.textContent = template.replace('%c', formatFromNow(timestamp));
|
2022-11-26 14:50:59 +01:00
|
|
|
}, 1000);
|
|
|
|
});
|
2022-10-18 22:34:53 +02:00
|
|
|
});
|