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    // (row, first column, last column) of the labels of vertical lines already placed, so that
146    // the labels of lines that are close do not print over each other
147    let mut taken: Vec<(i32, i32, i32)> = Vec::new();
148    // drawn after all lines, so that no later line is drawn through a label
149    let mut labels: Vec<(i32, i32, &str, Style)> = Vec::new();
150    for a in annotations {
151        let text = a.text.as_deref();
152        match a.kind {
153            AnnotationKind::HLine(y) => {
154                let Some(r) = y_cell(y).filter(|r| (0..h).contains(r)) else {
155                    continue;
156                };
157                for c in 0..w {
158                    set_glyph(buf, plot.x + c as u16, plot.y + r as u16, '╌', a.style);
159                }
160                if let Some(t) = text {
161                    let row = if r > 0 { r - 1 } else { r };
162                    put_text(buf, plot, w - text_width(t) as i32, row, t, a.style);
163                }
164            }
165            AnnotationKind::VLine(x) => {
166                let Some(c) = x_cell(x).filter(|c| (0..w).contains(c)) else {
167                    continue;
168                };
169                for r in 0..h {
170                    set_glyph(buf, plot.x + c as u16, plot.y + r as u16, '╎', a.style);
171                }
172                if let Some(t) = text {
173                    let tw = text_width(t) as i32;
174                    let col = if c + 1 + tw <= w { c + 1 } else { c - tw };
175                    // the first row from the top where the label meets no other
176                    let row = (0..h)
177                        .find(|r| {
178                            !taken
179                                .iter()
180                                .any(|&(tr, a0, a1)| tr == *r && col <= a1 && col + tw > a0)
181                        })
182                        .unwrap_or(0);
183                    taken.push((row, col, col + tw - 1));
184                    labels.push((col, row, t, a.style));
185                }
186            }
187            AnnotationKind::XRegion(x0, x1) => {
188                let (Some(c0), Some(c1)) = (x_cell(x0), x_cell(x1)) else {
189                    continue;
190                };
191                let (lo, hi) = (c0.min(c1).max(0), c0.max(c1).min(w - 1));
192                let bg = region_bg(a.style);
193                for c in lo..=hi {
194                    for r in 0..h {
195                        shade(buf, plot.x + c as u16, plot.y + r as u16, bg);
196                    }
197                }
198                if let (Some(t), true) = (text, lo <= hi) {
199                    put_text(buf, plot, lo, 0, t, a.style);
200                }
201            }
202            AnnotationKind::YRegion(y0, y1) => {
203                let (Some(r0), Some(r1)) = (y_cell(y0), y_cell(y1)) else {
204                    continue;
205                };
206                let (lo, hi) = (r0.min(r1).max(0), r0.max(r1).min(h - 1));
207                let bg = region_bg(a.style);
208                for r in lo..=hi {
209                    for c in 0..w {
210                        shade(buf, plot.x + c as u16, plot.y + r as u16, bg);
211                    }
212                }
213                if let (Some(t), true) = (text, lo <= hi) {
214                    put_text(buf, plot, 0, lo, t, a.style);
215                }
216            }
217            AnnotationKind::Label(x, y) => {
218                if let (Some(c), Some(r), Some(t)) = (x_cell(x), y_cell(y), text)
219                    && (0..w).contains(&c)
220                {
221                    put_text(buf, plot, c, r, t, a.style);
222                }
223            }
224        }
225    }
226    for (col, row, text, style) in labels {
227        put_text(buf, plot, col, row, text, style);
228    }
229}
230
231fn region_bg(style: Style) -> Color {
232    style.bg.or(style.fg).unwrap_or(Color::DarkGray)
233}
234
235fn shade(buf: &mut Buffer, x: u16, y: u16, bg: Color) {
236    if let Some(c) = buf.cell_mut((x, y)) {
237        c.set_bg(bg);
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    fn map(v: f64) -> Option<i32> {
246        v.is_finite().then(|| v.round() as i32)
247    }
248
249    #[test]
250    fn builders() {
251        let a = Annotation::hline(1.0).color(Color::Red).text("lim");
252        assert_eq!(a.kind, AnnotationKind::HLine(1.0));
253        assert_eq!(a.style.fg, Some(Color::Red));
254        assert_eq!(a.text.as_deref(), Some("lim"));
255        let r = Annotation::x_region(1.0, 2.0).color(Color::Blue);
256        assert_eq!(r.style.bg, Some(Color::Blue));
257    }
258
259    #[test]
260    fn draws_lines_and_region() {
261        let plot = Rect::new(1, 1, 10, 5);
262        let mut buf = Buffer::empty(Rect::new(0, 0, 12, 7));
263        let anns = [
264            Annotation::hline(2.0),
265            Annotation::vline(4.0).text("v"),
266            Annotation::y_region(3.0, 4.0).color(Color::Blue),
267        ];
268        draw_annotations(&mut buf, plot, &anns, &map, &map);
269        assert_eq!(buf[(2, 3)].symbol(), "╌");
270        assert_eq!(buf[(5, 5)].symbol(), "╎");
271        assert_eq!(buf[(6, 1)].symbol(), "v");
272        assert_eq!(buf[(8, 4)].bg, Color::Blue);
273    }
274
275    #[test]
276    fn labels_of_close_vertical_lines_do_not_overlap() {
277        let plot = Rect::new(0, 0, 30, 4);
278        let mut buf = Buffer::empty(plot);
279        let anns = [
280            Annotation::vline(5.0).text("first"),
281            Annotation::vline(7.0).text("second"),
282            Annotation::vline(20.0).text("far"),
283        ];
284        draw_annotations(&mut buf, plot, &anns, &map, &map);
285        let row = |y: u16| {
286            (0..30)
287                .map(|x| buf[(x, y)].symbol().to_string())
288                .collect::<String>()
289        };
290        assert!(row(0).contains("first"), "{}", row(0));
291        // the second label is one row down, whole
292        assert!(row(1).contains("second"), "{}", row(1));
293        // a line far away keeps the top row
294        assert!(row(0).contains("far"), "{}", row(0));
295    }
296
297    #[test]
298    fn out_of_range_and_nan_safe() {
299        let plot = Rect::new(0, 0, 4, 3);
300        let mut buf = Buffer::empty(plot);
301        let anns = [
302            Annotation::hline(99.0),
303            Annotation::vline(f64::NAN),
304            Annotation::x_region(-50.0, 50.0),
305            Annotation::label(1.0, 1.0, "very long label text"),
306            Annotation::label(-5.0, 1.0, "x"),
307        ];
308        draw_annotations(&mut buf, plot, &anns, &map, &map);
309        draw_annotations(&mut buf, Rect::new(0, 0, 0, 0), &anns, &map, &map);
310    }
311}