1use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::util::{darken, dim_text, format_compact, format_tick, nice_bounds, nice_ticks, pick};
7use ratatui::{
8 buffer::Buffer,
9 layout::Rect,
10 style::{Color, Modifier, Style},
11 widgets::Block,
12};
13
14#[derive(Debug, Clone, PartialEq)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct LollipopItem {
18 pub label: String,
20 pub value: f64,
22 pub from: Option<f64>,
24 pub color: Option<Color>,
26}
27
28impl LollipopItem {
29 pub fn new(label: impl Into<String>, value: f64) -> Self {
31 Self {
32 label: label.into(),
33 value,
34 from: None,
35 color: None,
36 }
37 }
38
39 pub fn from(mut self, from: f64) -> Self {
41 self.from = Some(from);
42 self
43 }
44
45 pub fn color(mut self, c: Color) -> Self {
47 self.color = Some(c);
48 self
49 }
50}
51
52#[derive(Debug, Clone)]
66pub struct LollipopChart {
67 items: Vec<LollipopItem>,
68 baseline: f64,
69 show_values: bool,
70 head: char,
71 sorted: bool,
72 theme: Option<Theme>,
73 base: Option<Style>,
74 block: Option<Block<'static>>,
75}
76
77impl LollipopChart {
78 pub fn new(items: impl IntoIterator<Item = LollipopItem>) -> Self {
80 Self {
81 items: items.into_iter().collect(),
82 baseline: 0.0,
83 show_values: true,
84 head: '●',
85 sorted: false,
86 theme: None,
87 base: None,
88 block: None,
89 }
90 }
91
92 setter!(
93 baseline: f64
95 );
96 setter!(
97 show_values: bool
99 );
100 setter!(
101 head: char
103 );
104 setter!(
105 sorted: bool
107 );
108 theme_setter!(
109 theme
111 );
112 base_style_setter!(base);
113 block_setter!(block, 'static);
114
115 fn render_into(&self, area: Rect, buf: &mut Buffer) {
116 let area = area.intersection(buf.area);
117 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
118 if inner.width < 10 || inner.height < 2 {
119 return;
120 }
121 let mut rows: Vec<&LollipopItem> = self
122 .items
123 .iter()
124 .filter(|i| i.value.is_finite() && i.from.is_none_or(f64::is_finite))
125 .collect();
126 if rows.is_empty() {
127 return;
128 }
129 if self.sorted {
130 rows.sort_by(|a, b| b.value.total_cmp(&a.value));
131 }
132 let (mut lo, mut hi) = (self.baseline, self.baseline);
133 for r in &rows {
134 for v in [Some(r.value), r.from].into_iter().flatten() {
135 lo = lo.min(v);
136 hi = hi.max(v);
137 }
138 }
139 let (lo, hi) = nice_bounds(lo, hi, 5);
140 let span = (hi - lo).max(f64::EPSILON);
141 let (dim, text) = dim_text(&self.theme);
142
143 let lw = rows
144 .iter()
145 .map(|r| r.label.chars().count())
146 .max()
147 .unwrap_or(0)
148 .min(inner.width as usize / 3) as u16;
149 let vw: u16 = if self.show_values { 7 } else { 1 };
150 let plot_x = inner.x + lw + 1;
151 let plot_w = inner.width.saturating_sub(lw + 1 + vw);
152 let plot_h = inner.height - 1;
153 if plot_w < 4 {
154 return;
155 }
156 let px = |v: f64| {
157 plot_x + (((v - lo) / span).clamp(0.0, 1.0) * (plot_w - 1) as f64).round() as u16
158 };
159
160 let ticks = nice_ticks(lo, hi, (plot_w as usize / 10).max(2));
162 let step = if ticks.len() >= 2 {
163 ticks[1] - ticks[0]
164 } else {
165 1.0
166 };
167 for &t in &ticks {
168 let x = px(t);
169 for y in inner.y..inner.y + plot_h {
170 buf[(x, y)].set_char('┊').set_style(dim);
171 }
172 let l = format_tick(t, step);
173 let lx = x.saturating_sub(l.chars().count() as u16 / 2).max(plot_x);
174 put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text);
175 }
176 let bx = px(self.baseline);
177 for y in inner.y..inner.y + plot_h {
178 buf[(bx, y)]
179 .set_char('│')
180 .set_style(dim.add_modifier(Modifier::BOLD));
181 }
182
183 let n = rows.len() as u16;
184 let step_y = if plot_h >= n * 2 { 2 } else { 1 };
185 let used = (n * step_y).min(plot_h);
186 let y0 = inner.y + (plot_h - used) / 2;
187 for (i, r) in rows.iter().enumerate() {
188 let y = y0 + i as u16 * step_y;
189 if y >= inner.y + plot_h {
190 break;
191 }
192 crate::interact::record_point(Rect::new(inner.x, y, inner.width, 1), 0, i, || {
193 (r.label.clone(), vec![crate::util::format_compact(r.value)])
194 });
195 let c = r.color.unwrap_or_else(|| pick(&self.theme, 0));
196 let stem = Style::default().fg(darken(c, 0.25));
197 let label: String = r.label.chars().take(lw as usize).collect();
198 let lx = inner.x + lw.saturating_sub(label.chars().count() as u16);
199 put_str(buf, lx, y, inner.x + lw, &label, text);
200 let start = r.from.unwrap_or(self.baseline);
201 let (a, b) = (px(start).min(px(r.value)), px(start).max(px(r.value)));
202 for x in a..=b {
203 buf[(x, y)].set_char('━').set_style(stem);
204 }
205 if r.from.is_some() {
206 buf[(px(start), y)]
207 .set_char(self.head)
208 .set_style(Style::default().fg(darken(c, 0.45)));
209 }
210 buf[(px(r.value), y)]
211 .set_char(self.head)
212 .set_style(Style::default().fg(c).add_modifier(Modifier::BOLD));
213 if self.show_values {
214 let vx = px(r.value).max(px(start)) + 2;
215 put_str(buf, vx, y, inner.right(), &format_compact(r.value), text);
216 }
217 }
218 }
219}
220
221widget_impls!(LollipopChart);
222
223#[cfg(feature = "theme")]
224impl tui_nuances::Themed for LollipopChart {
225 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
226 self.theme(theme)
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use ratatui::widgets::Widget;
234
235 fn render(c: &LollipopChart, w: u16, h: u16) -> Buffer {
236 let a = Rect::new(0, 0, w, h);
237 let mut b = Buffer::empty(a);
238 c.render(a, &mut b);
239 b
240 }
241
242 fn txt(b: &Buffer) -> String {
243 b.content().iter().map(|c| c.symbol()).collect()
244 }
245
246 fn items() -> Vec<LollipopItem> {
247 vec![
248 LollipopItem::new("alpha", 10.0),
249 LollipopItem::new("beta", 25.0),
250 LollipopItem::new("gamma", -5.0),
251 ]
252 }
253
254 #[test]
255 fn draws_labels_heads_and_values() {
256 let t = txt(&render(&LollipopChart::new(items()), 60, 10));
257 assert!(t.contains("alpha") && t.contains('●') && t.contains("25"));
258 }
259
260 #[test]
261 fn values_toggle_and_custom_head() {
262 let c = LollipopChart::new(items()).show_values(false).head('◆');
263 let t = txt(&render(&c, 60, 10));
264 assert!(t.contains('◆') && !t.contains("25"));
265 }
266
267 #[test]
268 fn dumbbell_draws_both_ends() {
269 let c = LollipopChart::new([LollipopItem::new("x", 20.0).from(5.0).color(Color::Red)]);
270 let b = render(&c, 60, 4);
271 assert!(b.content().iter().filter(|c| c.symbol() == "●").count() >= 2);
272 }
273
274 #[test]
275 fn sorted_orders_largest_first() {
276 let c = LollipopChart::new(items()).sorted(true);
277 let t = txt(&render(&c, 60, 10));
278 assert!(t.find("beta").unwrap() < t.find("alpha").unwrap());
279 }
280
281 #[test]
282 fn degenerate_inputs_do_not_panic() {
283 let c = LollipopChart::new([
284 LollipopItem::new("n", f64::NAN),
285 LollipopItem::new("i", f64::INFINITY).from(f64::NAN),
286 LollipopItem::new("big", 1e300),
287 ]);
288 for (w, h) in [(0, 0), (1, 1), (10, 2), (40, 3), (200, 60)] {
289 render(&c, w, h);
290 render(&LollipopChart::new(items()), w, h);
291 }
292 render(&LollipopChart::new([]), 40, 10);
293 }
294}