1use crate::canvas::{Canvas, Marker};
5use crate::text::put_str;
6use crate::theme::{self, Theme};
7use crate::util::{darken, dim_text, format_tick, nice_bounds, nice_ticks, pick};
8use ratatui::{
9 buffer::Buffer,
10 layout::Rect,
11 style::{Color, Style},
12 widgets::Block,
13};
14
15#[derive(Debug, Clone, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct AreaLayer {
19 pub name: String,
21 pub values: Vec<f64>,
23 pub color: Option<Color>,
25}
26
27impl AreaLayer {
28 pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
30 Self {
31 name: name.into(),
32 values: values.into_iter().collect(),
33 color: None,
34 }
35 }
36
37 pub fn color(mut self, c: Color) -> Self {
39 self.color = Some(c);
40 self
41 }
42}
43
44#[derive(Debug, Clone)]
58pub struct StackedAreaChart {
59 layers: Vec<AreaLayer>,
60 normalize: bool,
61 legend: bool,
62 outline: bool,
63 hidden: Vec<usize>,
64 hidden_legend: Vec<usize>,
65 marker: Marker,
66 theme: Option<Theme>,
67 base: Option<Style>,
68 block: Option<Block<'static>>,
69}
70
71impl StackedAreaChart {
72 pub fn new(layers: impl IntoIterator<Item = AreaLayer>) -> Self {
74 Self {
75 layers: layers.into_iter().collect(),
76 normalize: false,
77 legend: true,
78 outline: true,
79 hidden: vec![],
80 hidden_legend: vec![],
81 marker: Marker::HalfBlock,
82 theme: None,
83 base: None,
84 block: None,
85 }
86 }
87
88 setter!(
89 normalize: bool
91 );
92 setter!(
93 legend: bool
95 );
96 setter!(
97 outline: bool
99 );
100 setter!(
101 marker: Marker
103 );
104 #[must_use]
107 pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
108 self.hidden = hidden.into_iter().collect();
109 self
110 }
111 theme_setter!(
112 theme
114 );
115 base_style_setter!(base);
116 block_setter!(block, 'static);
117
118 fn render_into(&self, area: Rect, buf: &mut Buffer) {
119 if !self.hidden.is_empty() {
120 let mut c = self.clone();
121 for &h in &self.hidden {
122 if let Some(l) = c.layers.get_mut(h) {
123 l.values.iter_mut().for_each(|v| *v = 0.0);
124 }
125 }
126 c.hidden.clear();
127 c.hidden_legend = self.hidden.clone();
128 return c.render_into(area, buf);
129 }
130 let area = area.intersection(buf.area);
131 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
132 let n = self
133 .layers
134 .iter()
135 .map(|l| l.values.len())
136 .max()
137 .unwrap_or(0);
138 if n < 2 || inner.width < 8 || inner.height < 4 {
139 return;
140 }
141 let clean = |v: f64| if v.is_finite() { v.max(0.0) } else { 0.0 };
142 let mut tops: Vec<Vec<f64>> = Vec::with_capacity(self.layers.len());
144 let mut run = vec![0.0; n];
145 for l in &self.layers {
146 for (i, r) in run.iter_mut().enumerate() {
147 *r += clean(l.values.get(i).copied().unwrap_or(0.0));
148 }
149 tops.push(run.clone());
150 }
151 let totals = run;
152 if self.normalize {
153 for t in tops.iter_mut() {
154 for (i, v) in t.iter_mut().enumerate() {
155 *v = if totals[i] > 0.0 {
156 *v / totals[i] * 100.0
157 } else {
158 0.0
159 };
160 }
161 }
162 }
163 let max = tops
164 .last()
165 .map_or(0.0, |t| t.iter().copied().fold(0.0, f64::max));
166 if max <= 0.0 {
167 return;
168 }
169 let (_, hi) = nice_bounds(0.0, max, 5);
170 let (dim, text) = dim_text(&self.theme);
171 let legend = self.legend && inner.height >= 6;
172 let plot_h = inner.height - u16::from(legend);
173 let ticks = nice_ticks(0.0, hi, (plot_h as usize / 3).max(2));
174 let step = if ticks.len() >= 2 {
175 ticks[1] - ticks[0]
176 } else {
177 1.0
178 };
179 let labels: Vec<String> = ticks
180 .iter()
181 .map(|t| {
182 format!(
183 "{}{}",
184 format_tick(*t, step),
185 if self.normalize { "%" } else { "" }
186 )
187 })
188 .collect();
189 let gutter = (labels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16 + 1)
190 .min(inner.width / 2);
191 let plot = Rect::new(inner.x + gutter, inner.y, inner.width - gutter, plot_h);
192 if plot.width < 2 || plot.height < 2 {
193 return;
194 }
195 for (t, l) in ticks.iter().zip(&labels) {
196 let f = (t / hi).clamp(0.0, 1.0);
197 let y = plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16;
198 let w = l.chars().count() as u16;
199 put_str(
200 buf,
201 inner.x + gutter.saturating_sub(w + 1),
202 y,
203 plot.x,
204 l,
205 dim,
206 );
207 for x in plot.x..plot.right() {
208 buf[(x, y)].set_char('┈').set_style(dim);
209 }
210 }
211 let mut cv = Canvas::new(plot.width, plot.height, self.marker);
212 let (pw, ph) = (cv.px_w(), cv.px_h());
213 let ypx = |v: f64| ((1.0 - v / hi) * (ph - 1) as f64).round() as i32;
214 let at = |t: &[f64], px: i32| {
215 let f = px as f64 / (pw - 1).max(1) as f64 * (n - 1) as f64;
216 let i = (f.floor() as usize).min(n - 2);
217 t[i] + (t[i + 1] - t[i]) * (f - i as f64)
218 };
219 for (li, l) in self.layers.iter().enumerate().rev() {
221 let c = l.color.unwrap_or_else(|| pick(&self.theme, li));
222 let fill = darken(c, 0.5);
223 for px in 0..pw {
224 let top = ypx(at(&tops[li], px));
225 let bottom = if li == 0 {
226 ph - 1
227 } else {
228 ypx(at(&tops[li - 1], px))
229 };
230 for py in top..=bottom {
231 cv.set(px, py, fill);
232 }
233 if self.outline {
234 cv.set(px, top, c);
235 }
236 }
237 }
238 cv.render(buf, plot);
239 if crate::interact::recording() {
240 let (rx, ry) = self.marker.resolution();
241 let (rx, ry) = (i32::from(rx), i32::from(ry));
242 for c in 0..plot.width {
243 let px = (i32::from(c) * rx + rx / 2).min(pw - 1);
244 let di = ((px as f64 / (pw - 1).max(1) as f64 * (n - 1) as f64).round() as usize)
245 .min(n - 1);
246 for (li, l) in self.layers.iter().enumerate() {
247 if self.hidden_legend.contains(&li) {
248 continue;
249 }
250 let top = ypx(at(&tops[li], px)).max(0) / ry;
251 let bottom = if li == 0 {
252 i32::from(plot.height) - 1
253 } else {
254 ypx(at(&tops[li - 1], px)).max(0) / ry
255 };
256 if bottom < top {
257 continue;
258 }
259 let rect = Rect::new(
260 plot.x + c,
261 plot.y + top as u16,
262 1,
263 (bottom - top + 1) as u16,
264 )
265 .intersection(plot);
266 crate::interact::record_point(rect, li, di, || {
267 let v = l.values.get(di).copied().unwrap_or(0.0);
268 let mut lines = vec![crate::util::format_compact(clean(v))];
269 if totals[di] > 0.0 {
270 lines.push(format!("{:.0}% of total", clean(v) / totals[di] * 100.0));
271 }
272 (l.name.clone(), lines)
273 });
274 }
275 }
276 }
277 if legend {
278 let mut x = plot.x;
279 let y = inner.bottom() - 1;
280 for (li, l) in self.layers.iter().enumerate() {
281 let c = l.color.unwrap_or_else(|| pick(&self.theme, li));
282 let w = l.name.chars().count() as u16 + 3;
283 if x + w > inner.right() {
284 break;
285 }
286 let off = self.hidden_legend.contains(&li);
287 put_str(
288 buf,
289 x,
290 y,
291 inner.right(),
292 if off { "□" } else { "■" },
293 Style::default().fg(c),
294 );
295 let name_style = if off {
296 text.add_modifier(
297 ratatui::style::Modifier::CROSSED_OUT | ratatui::style::Modifier::DIM,
298 )
299 } else {
300 text
301 };
302 put_str(buf, x + 2, y, inner.right(), &l.name, name_style);
303 crate::interact::record_legend(Rect::new(x, y, w, 1), li, &l.name);
304 x += w + 1;
305 }
306 }
307 }
308}
309
310widget_impls!(StackedAreaChart);
311
312#[cfg(feature = "theme")]
313impl tui_nuances::Themed for StackedAreaChart {
314 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
315 self.theme(theme)
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use ratatui::widgets::Widget;
323
324 fn render(c: &StackedAreaChart, w: u16, h: u16) -> Buffer {
325 let a = Rect::new(0, 0, w, h);
326 let mut b = Buffer::empty(a);
327 c.render(a, &mut b);
328 b
329 }
330
331 fn chart() -> StackedAreaChart {
332 StackedAreaChart::new([
333 AreaLayer::new("web", [1.0, 2.0, 3.0, 4.0]).color(Color::Red),
334 AreaLayer::new("api", [2.0, 2.0, 2.0, 2.0]).color(Color::Blue),
335 ])
336 }
337
338 #[test]
339 fn draws_layers_and_legend() {
340 let b = render(&chart(), 50, 14);
341 let t: String = b.content().iter().map(|c| c.symbol()).collect();
342 assert!(t.contains("web") && t.contains("api"));
343 assert!(b.content().iter().any(|c| c.fg == Color::Red));
344 assert!(b.content().iter().any(|c| c.fg == Color::Blue));
345 }
346
347 #[test]
348 fn stacking_puts_later_layers_above() {
349 let b = render(&chart().legend(false), 50, 14);
350 let first = |col: Color| {
351 b.content()
352 .iter()
353 .position(|c| c.fg == col && c.symbol() != " ")
354 .unwrap()
355 };
356 assert!(first(Color::Blue) < first(Color::Red) + 50 * 14);
357 assert!(first(Color::Blue) <= first(Color::Red));
359 }
360
361 #[test]
362 fn normalize_shows_percent_axis() {
363 let b = render(&chart().normalize(true), 50, 14);
364 let t: String = b.content().iter().map(|c| c.symbol()).collect();
365 assert!(t.contains('%'));
366 }
367
368 #[test]
369 fn outline_toggle() {
370 assert_ne!(
371 render(&chart(), 50, 14),
372 render(&chart().outline(false), 50, 14)
373 );
374 }
375
376 #[test]
377 fn degenerate_inputs_do_not_panic() {
378 let c = StackedAreaChart::new([
379 AreaLayer::new("n", [f64::NAN, f64::INFINITY, -3.0, 1e300]),
380 AreaLayer::new("short", [1.0]),
381 ]);
382 for (w, h) in [(0, 0), (1, 1), (8, 4), (3, 40), (200, 60)] {
383 render(&c, w, h);
384 render(&chart().normalize(true), w, h);
385 }
386 render(&StackedAreaChart::new([]), 40, 10);
387 render(
388 &StackedAreaChart::new([AreaLayer::new("z", [0.0, 0.0])]),
389 40,
390 10,
391 );
392 }
393}