Skip to content

Commit

Permalink
feat(web): format post creation time dynamically based on age using c…
Browse files Browse the repository at this point in the history
…hrono for improved user experience
  • Loading branch information
Michael-Liendo committed Sep 24, 2024
1 parent a68bea5 commit d881642
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion crates/web/src/components/feed/post.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
use chrono::{TimeZone, Utc};
use leptos::{component, view, IntoView};

use townhall_client::post::posts::posts::PostsPostsEdgesNode;

const LONG_TO_SHORT_CUTOFF_DAYS: i64 = 3;

#[component]
pub fn Post(post: PostsPostsEdgesNode) -> impl IntoView {
let post_created_at_date_time = Utc::from_utc_datetime(&Utc, &post.created_at.naive_utc());
let now_date = Utc::now();

let diff_in_seconds = now_date
.signed_duration_since(post_created_at_date_time)
.num_seconds();

let format_string = match diff_in_seconds {
_ if diff_in_seconds > 86400 * LONG_TO_SHORT_CUTOFF_DAYS => "%m/%d/%y".to_string(), // More than 3 days
diff_in_seconds if diff_in_seconds > 86400 => {
format!("{} Days ago", diff_in_seconds / 86400)
} // Within 3 days
diff_in_seconds if diff_in_seconds > 3600 => {
format!("{} hours ago", diff_in_seconds / 3600)
} // Within 1 day
diff_in_seconds if diff_in_seconds > 60 => {
format!("{} minutes ago", diff_in_seconds / 60)
} // Within 1 hour
_ => format!("{} seconds ago", diff_in_seconds),
};

let formatted_date = post_created_at_date_time.format(&format_string).to_string();

view! {
<li class="feed-post bg-white rounded-md p-4">
<div>
Expand All @@ -13,7 +39,7 @@ pub fn Post(post: PostsPostsEdgesNode) -> impl IntoView {
</figure>
<div class="flex flex-col ml-2">
<strong>{post.author.username}</strong>
<time class="text-sm text-gray-400">2 hours ago</time>
<time class="text-sm text-gray-400">{formatted_date}</time>
</div>
</article>
</div>
Expand Down

0 comments on commit d881642

Please sign in to comment.