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    hidden: Vec<usize>,
116    track: Option<Color>,
117    theme: Option<Theme>,
118    base: Option<Style>,
119    block: Option<Block<'static>>,
120}
121
122impl RadialBar {
123    /// Create a chart from rings, outermost first.
124    pub fn new(rings: impl IntoIterator<Item = RadialRing>) -> Self {
125        Self {
126            rings: rings.into_iter().collect(),
127            sweep: RadialSweep::Arc,
128            legend: true,
129            hidden: Vec::new(),
130            track: None,
131            theme: None,
132            base: None,
133            block: None,
134        }
135    }
136
137    setter!(
138        /// 270° or full sweep.
139        sweep: RadialSweep
140    );
141    setter!(
142        /// Show the legend (default on, when there is room).
143        legend: bool
144    );
145    opt_setter!(
146        /// Color of the unfilled track (default: theme grid / dark gray).
147        track => track: Color
148    );
149    theme_setter!(
150        /// Apply a [`Theme`]; explicit ring colors win.
151        theme
152    );
153    base_style_setter!(base);
154    block_setter!(block, 'static);
155
156    /// Hide rings by index. They keep their slot and legend entry (dimmed),
157    /// so they can be toggled back, see [`Interaction`](crate::Interaction).
158    #[must_use]
159    pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
160        self.hidden = hidden.into_iter().collect();
161        self
162    }
163
164    fn ring_color(&self, r: &RadialRing, i: usize) -> Color {
165        r.color.unwrap_or_else(|| {
166            self.theme
167                .as_ref()
168                .map_or(PALETTE[i % PALETTE.len()], |t| t.color(i))
169        })
170    }
171
172    fn track_color(&self) -> Color {
173        self.track
174            .unwrap_or_else(|| self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid))
175    }
176
177    fn draw_rings(&self, buf: &mut Buffer, area: Rect) {
178        if self.rings.is_empty() || area.is_empty() {
179            return;
180        }
181        let track = self.track_color();
182        let mut g = Braille::new(area.width, area.height);
183        let (w, h) = (g.dots_w(), g.dots_h());
184        let c = (w / 2.0, h / 2.0);
185        let r = w.min(h) / 2.0 - 0.5;
186        let n = self.rings.len() as f64;
187        let pitch = (r * 0.85) / n;
188        if pitch >= 1.5 {
189            let thick = (pitch - 1.2).max(1.5).min(pitch);
190            let sw = match self.sweep {
191                RadialSweep::Arc => (0.625, 0.75),
192                RadialSweep::Full => (0.0, 1.0),
193            };
194            for (i, ring) in self.rings.iter().enumerate() {
195                let outer = r - i as f64 * pitch;
196                let inner = (outer - thick).max(0.0);
197                let frac = if self.hidden.contains(&i) {
198                    0.0
199                } else {
200                    ring.fraction()
201                };
202                let color = self.ring_color(ring, i);
203                g.ring(c, (inner, outer), sw, |pos| {
204                    Some(if frac >= 1.0 || pos < frac {
205                        (color, 1)
206                    } else {
207                        (track, 0)
208                    })
209                });
210            }
211            if crate::interact::recording() {
212                let mut owner = vec![None; usize::from(area.width) * usize::from(area.height)];
213                for cy in 0..area.height {
214                    for cx in 0..area.width {
215                        let dx = (f64::from(cx) + 0.5) * 2.0 - c.0;
216                        let dy = (f64::from(cy) + 0.5) * 4.0 - c.1;
217                        let d = dx.hypot(dy);
218                        let turn = (dx.atan2(-dy) / std::f64::consts::TAU).rem_euclid(1.0);
219                        if (turn - sw.0).rem_euclid(1.0) > sw.1 {
220                            continue;
221                        }
222                        for i in (0..self.rings.len()).filter(|i| !self.hidden.contains(i)) {
223                            let outer = r - i as f64 * pitch;
224                            if d <= outer && d >= (outer - thick).max(0.0) - 1.0 {
225                                owner
226                                    [usize::from(cy) * usize::from(area.width) + usize::from(cx)] =
227                                    Some(i);
228                                break;
229                            }
230                        }
231                    }
232                }
233                crate::interact::record_grid(
234                    area,
235                    &owner,
236                    |i| i,
237                    |i| {
238                        let ring = &self.rings[i];
239                        (
240                            ring.label.clone(),
241                            vec![
242                                format!(
243                                    "{} / {}",
244                                    crate::util::format_compact(ring.value),
245                                    crate::util::format_compact(ring.max)
246                                ),
247                                format!("{:.0}%", ring.fraction() * 100.0),
248                            ],
249                        )
250                    },
251                );
252            }
253        }
254        g.blit(area, buf);
255    }
256
257    fn draw_legend(&self, buf: &mut Buffer, area: Rect) {
258        let text = self
259            .theme
260            .as_ref()
261            .map_or(Style::default(), |t| Style::default().fg(t.foreground));
262        let label_w = area.width.saturating_sub(7) as usize;
263        for (i, ring) in self.rings.iter().enumerate() {
264            let y = area.y + i as u16;
265            if y >= area.bottom() {
266                break;
267            }
268            let color = self.ring_color(ring, i);
269            let off = self.hidden.contains(&i);
270            let text = if off {
271                text.add_modifier(Modifier::DIM | Modifier::CROSSED_OUT)
272            } else {
273                text
274            };
275            buf.set_string(
276                area.x,
277                y,
278                if off { "□" } else { "■" },
279                Style::default().fg(color),
280            );
281            let label = truncate(&ring.label, label_w);
282            buf.set_string(area.x + 2, y, &label, text);
283            crate::interact::record_legend(
284                Rect::new(area.x, y, 2 + text_width(&label) as u16, 1),
285                i,
286                &ring.label,
287            );
288            let pct = format!("{:.0}%", ring.fraction() * 100.0);
289            let px = area.right().saturating_sub(pct.len() as u16);
290            if px > area.x + 2 + text_width(&label) as u16 {
291                buf.set_string(
292                    px,
293                    y,
294                    &pct,
295                    Style::default().fg(color).add_modifier(Modifier::BOLD),
296                );
297            }
298        }
299    }
300
301    fn render_into(&self, area: Rect, buf: &mut Buffer) {
302        let area = area.intersection(buf.area);
303        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
304        let (chart, legend) = split(inner, &self.rings, self.legend);
305        self.draw_rings(buf, chart);
306        if let Some(l) = legend {
307            self.draw_legend(buf, l);
308        }
309    }
310}
311
312widget_impls!(RadialBar);
313
314#[cfg(feature = "theme")]
315impl tui_nuances::Themed for RadialBar {
316    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
317        self.theme(theme)
318    }
319}
320
321/// Splits `inner` into the rings area and an optional legend area.
322fn split(inner: Rect, rings: &[RadialRing], legend: bool) -> (Rect, Option<Rect>) {
323    if !legend || rings.is_empty() {
324        return (inner, None);
325    }
326    let longest = rings
327        .iter()
328        .map(|r| text_width(&r.label))
329        .max()
330        .unwrap_or(0);
331    let lw = (longest + 8).clamp(14, 32) as u16;
332    // Keep at least a 12-column chart.
333    if inner.width < lw + 12 {
334        return (inner, None);
335    }
336    let chart_w = inner.width - lw - 1;
337    let chart = Rect::new(inner.x, inner.y, chart_w, inner.height);
338    let ly = inner.y + inner.height.saturating_sub(rings.len() as u16) / 2;
339    let leg = Rect::new(
340        inner.x + chart_w + 1,
341        ly,
342        lw,
343        (rings.len() as u16).min(inner.bottom() - ly),
344    );
345    (chart, Some(leg))
346}
347
348/// Concentric 270° rings, one per `(label, percent)`, with a legend.
349///
350/// # Example
351///
352/// ```
353/// use tui_chart::RingStack;
354///
355/// let stack = RingStack::new([("CPU", 72.0), ("RAM", 48.0), ("Disk", 91.0)]);
356/// # let _ = stack;
357/// ```
358#[derive(Debug, Clone, Default)]
359pub struct RingStack {
360    items: Vec<(String, f64)>,
361    colors: Vec<Color>,
362    inner: RadialBar,
363}
364
365impl RingStack {
366    /// Create a ring stack from `(label, percent)` pairs, outermost first.
367    pub fn new<S: Into<String>>(items: impl IntoIterator<Item = (S, f64)>) -> Self {
368        Self {
369            items: items.into_iter().map(|(l, v)| (l.into(), v)).collect(),
370            colors: Vec::new(),
371            inner: RadialBar::new([]),
372        }
373    }
374
375    /// Ring colors by position (the theme / palette fills in the rest).
376    pub fn colors(mut self, colors: impl IntoIterator<Item = Color>) -> Self {
377        self.colors = colors.into_iter().collect();
378        self
379    }
380
381    /// Hide rings by index, see [`RadialBar::hidden`].
382    #[must_use]
383    pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
384        self.inner = self.inner.hidden(hidden);
385        self
386    }
387
388    /// Show or hide the legend.
389    pub fn legend(mut self, show: bool) -> Self {
390        self.inner = self.inner.legend(show);
391        self
392    }
393
394    /// Color of the unfilled track.
395    pub fn track(mut self, c: Color) -> Self {
396        self.inner = self.inner.track(c);
397        self
398    }
399
400    /// Apply a [`Theme`]; explicit colors win.
401    #[cfg(feature = "theme")]
402    pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
403        self.inner = self.inner.theme(theme);
404        self
405    }
406
407    /// Base style painted over the whole area.
408    pub fn base_style(mut self, style: Style) -> Self {
409        self.inner = self.inner.base_style(style);
410        self
411    }
412
413    /// Wrap the chart in a [`Block`].
414    pub fn block(mut self, b: Block<'static>) -> Self {
415        self.inner = self.inner.block(b);
416        self
417    }
418
419    fn render_into(&self, area: Rect, buf: &mut Buffer) {
420        let rings = self.items.iter().enumerate().map(|(i, (l, pct))| {
421            let mut r = RadialRing::new(l.clone(), *pct, 100.0);
422            r.color = self.colors.get(i).copied();
423            r
424        });
425        let mut bar = self.inner.clone();
426        bar.rings = rings.collect();
427        bar.render_into(area, buf);
428    }
429}
430
431widget_impls!(RingStack);
432
433#[cfg(feature = "theme")]
434impl tui_nuances::Themed for RingStack {
435    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
436        self.theme(theme)
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    #![allow(clippy::assert_is_empty, clippy::float_cmp)]
443    use super::*;
444    use ratatui::widgets::Widget;
445
446    fn draw(w: impl Widget, width: u16, height: u16) -> Buffer {
447        let a = Rect::new(0, 0, width, height);
448        let mut b = Buffer::empty(a);
449        w.render(a, &mut b);
450        b
451    }
452
453    fn text(b: &Buffer) -> String {
454        b.content()
455            .iter()
456            .map(ratatui::buffer::Cell::symbol)
457            .collect()
458    }
459
460    fn rings() -> Vec<RadialRing> {
461        vec![
462            RadialRing::new("Move", 420.0, 600.0),
463            RadialRing::new("Exercise", 25.0, 30.0).color(Color::Red),
464            RadialRing::new("Stand", 9.0, 12.0),
465        ]
466    }
467
468    #[test]
469    fn fraction_guards() {
470        assert_eq!(RadialRing::new("a", 5.0, 0.0).fraction(), 0.0);
471        assert_eq!(RadialRing::new("a", f64::NAN, 10.0).fraction(), 0.0);
472        assert_eq!(RadialRing::new("a", 50.0, 10.0).fraction(), 1.0);
473        assert_eq!(RadialRing::new("a", -5.0, 10.0).fraction(), 0.0);
474        assert!((RadialRing::new("a", 3.0, 12.0).fraction() - 0.25).abs() < 1e-12);
475    }
476
477    #[test]
478    fn renders_rings_and_legend() {
479        let b = draw(RadialBar::new(rings()), 50, 14);
480        let t = text(&b);
481        assert!(t.contains("Move") && t.contains("Exercise") && t.contains("70%"));
482        assert!(b
483            .content()
484            .iter()
485            .any(|c| c.fg == Color::Red && c.symbol() != " "));
486    }
487
488    #[test]
489    fn legend_can_be_hidden() {
490        let t = text(&draw(RadialBar::new(rings()).legend(false), 50, 14));
491        assert!(!t.contains("Move"));
492    }
493
494    #[test]
495    fn full_sweep_differs_from_arc() {
496        let a = draw(RadialBar::new(rings()).legend(false), 30, 14);
497        let b = draw(
498            RadialBar::new(rings())
499                .legend(false)
500                .sweep(RadialSweep::Full),
501            30,
502            14,
503        );
504        assert_ne!(a, b);
505    }
506
507    #[test]
508    fn value_changes_picture() {
509        let lo = draw(
510            RadialBar::new(vec![RadialRing::new("a", 10.0, 100.0)]).legend(false),
511            20,
512            10,
513        );
514        let hi = draw(
515            RadialBar::new(vec![RadialRing::new("a", 90.0, 100.0)]).legend(false),
516            20,
517            10,
518        );
519        assert_ne!(lo, hi);
520    }
521
522    #[test]
523    fn robust_to_odd_sizes_and_input() {
524        for (w, h) in [(0, 0), (1, 1), (4, 2), (13, 3), (60, 30)] {
525            let _ = draw(RadialBar::new(rings()), w, h);
526            let _ = draw(RadialBar::new(Vec::new()), w, h);
527            let _ = draw(
528                RadialBar::new(vec![RadialRing::new("x", f64::NAN, f64::NAN)]),
529                w,
530                h,
531            );
532            let many: Vec<RadialRing> = (0..40)
533                .map(|i| RadialRing::new("r", f64::from(i), 40.0))
534                .collect();
535            let _ = draw(RadialBar::new(many), w, h);
536        }
537    }
538
539    #[test]
540    fn ring_stack_renders_percentages() {
541        let t = text(&draw(
542            RingStack::new([("CPU", 72.0), ("RAM", 48.0)]).block(Block::bordered().title("Sys")),
543            50,
544            14,
545        ));
546        assert!(t.contains("CPU") && t.contains("72%") && t.contains("Sys"));
547    }
548
549    #[test]
550    fn ring_stack_custom_colors() {
551        let b = draw(
552            RingStack::new([("A", 100.0)])
553                .colors([Color::Magenta])
554                .legend(false),
555            20,
556            10,
557        );
558        assert!(b
559            .content()
560            .iter()
561            .any(|c| c.fg == Color::Magenta && c.symbol() != " "));
562    }
563}