bolt.diy/app/components/sidebar/date-binning.ts

60 lines
1.3 KiB
TypeScript
Raw Normal View History

import { format, isAfter, isThisWeek, isThisYear, isToday, isYesterday, subDays } from 'date-fns';
import type { ChatHistoryItem } from '~/lib/persistence';
2024-07-31 21:21:40 +00:00
type Bin = { category: string; items: ChatHistoryItem[] };
2024-07-31 21:21:40 +00:00
export function binDates(_list: ChatHistoryItem[]) {
2024-07-31 21:21:40 +00:00
const list = _list.toSorted((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
const binLookup: Record<string, Bin> = {};
const bins: Array<Bin> = [];
list.forEach((item) => {
const category = dateCategory(new Date(item.timestamp));
if (!(category in binLookup)) {
const bin = {
category,
items: [item],
};
binLookup[category] = bin;
2024-07-31 21:21:40 +00:00
bins.push(bin);
} else {
binLookup[category].items.push(item);
}
});
return bins;
}
function dateCategory(date: Date) {
if (isToday(date)) {
return 'Today';
}
if (isYesterday(date)) {
return 'Yesterday';
}
if (isThisWeek(date)) {
2025-01-28 10:39:12 +00:00
// e.g., "Mon" instead of "Monday"
return format(date, 'EEE');
2024-07-31 21:21:40 +00:00
}
const thirtyDaysAgo = subDays(new Date(), 30);
if (isAfter(date, thirtyDaysAgo)) {
2025-01-28 10:39:12 +00:00
return 'Past 30 Days';
2024-07-31 21:21:40 +00:00
}
if (isThisYear(date)) {
2025-01-28 10:39:12 +00:00
// e.g., "Jan" instead of "January"
return format(date, 'LLL');
2024-07-31 21:21:40 +00:00
}
2025-01-28 10:39:12 +00:00
// e.g., "Jan 2023" instead of "January 2023"
return format(date, 'LLL yyyy');
2024-07-31 21:21:40 +00:00
}