philomena/assets/js/timeago.ts

76 lines
2 KiB
TypeScript
Raw Permalink Normal View History

2019-10-05 02:09:52 +02:00
/*
* Frontend timestamps.
*/
2024-04-16 14:02:12 +02:00
import { assertNotNull } from './utils/assert';
const strings: Record<string, string> = {
2019-10-05 02:09:52 +02:00
seconds: 'less than a minute',
minute: 'about a minute',
minutes: '%d minutes',
hour: 'about an hour',
hours: 'about %d hours',
day: 'a day',
days: '%d days',
month: 'about a month',
months: '%d months',
year: 'about a year',
years: '%d years',
};
2024-04-16 14:02:12 +02:00
function distance(time: Date) {
return new Date().getTime() - time.getTime();
2019-10-05 02:09:52 +02:00
}
2024-04-16 14:02:12 +02:00
function substitute(key: string, amount: number) {
return strings[key].replace('%d', Math.round(amount).toString());
2019-10-05 02:09:52 +02:00
}
2024-04-16 14:02:12 +02:00
function setTimeAgo(el: HTMLTimeElement) {
const datetime = el.getAttribute('datetime');
if (!datetime) {
return;
}
const date = new Date(datetime);
2019-10-05 02:09:52 +02:00
const distMillis = distance(date);
2024-07-04 02:27:59 +02:00
const seconds = Math.abs(distMillis) / 1000;
const minutes = seconds / 60;
const hours = minutes / 60;
const days = hours / 24;
const months = days / 30;
const years = days / 365;
2019-10-05 02:09:52 +02:00
const words =
2024-07-04 02:27:59 +02:00
(seconds < 45 && substitute('seconds', seconds)) ||
(seconds < 90 && substitute('minute', 1)) ||
(minutes < 45 && substitute('minutes', minutes)) ||
(minutes < 90 && substitute('hour', 1)) ||
(hours < 24 && substitute('hours', hours)) ||
(hours < 42 && substitute('day', 1)) ||
(days < 30 && substitute('days', days)) ||
(days < 45 && substitute('month', 1)) ||
(days < 365 && substitute('months', months)) ||
(years < 1.5 && substitute('year', 1)) ||
substitute('years', years);
2019-10-05 02:09:52 +02:00
if (!el.getAttribute('title')) {
2024-04-16 14:02:12 +02:00
el.setAttribute('title', assertNotNull(el.textContent));
2019-10-05 02:09:52 +02:00
}
el.textContent = words + (distMillis < 0 ? ' from now' : ' ago');
}
2024-04-16 14:02:12 +02:00
export function timeAgo(args: HTMLTimeElement[] | HTMLCollectionOf<HTMLTimeElement>) {
for (const el of args) {
setTimeAgo(el);
}
2019-10-05 02:09:52 +02:00
}
2024-04-16 14:02:12 +02:00
export function setupTimestamps() {
2019-10-05 02:09:52 +02:00
timeAgo(document.getElementsByTagName('time'));
window.setTimeout(setupTimestamps, 60000);
}
window.booru.timeAgo = timeAgo;