Format post and comment votes with a decimal place, like vanilla reddit does. (#324)

* Format post and comment votes with a decimal place, like vanilla reddit does.

Before this change, a vote count of 1999 was displayed as 1k, which is a pretty big gap. The displayed count also differed from what Reddit does. Now, the behaviour is consistent.

Added some tests for format_num.

* Provide more space for post scores

Co-authored-by: spikecodes <19519553+spikecodes@users.noreply.github.com>
This commit is contained in:
mikupls 2021-11-21 05:07:45 +01:00 committed by GitHub
parent f7de5285e4
commit 5d9c320a7e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 8 deletions

View file

@ -544,12 +544,14 @@ pub fn rewrite_urls(input_text: &str) -> String {
})
}
// Append `m` and `k` for millions and thousands respectively
// Format vote count to a string that will be displayed.
// Append `m` and `k` for millions and thousands respectively, and
// round to the nearest tenth.
pub fn format_num(num: i64) -> (String, String) {
let truncated = if num >= 1_000_000 || num <= -1_000_000 {
format!("{}m", num / 1_000_000)
format!("{:.1}m", num as f64 / 1_000_000.0)
} else if num >= 1000 || num <= -1000 {
format!("{}k", num / 1_000)
format!("{:.1}k", num as f64 / 1_000.0)
} else {
num.to_string()
};
@ -628,3 +630,32 @@ pub async fn error(req: Request<Body>, msg: String) -> Result<Response<Body>, St
Ok(Response::builder().status(404).header("content-type", "text/html").body(body.into()).unwrap_or_default())
}
#[cfg(test)]
mod tests {
use super::format_num;
#[test]
fn format_num_works() {
assert_eq!(
format_num(567),
("567".to_string(), "567".to_string())
);
assert_eq!(
format_num(1234),
("1.2k".to_string(), "1234".to_string())
);
assert_eq!(
format_num(1999),
("2.0k".to_string(), "1999".to_string())
);
assert_eq!(
format_num(1001),
("1.0k".to_string(), "1001".to_string())
);
assert_eq!(
format_num(1_999_999),
("2.0m".to_string(), "1999999".to_string())
);
}
}

View file

@ -697,12 +697,12 @@ a.search_subreddit:hover {
.post_score {
padding-top: 16px;
padding-left: 12px;
font-size: 13px;
font-weight: bold;
text-align: end;
color: var(--accent);
grid-area: post_score;
text-align: end;
text-align: center;
border-radius: 5px 0 0 5px;
transition: 0.2s background;
}
@ -712,7 +712,7 @@ a.search_subreddit:hover {
}
.post_header {
margin: 15px 20px 5px 15px;
margin: 15px 20px 5px 12px;
grid-area: post_header;
}
@ -724,7 +724,7 @@ a.search_subreddit:hover {
font-size: 16px;
font-weight: 500;
line-height: 1.5;
margin: 5px 15px;
margin: 5px 15px 5px 12px;
grid-area: post_title;
}
@ -1076,7 +1076,7 @@ summary.comment_data {
}
.compact .post_header {
margin: 15px 15px 2.5px 15px;
margin: 15px 15px 2.5px 12px;
font-size: 14px;
}