misuzu/assets/misuzu.js/ext/sakuya.js

44 lines
1.3 KiB
JavaScript

const MszSakuya = (function() {
const formatter = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
const divisions = [
{ amount: 60, name: 'seconds' },
{ amount: 60, name: 'minutes' },
{ amount: 24, name: 'hours' },
{ amount: 7, name: 'days' },
{ amount: 4.34524, name: 'weeks' },
{ amount: 12, name: 'months' },
{ amount: Infinity, name: 'years' },
];
const formatTimeAgo = function(date) {
let duration = (date - new Date()) / 1000;
for(const div of divisions) {
if(Math.abs(duration) < div.amount)
return formatter.format(Math.round(duration), div.name);
duration /= div.amount;
}
};
// todo: update at intervals
const trackElement = function(elem) {
if(elem.dateTime === undefined)
return;
try {
const dateTime = new Date(elem.dateTime);
elem.textContent = formatTimeAgo(dateTime);
} catch {}
};
const trackElements = function(elems) {
for(const elem of elems)
trackElement(elem);
};
return {
formatTimeAgo: formatTimeAgo,
trackElement: trackElement,
trackElements: trackElements,
};
})();