Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use relative date formatting in chat history #286

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}
Loading