Add human reading time and human datetime

This commit is contained in:
Florian RICHER 2024-01-12 00:28:32 +01:00
parent 8b7e528bc9
commit 192d3e37b5
5 changed files with 51 additions and 5 deletions

View file

@ -4,7 +4,6 @@ pub mod models;
mod pages;
#[cfg(feature = "ssr")]
mod utils;
use leptos::*;

View file

@ -4,6 +4,10 @@ use crate::app::{
models::Post,
components::{
Loading, Nav
},
utils::{
datetime::human_datetime,
reading_time::human_reading_time
}
};
@ -86,8 +90,8 @@ pub fn PostListCard(
<PostTags tags=post.metadata.tags.clone()/>
<h2><A href=format!("/posts/{}", post.metadata.slug.clone())>{post.metadata.title.clone()}</A></h2>
<p>{post.metadata.description.clone()}</p>
<span>{post.metadata.date.format("%d-%m-%Y").to_string()}</span>
<span>{post.metadata.reading_time}</span>
<span>{human_datetime(&post.metadata.date)}</span>
<span>{human_reading_time(post.metadata.reading_time)}</span>
</div>
</div>
}
@ -146,8 +150,8 @@ pub fn PostElement() -> impl IntoView {
<img src={post.metadata.image_path.clone()} alt=format!("Image {}", post.metadata.title)/>
<h1>{post.metadata.title.clone()}</h1>
<p>{post.metadata.description.clone()}</p>
<span>{post.metadata.date.format("%d-%m-%Y").to_string()}</span>
<span>{post.metadata.reading_time}</span>
<span>{human_datetime(&post.metadata.date)}</span>
<span>{human_reading_time(post.metadata.reading_time)}</span>
<PostTags tags=post.metadata.tags.clone()/>
</div>

28
src/app/utils/datetime.rs Normal file
View file

@ -0,0 +1,28 @@
use chrono::{Datelike, DateTime, Local};
pub fn human_datetime(datetime: &DateTime<Local>) -> String {
format!(
"{day} {month} {year}",
day = datetime.day(),
month = human_month(datetime.month()),
year = datetime.year()
)
}
fn human_month<'a>(month: u32) -> &'a str {
match month {
1 => "Jan.",
2 => "Feb.",
3 => "Mar.",
4 => "Avr.",
5 => "Mai",
6 => "Juin",
7 => "Juillet",
8 => "Août",
9 => "Sept.",
10 => "Oct.",
11 => "Nov.",
12 => "Dec.",
_ => "Invalide"
}
}

View file

@ -1,2 +1,5 @@
#[cfg(feature = "ssr")]
pub(crate) mod data_src;
pub(crate) mod datetime;
pub(crate) mod reading_time;

View file

@ -1,3 +1,4 @@
#[cfg(feature = "ssr")]
pub fn calculate_reading_time(content: &String) -> u64 {
let doc_read_time = estimated_read_time::Options::new()
.word_length(5)
@ -7,4 +8,15 @@ pub fn calculate_reading_time(content: &String) -> u64 {
.unwrap_or_default();
estimated_read_time::text(&content, &doc_read_time).seconds()
}
pub fn human_reading_time(reading_time: u64) -> String {
match reading_time {
0..=60 => format!("{reading_time}s"),
_ => {
let min = reading_time / 60;
let secs = reading_time - min * 60;
format!("{min}min {secs}s")
}
}
}