From 79bd22a704f5b8a37ff74baeb085625bdb42392c Mon Sep 17 00:00:00 2001 From: Guocork <114151398+Guocork@users.noreply.github.com> Date: Thu, 24 Oct 2024 15:51:12 +0800 Subject: [PATCH] Use relative date formatting in chat history (#286) --- src/chat/chat_history_card.rs | 36 ++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/chat/chat_history_card.rs b/src/chat/chat_history_card.rs index 7fe91658..98831abd 100644 --- a/src/chat/chat_history_card.rs +++ b/src/chat/chat_history_card.rs @@ -2,7 +2,7 @@ use crate::{ data::{chats::chat::ChatID, store::Store}, shared::modal::ModalWidgetExt, }; -use chrono::{DateTime, Local, TimeZone}; +use chrono::{DateTime, Duration, Local, TimeZone}; use makepad_widgets::*; @@ -295,9 +295,10 @@ impl Widget for ChatHistoryCard { let datetime = DateTime::from_timestamp_millis(chat.borrow().id as i64).expect("Invalid timestamp"); let local_datetime: DateTime = Local.from_utc_datetime(&datetime.naive_utc()); - let formatted_date = local_datetime.format("%-I:%M %p, %-d/%m/%y").to_string(); + if let Some(formatted_date) = relative_format(local_datetime) { + date_label.set_text(&formatted_date); + } - date_label.set_text(&formatted_date); self.view.draw_walk(cx, scope, walk) } @@ -499,3 +500,32 @@ pub enum ChatHistoryCardAction { MenuClosed(ChatID), DeleteChatOptionSelected(ChatID), } + + +fn relative_format(datetime: DateTime) -> Option { + + // Calculate the time difference between now and the given timestamp + let now = Local::now(); + let duration = now - datetime; + + // Handle different time ranges and format accordingly + if duration < Duration::seconds(60) { + Some("Now".to_string()) + } else if duration < Duration::minutes(60) { + let minutes_text = if duration.num_minutes() == 1 { "min" } else { "mins" }; + Some(format!("{} {} ago", duration.num_minutes(), minutes_text)) + } else if duration < Duration::hours(24) && now.date_naive() == datetime.date_naive() { + Some(format!("{}", datetime.format("%H:%M"))) // "HH:MM" format for today + } else if duration < Duration::hours(48) { + if let Some(yesterday) = now.date_naive().succ_opt() { + if yesterday == datetime.date_naive() { + return Some(format!("Yesterday at {}", datetime.format("%H:%M"))); + } + } + Some(format!("{}", datetime.format("%A"))) // Fallback to day of the week if not yesterday + } else if duration < Duration::weeks(1) { + Some(format!("{}", datetime.format("%A"))) // Day of the week (e.g., "Tuesday") + } else { + Some(format!("{}", datetime.format("%F"))) // "YYYY-MM-DD" format for older messages + } +}