Skip to main content

tui_chart/
annotation.rs

1//! Reusable chart annotations: reference lines, shaded regions and text labels.
2//!
3//! [`draw_annotations`] is chart-agnostic: callers supply closures mapping data
4//! values to cell offsets relative to the plot rectangle.
5
6use crate::layout::text_width;
7use ratatui::{
8    buffer::Buffer,
9    layout::Rect,
10    style::{Color, Style},
11};
12
13/// Geometry of an [`Annotation`] in data coordinates.
14#[derive(Debug, Clone, Copy, PartialEq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum AnnotationKind {
17    /// Horizontal reference line at `y`.
18    HLine(f64),
19    /// Vertical reference line at `x`.
20    VLine(f64),
21    /// Vertical band shading `x0..=x1` over the full plot height.
22    XRegion(f64, f64),
23    /// Horizontal band shading `y0..=y1` over the full plot width.
24    YRegion(f64, f64),
25    /// Free text anchored at `(x, y)`.
26    Label(f64, f64),
27}
28
29/// A reference line, shaded band or text label drawn over a plot.
30#[derive(Debug, Clone, PartialEq)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub struct Annotation {
33    /// Geometry in data coordinates.
34    pub kind: AnnotationKind,
35    /// Style (foreground for lines/text; regions use `bg`, falling back to `fg`).
36    pub style: Style,
37    /// Optional text label.
38    pub text: Option<String>,
39}
40
41impl Annotation {
42    fn make(kind: AnnotationKind, text: Option<String>) -> Self {
43        Self {
44            kind,
45            style: Style::default().fg(Color::Yellow),
46            text,
47        }
48    }
49
50    /// Horizontal line at data `y`.
51    pub fn hline(y: f64) -> Self {
52        Self::make(AnnotationKind::HLine(y), None)
53    }
54
55    /// Vertical line at data `x`.
56    pub fn vline(x: f64) -> Self {
57        Self::make(AnnotationKind::VLine(x), None)
58    }
59
60    /// Shaded vertical band between `x0` and `x1`.
61    pub fn x_region(x0: f64, x1: f64) -> Self {
62        let mut a = Self::make(AnnotationKind::XRegion(x0, x1), None);
63        a.style = Style::default().fg(Color::Gray).bg(Color::DarkGray);
64        a
65    }
66
67    /// Shaded horizontal band between `y0` and `y1`.
68    pub fn y_region(y0: f64, y1: f64) -> Self {
69        let mut a = Self::make(AnnotationKind::YRegion(y0, y1), None);
70        a.style = Style::default().fg(Color::Gray).bg(Color::DarkGray);
71        a
72    }
73
74    /// Text label at `(x, y)`.
75    pub fn label(x: f64, y: f64, text: impl Into<String>) -> Self {
76        Self::make(AnnotationKind::Label(x, y), Some(text.into()))
77    }
78
79    /// Set the color (foreground; for regions also the band background).
80    pub fn color(mut self, color: Color) -> Self {
81        self.style = self.style.fg(color);
82        if matches!(
83            self.kind,
84            AnnotationKind::XRegion(..) | AnnotationKind::YRegion(..)
85        ) {
86            self.style = self.style.bg(color);
87        }
88        self
89    }
90
91    setter!(
92        /// Set the full style.
93        style: Style
94    );
95
96    /// Attach a text label.
97    pub fn text(mut self, text: impl Into<String>) -> Self {
98        self.text = Some(text.into());
99        self
100    }
101}
102
103fn put_text(buf: &mut Buffer, plot: Rect, col: i32, row: i32, text: &str, style: Style) {
104    if row < 0 || row >= plot.height as i32 {
105        return;
106    }
107    let w = text_width(text) as i32;
108    let start = col.clamp(0, (plot.width as i32 - w).max(0));
109    let max = plot.width as i32 - start;
110    if max <= 0 {
111        return;
112    }
113    buf.set_stringn(
114        plot.x + start as u16,
115        plot.y + row as u16,
116        text,
117        max as usize,
118        style,
119    );
120}
121
122fn set_glyph(buf: &mut Buffer, x: u16, y: u16, ch: char, style: Style) {
123    if let Some(c) = buf.cell_mut((x, y)) {
124        c.set_char(ch).set_style(style);
125    }
126}
127
128/// Draw `annotations` inside `plot`.
129///
130/// `x_cell` / `y_cell` map a data value to a cell column / row **relative to the
131/// plot's top-left** (may fall outside the plot; return `None` if unmappable).
132/// Call before drawing data so data glyphs stay on top. Never panics on
133/// degenerate areas or non-finite values.
134pub fn draw_annotations(
135    buf: &mut Buffer,
136    plot: Rect,
137    annotations: &[Annotation],
138    x_cell: &dyn Fn(f64) -> Option<i32>,
139    y_cell: &dyn Fn(f64) -> Option<i32>,
140) {
141    if plot.width == 0 || plot.height == 0 {
142        return;
143    }
144    let (w, h) = (plot.width as i32, plot.height as i32);
145    for a in annotations {
146        let text = a.text.as_deref();
147        match a.kind {
148            AnnotationKind::HLine(y) => {
149                let Some(r) = y_cell(y).filter(|r| (0..h).contains(r)) else {
150                    continue;
151                };
152                for c in 0..w {
153                    set_glyph(buf, plot.x + c as u16, plot.y + r as u16, '╌', a.style);
154                }
155                if let Some(t) = text {
156                    let row = if r > 0 { r - 1 } else { r };
157                    put_text(buf, plot, w - text_width(t) as i32, row, t, a.style);
158                }
159            }
160            AnnotationKind::VLine(x) => {
161                let Some(c) = x_cell(x).filter(|c| (0..w).contains(c)) else {
162                    continue;
163                };
164                for r in 0..h {
165                    set_glyph(buf, plot.x + c as u16, plot.y + r as u16, '╎', a.style);
166                }
167                if let Some(t) = text {
168                    let tw = text_width(t) as i32;
169                    let col = if c + 1 + tw <= w { c + 1 } else { c - tw };
170                    put_text(buf, plot, col, 0, t, a.style);
171                }
172            }
173            AnnotationKind::XRegion(x0, x1) => {
174                let (Some(c0), Some(c1)) = (x_cell(x0), x_cell(x1)) else {
175                    continue;
176                };
177                let (lo, hi) = (c0.min(c1).max(0), c0.max(c1).min(w - 1));
178                let bg = region_bg(a.style);
179                for c in lo..=hi {
180                    for r in 0..h {
181                        shade(buf, plot.x + c as u16, plot.y + r as u16, bg);
182                    }
183                }
184                if let (Some(t), true) = (text, lo <= hi) {
185                    put_text(buf, plot, lo, 0, t, a.style);
186                }
187            }
188            AnnotationKind::YRegion(y0, y1) => {
189                let (Some(r0), Some(r1)) = (y_cell(y0), y_cell(y1)) else {
190                    continue;
191                };
192                let (lo, hi) = (r0.min(r1).max(0), r0.max(r1).min(h - 1));
193                let bg = region_bg(a.style);
194                for r in lo..=hi {
195                    for c in 0..w {
196                        shade(buf, plot.x + c as u16, plot.y + r as u16, bg);
197                    }
198                }
199                if let (Some(t), true) = (text, lo <= hi) {
200                    put_text(buf, plot, 0, lo, t, a.style);
201                }
202            }
203            AnnotationKind::Label(x, y) => {
204                if let (Some(c), Some(r), Some(t)) = (x_cell(x), y_cell(y), text) {
205                    if (0..w).contains(&c) {
206                        put_text(buf, plot, c, r, t, a.style);
207                    }
208                }
209            }
210        }
211    }
212}
213
214fn region_bg(style: Style) -> Color {
215    style.bg.or(style.fg).unwrap_or(Color::DarkGray)
216}
217
218fn shade(buf: &mut Buffer, x: u16, y: u16, bg: Color) {
219    if let Some(c) = buf.cell_mut((x, y)) {
220        c.set_bg(bg);
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    fn map(v: f64) -> Option<i32> {
229        v.is_finite().then(|| v.round() as i32)
230    }
231
232    #[test]
233    fn builders() {
234        let a = Annotation::hline(1.0).color(Color::Red).text("lim");
235        assert_eq!(a.kind, AnnotationKind::HLine(1.0));
236        assert_eq!(a.style.fg, Some(Color::Red));
237        assert_eq!(a.text.as_deref(), Some("lim"));
238        let r = Annotation::x_region(1.0, 2.0).color(Color::Blue);
239        assert_eq!(r.style.bg, Some(Color::Blue));
240    }
241
242    #[test]
243    fn draws_lines_and_region() {
244        let plot = Rect::new(1, 1, 10, 5);
245        let mut buf = Buffer::empty(Rect::new(0, 0, 12, 7));
246        let anns = [
247            Annotation::hline(2.0),
248            Annotation::vline(4.0).text("v"),
249            Annotation::y_region(3.0, 4.0).color(Color::Blue),
250        ];
251        draw_annotations(&mut buf, plot, &anns, &map, &map);
252        assert_eq!(buf[(2, 3)].symbol(), "╌");
253        assert_eq!(buf[(5, 5)].symbol(), "╎");
254        assert_eq!(buf[(6, 1)].symbol(), "v");
255        assert_eq!(buf[(8, 4)].bg, Color::Blue);
256    }
257
258    #[test]
259    fn out_of_range_and_nan_safe() {
260        let plot = Rect::new(0, 0, 4, 3);
261        let mut buf = Buffer::empty(plot);
262        let anns = [
263            Annotation::hline(99.0),
264            Annotation::vline(f64::NAN),
265            Annotation::x_region(-50.0, 50.0),
266            Annotation::label(1.0, 1.0, "very long label text"),
267            Annotation::label(-5.0, 1.0, "x"),
268        ];
269        draw_annotations(&mut buf, plot, &anns, &map, &map);
270        draw_annotations(&mut buf, Rect::new(0, 0, 0, 0), &anns, &map, &map);
271    }
272}