Skip to main content

tui_chart/
axis.rs

1//! Axis configuration shared by all charts.
2
3use crate::theme::Theme;
4use crate::util::{format_tick, nice_ticks, tick_step};
5use ratatui::style::{Color, Style};
6use std::fmt;
7use std::sync::Arc;
8
9/// Shared tick-label formatter.
10pub(crate) type Formatter = Arc<dyn Fn(f64) -> String + Send + Sync>;
11
12/// Look of grid lines.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub enum GridStyle {
16    /// Dotted (`·`), the default.
17    #[default]
18    Dotted,
19    /// Dashed (`╌` / `╎`).
20    Dashed,
21    /// Solid thin lines (`─` / `│`).
22    Solid,
23}
24
25impl GridStyle {
26    /// Glyph for a horizontal (`true`) or vertical grid line.
27    pub(crate) fn glyph(self, horizontal: bool) -> char {
28        match (self, horizontal) {
29            (GridStyle::Dotted, _) => '·',
30            (GridStyle::Dashed, true) => '╌',
31            (GridStyle::Dashed, false) => '╎',
32            (GridStyle::Solid, true) => '─',
33            (GridStyle::Solid, false) => '│',
34        }
35    }
36}
37
38/// Configuration for a chart axis (title, bounds, ticks, grid, labels).
39#[derive(Clone)]
40pub struct Axis {
41    pub(crate) title: Option<String>,
42    pub(crate) bounds: Option<(f64, f64)>,
43    pub(crate) ticks: usize,
44    pub(crate) style: Style,
45    pub(crate) label_style: Style,
46    pub(crate) grid: bool,
47    pub(crate) grid_style: Style,
48    pub(crate) labels: Option<Vec<String>>,
49    pub(crate) formatter: Option<Formatter>,
50    pub(crate) grid_kind: GridStyle,
51    pub(crate) explicit: u8,
52}
53
54const EXPL_STYLE: u8 = 1;
55const EXPL_LABEL: u8 = 2;
56const EXPL_GRID: u8 = 4;
57
58impl fmt::Debug for Axis {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.debug_struct("Axis")
61            .field("title", &self.title)
62            .field("bounds", &self.bounds)
63            .field("ticks", &self.ticks)
64            .field("grid", &self.grid)
65            .field("grid_kind", &self.grid_kind)
66            .field("labels", &self.labels)
67            .field("formatter", &self.formatter.as_ref().map(|_| "<fn>"))
68            .finish()
69    }
70}
71
72impl Default for Axis {
73    fn default() -> Self {
74        Self {
75            title: None,
76            bounds: None,
77            ticks: 5,
78            style: Style::default().fg(Color::DarkGray),
79            label_style: Style::default().fg(Color::Gray),
80            grid: false,
81            grid_style: Style::default().fg(Color::DarkGray),
82            labels: None,
83            formatter: None,
84            grid_kind: GridStyle::default(),
85            explicit: 0,
86        }
87    }
88}
89
90impl Axis {
91    /// Create an axis with defaults (auto bounds, 5 ticks, no grid).
92    pub fn new() -> Self {
93        Self::default()
94    }
95
96    /// Axis title (drawn at the top for y, at the bottom for x).
97    pub fn title(mut self, title: impl Into<String>) -> Self {
98        self.title = Some(title.into());
99        self
100    }
101
102    /// Fixed `(min, max)` bounds instead of auto-scaling.
103    pub fn bounds(mut self, min: f64, max: f64) -> Self {
104        self.bounds = Some((min, max));
105        self
106    }
107
108    /// Desired number of ticks (min 2).
109    pub fn ticks(mut self, ticks: usize) -> Self {
110        self.ticks = ticks.max(2);
111        self
112    }
113
114    /// Style of the axis line.
115    pub fn style(mut self, style: Style) -> Self {
116        self.style = style;
117        self.explicit |= EXPL_STYLE;
118        self
119    }
120
121    /// Style of tick labels and the title.
122    pub fn label_style(mut self, style: Style) -> Self {
123        self.label_style = style;
124        self.explicit |= EXPL_LABEL;
125        self
126    }
127
128    setter!(
129        /// Draw dotted grid lines at each tick.
130        grid: bool
131    );
132
133    /// Style of the grid lines.
134    pub fn grid_style(mut self, style: Style) -> Self {
135        self.grid_style = style;
136        self.explicit |= EXPL_GRID;
137        self
138    }
139
140    setter!(
141        /// Grid line look: dotted (default), dashed or solid.
142        grid_lines => grid_kind: GridStyle
143    );
144
145    /// Apply a theme to every style not set explicitly on this axis.
146    pub(crate) fn theme_in_place(&mut self, t: &Theme) {
147        if self.explicit & EXPL_STYLE == 0 {
148            self.style = t.axis_style();
149        }
150        if self.explicit & EXPL_LABEL == 0 {
151            self.label_style = t.label_style();
152        }
153        if self.explicit & EXPL_GRID == 0 {
154            self.grid_style = t.grid_style();
155        }
156    }
157
158    /// Style axis line, tick labels and grid from `theme`; styles set
159    /// explicitly on this axis win regardless of call order.
160    #[must_use]
161    #[cfg(feature = "theme")]
162    pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
163        self.theme_in_place(&theme.into());
164        self
165    }
166
167    /// Custom, evenly spaced tick labels (overrides numeric ticks).
168    pub fn labels<I, S>(mut self, labels: I) -> Self
169    where
170        I: IntoIterator<Item = S>,
171        S: Into<String>,
172    {
173        self.labels = Some(labels.into_iter().map(Into::into).collect());
174        self
175    }
176
177    /// Custom number formatter for tick labels. Accepts function pointers and
178    /// (capturing) closures.
179    pub fn formatter(mut self, f: impl Fn(f64) -> String + Send + Sync + 'static) -> Self {
180        self.formatter = Some(Arc::new(f));
181        self
182    }
183
184    /// Alias of [`Axis::formatter`] taking an already shared formatter.
185    pub fn formatter_fn(mut self, f: Arc<dyn Fn(f64) -> String + Send + Sync>) -> Self {
186        self.formatter = Some(f);
187        self
188    }
189
190    /// Format a value with the custom formatter, if any.
191    pub(crate) fn format(&self, v: f64) -> Option<String> {
192        self.formatter.as_ref().map(|f| f(v))
193    }
194
195    /// `(fraction in 0..=1, label)` for each tick within `bounds`.
196    pub(crate) fn tick_marks(&self, bounds: (f64, f64)) -> Vec<(f64, String)> {
197        if let Some(labels) = &self.labels {
198            let n = labels.len();
199            return labels
200                .iter()
201                .enumerate()
202                .map(|(i, l)| {
203                    let f = if n <= 1 {
204                        0.0
205                    } else {
206                        i as f64 / (n - 1) as f64
207                    };
208                    (f, l.clone())
209                })
210                .collect();
211        }
212        let (lo, hi) = bounds;
213        if hi <= lo {
214            return vec![];
215        }
216        let ticks = nice_ticks(lo, hi, self.ticks);
217        let step = tick_step(&ticks);
218        ticks
219            .iter()
220            .map(|&v| {
221                let label = match self.format(v) {
222                    Some(l) => l,
223                    None => format_tick(v, step),
224                };
225                ((v - lo) / (hi - lo), label)
226            })
227            .collect()
228    }
229}
230
231#[cfg(feature = "theme")]
232impl tui_nuances::Themed for Axis {
233    fn apply_theme(self, theme: &Theme) -> Self {
234        self.theme(theme)
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn numeric_marks() {
244        let m = Axis::new().tick_marks((0.0, 100.0));
245        assert_eq!(m.first().unwrap().1, "0");
246        assert_eq!(m.last().unwrap().1, "100");
247        assert!((m.last().unwrap().0 - 1.0).abs() < 1e-12);
248    }
249
250    #[test]
251    fn custom_labels_even() {
252        let m = Axis::new().labels(["a", "b", "c"]).tick_marks((0.0, 1.0));
253        assert_eq!(m.len(), 3);
254        assert_eq!(m[1], (0.5, "b".to_string()));
255    }
256
257    #[test]
258    fn formatter_applies() {
259        let m = Axis::new()
260            .formatter(|v| format!("${v}"))
261            .tick_marks((0.0, 10.0));
262        assert!(m[0].1.starts_with('$'));
263    }
264
265    #[test]
266    fn closure_formatter_captures() {
267        let unit = String::from("kg");
268        let m = Axis::new()
269            .formatter(move |v| format!("{v}{unit}"))
270            .tick_marks((0.0, 10.0));
271        assert!(m[0].1.ends_with("kg"));
272    }
273
274    #[cfg(feature = "theme")]
275    #[test]
276    fn theme_respects_explicit() {
277        let t = Theme::dracula();
278        let mut a = Axis::new().style(Style::default().fg(Color::Red));
279        a.theme_in_place(&t);
280        assert_eq!(a.style.fg, Some(Color::Red));
281        assert_eq!(a.label_style.fg, Some(t.muted));
282    }
283
284    #[test]
285    fn builder_sets_fields() {
286        let a = Axis::new().title("t").bounds(1.0, 2.0).ticks(0).grid(true);
287        assert_eq!(a.title.as_deref(), Some("t"));
288        assert_eq!(a.bounds, Some((1.0, 2.0)));
289        assert_eq!(a.ticks, 2);
290        assert!(a.grid);
291    }
292
293    #[test]
294    fn degenerate_bounds_no_marks() {
295        assert!(Axis::new().tick_marks((1.0, 1.0)).is_empty());
296    }
297}