Skip to main content

tui_chart/
radial.rs

1//! Concentric progress rings: [`RadialBar`] (value / max per ring) and
2//! [`RingStack`] (percentages, 270° sweep). Drawn with braille dots.
3
4#![allow(
5    clippy::cast_possible_truncation,
6    clippy::cast_precision_loss,
7    clippy::cast_sign_loss,
8    clippy::many_single_char_names,
9    clippy::too_many_lines,
10    clippy::cast_possible_wrap
11)]
12
13use crate::braille::Braille;
14use crate::theme::{self, Theme};
15use crate::PALETTE;
16use ratatui::{
17    buffer::Buffer,
18    layout::Rect,
19    style::{Color, Modifier, Style},
20    text::Span,
21    widgets::Block,
22};
23
24fn text_width(s: &str) -> usize {
25    Span::raw(s).width()
26}
27
28fn truncate(s: &str, max: usize) -> String {
29    let mut out = String::new();
30    let mut w = 0;
31    for ch in s.chars() {
32        let cw = text_width(ch.encode_utf8(&mut [0; 4]));
33        if w + cw > max {
34            break;
35        }
36        out.push(ch);
37        w += cw;
38    }
39    out
40}
41
42/// One ring of a [`RadialBar`].
43#[derive(Debug, Clone, PartialEq)]
44#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
45pub struct RadialRing {
46    /// Ring label (shown in the legend).
47    pub label: String,
48    /// Current value.
49    pub value: f64,
50    /// Value at which the ring is full.
51    pub max: f64,
52    /// Explicit color.
53    pub color: Option<Color>,
54}
55
56impl RadialRing {
57    /// A ring showing `value` out of `max`.
58    pub fn new(label: impl Into<String>, value: f64, max: f64) -> Self {
59        Self {
60            label: label.into(),
61            value,
62            max,
63            color: None,
64        }
65    }
66
67    /// Explicit ring color (default: the theme / default palette, by position).
68    pub fn color(mut self, c: Color) -> Self {
69        self.color = Some(c);
70        self
71    }
72
73    /// Fraction of the ring that is filled, `0..=1` (`0` for bad input).
74    pub fn fraction(&self) -> f64 {
75        if self.max.is_finite() && self.max > 0.0 && self.value.is_finite() {
76            (self.value / self.max).clamp(0.0, 1.0)
77        } else {
78            0.0
79        }
80    }
81}
82
83/// Sweep of a [`RadialBar`].
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
85#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
86pub enum RadialSweep {
87    /// 270° with the gap at the bottom (default).
88    #[default]
89    Arc,
90    /// Full 360° rings starting at 12 o'clock.
91    Full,
92}
93
94/// Concentric progress rings, outermost first, with an optional legend.
95///
96/// # Example
97///
98/// ```
99/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
100/// use tui_chart::{RadialBar, RadialRing};
101///
102/// let chart = RadialBar::new([
103///     RadialRing::new("Move", 420.0, 600.0),
104///     RadialRing::new("Exercise", 25.0, 30.0),
105/// ]);
106/// let area = Rect::new(0, 0, 50, 14);
107/// let mut buf = Buffer::empty(area);
108/// chart.render(area, &mut buf);
109/// ```
110#[derive(Debug, Clone, Default)]
111pub struct RadialBar {
112    rings: Vec<RadialRing>,
113    sweep: RadialSweep,
114    legend: bool,
115    track: Option<Color>,
116    theme: Option<Theme>,
117    base: Option<Style>,
118    block: Option<Block<'static>>,
119}
120
121impl RadialBar {
122    /// Create a chart from rings, outermost first.
123    pub fn new(rings: impl IntoIterator<Item = RadialRing>) -> Self {
124        Self {
125            rings: rings.into_iter().collect(),
126            sweep: RadialSweep::Arc,
127            legend: true,
128            track: None,
129            theme: None,
130            base: None,
131            block: None,
132        }
133    }
134
135    setter!(
136        /// 270° or full sweep.
137        sweep: RadialSweep
138    );
139    setter!(
140        /// Show the legend (default on, when there is room).
141        legend: bool
142    );
143    opt_setter!(
144        /// Color of the unfilled track (default: theme grid / dark gray).
145        track => track: Color
146    );
147    theme_setter!(
148        /// Apply a [`Theme`]; explicit ring colors win.
149        theme
150    );
151    base_style_setter!(base);
152    block_setter!(block, 'static);
153
154    fn ring_color(&self, r: &RadialRing, i: usize) -> Color {
155        r.color.unwrap_or_else(|| {
156            self.theme
157                .as_ref()
158                .map_or(PALETTE[i % PALETTE.len()], |t| t.color(i))
159        })
160    }
161
162    fn track_color(&self) -> Color {
163        self.track
164            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid))
165    }
166
167    fn draw_rings(&self, buf: &mut Buffer, area: Rect) {
168        if self.rings.is_empty() || area.is_empty() {
169            return;
170        }
171        let track = self.track_color();
172        let mut g = Braille::new(area.width, area.height);
173        let (w, h) = (g.dots_w(), g.dots_h());
174        let c = (w / 2.0, h / 2.0);
175        let r = w.min(h) / 2.0 - 0.5;
176        let n = self.rings.len() as f64;
177        let pitch = (r * 0.85) / n;
178        if pitch >= 1.5 {
179            let thick = (pitch - 1.2).max(1.5).min(pitch);
180            let sw = match self.sweep {
181                RadialSweep::Arc => (0.625, 0.75),
182                RadialSweep::Full => (0.0, 1.0),
183            };
184            for (i, ring) in self.rings.iter().enumerate() {
185                let outer = r - i as f64 * pitch;
186                let inner = (outer - thick).max(0.0);
187                let frac = ring.fraction();
188                let color = self.ring_color(ring, i);
189                g.ring(c, (inner, outer), sw, |pos| {
190                    Some(if frac >= 1.0 || pos < frac {
191                        (color, 1)
192                    } else {
193                        (track, 0)
194                    })
195                });
196            }
197            if crate::interact::recording() {
198                let mut owner = vec![None; usize::from(area.width) * usize::from(area.height)];
199                for cy in 0..area.height {
200                    for cx in 0..area.width {
201                        let dx = (f64::from(cx) + 0.5) * 2.0 - c.0;
202                        let dy = (f64::from(cy) + 0.5) * 4.0 - c.1;
203                        let d = dx.hypot(dy);
204                        let turn = (dx.atan2(-dy) / std::f64::consts::TAU).rem_euclid(1.0);
205                        if (turn - sw.0).rem_euclid(1.0) > sw.1 {
206                            continue;
207                        }
208                        for i in 0..self.rings.len() {
209                            let outer = r - i as f64 * pitch;
210                            if d <= outer && d >= (outer - thick).max(0.0) - 1.0 {
211                                owner
212                                    [usize::from(cy) * usize::from(area.width) + usize::from(cx)] =
213                                    Some(i);
214                                break;
215                            }
216                        }
217                    }
218                }
219                crate::interact::record_grid(
220                    area,
221                    &owner,
222                    |i| i,
223                    |i| {
224                        let ring = &self.rings[i];
225                        (
226                            ring.label.clone(),
227                            vec![
228                                format!(
229                                    "{} / {}",
230                                    crate::util::format_compact(ring.value),
231                                    crate::util::format_compact(ring.max)
232                                ),
233                                format!("{:.0}%", ring.fraction() * 100.0),
234                            ],
235                        )
236                    },
237                );
238            }
239        }
240        g.blit(area, buf);
241    }
242
243    fn draw_legend(&self, buf: &mut Buffer, area: Rect) {
244        let text = self
245            .theme
246            .as_ref()
247            .map_or(Style::default(), |t| Style::default().fg(t.foreground));
248        let label_w = area.width.saturating_sub(7) as usize;
249        for (i, ring) in self.rings.iter().enumerate() {
250            let y = area.y + i as u16;
251            if y >= area.bottom() {
252                break;
253            }
254            let color = self.ring_color(ring, i);
255            buf.set_string(area.x, y, "■", Style::default().fg(color));
256            let label = truncate(&ring.label, label_w);
257            buf.set_string(area.x + 2, y, &label, text);
258            let pct = format!("{:.0}%", ring.fraction() * 100.0);
259            let px = area.right().saturating_sub(pct.len() as u16);
260            if px > area.x + 2 + text_width(&label) as u16 {
261                buf.set_string(
262                    px,
263                    y,
264                    &pct,
265                    Style::default().fg(color).add_modifier(Modifier::BOLD),
266                );
267            }
268        }
269    }
270
271    fn render_into(&self, area: Rect, buf: &mut Buffer) {
272        let area = area.intersection(buf.area);
273        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
274        let (chart, legend) = split(inner, &self.rings, self.legend);
275        self.draw_rings(buf, chart);
276        if let Some(l) = legend {
277            self.draw_legend(buf, l);
278        }
279    }
280}
281
282widget_impls!(RadialBar);
283
284#[cfg(feature = "theme")]
285impl tui_nuances::Themed for RadialBar {
286    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
287        self.theme(theme)
288    }
289}
290
291/// Splits `inner` into the rings area and an optional legend area.
292fn split(inner: Rect, rings: &[RadialRing], legend: bool) -> (Rect, Option<Rect>) {
293    if !legend || rings.is_empty() {
294        return (inner, None);
295    }
296    let longest = rings
297        .iter()
298        .map(|r| text_width(&r.label))
299        .max()
300        .unwrap_or(0);
301    let lw = (longest + 8).clamp(14, 32) as u16;
302    // Keep at least a 12-column chart.
303    if inner.width < lw + 12 {
304        return (inner, None);
305    }
306    let chart_w = inner.width - lw - 1;
307    let chart = Rect::new(inner.x, inner.y, chart_w, inner.height);
308    let ly = inner.y + inner.height.saturating_sub(rings.len() as u16) / 2;
309    let leg = Rect::new(
310        inner.x + chart_w + 1,
311        ly,
312        lw,
313        (rings.len() as u16).min(inner.bottom() - ly),
314    );
315    (chart, Some(leg))
316}
317
318/// Concentric 270° rings, one per `(label, percent)`, with a legend.
319///
320/// # Example
321///
322/// ```
323/// use tui_chart::RingStack;
324///
325/// let stack = RingStack::new([("CPU", 72.0), ("RAM", 48.0), ("Disk", 91.0)]);
326/// # let _ = stack;
327/// ```
328#[derive(Debug, Clone, Default)]
329pub struct RingStack {
330    items: Vec<(String, f64)>,
331    colors: Vec<Color>,
332    inner: RadialBar,
333}
334
335impl RingStack {
336    /// Create a ring stack from `(label, percent)` pairs, outermost first.
337    pub fn new<S: Into<String>>(items: impl IntoIterator<Item = (S, f64)>) -> Self {
338        Self {
339            items: items.into_iter().map(|(l, v)| (l.into(), v)).collect(),
340            colors: Vec::new(),
341            inner: RadialBar::new([]),
342        }
343    }
344
345    /// Ring colors by position (the theme / palette fills in the rest).
346    pub fn colors(mut self, colors: impl IntoIterator<Item = Color>) -> Self {
347        self.colors = colors.into_iter().collect();
348        self
349    }
350
351    /// Show or hide the legend.
352    pub fn legend(mut self, show: bool) -> Self {
353        self.inner = self.inner.legend(show);
354        self
355    }
356
357    /// Color of the unfilled track.
358    pub fn track(mut self, c: Color) -> Self {
359        self.inner = self.inner.track(c);
360        self
361    }
362
363    /// Apply a [`Theme`]; explicit colors win.
364    #[cfg(feature = "theme")]
365    pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
366        self.inner = self.inner.theme(theme);
367        self
368    }
369
370    /// Base style painted over the whole area.
371    pub fn base_style(mut self, style: Style) -> Self {
372        self.inner = self.inner.base_style(style);
373        self
374    }
375
376    /// Wrap the chart in a [`Block`].
377    pub fn block(mut self, b: Block<'static>) -> Self {
378        self.inner = self.inner.block(b);
379        self
380    }
381
382    fn render_into(&self, area: Rect, buf: &mut Buffer) {
383        let rings = self.items.iter().enumerate().map(|(i, (l, pct))| {
384            let mut r = RadialRing::new(l.clone(), *pct, 100.0);
385            r.color = self.colors.get(i).copied();
386            r
387        });
388        let mut bar = self.inner.clone();
389        bar.rings = rings.collect();
390        bar.render_into(area, buf);
391    }
392}
393
394widget_impls!(RingStack);
395
396#[cfg(feature = "theme")]
397impl tui_nuances::Themed for RingStack {
398    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
399        self.theme(theme)
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    #![allow(clippy::assert_is_empty, clippy::float_cmp)]
406    use super::*;
407    use ratatui::widgets::Widget;
408
409    fn draw(w: impl Widget, width: u16, height: u16) -> Buffer {
410        let a = Rect::new(0, 0, width, height);
411        let mut b = Buffer::empty(a);
412        w.render(a, &mut b);
413        b
414    }
415
416    fn text(b: &Buffer) -> String {
417        b.content()
418            .iter()
419            .map(ratatui::buffer::Cell::symbol)
420            .collect()
421    }
422
423    fn rings() -> Vec<RadialRing> {
424        vec![
425            RadialRing::new("Move", 420.0, 600.0),
426            RadialRing::new("Exercise", 25.0, 30.0).color(Color::Red),
427            RadialRing::new("Stand", 9.0, 12.0),
428        ]
429    }
430
431    #[test]
432    fn fraction_guards() {
433        assert_eq!(RadialRing::new("a", 5.0, 0.0).fraction(), 0.0);
434        assert_eq!(RadialRing::new("a", f64::NAN, 10.0).fraction(), 0.0);
435        assert_eq!(RadialRing::new("a", 50.0, 10.0).fraction(), 1.0);
436        assert_eq!(RadialRing::new("a", -5.0, 10.0).fraction(), 0.0);
437        assert!((RadialRing::new("a", 3.0, 12.0).fraction() - 0.25).abs() < 1e-12);
438    }
439
440    #[test]
441    fn renders_rings_and_legend() {
442        let b = draw(RadialBar::new(rings()), 50, 14);
443        let t = text(&b);
444        assert!(t.contains("Move") && t.contains("Exercise") && t.contains("70%"));
445        assert!(b
446            .content()
447            .iter()
448            .any(|c| c.fg == Color::Red && c.symbol() != " "));
449    }
450
451    #[test]
452    fn legend_can_be_hidden() {
453        let t = text(&draw(RadialBar::new(rings()).legend(false), 50, 14));
454        assert!(!t.contains("Move"));
455    }
456
457    #[test]
458    fn full_sweep_differs_from_arc() {
459        let a = draw(RadialBar::new(rings()).legend(false), 30, 14);
460        let b = draw(
461            RadialBar::new(rings())
462                .legend(false)
463                .sweep(RadialSweep::Full),
464            30,
465            14,
466        );
467        assert_ne!(a, b);
468    }
469
470    #[test]
471    fn value_changes_picture() {
472        let lo = draw(
473            RadialBar::new(vec![RadialRing::new("a", 10.0, 100.0)]).legend(false),
474            20,
475            10,
476        );
477        let hi = draw(
478            RadialBar::new(vec![RadialRing::new("a", 90.0, 100.0)]).legend(false),
479            20,
480            10,
481        );
482        assert_ne!(lo, hi);
483    }
484
485    #[test]
486    fn robust_to_odd_sizes_and_input() {
487        for (w, h) in [(0, 0), (1, 1), (4, 2), (13, 3), (60, 30)] {
488            let _ = draw(RadialBar::new(rings()), w, h);
489            let _ = draw(RadialBar::new(Vec::new()), w, h);
490            let _ = draw(
491                RadialBar::new(vec![RadialRing::new("x", f64::NAN, f64::NAN)]),
492                w,
493                h,
494            );
495            let many: Vec<RadialRing> = (0..40)
496                .map(|i| RadialRing::new("r", f64::from(i), 40.0))
497                .collect();
498            let _ = draw(RadialBar::new(many), w, h);
499        }
500    }
501
502    #[test]
503    fn ring_stack_renders_percentages() {
504        let t = text(&draw(
505            RingStack::new([("CPU", 72.0), ("RAM", 48.0)]).block(Block::bordered().title("Sys")),
506            50,
507            14,
508        ));
509        assert!(t.contains("CPU") && t.contains("72%") && t.contains("Sys"));
510    }
511
512    #[test]
513    fn ring_stack_custom_colors() {
514        let b = draw(
515            RingStack::new([("A", 100.0)])
516                .colors([Color::Magenta])
517                .legend(false),
518            20,
519            10,
520        );
521        assert!(b
522            .content()
523            .iter()
524            .any(|c| c.fg == Color::Magenta && c.symbol() != " "));
525    }
526}