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)]
42pub struct RadarChart<'a> {
43 axes: Vec<String>,
44 series: Vec<RadarSeries>,
45 max: Option<f64>,
46 rings: usize,
47 fill: bool,
48 show_labels: bool,
49 legend: bool,
50 theme: Option<Theme>,
51 base: Option<Style>,
52 marker: Marker,
53 block: Option<Block<'a>>,
54}
55
56impl<'a> RadarChart<'a> {
57 pub fn new(axes: impl IntoIterator<Item = impl Into<String>>) -> Self {
59 Self {
60 axes: axes.into_iter().map(Into::into).collect(),
61 series: Vec::new(),
62 max: None,
63 rings: 4,
64 fill: false,
65 show_labels: true,
66 legend: true,
67 theme: None,
68 base: None,
69 marker: Marker::Braille,
70 block: None,
71 }
72 }
73 pub fn series(mut self, s: RadarSeries) -> Self {
75 self.series.push(s);
76 self
77 }
78 opt_setter!(
79 max: f64
81 );
82 setter!(
83 rings: usize
85 );
86 setter!(
87 fill: bool
89 );
90 setter!(
91 show_labels: bool
93 );
94 theme_setter!(
95 theme
98 );
99 base_style_setter!(base);
100 fn series_color(&self, i: usize, s: &RadarSeries) -> Color {
101 s.color
102 .unwrap_or_else(|| self.theme.as_ref().map_or(Color::Cyan, |t| t.color(i)))
103 }
104 setter!(
105 marker: Marker
107 );
108
109 setter!(
110 legend: bool
112 );
113
114 block_setter!(block, 'a);
115
116 fn draw(&self, area: Rect, buf: &mut Buffer) {
117 let n = self.axes.len();
118 if n < 3 || area.width < 3 || area.height < 3 {
119 return;
120 }
121 let legend = self.legend && area.height >= 9 && !self.series.is_empty();
122 let full = area;
123 let area = if legend {
124 Rect::new(area.x, area.y, area.width, area.height - 1)
125 } else {
126 area
127 };
128 let lab_w = self
129 .axes
130 .iter()
131 .map(|a| a.chars().count())
132 .max()
133 .unwrap_or(0) as u16;
134 let labels = self.show_labels && area.height >= 5 && area.width > 2 * lab_w + 4;
135 let (mx, my) = if labels { (lab_w, 1) } else { (0, 0) };
136 let plot = Rect::new(
137 area.x + mx,
138 area.y + my,
139 area.width - 2 * mx,
140 area.height - 2 * my,
141 );
142 let max = self
143 .max
144 .filter(|m| m.is_finite() && *m > 0.0)
145 .unwrap_or_else(|| {
146 let m = self
147 .series
148 .iter()
149 .flat_map(|s| s.values.iter().copied())
150 .filter(|v| v.is_finite())
151 .fold(0.0, f64::max);
152 if m > 0.0 {
153 m
154 } else {
155 1.0
156 }
157 });
158 let mut cv = Canvas::new(plot.width, plot.height, self.marker);
159 let (pw, ph) = (cv.px_w() as f64, cv.px_h() as f64);
160 let r = ((pw - 1.0) / 2.0).min((ph - 1.0) / 2.0).max(1.0);
161 let (cx, cy) = ((pw - 1.0) / 2.0, (ph - 1.0) / 2.0);
162 let ang =
163 |i: usize| -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * i as f64 / n as f64;
164 let pt = |i: usize, rad: f64| {
165 (
166 (cx + rad * ang(i).cos()).round() as i32,
167 (cy + rad * ang(i).sin()).round() as i32,
168 )
169 };
170 let grid = self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid);
171 let fg = self.theme.as_ref().map_or(Color::White, |t| t.foreground);
172 for k in 1..=self.rings {
173 let rad = r * k as f64 / self.rings as f64;
174 for i in 0..n {
175 let (a, b) = (pt(i, rad), pt((i + 1) % n, rad));
176 cv.line(a.0, a.1, b.0, b.1, grid);
177 }
178 }
179 for i in 0..n {
180 let b = pt(i, r);
181 cv.line(cx.round() as i32, cy.round() as i32, b.0, b.1, grid);
182 }
183 let mut polys: Vec<(Color, Vec<(i32, i32)>)> = vec![];
184 for (si, s) in self.series.iter().enumerate() {
185 let color = self.series_color(si, s);
186 let pts: Vec<(i32, i32)> = (0..n)
187 .map(|i| {
188 let v = s
189 .values
190 .get(i)
191 .copied()
192 .filter(|v| v.is_finite())
193 .unwrap_or(0.0);
194 pt(i, r * (v / max).clamp(0.0, 1.0))
195 })
196 .collect();
197 polys.push((color, pts));
198 }
199 if self.fill {
200 for (color, pts) in &polys {
202 let dim = darken(*color, 0.55);
203 for py in 0..ph as i32 {
204 let mut xs: Vec<f64> = vec![];
205 for i in 0..n {
206 let (a, b) = (pts[i], pts[(i + 1) % n]);
207 let (y0, y1) = (a.1.min(b.1), a.1.max(b.1));
208 if py >= y0 && py < y1 {
209 let t = (py - a.1) as f64 / (b.1 - a.1) as f64;
210 xs.push(a.0 as f64 + t * (b.0 - a.0) as f64);
211 }
212 }
213 xs.sort_by(|a, b| a.total_cmp(b));
214 for pair in xs.chunks(2) {
215 if let [x0, x1] = pair {
216 for px in x0.round() as i32..=x1.round() as i32 {
217 cv.set(px, py, dim);
218 }
219 }
220 }
221 }
222 }
223 }
224 for (color, pts) in &polys {
225 for i in 0..n {
226 let (a, b) = (pts[i], pts[(i + 1) % n]);
227 cv.line(a.0, a.1, b.0, b.1, *color);
228 }
229 for &(x, y) in pts {
230 for (dx, dy) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] {
231 cv.set(x + dx, y + dy, *color);
232 }
233 }
234 }
235 cv.render(buf, plot);
236 if self.rings > 0 && plot.height >= 9 {
238 let (rxd, ryd) = self.marker.resolution();
239 let dim = Style::default().fg(darken(fg, 0.4));
240 let ccx = plot.x as i32 + plot.width as i32 / 2;
241 let ccy = plot.y as i32 + plot.height as i32 / 2;
242 for k in 1..=self.rings {
243 let v = max * k as f64 / self.rings as f64;
244 let y = ccy - (r * k as f64 / self.rings as f64 / ryd as f64).round() as i32;
245 let _ = rxd;
246 let t = crate::util::format_tick(v, max / self.rings as f64);
247 if y > plot.y as i32 && y < plot.bottom() as i32 && ccx + 2 < plot.right() as i32 {
248 crate::text::put_str(buf, (ccx + 2) as u16, y as u16, plot.right(), &t, dim);
249 }
250 }
251 }
252 if legend {
253 let mut x = full.x + 1;
254 let y = full.bottom() - 1;
255 for (si, se) in self.series.iter().enumerate() {
256 let c = self.series_color(si, se);
257 let name = format!(" {}", se.name);
258 if x + 2 + name.chars().count() as u16 > full.right() {
259 break;
260 }
261 crate::text::put_str(buf, x, y, full.right(), "●", Style::default().fg(c));
262 crate::text::put_str(buf, x + 1, y, full.right(), &name, Style::default().fg(fg));
263 x += 3 + name.chars().count() as u16;
264 }
265 }
266 if labels {
267 for (i, l) in self.axes.iter().enumerate() {
268 let (ux, uy) = (ang(i).cos(), ang(i).sin());
269 let w = l.chars().count() as i32;
270 let ccx = plot.x as i32 + plot.width as i32 / 2;
271 let ccy = plot.y as i32 + plot.height as i32 / 2;
272 let (rxd, ryd) = self.marker.resolution();
273 let (rx, ry) = (r / rxd as f64, r / ryd as f64);
274 let ex = ccx + (ux * (rx + 1.5)).round() as i32;
275 let ey = ccy + (uy * (ry + 1.0)).round() as i32;
276 let x = if ux > 0.3 {
277 ex
278 } else if ux < -0.3 {
279 ex - w
280 } else {
281 ex - w / 2
282 };
283 let y = ey.clamp(area.y as i32, area.bottom() as i32 - 1);
284 for (j, ch) in l.chars().enumerate() {
285 let xx = x + j as i32;
286 if xx >= area.x as i32 && xx < area.right() as i32 {
287 if let Some(c) = buf.cell_mut((xx as u16, y as u16)) {
288 c.set_char(ch).set_fg(fg);
289 }
290 }
291 }
292 }
293 }
294 }
295}
296
297impl RadarChart<'_> {
298 fn render_into(&self, area: Rect, buf: &mut Buffer) {
299 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
300 self.draw(inner, buf);
301 }
302}
303
304widget_impls!(RadarChart<'_>);
305
306#[cfg(feature = "theme")]
307impl<'a> tui_nuances::Themed for RadarChart<'a> {
308 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
309 self.theme(theme)
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316 use ratatui::widgets::Widget;
317
318 fn chart() -> RadarChart<'static> {
319 RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
320 .series(RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]).color(Color::Red))
321 .max(5.0)
322 }
323
324 fn run(c: RadarChart, 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 #[test]
332 fn draws_series_and_labels() {
333 let b = run(chart(), 40, 20);
334 assert!(b
335 .content()
336 .iter()
337 .any(|c| c.fg == Color::Red && c.symbol() != " "));
338 assert!(b
339 .content()
340 .iter()
341 .any(|c| c.fg == Color::DarkGray && c.symbol() != " "));
342 let t: String = b.content().iter().map(|c| c.symbol()).collect();
343 assert!(t.contains("Atk") && t.contains("Hp"));
344 }
345
346 #[cfg(feature = "theme")]
347 #[test]
348 fn theme_palette_and_override() {
349 let t = Theme::nord();
350 let mk = |c: Option<Color>| {
351 let s = RadarSeries::new("a", [5.0, 3.0, 4.0, 2.0, 5.0]);
352 let s = if let Some(c) = c { s.color(c) } else { s };
353 RadarChart::new(["Atk", "Def", "Spd", "Int", "Hp"])
354 .series(s)
355 .series(RadarSeries::new("b", [1.0, 2.0, 3.0, 4.0, 5.0]))
356 .max(5.0)
357 .theme(&t)
358 };
359 let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.fg == c && x.symbol() != " ");
360 let b = run(mk(None), 40, 20);
361 assert!(has(&b, t.color(0)) && has(&b, t.color(1)));
362 assert_eq!(b[(0, 0)].bg, t.background.unwrap());
363 let b = run(mk(Some(Color::Red)), 40, 20);
364 assert!(has(&b, Color::Red) && !has(&b, t.color(0)) && has(&b, t.color(1)));
365 }
366
367 #[test]
368 fn fill_covers_more_cells() {
369 let count = |b: &Buffer| {
370 b.content()
371 .iter()
372 .filter(|c| c.symbol() != " " && c.fg != Color::DarkGray && c.fg != Color::White)
373 .count()
374 };
375 assert!(count(&run(chart().fill(true), 40, 20)) > count(&run(chart(), 40, 20)));
376 }
377
378 #[test]
379 fn degenerate_inputs() {
380 run(chart(), 0, 0);
381 run(chart(), 3, 3);
382 run(chart(), 5, 40);
383 run(RadarChart::new(["a"]), 20, 10);
384 run(
385 RadarChart::new(["a", "b", "c"])
386 .series(RadarSeries::new("n", [f64::NAN, -1.0]))
387 .rings(0),
388 20,
389 10,
390 );
391 }
392}