Lines
100 %
Functions
98.65 %
Branches
use super::super::legend::text_width;
use super::cut;
use crate::layout::Metrics;
use crate::spec::{ChartKind, ChartSpec, Series, SeriesPoint};
use crate::svg::render_svg;
use crate::text::render_text_default;
use plotters::prelude::{BLACK, IntoDrawingArea, SVGBackend};
const NAMES: [&str; 10] = [
"rent",
"groceries",
"subscription",
"transportation",
"clothes",
"utilities",
"insurance",
"gifts",
"travel",
"(uncategorized)",
];
fn category(name: &str, y: i64) -> Series {
Series {
label: name.to_string(),
commodity_symbol: "USD".to_string(),
points: vec![SeriesPoint {
x: name.to_string(),
y_num: y,
y_denom: 1,
}],
}
fn spec(names: &[String]) -> ChartSpec {
let count = i64::try_from(names.len()).unwrap_or(0);
ChartSpec {
title: "Category Breakdown".to_string(),
kind: ChartKind::HBar,
x_label: "Category".to_string(),
y_label: "Amount (USD)".to_string(),
series: names
.iter()
.zip((1..=count).rev())
.map(|(name, rank)| category(name, rank * 100))
.collect(),
notes: vec![],
fn ten() -> ChartSpec {
spec(&NAMES.map(String::from))
fn attr(tag: &str, name: &str) -> Option<f64> {
let rest = tag.split_once(&format!(" {name}=\""))?.1;
rest.split('"').next()?.parse().ok()
struct Label {
text: String,
x: f64,
y: f64,
/// The `<text>` elements of the SVG that hold one of the category labels.
fn labels(svg: &str, known: impl Fn(&str) -> bool) -> Vec<Label> {
svg.split("<text")
.skip(1)
.filter_map(|tag| {
let (head, rest) = tag.split_once('>')?;
let text = rest.split("</text>").next()?.trim().to_string();
known(&text).then(|| Label {
x: attr(head, "x").unwrap_or(f64::NAN),
y: attr(head, "y").unwrap_or(f64::NAN),
text,
})
.collect()
fn category_labels(svg: &str) -> Vec<Label> {
labels(svg, |text| NAMES.contains(&text))
#[test]
fn ten_categories_have_no_overlapping_labels_at_1000_by_480() {
let svg = render_svg(&ten(), 1000, 480, 14);
let mut found = category_labels(&svg);
assert_eq!(found.len(), 10, "every category is labelled");
found.sort_by(|a, b| a.y.total_cmp(&b.y));
for pair in found.windows(2) {
assert!(
pair[1].y - pair[0].y >= 24.0,
"{} and {} are closer than a text line",
pair[0].text,
pair[1].text
);
assert!((pair[1].x - pair[0].x).abs() < 0.5, "labels share an edge");
fn categories_run_top_to_bottom_in_spec_order() {
let order: Vec<&str> = found.iter().map(|l| l.text.as_str()).collect();
assert_eq!(order, NAMES);
fn bars_run_right_from_the_axis_in_proportion_to_their_value() {
let bars: Vec<(f64, f64)> = svg
.split("<rect")
.filter_map(|tag| Some((attr(tag, "width")?, attr(tag, "height")?)))
.filter(|&(width, height)| width < 900.0 && height < 100.0 && height > 2.0)
.collect();
let widths: Vec<f64> = bars.iter().map(|b| b.0).collect();
widths.windows(2).all(|pair| pair[0] > pair[1]),
"widths fall with the values: {widths:?}"
let tall = bars.iter().map(|b| b.1).fold(0.0_f64, f64::max);
let short = bars.iter().map(|b| b.1).fold(f64::MAX, f64::min);
(tall - short).abs() < 1.5,
"every bar is as thick as a slot share"
fn a_label_longer_than_its_cap_is_cut_with_an_ellipsis() {
let long = "a-very-long-category-name-indeed";
let svg = render_svg(&spec(&[long.to_string(), "rent".to_string()]), 400, 300, 14);
let found = labels(&svg, |text| text.ends_with('…'));
assert_eq!(found.len(), 1, "one label is cut");
assert!(found[0].text.len() < long.len() + 3);
assert!(long.starts_with(found[0].text.trim_end_matches('…')));
found[0].x <= 400.0 / 3.0 + 400.0 * 0.2,
"the cut label stays at the left"
fn cut_measures_the_text_not_its_characters() {
let width = |text: &str| -> i32 {
text.chars()
.map(|c| if c == 'i' { 2 } else { 10 })
.sum::<i32>()
};
assert_eq!(cut("WWWW", 40, width), "WWWW");
assert_eq!(cut("WWWWWW", 40, width), "WWW…");
assert_eq!(cut("iiiiiiiiiiii", 24, width), "iiiiiiiiiiii");
assert_eq!(cut(&"i".repeat(28), 24, width), "iiiiiii…");
assert_eq!(cut("WWWW", 5, width), "…");
fn more_categories_than_rows_are_counted_in_a_note() {
let names: Vec<String> = (1..=30).map(|n| format!("cat{n:02}")).collect();
let svg = render_svg(&spec(&names), 1000, 300, 14);
let shown = labels(&svg, |text| text.starts_with("cat"));
shown.len() < 30 && shown.len() >= 2,
"{} rows shown",
shown.len()
let hidden = 30 - shown.len();
let note = labels(&svg, |text| text.ends_with("more"));
assert_eq!(note.len(), 1, "one note");
assert_eq!(note[0].text, format!("+{hidden} more"));
let mut ys: Vec<f64> = shown.iter().map(|l| l.y).collect();
ys.sort_by(f64::total_cmp);
ys.last().is_some_and(|&lowest| lowest < note[0].y),
"rows sit above the note"
ys.windows(2).all(|pair| pair[1] - pair[0] >= 22.0),
"rows stay a text line apart"
fn the_text_format_lists_every_category_with_its_bar() {
let text = render_text_default(&ten());
for name in NAMES {
assert!(text.contains(name), "{name} is listed:\n{text}");
assert!(text.contains('█'));
fn a_negative_category_runs_left_of_zero_and_clear_of_its_label() {
let mut refund = spec(&["salary".to_string(), "refund".to_string()]);
refund.series[1] = category("refund", -200);
let svg = render_svg(&refund, 600, 300, 14);
let names = labels(&svg, |text| text == "salary" || text == "refund");
let zero = labels(&svg, |text| text == "0");
let minus = labels(&svg, |text| text.starts_with('-'));
assert_eq!(
(names.len(), zero.len()),
(2, 1),
"labels and the zero tick"
assert!(!minus.is_empty(), "a negative tick is drawn");
.filter_map(|tag| Some((attr(tag, "x")?, attr(tag, "width")?)))
.filter(|&(_, width)| width < 500.0)
let leftmost = bars.iter().map(|b| b.0).fold(f64::MAX, f64::min);
names.iter().all(|l| l.x < leftmost),
"labels end left of every bar"
bars.iter()
.any(|&(x, w)| x < zero[0].x && (x + w - zero[0].x).abs() < 1.5),
"the negative bar ends at zero and starts left of it: {bars:?}"
fn ten_categories_and_two_notes_fit_a_standard_terminal_pane() {
let mut owner = ten();
owner.notes = vec![
"Showing top 10 categories.".into(),
"Showing USD only.".into(),
let svg = render_svg(&owner, 780, 400, 14);
assert_eq!(category_labels(&svg).len(), 10, "every category is drawn");
labels(&svg, |text| text.ends_with("more")).is_empty(),
"no more note"
fn value_ticks_stay_apart_on_a_narrow_chart() {
let svg = render_svg(&ten(), 380, 300, 14);
let mut ticks = labels(&svg, |text| {
!text.is_empty()
&& text
.chars()
.all(|c| c.is_ascii_digit() || c == ',' || c == '-')
});
assert!(ticks.len() >= 2, "ticks are drawn");
ticks.sort_by(|a, b| a.x.total_cmp(&b.x));
let mut buf = String::new();
let backend = SVGBackend::with_string(&mut buf, (380, 300));
let area = backend.into_drawing_area();
let metrics = Metrics::new(14, BLACK);
for pair in ticks.windows(2) {
let half = f64::from(
text_width(&area, &pair[0].text, metrics) + text_width(&area, &pair[1].text, metrics),
) / 2.0;
pair[1].x - pair[0].x >= half + f64::from(metrics.px_i32(14)),
"{} and {} are closer than their labels and a gap",