1
0
Fork 0

Perf fixes

This commit is contained in:
Lim Chee Aun 2023-12-24 22:49:23 +08:00
parent 94075086ce
commit 7cfa839e1c
2 changed files with 32 additions and 38 deletions

View file

@ -8,7 +8,6 @@ import dayjs from 'dayjs';
import dayjsTwitter from 'dayjs-twitter';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useEffect, useState } from 'preact/hooks';
dayjs.extend(dayjsTwitter);
dayjs.extend(localizedFormat);
@ -19,36 +18,19 @@ const dtf = new Intl.DateTimeFormat();
export default function RelativeTime({ datetime, format }) {
if (!datetime) return null;
const date = dayjs(datetime);
const [dateStr, setDateStr] = useState('');
useEffect(() => {
let timer, raf;
const update = () => {
raf = requestAnimationFrame(() => {
let str;
if (format === 'micro') {
// If date <= 1 day ago or day is within this year
const now = dayjs();
const dayDiff = now.diff(date, 'day');
if (dayDiff <= 1 || now.year() === date.year()) {
str = date.twitter();
} else {
str = dtf.format(date.toDate());
}
} else {
str = date.fromNow();
}
setDateStr(str);
timer = setTimeout(update, 30_000);
});
};
raf = requestAnimationFrame(update);
return () => {
clearTimeout(timer);
cancelAnimationFrame(raf);
};
}, [date]);
let dateStr;
if (format === 'micro') {
// If date <= 1 day ago or day is within this year
const now = dayjs();
const dayDiff = now.diff(date, 'day');
if (dayDiff <= 1 || now.year() === date.year()) {
dateStr = date.twitter();
} else {
dateStr = dtf.format(date.toDate());
}
} else {
dateStr = date.fromNow();
}
return (
<time datetime={date.toISOString()} title={date.format('LLLL')}>

View file

@ -1,20 +1,32 @@
import mem from './mem';
const { locale } = new Intl.DateTimeFormat().resolvedOptions();
function niceDateTime(date, { hideTime, formatOpts } = {}) {
if (!(date instanceof Date)) {
date = new Date(date);
}
const _DateTimeFormat = (opts) => {
const { dateYear, hideTime, formatOpts } = opts || {};
const currentYear = new Date().getFullYear();
const dateText = Intl.DateTimeFormat(locale, {
return Intl.DateTimeFormat(locale, {
// Show year if not current year
year: date.getFullYear() === currentYear ? undefined : 'numeric',
year: dateYear === currentYear ? undefined : 'numeric',
month: 'short',
day: 'numeric',
// Hide time if requested
hour: hideTime ? undefined : 'numeric',
minute: hideTime ? undefined : 'numeric',
...formatOpts,
}).format(date);
});
};
const DateTimeFormat = mem(_DateTimeFormat);
function niceDateTime(date, dtfOpts) {
if (!(date instanceof Date)) {
date = new Date(date);
}
const DTF = DateTimeFormat({
dateYear: date.getFullYear(),
...dtfOpts,
});
const dateText = DTF.format(date);
return dateText;
}