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