Skip to content

Commit

Permalink
Use relative date formatting in chat history (#286)
Browse files Browse the repository at this point in the history
  • Loading branch information
Guocork authored Oct 24, 2024
1 parent 5a5e739 commit 79bd22a
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions src/chat/chat_history_card.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;

Expand Down Expand Up @@ -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> = 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)
}
Expand Down Expand Up @@ -499,3 +500,32 @@ pub enum ChatHistoryCardAction {
MenuClosed(ChatID),
DeleteChatOptionSelected(ChatID),
}


fn relative_format(datetime: DateTime<Local>) -> Option<String> {

// 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
}
}

0 comments on commit 79bd22a

Please sign in to comment.