1use crate::spec::{ChartKind, ChartSpec, SeriesPoint};
11
12const DEFAULT_WIDTH: usize = 48;
13
14#[must_use]
17pub fn render_text(spec: &ChartSpec, width: usize) -> String {
18 let width = width.clamp(10, 200);
19 let mut out = header(spec);
20
21 match spec.kind {
22 ChartKind::Bar | ChartKind::HBar | ChartKind::StackedBar => {
23 draw_bars(spec, width, &mut out)
24 }
25 ChartKind::Line => draw_lines(spec, width, &mut out),
26 }
27
28 push_notes(spec, &mut out);
29
30 out
31}
32
33fn header(spec: &ChartSpec) -> String {
34 let mut out = format!("{}\n", spec.title);
35 if !spec.y_label.is_empty() {
36 out.push_str(&format!(" ({})\n", spec.y_label));
37 }
38 out
39}
40
41fn push_notes(spec: &ChartSpec, out: &mut String) {
42 if spec.notes.is_empty() {
43 return;
44 }
45 out.push('\n');
46 for note in &spec.notes {
47 out.push_str(" · ");
48 out.push_str(note);
49 out.push('\n');
50 }
51}
52
53#[must_use]
56pub fn render_text_default(spec: &ChartSpec) -> String {
57 render_text(spec, DEFAULT_WIDTH)
58}
59
60fn bar_rows(spec: &ChartSpec) -> Vec<(String, f64, String)> {
62 let mut rows = Vec::new();
63 for series in &spec.series {
64 let prefix = if spec.series.len() > 1 {
65 format!("{}:", series.label)
66 } else {
67 String::new()
68 };
69 for point in &series.points {
70 let label = if prefix.is_empty() {
71 point.x.clone()
72 } else if point.x.is_empty() || point.x == series.label {
73 series.label.clone()
74 } else {
75 format!("{prefix}{}", point.x)
76 };
77 rows.push((
78 label,
79 point.y_f64(),
80 amount::display(point.y_num, point.y_denom),
81 ));
82 }
83 }
84 rows
85}
86
87fn draw_bars(spec: &ChartSpec, width: usize, out: &mut String) {
88 let rows = bar_rows(spec);
89
90 if rows.is_empty() {
91 out.push_str(" (no data)\n");
92 return;
93 }
94
95 let label_width = rows
96 .iter()
97 .map(|(l, ..)| l.chars().count())
98 .max()
99 .unwrap_or(1)
100 .min(width / 2);
101 let max_abs = rows
102 .iter()
103 .map(|(_, v, _)| v.abs())
104 .fold(0.0_f64, f64::max)
105 .max(1.0);
106 let bar_width = width.saturating_sub(label_width + 3).max(4);
107
108 for (label, value, shown) in rows {
109 let filled = ((value.abs() / max_abs) * bar_width as f64).round() as usize;
110 let bar: String = "█".repeat(filled.min(bar_width));
111 let label_trunc: String = truncate_left(&label, label_width);
112 let sign = if value < 0.0 { "-" } else { " " };
113 out.push_str(&format!(
114 " {label_trunc:>label_width$} {sign}{bar} {shown}\n",
115 ));
116 }
117}
118
119fn draw_lines(spec: &ChartSpec, width: usize, out: &mut String) {
120 if spec.series.is_empty() || spec.series.iter().all(|s| s.points.is_empty()) {
124 out.push_str(" (no data)\n");
125 return;
126 }
127
128 let (min, max) = spec
129 .series
130 .iter()
131 .flat_map(|s| s.points.iter().map(SeriesPoint::y_f64))
132 .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), y| {
133 (mn.min(y), mx.max(y))
134 });
135 let span = (max - min).abs().max(1.0);
136 let label_width = spec
137 .series
138 .iter()
139 .map(|s| s.label.chars().count())
140 .max()
141 .unwrap_or(1)
142 .min(width / 2);
143 let line_width = width.saturating_sub(label_width + 3).max(4);
144 const BLOCKS: &[char] = &['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
145
146 for series in &spec.series {
147 let label = truncate_left(&series.label, label_width);
148 let sparkline: String = (0..series.points.len().min(line_width))
149 .map(|idx| {
150 let y = series.points[idx].y_f64();
151 let pos = ((y - min) / span * (BLOCKS.len() - 1) as f64)
152 .round()
153 .clamp(0.0, (BLOCKS.len() - 1) as f64);
154 BLOCKS[pos as usize]
155 })
156 .collect();
157 out.push_str(&format!(" {label:>label_width$} {sparkline}\n"));
158 }
159}
160
161fn truncate_left(s: &str, max: usize) -> String {
162 let chars: Vec<char> = s.chars().collect();
163 if chars.len() <= max {
164 s.to_string()
165 } else {
166 chars[chars.len() - max..].iter().collect()
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use crate::spec::{ChartKind, Series, SeriesPoint};
177
178 fn sample_bar() -> ChartSpec {
179 ChartSpec {
180 title: "Balance".to_string(),
181 kind: ChartKind::Bar,
182 x_label: "Account".to_string(),
183 y_label: "USD".to_string(),
184 series: vec![
185 Series {
186 label: "Assets".to_string(),
187 commodity_symbol: "USD".to_string(),
188 points: vec![SeriesPoint {
189 x: "Assets".to_string(),
190 y_num: 10_000,
191 y_denom: 1,
192 }],
193 },
194 Series {
195 label: "Income".to_string(),
196 commodity_symbol: "USD".to_string(),
197 points: vec![SeriesPoint {
198 x: "Income".to_string(),
199 y_num: -3_000,
200 y_denom: 1,
201 }],
202 },
203 ],
204 notes: vec!["Top 2 accounts.".to_string()],
205 }
206 }
207
208 #[test]
209 fn render_text_contains_title_and_labels() {
210 let out = render_text(&sample_bar(), 40);
211 assert!(out.contains("Balance"));
212 assert!(out.contains("Assets"));
213 assert!(out.contains("Income"));
214 assert!(out.contains("Top 2 accounts."));
215 }
216
217 #[test]
218 fn render_text_empty_spec_is_safe() {
219 let spec = ChartSpec {
220 title: "Empty".to_string(),
221 kind: ChartKind::Bar,
222 x_label: String::new(),
223 y_label: String::new(),
224 series: vec![],
225 notes: vec![],
226 };
227 let out = render_text(&spec, 20);
228 assert!(out.contains("no data"));
229 }
230
231 #[test]
232 fn render_text_line_uses_sparkline_blocks() {
233 let spec = ChartSpec {
234 title: "Line".to_string(),
235 kind: ChartKind::Line,
236 x_label: "Month".to_string(),
237 y_label: "USD".to_string(),
238 series: vec![Series {
239 label: "Income".to_string(),
240 commodity_symbol: "USD".to_string(),
241 points: vec![
242 SeriesPoint {
243 x: "Jan".to_string(),
244 y_num: 100,
245 y_denom: 1,
246 },
247 SeriesPoint {
248 x: "Feb".to_string(),
249 y_num: 200,
250 y_denom: 1,
251 },
252 SeriesPoint {
253 x: "Mar".to_string(),
254 y_num: 50,
255 y_denom: 1,
256 },
257 ],
258 }],
259 notes: vec![],
260 };
261 let out = render_text(&spec, 30);
262 assert!(out.chars().any(|c| "▁▂▃▄▅▆▇█".contains(c)));
264 }
265
266 fn flat_point_chart(points: &[(&str, i64, i64)]) -> ChartSpec {
267 let series = points
268 .iter()
269 .map(|&(name, num, denom)| Series {
270 label: name.to_string(),
271 commodity_symbol: "USD".to_string(),
272 points: vec![SeriesPoint {
273 x: name.to_string(),
274 y_num: num,
275 y_denom: denom,
276 }],
277 })
278 .collect();
279 ChartSpec {
280 title: "Flat".to_string(),
281 kind: ChartKind::Bar,
282 x_label: String::new(),
283 y_label: String::new(),
284 series,
285 notes: vec![],
286 }
287 }
288
289 #[test]
290 fn flat_bars_print_their_label_once() {
291 let out = render_text(&flat_point_chart(&[("Food", 5, 1), ("Rent", 9, 1)]), 40);
292 assert!(!out.contains("Food:Food"), "{out}");
293 assert!(out.contains("Food "), "{out}");
294 }
295
296 #[test]
297 fn bar_values_print_exactly() {
298 let out = render_text(&flat_point_chart(&[("A", 1, 3), ("B", 12345, 100)]), 40);
299 assert!(out.contains(" 1/3\n"), "{out}");
300 assert!(out.contains(" 123.45\n"), "{out}");
301 let long = render_text(&flat_point_chart(&[("A", 1234567, 1000)]), 40);
302 assert!(long.contains(" 1234.567\n"), "{long}");
303 }
304
305 #[test]
306 fn truncate_left_keeps_tail() {
307 assert_eq!(truncate_left("Expenses:Food", 5), ":Food");
308 assert_eq!(truncate_left("Food", 10), "Food");
309 }
310}