1
use super::super::legend::text_width;
2
use super::cut;
3
use crate::layout::Metrics;
4
use crate::spec::{ChartKind, ChartSpec, Series, SeriesPoint};
5
use crate::svg::render_svg;
6
use crate::text::render_text_default;
7
use plotters::prelude::{BLACK, IntoDrawingArea, SVGBackend};
8

            
9
const NAMES: [&str; 10] = [
10
    "rent",
11
    "groceries",
12
    "subscription",
13
    "transportation",
14
    "clothes",
15
    "utilities",
16
    "insurance",
17
    "gifts",
18
    "travel",
19
    "(uncategorized)",
20
];
21

            
22
95
fn category(name: &str, y: i64) -> Series {
23
95
    Series {
24
95
        label: name.to_string(),
25
95
        commodity_symbol: "USD".to_string(),
26
95
        points: vec![SeriesPoint {
27
95
            x: name.to_string(),
28
95
            y_num: y,
29
95
            y_denom: 1,
30
95
        }],
31
95
    }
32
95
}
33

            
34
9
fn spec(names: &[String]) -> ChartSpec {
35
9
    let count = i64::try_from(names.len()).unwrap_or(0);
36
    ChartSpec {
37
9
        title: "Category Breakdown".to_string(),
38
9
        kind: ChartKind::HBar,
39
9
        x_label: "Category".to_string(),
40
9
        y_label: "Amount (USD)".to_string(),
41
9
        series: names
42
9
            .iter()
43
9
            .zip((1..=count).rev())
44
94
            .map(|(name, rank)| category(name, rank * 100))
45
            .collect(),
46
9
        notes: vec![],
47
    }
48
9
}
49

            
50
6
fn ten() -> ChartSpec {
51
6
    spec(&NAMES.map(String::from))
52
6
}
53

            
54
118
fn attr(tag: &str, name: &str) -> Option<f64> {
55
118
    let rest = tag.split_once(&format!(" {name}=\""))?.1;
56
118
    rest.split('"').next()?.parse().ok()
57
118
}
58

            
59
struct Label {
60
    text: String,
61
    x: f64,
62
    y: f64,
63
}
64

            
65
/// The `<text>` elements of the SVG that hold one of the category labels.
66
11
fn labels(svg: &str, known: impl Fn(&str) -> bool) -> Vec<Label> {
67
11
    svg.split("<text")
68
11
        .skip(1)
69
162
        .filter_map(|tag| {
70
162
            let (head, rest) = tag.split_once('>')?;
71
162
            let text = rest.split("</text>").next()?.trim().to_string();
72
162
            known(&text).then(|| Label {
73
47
                x: attr(head, "x").unwrap_or(f64::NAN),
74
47
                y: attr(head, "y").unwrap_or(f64::NAN),
75
47
                text,
76
47
            })
77
162
        })
78
        .collect()
79
11
}
80

            
81
3
fn category_labels(svg: &str) -> Vec<Label> {
82
59
    labels(svg, |text| NAMES.contains(&text))
83
3
}
84

            
85
#[test]
86
1
fn ten_categories_have_no_overlapping_labels_at_1000_by_480() {
87
1
    let svg = render_svg(&ten(), 1000, 480, 14);
88
1
    let mut found = category_labels(&svg);
89
1
    assert_eq!(found.len(), 10, "every category is labelled");
90
9
    found.sort_by(|a, b| a.y.total_cmp(&b.y));
91
1
    for pair in found.windows(2) {
92
9
        assert!(
93
9
            pair[1].y - pair[0].y >= 24.0,
94
            "{} and {} are closer than a text line",
95
            pair[0].text,
96
            pair[1].text
97
        );
98
9
        assert!((pair[1].x - pair[0].x).abs() < 0.5, "labels share an edge");
99
    }
100
1
}
101

            
102
#[test]
103
1
fn categories_run_top_to_bottom_in_spec_order() {
104
1
    let svg = render_svg(&ten(), 1000, 480, 14);
105
1
    let mut found = category_labels(&svg);
106
9
    found.sort_by(|a, b| a.y.total_cmp(&b.y));
107
10
    let order: Vec<&str> = found.iter().map(|l| l.text.as_str()).collect();
108
1
    assert_eq!(order, NAMES);
109
1
}
110

            
111
#[test]
112
1
fn bars_run_right_from_the_axis_in_proportion_to_their_value() {
113
1
    let svg = render_svg(&ten(), 1000, 480, 14);
114
1
    let bars: Vec<(f64, f64)> = svg
115
1
        .split("<rect")
116
1
        .skip(1)
117
10
        .filter_map(|tag| Some((attr(tag, "width")?, attr(tag, "height")?)))
118
10
        .filter(|&(width, height)| width < 900.0 && height < 100.0 && height > 2.0)
119
        .collect();
120
10
    let widths: Vec<f64> = bars.iter().map(|b| b.0).collect();
121
1
    assert!(
122
9
        widths.windows(2).all(|pair| pair[0] > pair[1]),
123
        "widths fall with the values: {widths:?}"
124
    );
125
10
    let tall = bars.iter().map(|b| b.1).fold(0.0_f64, f64::max);
126
10
    let short = bars.iter().map(|b| b.1).fold(f64::MAX, f64::min);
127
1
    assert!(
128
1
        (tall - short).abs() < 1.5,
129
        "every bar is as thick as a slot share"
130
    );
131
1
}
132

            
133
#[test]
134
1
fn a_label_longer_than_its_cap_is_cut_with_an_ellipsis() {
135
1
    let long = "a-very-long-category-name-indeed";
136
1
    let svg = render_svg(&spec(&[long.to_string(), "rent".to_string()]), 400, 300, 14);
137
8
    let found = labels(&svg, |text| text.ends_with('…'));
138
1
    assert_eq!(found.len(), 1, "one label is cut");
139
1
    assert!(found[0].text.len() < long.len() + 3);
140
1
    assert!(long.starts_with(found[0].text.trim_end_matches('…')));
141
1
    assert!(
142
1
        found[0].x <= 400.0 / 3.0 + 400.0 * 0.2,
143
        "the cut label stays at the left"
144
    );
145
1
}
146

            
147
#[test]
148
1
fn cut_measures_the_text_not_its_characters() {
149
33
    let width = |text: &str| -> i32 {
150
33
        text.chars()
151
457
            .map(|c| if c == 'i' { 2 } else { 10 })
152
            .sum::<i32>()
153
33
    };
154
1
    assert_eq!(cut("WWWW", 40, width), "WWWW");
155
1
    assert_eq!(cut("WWWWWW", 40, width), "WWW…");
156
1
    assert_eq!(cut("iiiiiiiiiiii", 24, width), "iiiiiiiiiiii");
157
1
    assert_eq!(cut(&"i".repeat(28), 24, width), "iiiiiii…");
158
1
    assert_eq!(cut("WWWW", 5, width), "…");
159
1
}
160

            
161
#[test]
162
1
fn more_categories_than_rows_are_counted_in_a_note() {
163
30
    let names: Vec<String> = (1..=30).map(|n| format!("cat{n:02}")).collect();
164
1
    let svg = render_svg(&spec(&names), 1000, 300, 14);
165
15
    let shown = labels(&svg, |text| text.starts_with("cat"));
166
1
    assert!(
167
1
        shown.len() < 30 && shown.len() >= 2,
168
        "{} rows shown",
169
        shown.len()
170
    );
171
1
    let hidden = 30 - shown.len();
172
15
    let note = labels(&svg, |text| text.ends_with("more"));
173
1
    assert_eq!(note.len(), 1, "one note");
174
1
    assert_eq!(note[0].text, format!("+{hidden} more"));
175
7
    let mut ys: Vec<f64> = shown.iter().map(|l| l.y).collect();
176
1
    ys.sort_by(f64::total_cmp);
177
1
    assert!(
178
1
        ys.last().is_some_and(|&lowest| lowest < note[0].y),
179
        "rows sit above the note"
180
    );
181
1
    assert!(
182
6
        ys.windows(2).all(|pair| pair[1] - pair[0] >= 22.0),
183
        "rows stay a text line apart"
184
    );
185
1
}
186

            
187
#[test]
188
1
fn the_text_format_lists_every_category_with_its_bar() {
189
1
    let text = render_text_default(&ten());
190
1
    for name in NAMES {
191
10
        assert!(text.contains(name), "{name} is listed:\n{text}");
192
    }
193
1
    assert!(text.contains('█'));
194
1
}
195

            
196
#[test]
197
1
fn a_negative_category_runs_left_of_zero_and_clear_of_its_label() {
198
1
    let mut refund = spec(&["salary".to_string(), "refund".to_string()]);
199
1
    refund.series[1] = category("refund", -200);
200
1
    let svg = render_svg(&refund, 600, 300, 14);
201
10
    let names = labels(&svg, |text| text == "salary" || text == "refund");
202
10
    let zero = labels(&svg, |text| text == "0");
203
10
    let minus = labels(&svg, |text| text.starts_with('-'));
204
1
    assert_eq!(
205
1
        (names.len(), zero.len()),
206
1
        (2, 1),
207
        "labels and the zero tick"
208
    );
209
1
    assert!(!minus.is_empty(), "a negative tick is drawn");
210
1
    let bars: Vec<(f64, f64)> = svg
211
1
        .split("<rect")
212
1
        .skip(1)
213
2
        .filter_map(|tag| Some((attr(tag, "x")?, attr(tag, "width")?)))
214
2
        .filter(|&(_, width)| width < 500.0)
215
        .collect();
216
2
    let leftmost = bars.iter().map(|b| b.0).fold(f64::MAX, f64::min);
217
1
    assert!(
218
2
        names.iter().all(|l| l.x < leftmost),
219
        "labels end left of every bar"
220
    );
221
1
    assert!(
222
1
        bars.iter()
223
2
            .any(|&(x, w)| x < zero[0].x && (x + w - zero[0].x).abs() < 1.5),
224
        "the negative bar ends at zero and starts left of it: {bars:?}"
225
    );
226
1
}
227

            
228
#[test]
229
1
fn ten_categories_and_two_notes_fit_a_standard_terminal_pane() {
230
1
    let mut owner = ten();
231
1
    owner.notes = vec![
232
1
        "Showing top 10 categories.".into(),
233
1
        "Showing USD only.".into(),
234
1
    ];
235
1
    let svg = render_svg(&owner, 780, 400, 14);
236
1
    assert_eq!(category_labels(&svg).len(), 10, "every category is drawn");
237
1
    assert!(
238
21
        labels(&svg, |text| text.ends_with("more")).is_empty(),
239
        "no more note"
240
    );
241
1
}
242

            
243
#[test]
244
1
fn value_ticks_stay_apart_on_a_narrow_chart() {
245
1
    let svg = render_svg(&ten(), 380, 300, 14);
246
14
    let mut ticks = labels(&svg, |text| {
247
14
        !text.is_empty()
248
13
            && text
249
13
                .chars()
250
19
                .all(|c| c.is_ascii_digit() || c == ',' || c == '-')
251
14
    });
252
1
    assert!(ticks.len() >= 2, "ticks are drawn");
253
2
    ticks.sort_by(|a, b| a.x.total_cmp(&b.x));
254
1
    let mut buf = String::new();
255
1
    let backend = SVGBackend::with_string(&mut buf, (380, 300));
256
1
    let area = backend.into_drawing_area();
257
1
    let metrics = Metrics::new(14, BLACK);
258
1
    for pair in ticks.windows(2) {
259
2
        let half = f64::from(
260
2
            text_width(&area, &pair[0].text, metrics) + text_width(&area, &pair[1].text, metrics),
261
2
        ) / 2.0;
262
2
        assert!(
263
2
            pair[1].x - pair[0].x >= half + f64::from(metrics.px_i32(14)),
264
            "{} and {} are closer than their labels and a gap",
265
            pair[0].text,
266
            pair[1].text
267
        );
268
    }
269
1
}