48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
import {
|
|
formatChatDateLabel,
|
|
parseMessageDate,
|
|
} from "@/lib/chat/formatMessageTime";
|
|
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";
|
|
|
|
export type DateGroupedItem<T> =
|
|
| { type: "date"; label: string; key: string }
|
|
| { type: "item"; item: T; key: string };
|
|
|
|
function dayKey(createdAt?: string | null): string {
|
|
const d = parseMessageDate(createdAt);
|
|
if (d) return d.toDateString();
|
|
return "unknown-day";
|
|
}
|
|
|
|
export function groupItemsByDate<T>(
|
|
items: T[],
|
|
getCreatedAt: (item: T) => string | null | undefined,
|
|
getItemKey: (item: T, index: number) => string,
|
|
lang: AppLanguage = DEFAULT_LANGUAGE
|
|
): DateGroupedItem<T>[] {
|
|
const groups: DateGroupedItem<T>[] = [];
|
|
let lastDay = "";
|
|
|
|
items.forEach((item, index) => {
|
|
const createdAt = getCreatedAt(item);
|
|
const dk = dayKey(createdAt);
|
|
|
|
if (dk !== lastDay) {
|
|
lastDay = dk;
|
|
groups.push({
|
|
type: "date",
|
|
label: formatChatDateLabel(createdAt, lang),
|
|
key: `date-${dk}`,
|
|
});
|
|
}
|
|
|
|
groups.push({
|
|
type: "item",
|
|
item,
|
|
key: getItemKey(item, index),
|
|
});
|
|
});
|
|
|
|
return groups;
|
|
}
|