Skip to main content

tui_chart/
accessibility.rs

1//! Accessibility helpers: render any chart without relying on colour.
2//!
3//! [`Monochrome`] wraps a widget, renders it normally and then post-processes
4//! the cells it touched:
5//!
6//! * solid colour fills (a coloured *background* on a blank cell, as drawn by
7//!   heatmaps, treemaps, calendars, bars) become shade glyphs `░▒▓█` chosen by
8//!   luminance, so intensity is still readable;
9//! * coloured foreground glyphs keep their shape, lose their colour, and dark
10//!   (low luminance) ones get the `DIM` modifier so contrast between series
11//!   survives;
12//! * all colours are reset, so the terminal's own foreground/background apply.
13//!
14//! [`Monochrome::auto`] only does this when the `NO_COLOR` environment
15//! variable is set (<https://no-color.org>), so one code path serves both.
16//!
17//! ```
18//! use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
19//! use tui_chart::{Heatmap, Monochrome};
20//!
21//! let area = Rect::new(0, 0, 20, 6);
22//! let mut buf = Buffer::empty(area);
23//! Monochrome::new(Heatmap::new(vec![vec![0.0, 0.5, 1.0]]).cell_width(4)).render(area, &mut buf);
24//! assert!(buf.content().iter().any(|c| matches!(c.symbol(), "░" | "▒" | "▓" | "█")));
25//! ```
26
27use crate::util::to_rgb;
28use ratatui::{
29    buffer::Buffer,
30    layout::Rect,
31    style::{Color, Modifier},
32    widgets::Widget,
33};
34
35/// `true` when the `NO_COLOR` environment variable is set to a non-empty value.
36pub fn no_color_requested() -> bool {
37    std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty())
38}
39
40fn luminance(c: Color) -> f64 {
41    let (r, g, b) = to_rgb(c);
42    (0.2126 * r as f64 + 0.7152 * g as f64 + 0.0722 * b as f64) / 255.0
43}
44
45/// Strip colour from `area` of `buf`, replacing solid fills by shade glyphs.
46pub fn strip_color(buf: &mut Buffer, area: Rect) {
47    const SHADES: [&str; 5] = [" ", "░", "▒", "▓", "█"];
48    let area = area.intersection(buf.area);
49    for y in area.top()..area.bottom() {
50        for x in area.left()..area.right() {
51            let cell = &mut buf[(x, y)];
52            let blank = cell.symbol().trim().is_empty();
53            let (fg, bg) = (cell.fg, cell.bg);
54            if blank && bg != Color::Reset {
55                let l = luminance(bg);
56                let i = (l * (SHADES.len() - 1) as f64).round() as usize;
57                cell.set_symbol(SHADES[i.min(SHADES.len() - 1)]);
58            } else if !blank && fg != Color::Reset && luminance(fg) < 0.35 {
59                cell.modifier.insert(Modifier::DIM);
60            }
61            cell.set_fg(Color::Reset);
62            cell.set_bg(Color::Reset);
63        }
64    }
65}
66
67/// Renders the wrapped widget, then removes its colours (see the module docs).
68#[derive(Debug, Clone)]
69pub struct Monochrome<W> {
70    inner: W,
71    only_if_no_color: bool,
72}
73
74impl<W> Monochrome<W> {
75    /// Always render without colour.
76    pub fn new(inner: W) -> Self {
77        Self {
78            inner,
79            only_if_no_color: false,
80        }
81    }
82
83    /// Render without colour only when `NO_COLOR` is set.
84    pub fn auto(inner: W) -> Self {
85        Self {
86            inner,
87            only_if_no_color: true,
88        }
89    }
90}
91
92impl<W: Widget> Widget for Monochrome<W> {
93    fn render(self, area: Rect, buf: &mut Buffer) {
94        let strip = !self.only_if_no_color || no_color_requested();
95        self.inner.render(area, buf);
96        if strip {
97            strip_color(buf, area);
98        }
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::{BarChart, BarGroup, Heatmap, LineChart, Series};
106
107    fn has_color(b: &Buffer) -> bool {
108        b.content()
109            .iter()
110            .any(|c| c.fg != Color::Reset || c.bg != Color::Reset)
111    }
112
113    #[test]
114    fn removes_all_colors() {
115        let area = Rect::new(0, 0, 40, 12);
116        let mut plain = Buffer::empty(area);
117        LineChart::new(vec![
118            Series::new("a").data((0..20).map(|i| (i as f64, i as f64))),
119        ])
120        .render(area, &mut plain);
121        assert!(has_color(&plain));
122        let mut mono = Buffer::empty(area);
123        Monochrome::new(LineChart::new(vec![
124            Series::new("a").data((0..20).map(|i| (i as f64, i as f64))),
125        ]))
126        .render(area, &mut mono);
127        assert!(!has_color(&mono));
128        // glyph shapes survive
129        let glyphs = |b: &Buffer| {
130            b.content()
131                .iter()
132                .map(|c| c.symbol().to_string())
133                .collect::<Vec<_>>()
134        };
135        assert_eq!(glyphs(&plain), glyphs(&mono));
136    }
137
138    #[test]
139    fn fills_become_shades_by_intensity() {
140        let area = Rect::new(0, 0, 24, 3);
141        let mut b = Buffer::empty(area);
142        Monochrome::new(
143            Heatmap::new(vec![vec![0.0, 0.25, 0.5, 0.75, 1.0]])
144                .cell_width(4)
145                .legend(false),
146        )
147        .render(area, &mut b);
148        let t: String = b.content().iter().map(|c| c.symbol()).collect();
149        assert!(!has_color(&b));
150        assert!(t.contains('▓') || t.contains('█'));
151        assert!(t.contains('░') || t.contains('▒') || t.contains(' '));
152    }
153
154    #[test]
155    fn auto_follows_no_color_env() {
156        let area = Rect::new(0, 0, 30, 8);
157        let mk = || BarChart::new(vec![BarGroup::new("a", [3.0, 5.0])]);
158        // without NO_COLOR: untouched (assumes the test env does not set it)
159        if !no_color_requested() {
160            let mut b = Buffer::empty(area);
161            Monochrome::auto(mk()).render(area, &mut b);
162            assert!(has_color(&b));
163        }
164        let mut b = Buffer::empty(area);
165        Monochrome::new(mk()).render(area, &mut b);
166        assert!(!has_color(&b));
167    }
168
169    #[test]
170    fn handles_out_of_bounds_areas() {
171        let mut b = Buffer::empty(Rect::new(0, 0, 5, 5));
172        strip_color(&mut b, Rect::new(3, 3, 50, 50));
173        strip_color(&mut b, Rect::new(0, 0, 0, 0));
174    }
175}