1use crate::canvas::{Canvas, Marker};
4use crate::theme::{self, Theme};
5use crate::util::darken;
6use ratatui::{
7 buffer::Buffer,
8 layout::Rect,
9 style::{Color, Style},
10 widgets::Block,
11};
12
13#[derive(Debug, Clone)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct RadarSeries {
17 pub name: String,
19 pub values: Vec<f64>,
21 pub color: Option<Color>,
23}
24
25impl RadarSeries {
26 pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
28 Self {
29 name: name.into(),
30 values: values.into_iter().collect(),
31 color: None,
32 }
33 }
34 opt_setter!(
35 color: Color
37 );
38}
39
40#[derive(Debug, Clone)]
54pub struct RadarChart<'a> {
55 axes: Vec<String>,
56 series: Vec<RadarSeries>,
57 max: Option<f64>,
58 rings: usize,
59 fill: bool,
60 show_labels: bool,
61 legend: bool,
62 hidden: Vec<usize>,
63 theme: Option<Theme>,
64 base: Option<Style>,
65 marker: Marker,
66 block: Option<Block<'a>>,
67}
68
69impl<'a> RadarChart<'a> {
70 pub fn new(axes: impl IntoIterator<Item = impl Into<String>>) -> Self {
72 Self {
73 axes: axes.into_iter().map(Into::into).collect(),
74 series: Vec::new(),
75 max: None,
76 rings: 4,
77 fill: false,
78 show_labels: true,
79 legend: true,
80 hidden: vec![],
81 theme: None,
82 base: None,
83 marker: Marker::Braille,
84 block: None,
85 }
86 }
87 pub fn series(mut self, s: RadarSeries) -> Self {
89 self.series.push(s);
90 self
91 }
92 opt_setter!(
93 max: f64
95 );
96 setter!(
97 rings: usize
99 );
100 setter!(
101 fill: bool
103 );
104 setter!(
105 show_labels: bool
107 );
108 theme_setter!(
109 theme
112 );
113 base_style_setter!(base);
114 fn series_color(&self, i: usize, s: &RadarSeries) -> Color {
115 s.color
116 .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.color(i)))
117 }
118 setter!(
119 marker: Marker
121 );
122
123 setter!(
124 legend: bool
126 );
127
128 #[must_use]
131 pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
132 self.hidden = hidden.into_iter().collect();
133 self
134 }
135
136 block_setter!(block, 'a);
137
138 fn draw(&self, area: Rect, buf: &mut Buffer) {
139 let n = self.axes.len();
140 if n < 3 || area.width < 3 || area.height < 3 {
141 return;
142 }
143 let legend = self.legend && area.height >= 9 && !self.series.is_empty();
144 let full = area;
145 let area = if legend {
146 Rect::new(area.x, area.y, area.width, area.height - 1)
147 } else {
148 area
149 };
150 let lab_w = self
151 .axes
152 .iter()
153 .map(|a| a.chars().count())
154 .max()
155 .unwrap_or(0) as u16;
156 let labels = self.show_labels && area.height >= 5 && area.width > 2 * lab_w + 4;
157 let (mx, my) = if labels { (lab_w, 1) } else { (0, 0) };
158 let plot = Rect::new(
159 area.x + mx,
160 area.y + my,
161 area.width - 2 * mx,
162 area.height - 2 * my,
163 );
164 let max = self
165 .max
166 .filter(|m| m.is_finite() && *m > 0.0)
167 .unwrap_or_else(|| {
168 let m = self
169 .series
170 .iter()
171 .flat_map(|s| s.values.iter().copied())
172 .filter(|v| v.is_finite())
173 .fold(0.0, f64::max);
174 if m > 0.0 { m } else { 1.0 }
175 });
176 let mut cv = Canvas::new(plot.width, plot.height, self.marker);
177 let (pw, ph) = (cv.px_w() as f64, cv.px_h() as f64);
178 let r = ((pw - 1.0) / 2.0).min((ph - 1.0) / 2.0).max(1.0);
179 let (cx, cy) = ((pw - 1.0) / 2.0, (ph - 1.0) / 2.0);
180 let ang =
181 |i: usize| -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * i as f64 / n as f64;
182 let pt = |i: usize, rad: f64| {
183 (
184 (cx + rad * ang(i).cos()).round() as i32,
185 (cy + rad * ang(i).sin()).round() as i32,
186 )
187 };
188 let grid = self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid);
189 let fg = self.theme.as_ref().map_or(Color::White, |t| t.foreground);
190 for k in 1..=self.rings {
191 let rad = r * k as f64 / self.rings as f64;
192 for i in 0..n {
193 let (a, b) = (pt(i, rad), pt((i + 1) % n, rad));
194 cv.line(a.0, a.1, b.0, b.1, grid);
195 }
196 }
197 for i in 0..n {
198 let b = pt(i, r);
199 cv.line(cx.round() as i32, cy.round() as i32, b.0, b.1, grid);
200 }
201 let mut polys: Vec<(Color, Vec<(i32, i32)>)> = vec![];
202 for (si, s) in self.series.iter().enumerate() {
203 if self.hidden.contains(&si) {
204 continue;
205 }
206 let color = self.series_color(si, s);
207 let pts: Vec<(i32, i32)> = (0..n)
208 .map(|i| {
209 let v = s
210 .values
211 .get(i)
212 .copied()
213 .filter(|v| v.is_finite())
214 .unwrap_or(0.0);
215 pt(i, r * (v / max).clamp(0.0, 1.0))
216 })
217 .collect();
218 if crate::interact::recording() {
219 let (rx, ry) = self.marker.resolution();
220 for (i, &(x, y)) in pts.iter().enumerate() {
221 let rect = Rect::new(
222 plot.x + (x.max(0) / i32::from(rx)) as u16,
223 plot.y + (y.max(0) / i32::from(ry)) as u16,
224 1,
225 1,
226 )
227 .intersection(plot);
228 crate::interact::record_point(rect, si, i, || {
229 let v = s.values.get(i).copied().unwrap_or(0.0);
230 (
231 s.name.clone(),
232 vec![format!(
233 "{}: {}",
234 self.axes[i],
235 crate::util::format_compact(v)
236 )],
237 )
238 });
239 }
240 }
241 polys.push((color, pts));
242 }
243 if self.fill {
244 for (color, pts) in &polys {
246 let dim = darken(*color, 0.55);
247 for py in 0..ph as i32 {
248 let mut xs: Vec<f64> = vec![];
249 for i in 0..n {
250 let (a, b) = (pts[i], pts[(i + 1) % n]);
251 let (y0, y1) = (a.1.min(b.1), a.1.max(b.1));
252 if py >= y0 && py < y1 {
253 let t = (py - a.1) as f64 / (b.1 - a.1) as f64;
254 xs.push(a.0 as f64 + t * (b.0 - a.0) as f64);
255 }
256 }
257 xs.sort_by(|a, b| a.total_cmp(b));
258 for pair in xs.chunks(2) {
259 if let [x0, x1] = pair {
260 for px in x0.round() as i32..=x1.round() as i32 {
261 cv.set(px, py, dim);
262 }
263 }
264 }
265 }
266 }
267 }
268 for (color, pts) in &polys {
269 for i in 0..n {
270 let (a, b) = (pts[i], pts[(i + 1) % n]);
271 cv.line(a.0, a.1, b.0, b.1, *color);
272 }
273 for &(x, y) in pts {
274 for (dx, dy) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] {
275 cv.set(x + dx, y + dy, *color);
276 }
277 }
278 }
279 cv.render(buf, plot);
280 if self.rings > 0 && plot.height >= 9 {
282 let (rxd, ryd) = self.marker.resolution();
283 let dim = Style::default().fg(darken(fg, 0.4));
284 let ccx = plot.x as i32 + plot.width as i32 / 2;
285 let ccy = plot.y as i32 + plot.height as i32 / 2;
286 for k in 1..=self.rings {
287 let v = max * k as f64 / self.rings as f64;
288 let y = ccy - (r * k as f64 / self.rings as f64 / ryd as f64).round() as i32;
289 let _ = rxd;
290 let t = crate::util::format_tick(v, max / self.rings as f64);
291 if y > plot.y as i32 && y < plot.bottom() as i32 && ccx + 2 < plot.right() as i32 {
292 crate::text::put_str(buf, (ccx + 2) as u16, y as u16, plot.right(), &t, dim);
293 }
294 }
295 }
296 if legend {
297 let mut x = full.x + 1;
298 let y = full.bottom() - 1;
299 for (si, se) in self.series.iter().enumerate() {
300 let c = self.series_color(si, se);
301 let name = format!(" {}", se.name);
302 if x + 2 + name.chars().count() as u16 > full.right() {
303 break;
304 }
305 let off = self.hidden.contains(&si);
306 let name_style = if off {
307 Style::default().fg(fg).add_modifier(
308 ratatui::style::Modifier::CROSSED_OUT | ratatui::style::Modifier::DIM,
309 )
310 } else {
311 Style::default().fg(fg)
312 };
313 crate::text::put_str(
314 buf,
315 x,
316 y,
317 full.right(),
318 if off { "○" } else { "●" },
319 Style::default().fg(c),
320 );
321 crate::text::put_str(buf, x + 1, y, full.right(), &name, name_style);
322 crate::interact::record_legend(
323 Rect::new(x, y, 2 + name.chars().count() as u16, 1),
324 si,
325 &se.name,
326 );
327 x += 3 + name.chars().count() as u16;
328 }
329 }
330 if labels {
331 for (i, l) in self.axes.iter().enumerate() {
332 let (ux, uy) = (ang(i).cos(), ang(i).sin());
333 let w = l.chars().count() as i32;
334 let ccx = plot.x as i32 + plot.width as i32 / 2;
335 let ccy = plot.y as i32 + plot.height as i32 / 2;
336 let (rxd, ryd) = self.marker.resolution();
337 let (rx, ry) = (r / rxd as f64, r / ryd as f64);
338 let ex = ccx + (ux * (rx + 1.5)).round() as i32;
339 let ey = ccy + (uy * (ry + 1.0)).round() as i32;
340 let x = if ux > 0.3 {
341 ex
342 } else if ux < -0.3 {
343 ex - w
344 } else {
345 ex - w / 2
346 };
347 let y = ey.clamp(area.y as i32, area.bottom() as i32 - 1);
348 for (j, ch) in l.chars().enumerate() {
349 let xx = x + j as i32;
350 if xx >= area.x as i32
351 && xx < area.right() as i32
352 && let Some(c) = buf.cell_mut((xx as u16, y as u16))
353 {
354 c.set_char(ch).set_fg(fg);
355 }
356 }
357 }
358 }
359 }
360}
361
362impl RadarChart<'_> {
363 fn render_into(&self, area: Rect, buf: &mut Buffer) {
364 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
365 self.draw(inner, buf);
366 }
367}
368
369widget_impls!(RadarChart<'_>);
370
371#[cfg(feature = "theme")]
372impl<'a> tui_nuances::Themed for RadarChart<'a> {
373 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
374 self.theme(theme)
375 }
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381 use ratatui::widgets::Widget;
382
383 fn chart() -> RadarChart<'static> {
384 RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
385 .series(RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]).color(Color::Red))
386 .max(5.0)
387 }
388
389 fn run(c: RadarChart, w: u16, h: u16) -> Buffer {
390 let a = Rect::new(0, 0, w, h);
391 let mut b = Buffer::empty(a);
392 c.render(a, &mut b);
393 b
394 }
395
396 #[test]
397 fn draws_series_and_labels() {
398 let b = run(chart(), 40, 20);
399 assert!(
400 b.content()
401 .iter()
402 .any(|c| c.fg == Color::Red && c.symbol() != " ")
403 );
404 assert!(
405 b.content()
406 .iter()
407 .any(|c| c.fg == Color::DarkGray && c.symbol() != " ")
408 );
409 let t: String = b.content().iter().map(|c| c.symbol()).collect();
410 assert!(t.contains("Atk") && t.contains("Hp"));
411 }
412
413 #[cfg(feature = "theme")]
414 #[test]
415 fn theme_palette_and_override() {
416 let t = Theme::nord();
417 let mk = |c: Option<Color>| {
418 let s = RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]);
419 let s = if let Some(c) = c { s.color(c) } else { s };
420 RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
421 .series(s)
422 .series(RadarSeries::new("b", [1.0, 2.0, 3.0, 4.0, 5.0]))
423 .max(5.0)
424 .theme(&t)
425 };
426 let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.fg == c && x.symbol() != " ");
427 let b = run(mk(None), 40, 20);
428 assert!(has(&b, t.color(0)) && has(&b, t.color(1)));
429 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
430 let b = run(mk(Some(Color::Red)), 40, 20);
431 assert!(has(&b, Color::Red) && !has(&b, t.color(0)) && has(&b, t.color(1)));
432 }
433
434 #[test]
435 fn fill_covers_more_cells() {
436 let count = |b: &Buffer| {
437 b.content()
438 .iter()
439 .filter(|c| c.symbol() != " " && c.fg != Color::DarkGray && c.fg != Color::White)
440 .count()
441 };
442 assert!(count(&run(chart().fill(true), 40, 20)) > count(&run(chart(), 40, 20)));
443 }
444
445 #[test]
446 fn degenerate_inputs() {
447 run(chart(), 0, 0);
448 run(chart(), 3, 3);
449 run(chart(), 5, 40);
450 run(RadarChart::new(["a"]), 20, 10);
451 run(
452 RadarChart::new(["a", "b", "c"])
453 .series(RadarSeries::new("n", [f64::NAN, -1.0]))
454 .rings(0),
455 20,
456 10,
457 );
458 }
459}