import { Clock } from "lucide-react"; import { useShallow } from "zustand/react/shallow"; import { useFetchUser } from "~/hooks/use-fetch-user"; import type { Message } from "~/lib/api/types"; import { useUsersStore } from "~/stores/users-store"; import ChatMessageAttachment from "./chat-message-attachment"; import UserAvatar from "./user-avatar"; import UserContextMenu from "./user-context-menu"; interface ChatMessageProps { message: Message; } export default function ChatMessage({ message }: ChatMessageProps) { const { user } = useUsersStore( useShallow((state) => ({ user: state.users[message.authorId], })), ); useFetchUser(message.authorId); const formatMessageDate = (date: Date) => { const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const yesterday = new Date(today); yesterday.setDate(yesterday.getDate() - 1); const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()); // Get localized time string const timeString = date.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", hour12: false, }); const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1); if (messageDate.getTime() === today.getTime()) { // Use Intl.RelativeTimeFormat for localized "Today" const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: "auto", }); return `${capitalize(rtf.format(0, "day"))}, ${timeString}`; } else if (messageDate.getTime() === yesterday.getTime()) { // Use Intl.RelativeTimeFormat for localized "Yesterday" const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: "auto", }); return `${capitalize(rtf.format(-1, "day"))}, ${timeString}`; } else { return date.toLocaleDateString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: false, }); } }; return (
{user?.displayName || user?.username}
{formatMessageDate(message.createdAt)}
{message.content}
{message.attachments.map((file, i) => (
))}
); }