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)]
132pub(crate) enum Theme {}
133
134#[cfg(not(feature = "theme"))]
135pub(crate) struct ThemeFields {
136    pub background: Option<Color>,
137    pub foreground: Color,
138    pub muted: Color,
139    pub border: Color,
140    pub title: Color,
141    pub accent: Color,
142    pub axis: Color,
143    pub grid: Color,
144    pub bull: Color,
145    pub bear: Color,
146    pub neutral: Color,
147    pub crosshair: Color,
148    pub tooltip_fg: Color,
149    pub tooltip_bg: Color,
150}
151
152#[cfg(not(feature = "theme"))]
153impl Theme {
154    pub fn color(&self, _i: usize) -> Color {
155        match *self {}
156    }
157    pub fn axis_style(&self) -> Style {
158        match *self {}
159    }
160    pub fn label_style(&self) -> Style {
161        match *self {}
162    }
163    pub fn grid_style(&self) -> Style {
164        match *self {}
165    }
166    pub fn fill(&self, _area: Rect, _buf: &mut Buffer) {
167        match *self {}
168    }
169}
170
171#[cfg(not(feature = "theme"))]
172impl std::ops::Deref for Theme {
173    type Target = ThemeFields;
174    fn deref(&self) -> &ThemeFields {
175        match *self {}
176    }
177}
178
179#[cfg(not(feature = "theme"))]
180pub(crate) trait ChartThemeExt {
181    fn gradient(&self) -> Gradient;
182}
183
184#[cfg(not(feature = "theme"))]
185impl ChartThemeExt for Theme {
186    fn gradient(&self) -> Gradient {
187        match *self {}
188    }
189}
190
191#[cfg(all(test, feature = "theme"))]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn gradient_from_theme() {
197        for t in Theme::all() {
198            assert!(matches!(t.gradient(), Gradient::Custom(v) if v.len() == 3));
199        }
200    }
201
202    #[test]
203    fn ext_styles() {
204        let t = Theme::nord();
205        assert_eq!(t.crosshair_style().fg, Some(t.crosshair));
206        assert_eq!(t.tooltip_style().bg, Some(t.tooltip_bg));
207        assert_eq!(t.series_color(0), t.series_color(t.palette.len()));
208    }
209
210    #[test]
211    fn fill_paints_background() {
212        let mut b = Buffer::empty(Rect::new(0, 0, 3, 2));
213        Theme::dracula().fill(Rect::new(0, 0, 3, 2), &mut b);
214        assert_eq!(b[(1, 1)].bg, Theme::dracula().background.unwrap());
215    }
216}