1use crate::canvas::{Canvas, Marker};
4use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::util::{format_tick, nice_bounds, nice_ticks};
7use crate::PALETTE;
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 BubbleSeries {
19 pub name: String,
21 pub points: Vec<(f64, f64, f64)>,
23 pub color: Option<Color>,
25}
26
27impl BubbleSeries {
28 pub fn new(name: impl Into<String>, points: impl IntoIterator<Item = (f64, f64, f64)>) -> Self {
30 Self {
31 name: name.into(),
32 points: points.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, Default)]
58pub struct BubbleChart {
59 series: Vec<BubbleSeries>,
60 max_radius: Option<u16>,
61 marker: Marker,
62 theme: Option<Theme>,
63 base: Option<Style>,
64 block: Option<Block<'static>>,
65}
66
67impl BubbleChart {
68 pub fn new(series: impl IntoIterator<Item = BubbleSeries>) -> Self {
70 Self {
71 series: series.into_iter().collect(),
72 ..Self::default()
73 }
74 }
75
76 opt_setter!(
77 max_radius: u16
79 );
80
81 setter!(
82 marker: Marker
84 );
85
86 theme_setter!(
87 theme
89 );
90
91 base_style_setter!(base);
92
93 block_setter!(block, 'static);
94
95 fn render_into(&self, area: Rect, buf: &mut Buffer) {
96 let area = area.intersection(buf.area);
97 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
98 if inner.width < 8 || inner.height < 4 {
99 return;
100 }
101 let pts = || {
102 self.series.iter().flat_map(|s| {
103 s.points
104 .iter()
105 .filter(|(x, y, z)| x.is_finite() && y.is_finite() && z.is_finite())
106 })
107 };
108 if pts().next().is_none() {
109 return;
110 }
111 let (mut x0, mut x1) = (f64::MAX, f64::MIN);
112 let (mut y0, mut y1) = (f64::MAX, f64::MIN);
113 let mut zmax = 0f64;
114 for &(x, y, z) in pts() {
115 x0 = x0.min(x);
116 x1 = x1.max(x);
117 y0 = y0.min(y);
118 y1 = y1.max(y);
119 zmax = zmax.max(z.abs());
120 }
121 let (x0, x1) = nice_bounds(x0, x1, 5);
122 let (y0, y1) = nice_bounds(y0, y1, 5);
123 let (xs, ys) = ((x1 - x0).max(f64::EPSILON), (y1 - y0).max(f64::EPSILON));
124 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
125 let text = self
126 .theme
127 .as_ref()
128 .map_or(Style::default(), |t| t.label_style());
129
130 let yt = nice_ticks(y0, y1, (inner.height as usize / 3).max(2));
131 let ystep = if yt.len() >= 2 { yt[1] - yt[0] } else { 1.0 };
132 let ylabels: Vec<String> = yt.iter().map(|v| format_tick(*v, ystep)).collect();
133 let gutter = (ylabels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16 + 1)
134 .min(inner.width / 2);
135 let plot = Rect::new(
136 inner.x + gutter,
137 inner.y,
138 inner.width - gutter,
139 inner.height - 1,
140 );
141 if plot.width < 2 || plot.height < 2 {
142 return;
143 }
144 let mut cv = Canvas::new(plot.width, plot.height, self.marker);
145 let (pw, ph) = (cv.px_w(), cv.px_h());
146 let rmax = self
147 .max_radius
148 .map_or(((ph.min(pw / 2)) / 5).max(2), |r| r as i32);
149 let (ix, iy) = (rmax.min(pw / 3), rmax.min(ph / 3));
151 let (aw, ah) = (
152 (pw - 1 - 2 * ix).max(1) as f64,
153 (ph - 1 - 2 * iy).max(1) as f64,
154 );
155 for (si, s) in self.series.iter().enumerate() {
156 let color = s.color.unwrap_or_else(|| {
157 self.theme
158 .as_ref()
159 .map_or(PALETTE[si % PALETTE.len()], |t| t.color(si))
160 });
161 for &(x, y, z) in &s.points {
162 if !(x.is_finite() && y.is_finite() && z.is_finite()) {
163 continue;
164 }
165 let cx = ix + ((x - x0) / xs * aw).round() as i32;
166 let cy = iy + ((1.0 - (y - y0) / ys) * ah).round() as i32;
167 let r = if zmax > 0.0 {
168 ((z.abs() / zmax).sqrt() * rmax as f64).round() as i32
169 } else {
170 0
171 }
172 .max(1);
173 for dy in -r..=r {
174 for dx in -r..=r {
175 let (rx, ry) = self.marker.resolution();
177 let ax = dx * ry as i32 / rx as i32;
178 if ax * ax + dy * dy <= r * r {
179 cv.set(cx + dx, cy + dy, color);
180 }
181 }
182 }
183 }
184 }
185 for (v, l) in yt.iter().zip(&ylabels) {
186 let f = ((v - y0) / ys).clamp(0.0, 1.0);
187 let y = plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16;
188 let w = l.chars().count() as u16;
189 put_str(
190 buf,
191 inner.x + gutter.saturating_sub(w + 1),
192 y,
193 plot.x,
194 l,
195 dim,
196 );
197 for x in plot.x..plot.right() {
198 if buf[(x, y)].symbol() == " " {
199 buf[(x, y)].set_char('┈').set_style(dim);
200 }
201 }
202 }
203 cv.render(buf, plot);
204 let xt = nice_ticks(x0, x1, (plot.width as usize / 10).max(2));
205 let xstep = if xt.len() >= 2 { xt[1] - xt[0] } else { 1.0 };
206 for v in xt {
207 let f = ((v - x0) / xs).clamp(0.0, 1.0);
208 let x = plot.x + (f * (plot.width - 1) as f64).round() as u16;
209 let l = format_tick(v, xstep);
210 let lx = x.saturating_sub(l.chars().count() as u16 / 2).max(plot.x);
211 put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text);
212 }
213 }
214}
215
216widget_impls!(BubbleChart);
217
218#[cfg(feature = "theme")]
219impl tui_nuances::Themed for BubbleChart {
220 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
221 self.theme(theme)
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228 use ratatui::widgets::Widget;
229
230 fn render(c: &BubbleChart, w: u16, h: u16) -> Buffer {
231 let a = Rect::new(0, 0, w, h);
232 let mut b = Buffer::empty(a);
233 c.render(a, &mut b);
234 b
235 }
236
237 #[test]
238 fn bigger_size_covers_more_cells() {
239 let count = |z: f64| {
240 let c =
241 BubbleChart::new([
242 BubbleSeries::new("a", [(0.0, 0.0, 100.0), (10.0, 10.0, z)]).color(Color::Red)
243 ]);
244 render(&c, 60, 20)
245 .content()
246 .iter()
247 .filter(|c| c.fg == Color::Red && c.symbol() != " ")
248 .count()
249 };
250 assert!(count(100.0) > count(1.0));
251 }
252
253 #[test]
254 fn degenerate_inputs_do_not_panic() {
255 let c = BubbleChart::new([BubbleSeries::new(
256 "a",
257 [(f64::NAN, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, -3.0)],
258 )]);
259 render(&c, 40, 12);
260 render(&c, 5, 3);
261 render(&c, 0, 0);
262 render(&BubbleChart::new([]), 40, 12);
263 render(
264 &BubbleChart::new([BubbleSeries::new("z", [(0.0, 0.0, 0.0)])]),
265 40,
266 12,
267 );
268 }
269
270 #[test]
271 fn max_radius_limits_size() {
272 let count = |r: u16| {
273 let c =
274 BubbleChart::new([
275 BubbleSeries::new("a", [(0.0, 0.0, 10.0), (5.0, 5.0, 100.0)]).color(Color::Red),
276 ])
277 .max_radius(r);
278 render(&c, 60, 20)
279 .content()
280 .iter()
281 .filter(|c| c.fg == Color::Red && c.symbol() != " ")
282 .count()
283 };
284 assert!(count(8) > count(2));
285 }
286
287 #[test]
288 fn multiple_series_and_markers() {
289 for m in [Marker::Braille, Marker::HalfBlock, Marker::Dot] {
290 let c = BubbleChart::new([
291 BubbleSeries::new("a", [(1.0, 1.0, 5.0)]).color(Color::Red),
292 BubbleSeries::new("b", [(2.0, 3.0, 9.0)]).color(Color::Blue),
293 ])
294 .marker(m);
295 let b = render(&c, 50, 16);
296 assert!(b.content().iter().any(|x| x.fg == Color::Blue));
297 }
298 }
299}