1use 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
9pub(crate) type Formatter = Arc<dyn Fn(f64) -> String + Send + Sync>;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub enum GridStyle {
16 #[default]
18 Dotted,
19 Dashed,
21 Solid,
23}
24
25impl GridStyle {
26 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#[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 pub fn new() -> Self {
93 Self::default()
94 }
95
96 pub fn title(mut self, title: impl Into<String>) -> Self {
98 self.title = Some(title.into());
99 self
100 }
101
102 pub fn bounds(mut self, min: f64, max: f64) -> Self {
104 self.bounds = Some((min, max));
105 self
106 }
107
108 pub fn ticks(mut self, ticks: usize) -> Self {
110 self.ticks = ticks.max(2);
111 self
112 }
113
114 pub fn style(mut self, style: Style) -> Self {
116 self.style = style;
117 self.explicit |= EXPL_STYLE;
118 self
119 }
120
121 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 grid: bool
131 );
132
133 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_lines => grid_kind: GridStyle
143 );
144
145 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 #[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 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 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 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 pub(crate) fn format(&self, v: f64) -> Option<String> {
192 self.formatter.as_ref().map(|f| f(v))
193 }
194
195 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}