Skip to main content

tui_chart/
theme.rs

1//! Chart-specific theme glue on top of the shared [`tui_nuances::Theme`].
2//!
3//! The [`Theme`] type itself (built-ins, `from_base`, `next`/`prev`, serde)
4//! lives in the shared `tui-nuances` crate and is re-exported here. This module
5//! only adds what is chart-specific: [`ChartThemeExt`] (derived heatmap
6//! gradient, crosshair/tooltip styles) and the [`begin`] render helper.
7//!
8//! Every widget has a `.theme(..)` builder (and implements
9//! [`tui_nuances::Themed`]); explicit per-item colors (series colors, candle
10//! colors, `.base_style(..)`, axis styles ...) always win over the theme,
11//! regardless of call order.
12//!
13//! ```
14//! # #[cfg(feature = "theme")] {
15//! use tui_chart::{LineChart, Series, Theme};
16//!
17//! let theme = Theme::dracula();
18//! let chart = LineChart::new(vec![Series::new("a").values([1.0, 3.0, 2.0])]).theme(&theme);
19//! # let _ = chart;
20//! # }
21//! ```
22
23use crate::heatmap::Gradient;
24use ratatui::{buffer::Buffer, layout::Rect, style::Color, style::Style};
25#[cfg(feature = "theme")]
26pub use tui_nuances::Theme;
27
28/// Chart-specific helpers derived from a [`Theme`].
29#[cfg(feature = "theme")]
30pub trait ChartThemeExt {
31    /// Gradient from a dim tint of the background up to the accent and the
32    /// second palette color (used by heatmap / treemap / sparkline).
33    fn gradient(&self) -> Gradient;
34    /// Crosshair guide line style.
35    fn crosshair_style(&self) -> Style;
36    /// Crosshair tooltip style (`tooltip_fg` on `tooltip_bg`).
37    fn tooltip_style(&self) -> Style;
38    /// Series color `i`, cycling through the palette.
39    fn series_color(&self, i: usize) -> Color;
40}
41
42#[cfg(feature = "theme")]
43impl ChartThemeExt for Theme {
44    fn gradient(&self) -> Gradient {
45        let accent = to_rgb(self.accent);
46        let low = match self.background {
47            Some(bg) => mix(to_rgb(bg), accent, 0.2),
48            None => mix((0, 0, 0), accent, 0.25),
49        };
50        let high = to_rgb(self.color(1));
51        Gradient::Custom(vec![low, accent, high])
52    }
53
54    fn crosshair_style(&self) -> Style {
55        Style::default().fg(self.crosshair)
56    }
57
58    fn tooltip_style(&self) -> Style {
59        Style::default().fg(self.tooltip_fg).bg(self.tooltip_bg)
60    }
61
62    fn series_color(&self, i: usize) -> Color {
63        self.color(i)
64    }
65}
66
67/// Approximate RGB of any ratatui color.
68#[cfg(feature = "theme")]
69pub(crate) fn to_rgb(c: Color) -> (u8, u8, u8) {
70    match c {
71        Color::Rgb(r, g, b) => (r, g, b),
72        Color::Black => (0, 0, 0),
73        Color::Red => (205, 49, 49),
74        Color::Green => (13, 188, 121),
75        Color::Yellow => (229, 229, 16),
76        Color::Blue => (36, 114, 200),
77        Color::Magenta => (188, 63, 188),
78        Color::Cyan => (17, 168, 205),
79        Color::Gray => (180, 180, 180),
80        Color::DarkGray => (102, 102, 102),
81        Color::LightRed => (241, 76, 76),
82        Color::LightGreen => (35, 209, 139),
83        Color::LightYellow => (245, 245, 67),
84        Color::LightBlue => (59, 142, 234),
85        Color::LightMagenta => (214, 112, 214),
86        Color::LightCyan => (41, 184, 219),
87        Color::White => (255, 255, 255),
88        _ => (128, 128, 128),
89    }
90}
91
92#[cfg(feature = "theme")]
93use crate::scale::mix_rgb as mix;
94
95/// Render helper: fill background / base style, then the (themed) block.
96/// Returns the inner area.
97pub(crate) fn begin(
98    block: &Option<ratatui::widgets::Block<'_>>,
99    theme: &Option<Theme>,
100    style: Option<Style>,
101    area: Rect,
102    buf: &mut Buffer,
103) -> Rect {
104    use ratatui::widgets::Widget;
105    if let Some(t) = theme {
106        t.fill(area, buf);
107    }
108    if let Some(s) = style {
109        buf.set_style(area, s);
110    }
111    match block {
112        Some(b) => {
113            let inner = b.inner(area);
114            let mut b = b.clone();
115            if let Some(t) = theme {
116                b = b
117                    .style(Style::default().fg(t.border))
118                    .title_style(Style::default().fg(t.title));
119            }
120            b.render(area, buf);
121            inner
122        }
123        None => area,
124    }
125}
126
127/// Without the `theme` feature no `Theme` value can exist: this uninhabited
128/// stand-in keeps the internal `Option<Theme>` plumbing compiling (always
129/// `None`) so the widgets fall back to their built-in default colors.
130#[cfg(not(feature = "theme"))]
131#[derive(Debug, Clone, PartialEq)]
132#[allow(dead_code)]
133pub(crate) enum Theme {}
134
135#[cfg(not(feature = "theme"))]
136#[allow(dead_code)]
137pub(crate) struct ThemeFields {
138    pub background: Option<Color>,
139    pub foreground: Color,
140    pub muted: Color,
141    pub border: Color,
142    pub title: Color,
143    pub accent: Color,
144    pub axis: Color,
145    pub grid: Color,
146    pub bull: Color,
147    pub bear: Color,
148    pub neutral: Color,
149    pub progress: Color,
150    pub crosshair: Color,
151    pub tooltip_fg: Color,
152    pub tooltip_bg: Color,
153}
154
155#[cfg(not(feature = "theme"))]
156#[allow(dead_code)]
157impl Theme {
158    pub fn color(&self, _i: usize) -> Color {
159        match *self {}
160    }
161    pub fn axis_style(&self) -> Style {
162        match *self {}
163    }
164    pub fn label_style(&self) -> Style {
165        match *self {}
166    }
167    pub fn grid_style(&self) -> Style {
168        match *self {}
169    }
170    pub fn fill(&self, _area: Rect, _buf: &mut Buffer) {
171        match *self {}
172    }
173}
174
175#[cfg(not(feature = "theme"))]
176impl std::ops::Deref for Theme {
177    type Target = ThemeFields;
178    fn deref(&self) -> &ThemeFields {
179        match *self {}
180    }
181}
182
183#[cfg(not(feature = "theme"))]
184#[allow(dead_code)]
185pub(crate) trait ChartThemeExt {
186    fn gradient(&self) -> Gradient;
187}
188
189#[cfg(not(feature = "theme"))]
190impl ChartThemeExt for Theme {
191    fn gradient(&self) -> Gradient {
192        match *self {}
193    }
194}
195
196#[cfg(all(test, feature = "theme"))]
197mod tests {
198    use super::*;
199
200    #[test]
201    fn gradient_from_theme() {
202        for t in Theme::all() {
203            assert!(matches!(t.gradient(), Gradient::Custom(v) if v.len() == 3));
204        }
205    }
206
207    #[test]
208    fn ext_styles() {
209        let t = Theme::nord();
210        assert_eq!(t.crosshair_style().fg, Some(t.crosshair));
211        assert_eq!(t.tooltip_style().bg, Some(t.tooltip_bg));
212        assert_eq!(t.series_color(0), t.series_color(t.palette.len()));
213    }
214
215    #[test]
216    fn fill_paints_background() {
217        let mut b = Buffer::empty(Rect::new(0, 0, 3, 2));
218        Theme::dracula().fill(Rect::new(0, 0, 3, 2), &mut b);
219        assert_eq!(b[(1, 1)].bg, Theme::dracula().background.unwrap());
220    }
221}