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        }
198        g.blit(area, buf);
199    }
200
201    fn draw_legend(&self, buf: &mut Buffer, area: Rect) {
202        let text = self
203            .theme
204            .as_ref()
205            .map_or(Style::default(), |t| Style::default().fg(t.foreground));
206        let label_w = area.width.saturating_sub(7) as usize;
207        for (i, ring) in self.rings.iter().enumerate() {
208            let y = area.y + i as u16;
209            if y >= area.bottom() {
210                break;
211            }
212            let color = self.ring_color(ring, i);
213            buf.set_string(area.x, y, "■", Style::default().fg(color));
214            let label = truncate(&ring.label, label_w);
215            buf.set_string(area.x + 2, y, &label, text);
216            let pct = format!("{:.0}%", ring.fraction() * 100.0);
217            let px = area.right().saturating_sub(pct.len() as u16);
218            if px > area.x + 2 + text_width(&label) as u16 {
219                buf.set_string(
220                    px,
221                    y,
222                    &pct,
223                    Style::default().fg(color).add_modifier(Modifier::BOLD),
224                );
225            }
226        }
227    }
228
229    fn render_into(&self, area: Rect, buf: &mut Buffer) {
230        let area = area.intersection(buf.area);
231        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
232        let (chart, legend) = split(inner, &self.rings, self.legend);
233        self.draw_rings(buf, chart);
234        if let Some(l) = legend {
235            self.draw_legend(buf, l);
236        }
237    }
238}
239
240widget_impls!(RadialBar);
241
242#[cfg(feature = "theme")]
243impl tui_nuances::Themed for RadialBar {
244    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
245        self.theme(theme)
246    }
247}
248
249/// Splits `inner` into the rings area and an optional legend area.
250fn split(inner: Rect, rings: &[RadialRing], legend: bool) -> (Rect, Option<Rect>) {
251    if !legend || rings.is_empty() {
252        return (inner, None);
253    }
254    let longest = rings
255        .iter()
256        .map(|r| text_width(&r.label))
257        .max()
258        .unwrap_or(0);
259    let lw = (longest + 8).clamp(14, 32) as u16;
260    // Keep at least a 12-column chart.
261    if inner.width < lw + 12 {
262        return (inner, None);
263    }
264    let chart_w = inner.width - lw - 1;
265    let chart = Rect::new(inner.x, inner.y, chart_w, inner.height);
266    let ly = inner.y + inner.height.saturating_sub(rings.len() as u16) / 2;
267    let leg = Rect::new(
268        inner.x + chart_w + 1,
269        ly,
270        lw,
271        (rings.len() as u16).min(inner.bottom() - ly),
272    );
273    (chart, Some(leg))
274}
275
276/// Concentric 270° rings, one per `(label, percent)`, with a legend.
277///
278/// # Example
279///
280/// ```
281/// use tui_chart::RingStack;
282///
283/// let stack = RingStack::new([("CPU", 72.0), ("RAM", 48.0), ("Disk", 91.0)]);
284/// # let _ = stack;
285/// ```
286#[derive(Debug, Clone, Default)]
287pub struct RingStack {
288    items: Vec<(String, f64)>,
289    colors: Vec<Color>,
290    inner: RadialBar,
291}
292
293impl RingStack {
294    /// Create a ring stack from `(label, percent)` pairs, outermost first.
295    pub fn new<S: Into<String>>(items: impl IntoIterator<Item = (S, f64)>) -> Self {
296        Self {
297            items: items.into_iter().map(|(l, v)| (l.into(), v)).collect(),
298            colors: Vec::new(),
299            inner: RadialBar::new([]),
300        }
301    }
302
303    /// Ring colors by position (the theme / palette fills in the rest).
304    pub fn colors(mut self, colors: impl IntoIterator<Item = Color>) -> Self {
305        self.colors = colors.into_iter().collect();
306        self
307    }
308
309    /// Show or hide the legend.
310    pub fn legend(mut self, show: bool) -> Self {
311        self.inner = self.inner.legend(show);
312        self
313    }
314
315    /// Color of the unfilled track.
316    pub fn track(mut self, c: Color) -> Self {
317        self.inner = self.inner.track(c);
318        self
319    }
320
321    /// Apply a [`Theme`]; explicit colors win.
322    #[cfg(feature = "theme")]
323    pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
324        self.inner = self.inner.theme(theme);
325        self
326    }
327
328    /// Base style painted over the whole area.
329    pub fn base_style(mut self, style: Style) -> Self {
330        self.inner = self.inner.base_style(style);
331        self
332    }
333
334    /// Wrap the chart in a [`Block`].
335    pub fn block(mut self, b: Block<'static>) -> Self {
336        self.inner = self.inner.block(b);
337        self
338    }
339
340    fn render_into(&self, area: Rect, buf: &mut Buffer) {
341        let rings = self.items.iter().enumerate().map(|(i, (l, pct))| {
342            let mut r = RadialRing::new(l.clone(), *pct, 100.0);
343            r.color = self.colors.get(i).copied();
344            r
345        });
346        let mut bar = self.inner.clone();
347        bar.rings = rings.collect();
348        bar.render_into(area, buf);
349    }
350}
351
352widget_impls!(RingStack);
353
354#[cfg(feature = "theme")]
355impl tui_nuances::Themed for RingStack {
356    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
357        self.theme(theme)
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    #![allow(clippy::assert_is_empty, clippy::float_cmp)]
364    use super::*;
365    use ratatui::widgets::Widget;
366
367    fn draw(w: impl Widget, width: u16, height: u16) -> Buffer {
368        let a = Rect::new(0, 0, width, height);
369        let mut b = Buffer::empty(a);
370        w.render(a, &mut b);
371        b
372    }
373
374    fn text(b: &Buffer) -> String {
375        b.content()
376            .iter()
377            .map(ratatui::buffer::Cell::symbol)
378            .collect()
379    }
380
381    fn rings() -> Vec<RadialRing> {
382        vec![
383            RadialRing::new("Move", 420.0, 600.0),
384            RadialRing::new("Exercise", 25.0, 30.0).color(Color::Red),
385            RadialRing::new("Stand", 9.0, 12.0),
386        ]
387    }
388
389    #[test]
390    fn fraction_guards() {
391        assert_eq!(RadialRing::new("a", 5.0, 0.0).fraction(), 0.0);
392        assert_eq!(RadialRing::new("a", f64::NAN, 10.0).fraction(), 0.0);
393        assert_eq!(RadialRing::new("a", 50.0, 10.0).fraction(), 1.0);
394        assert_eq!(RadialRing::new("a", -5.0, 10.0).fraction(), 0.0);
395        assert!((RadialRing::new("a", 3.0, 12.0).fraction() - 0.25).abs() < 1e-12);
396    }
397
398    #[test]
399    fn renders_rings_and_legend() {
400        let b = draw(RadialBar::new(rings()), 50, 14);
401        let t = text(&b);
402        assert!(t.contains("Move") && t.contains("Exercise") && t.contains("70%"));
403        assert!(b
404            .content()
405            .iter()
406            .any(|c| c.fg == Color::Red && c.symbol() != " "));
407    }
408
409    #[test]
410    fn legend_can_be_hidden() {
411        let t = text(&draw(RadialBar::new(rings()).legend(false), 50, 14));
412        assert!(!t.contains("Move"));
413    }
414
415    #[test]
416    fn full_sweep_differs_from_arc() {
417        let a = draw(RadialBar::new(rings()).legend(false), 30, 14);
418        let b = draw(
419            RadialBar::new(rings())
420                .legend(false)
421                .sweep(RadialSweep::Full),
422            30,
423            14,
424        );
425        assert_ne!(a, b);
426    }
427
428    #[test]
429    fn value_changes_picture() {
430        let lo = draw(
431            RadialBar::new(vec![RadialRing::new("a", 10.0, 100.0)]).legend(false),
432            20,
433            10,
434        );
435        let hi = draw(
436            RadialBar::new(vec![RadialRing::new("a", 90.0, 100.0)]).legend(false),
437            20,
438            10,
439        );
440        assert_ne!(lo, hi);
441    }
442
443    #[test]
444    fn robust_to_odd_sizes_and_input() {
445        for (w, h) in [(0, 0), (1, 1), (4, 2), (13, 3), (60, 30)] {
446            let _ = draw(RadialBar::new(rings()), w, h);
447            let _ = draw(RadialBar::new(Vec::new()), w, h);
448            let _ = draw(
449                RadialBar::new(vec![RadialRing::new("x", f64::NAN, f64::NAN)]),
450                w,
451                h,
452            );
453            let many: Vec<RadialRing> = (0..40)
454                .map(|i| RadialRing::new("r", f64::from(i), 40.0))
455                .collect();
456            let _ = draw(RadialBar::new(many), w, h);
457        }
458    }
459
460    #[test]
461    fn ring_stack_renders_percentages() {
462        let t = text(&draw(
463            RingStack::new([("CPU", 72.0), ("RAM", 48.0)]).block(Block::bordered().title("Sys")),
464            50,
465            14,
466        ));
467        assert!(t.contains("CPU") && t.contains("72%") && t.contains("Sys"));
468    }
469
470    #[test]
471    fn ring_stack_custom_colors() {
472        let b = draw(
473            RingStack::new([("A", 100.0)])
474                .colors([Color::Magenta])
475                .legend(false),
476            20,
477            10,
478        );
479        assert!(b
480            .content()
481            .iter()
482            .any(|c| c.fg == Color::Magenta && c.symbol() != " "));
483    }
484}