Skip to main content

tui_chart/
line.rs

1//! Line, step, area and scatter charts.
2
3use crate::annotation::{draw_annotations, Annotation};
4use crate::axis::Axis;
5use crate::canvas::{Canvas, Marker};
6use crate::crosshair::{self, nearest_point, Crosshair, NearestPoint};
7use crate::heatmap::Gradient;
8use crate::layout::{self, text_width};
9use crate::theme::{self, Theme};
10use crate::util::{format_compact, format_tick, nice_bounds};
11use crate::PALETTE;
12use ratatui::{
13    buffer::Buffer,
14    layout::Rect,
15    style::{Color, Style},
16    widgets::Block,
17};
18
19/// How a series is drawn.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub enum LineMode {
23    /// Straight segments between points.
24    #[default]
25    Line,
26    /// Horizontal-then-vertical steps (good for discrete state).
27    Step,
28    /// Line with a shaded fill down to the x axis.
29    Area,
30    /// Points only.
31    Scatter,
32}
33
34/// Where the legend is drawn inside the plot.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37pub enum LegendPosition {
38    /// No legend.
39    None,
40    /// Top-left corner.
41    TopLeft,
42    /// Top-right corner.
43    #[default]
44    TopRight,
45    /// Bottom-left corner.
46    BottomLeft,
47    /// Bottom-right corner.
48    BottomRight,
49}
50
51/// One named data series of `(x, y)` points.
52#[derive(Debug, Clone, Default)]
53pub struct Series {
54    pub(crate) name: String,
55    pub(crate) data: Vec<(f64, f64)>,
56    pub(crate) color: Option<Color>,
57    pub(crate) mode: Option<LineMode>,
58    pub(crate) y_err: Vec<f64>,
59    pub(crate) band: Vec<(f64, f64)>,
60    pub(crate) smooth: bool,
61    pub(crate) secondary: bool,
62    pub(crate) fill_gradient: Option<Gradient>,
63}
64
65impl Series {
66    /// New empty series with a legend name.
67    pub fn new(name: impl Into<String>) -> Self {
68        Self {
69            name: name.into(),
70            ..Default::default()
71        }
72    }
73
74    /// Set the `(x, y)` data.
75    pub fn data(mut self, data: impl IntoIterator<Item = (f64, f64)>) -> Self {
76        self.data = data.into_iter().collect();
77        self
78    }
79
80    /// Plot values with x = 0, 1, 2, …
81    pub fn values(mut self, values: impl IntoIterator<Item = f64>) -> Self {
82        self.data = values
83            .into_iter()
84            .enumerate()
85            .map(|(i, v)| (i as f64, v))
86            .collect();
87        self
88    }
89
90    opt_setter!(
91        /// Series color (default: palette by index).
92        color: Color
93    );
94
95    opt_setter!(
96        /// Color an `Area` fill by value (bottom = low, top = high) instead of one flat color.
97        fill_gradient: Gradient
98    );
99
100    opt_setter!(
101        /// Override the chart's draw mode for this series.
102        mode: LineMode
103    );
104
105    /// Symmetric error bars: `y ± err[i]` for point `i`.
106    pub fn y_err(mut self, err: impl IntoIterator<Item = f64>) -> Self {
107        self.y_err = err.into_iter().collect();
108        self
109    }
110
111    /// Confidence band: `(lo, hi)` y-values for point `i`, shaded around the line.
112    pub fn band(mut self, band: impl IntoIterator<Item = (f64, f64)>) -> Self {
113        self.band = band.into_iter().collect();
114        self
115    }
116
117    setter!(
118        /// Smooth the line with Catmull-Rom spline interpolation (Line/Area modes).
119        smooth: bool
120    );
121
122    setter!(
123        /// Plot against the secondary (right) y axis.
124        secondary_axis => secondary: bool
125    );
126
127    /// Series name.
128    pub fn name(&self) -> &str {
129        &self.name
130    }
131
132    /// Number of points.
133    pub fn len(&self) -> usize {
134        self.data.len()
135    }
136
137    /// True if the series has no points.
138    pub fn is_empty(&self) -> bool {
139        self.data.is_empty()
140    }
141
142    /// All finite y extents (points, error bars, band edges).
143    fn y_values(&self) -> impl Iterator<Item = f64> + '_ {
144        self.data
145            .iter()
146            .enumerate()
147            .filter(|(_, (x, y))| x.is_finite() && y.is_finite())
148            .flat_map(|(i, &(_, y))| {
149                let mut v = vec![y];
150                if let Some(e) = self.y_err.get(i).filter(|e| e.is_finite()) {
151                    v.push(y - e.abs());
152                    v.push(y + e.abs());
153                }
154                if let Some(&(lo, hi)) = self.band.get(i) {
155                    v.push(lo);
156                    v.push(hi);
157                }
158                v
159            })
160            .filter(|v| v.is_finite())
161    }
162}
163
164/// Linear or log10 value → 0..=1 fraction mapping.
165#[derive(Debug, Clone, Copy)]
166struct Scale {
167    lo: f64,
168    hi: f64,
169    log: bool,
170}
171
172impl Scale {
173    fn frac(&self, v: f64) -> Option<f64> {
174        if !v.is_finite() {
175            return None;
176        }
177        if self.log {
178            if v <= 0.0 || self.lo <= 0.0 {
179                return None;
180            }
181            let (l0, l1) = (self.lo.log10(), self.hi.log10());
182            Some((v.log10() - l0) / (l1 - l0))
183        } else {
184            Some((v - self.lo) / (self.hi - self.lo))
185        }
186    }
187}
188
189/// Decade-aligned bounds from a raw positive range.
190fn log_bounds(raw: Option<(f64, f64)>) -> (f64, f64) {
191    match raw {
192        None => (1.0, 10.0),
193        Some((a, b)) => {
194            let lo = 10f64.powf(a.log10().floor());
195            let mut hi = 10f64.powf(b.log10().ceil());
196            if hi <= lo {
197                hi = lo * 10.0;
198            }
199            (lo, hi)
200        }
201    }
202}
203
204fn decade_label(k: i32) -> String {
205    if (0..=5).contains(&k) {
206        format!("{}", 10u64.pow(k as u32))
207    } else if (-3..0).contains(&k) {
208        let v = 10f64.powi(k);
209        format_tick(v, v)
210    } else {
211        format!("1e{k}")
212    }
213}
214
215/// Multi-series line / step / area / scatter chart with sub-cell resolution.
216#[derive(Debug, Clone, Default)]
217pub struct LineChart {
218    series: Vec<Series>,
219    x_axis: Axis,
220    y_axis: Axis,
221    y2_axis: Axis,
222    y_log: bool,
223    smooth: bool,
224    annotations: Vec<Annotation>,
225    crosshair: Option<Crosshair>,
226    block: Option<Block<'static>>,
227    marker: Marker,
228    mode: LineMode,
229    legend: LegendPosition,
230    legend_style: Option<Style>,
231    theme: Option<Theme>,
232    style: Option<Style>,
233}
234
235impl LineChart {
236    /// Create a chart from series.
237    pub fn new(series: Vec<Series>) -> Self {
238        Self {
239            series,
240            ..Default::default()
241        }
242    }
243
244    setter!(
245        /// Replace the series.
246        series: Vec<Series>
247    );
248
249    /// X axis configuration.
250    pub fn x_axis(mut self, axis: Axis) -> Self {
251        self.x_axis = axis;
252        if let Some(t) = &self.theme {
253            self.x_axis.theme_in_place(t);
254        }
255        self
256    }
257
258    /// Y axis configuration.
259    pub fn y_axis(mut self, axis: Axis) -> Self {
260        self.y_axis = axis;
261        if let Some(t) = &self.theme {
262            self.y_axis.theme_in_place(t);
263        }
264        self
265    }
266
267    /// Secondary (right) y axis configuration, used by `secondary_axis(true)` series.
268    pub fn y2_axis(mut self, axis: Axis) -> Self {
269        self.y2_axis = axis;
270        if let Some(t) = &self.theme {
271            self.y2_axis.theme_in_place(t);
272        }
273        self
274    }
275
276    setter!(
277        /// Logarithmic (base 10) primary y axis with decade ticks. Non-positive
278        /// values are not drawn.
279        y_log: bool
280    );
281
282    setter!(
283        /// Smooth all Line/Area series with Catmull-Rom splines.
284        smooth: bool
285    );
286
287    /// Add an annotation (reference line, region or label).
288    pub fn annotation(mut self, annotation: Annotation) -> Self {
289        self.annotations.push(annotation);
290        self
291    }
292
293    setter!(
294        /// Set (or clear) the crosshair cursor.
295        crosshair: Option<Crosshair>
296    );
297
298    block_setter!(block, 'static);
299
300    setter!(
301        /// Glyph family (default braille).
302        marker: Marker
303    );
304
305    setter!(
306        /// Default draw mode for all series.
307        mode: LineMode
308    );
309
310    /// Apply a [`Theme`]: axis/grid/border colors, background fill and the series
311    /// palette. Explicit series colors and explicitly styled axes still win.
312    #[cfg(feature = "theme")]
313    pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
314        let t = theme.into();
315        self.x_axis.theme_in_place(&t);
316        self.y_axis.theme_in_place(&t);
317        self.y2_axis.theme_in_place(&t);
318        self.theme = Some(t);
319        self
320    }
321
322    base_style_setter!(style);
323
324    opt_setter!(
325        /// Style of legend entry text (default: theme muted color / gray).
326        legend_style: Style
327    );
328
329    fn series_color(&self, i: usize, s: &Series) -> Color {
330        s.color.unwrap_or_else(|| match &self.theme {
331            Some(t) => t.color(i),
332            None => PALETTE[i % PALETTE.len()],
333        })
334    }
335
336    setter!(
337        /// Legend placement.
338        legend: LegendPosition
339    );
340
341    fn has_secondary(&self) -> bool {
342        self.series.iter().any(|s| s.secondary && !s.is_empty())
343    }
344
345    /// Raw `(min, max)` of y values of primary or secondary series.
346    fn y_range(&self, secondary: bool, positive_only: bool) -> Option<(f64, f64)> {
347        let mut r: Option<(f64, f64)> = None;
348        for v in self
349            .series
350            .iter()
351            .filter(|s| s.secondary == secondary)
352            .flat_map(|s| s.y_values())
353            .filter(|v| !positive_only || *v > 0.0)
354        {
355            r = Some(r.map_or((v, v), |(a, b)| (a.min(v), b.max(v))));
356        }
357        r
358    }
359
360    /// Resolved `(x_bounds, y_bounds)` (primary axis, data coordinates).
361    pub fn bounds(&self) -> ((f64, f64), (f64, f64)) {
362        let mut xs = (f64::INFINITY, f64::NEG_INFINITY);
363        for &(x, _) in self
364            .series
365            .iter()
366            .flat_map(|s| s.data.iter())
367            .filter(|(x, y)| x.is_finite() && y.is_finite())
368        {
369            xs = (xs.0.min(x), xs.1.max(x));
370        }
371        let x = self.x_axis.bounds.unwrap_or_else(|| {
372            if xs.0.is_finite() {
373                if xs.1 <= xs.0 {
374                    (xs.0 - 1.0, xs.1 + 1.0)
375                } else {
376                    xs
377                }
378            } else {
379                (0.0, 1.0)
380            }
381        });
382        let y = if self.y_log {
383            match self.y_axis.bounds {
384                Some((a, b)) if a > 0.0 && b > a => (a, b),
385                _ => log_bounds(self.y_range(false, true)),
386            }
387        } else {
388            self.y_axis.bounds.unwrap_or_else(|| {
389                self.y_range(false, false)
390                    .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y_axis.ticks))
391            })
392        };
393        (x, y)
394    }
395
396    /// Bounds of the secondary y axis, or `None` when no series uses it.
397    pub fn y2_bounds(&self) -> Option<(f64, f64)> {
398        if !self.has_secondary() {
399            return None;
400        }
401        Some(self.y2_axis.bounds.unwrap_or_else(|| {
402            self.y_range(true, false)
403                .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y2_axis.ticks))
404        }))
405    }
406
407    fn scales(&self) -> (Scale, Scale, Option<Scale>) {
408        let (xb, yb) = self.bounds();
409        (
410            Scale {
411                lo: xb.0,
412                hi: xb.1,
413                log: false,
414            },
415            Scale {
416                lo: yb.0,
417                hi: yb.1,
418                log: self.y_log,
419            },
420            self.y2_bounds().map(|b| Scale {
421                lo: b.0,
422                hi: b.1,
423                log: false,
424            }),
425        )
426    }
427
428    /// Data point (over all series) closest to data position `(x, y)`, measured
429    /// in plot-fraction space so both axes weigh equally. `y` is in primary-axis
430    /// units; secondary series are compared by their position on the plot.
431    pub fn nearest(&self, x: f64, y: f64) -> Option<NearestPoint> {
432        let (sx, sy, sy2) = self.scales();
433        let target = (sx.frac(x)?, sy.frac(y)?);
434        let mut best: Option<(f64, NearestPoint)> = None;
435        for (si, s) in self.series.iter().enumerate() {
436            let ys = if s.secondary { sy2.unwrap_or(sy) } else { sy };
437            let pts = s
438                .data
439                .iter()
440                .map(|&(px, py)| match (sx.frac(px), ys.frac(py)) {
441                    (Some(a), Some(b)) => (a, b),
442                    _ => (f64::NAN, f64::NAN),
443                });
444            if let Some((i, d)) = nearest_point(pts, target, (1.0, 1.0)) {
445                if best.is_none_or(|(bd, _)| d < bd) {
446                    let (px, py) = s.data[i];
447                    best = Some((
448                        d,
449                        NearestPoint {
450                            series: si,
451                            index: i,
452                            x: px,
453                            y: py,
454                        },
455                    ));
456                }
457            }
458        }
459        best.map(|b| b.1)
460    }
461
462    fn y_marks(&self, b: (f64, f64)) -> Vec<(f64, String)> {
463        if !self.y_log || self.y_axis.labels.is_some() {
464            return self.y_axis.tick_marks(b);
465        }
466        let (l0, l1) = (b.0.log10(), b.1.log10());
467        if l1.is_nan() || l1 <= l0 {
468            return vec![];
469        }
470        let (k0, k1) = ((l0 - 1e-9).ceil() as i32, (l1 + 1e-9).floor() as i32);
471        let n = (i64::from(k1) - i64::from(k0) + 1).max(0) as usize;
472        let stride = n.div_ceil(self.y_axis.ticks.max(2)).max(1);
473        (k0..=k1)
474            .step_by(stride)
475            .map(|k| {
476                let label = match self.y_axis.format(10f64.powi(k)) {
477                    Some(l) => l,
478                    None => decade_label(k),
479                };
480                (f64::from(k) - l0, label)
481            })
482            .map(|(d, l)| (d / (l1 - l0), l))
483            .collect()
484    }
485
486    fn render_inner(&self, area: Rect, buf: &mut Buffer) {
487        let inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
488        let (xb, yb) = self.bounds();
489        if xb.1 <= xb.0 || yb.1 <= yb.0 {
490            return;
491        }
492        let (sx, sy, sy2) = self.scales();
493        let y_marks = self.y_marks(yb);
494        let x_marks = self.x_axis.tick_marks(xb);
495        let y2_marks = match (&sy2, self.y2_bounds()) {
496            (Some(_), Some(b)) if b.1 > b.0 => self.y2_axis.tick_marks(b),
497            _ => vec![],
498        };
499        let y2_reserve = if sy2.is_some() {
500            y2_marks
501                .iter()
502                .map(|(_, l)| text_width(l))
503                .max()
504                .unwrap_or(0)
505                + 1
506        } else {
507            0
508        };
509        let inner = Rect {
510            width: inner.width.saturating_sub(y2_reserve),
511            ..inner
512        };
513        let yw = y_marks
514            .iter()
515            .map(|(_, l)| text_width(l))
516            .max()
517            .unwrap_or(0);
518        let Some(a) = layout::compute(
519            inner,
520            yw,
521            !x_marks.is_empty(),
522            self.x_axis.title.is_some(),
523            self.y_axis.title.is_some(),
524        ) else {
525            return;
526        };
527        let (rx, ry) = self.marker.resolution();
528        let plot = a.plot;
529        let y_ticks: Vec<(u16, String)> = y_marks
530            .iter()
531            .map(|(f, l)| (layout::frac_row(*f, plot.height, ry), l.clone()))
532            .collect();
533        let x_ticks: Vec<(u16, String)> = x_marks
534            .iter()
535            .map(|(f, l)| (layout::frac_col(*f, plot.width, rx), l.clone()))
536            .collect();
537
538        let grid_rows: Vec<u16> = if self.y_axis.grid {
539            y_ticks.iter().map(|t| t.0).collect()
540        } else {
541            vec![]
542        };
543        let grid_cols: Vec<u16> = if self.x_axis.grid {
544            x_ticks.iter().map(|t| t.0).collect()
545        } else {
546            vec![]
547        };
548        layout::draw_grid(
549            buf,
550            plot,
551            &grid_cols,
552            &grid_rows,
553            self.x_axis.grid_style,
554            self.x_axis.grid_kind,
555        );
556
557        // cell mappings relative to the plot (unclamped, may be outside)
558        let clampi = |v: f64| v.round().clamp(-20_000.0, 20_000.0) as i32;
559        let (nw, nh) = (
560            (plot.width as f64 * rx as f64 - 1.0).max(0.0),
561            (plot.height as f64 * ry as f64 - 1.0).max(0.0),
562        );
563        let x_cell = |x: f64| sx.frac(x).map(|f| clampi(f * nw).div_euclid(rx as i32));
564        let y_cell = |y: f64| {
565            sy.frac(y)
566                .map(|f| clampi((1.0 - f) * nh).div_euclid(ry as i32))
567        };
568        draw_annotations(buf, plot, &self.annotations, &x_cell, &y_cell);
569
570        let mut canvas = Canvas::new(plot.width, plot.height, self.marker);
571        let (pw, ph) = (canvas.px_w(), canvas.px_h());
572        let proj = |x: f64, y: f64, sec: bool| -> Option<(i32, i32)> {
573            let ys = if sec { sy2.as_ref()? } else { &sy };
574            let (fx, fy) = (sx.frac(x)?, ys.frac(y)?);
575            Some((
576                clampi(fx * (pw - 1) as f64),
577                clampi((1.0 - fy) * (ph - 1) as f64),
578            ))
579        };
580        for (i, s) in self.series.iter().enumerate() {
581            let color = self.series_color(i, s);
582            let mode = s.mode.unwrap_or(self.mode);
583            let sec = s.secondary && sy2.is_some();
584            let mut pts: Vec<(i32, i32)> = Vec::with_capacity(s.data.len());
585            let mut band: Vec<(i32, i32, i32)> = Vec::new();
586            for (k, &(x, y)) in s.data.iter().enumerate() {
587                if !x.is_finite() || !y.is_finite() {
588                    continue;
589                }
590                let Some(p) = proj(x, y, sec) else { continue };
591                pts.push(p);
592                if let Some(&(lo, hi)) = s.band.get(k) {
593                    let lo_p = proj(x, lo, sec).map_or(ph - 1, |q| q.1);
594                    let hi_p = proj(x, hi, sec).map_or(ph - 1, |q| q.1);
595                    band.push((p.0, lo_p, hi_p));
596                }
597                if let Some(e) = s.y_err.get(k).filter(|e| e.is_finite()) {
598                    let e = e.abs();
599                    let lo_p = proj(x, y - e, sec).map_or(ph - 1, |q| q.1);
600                    let hi_p = proj(x, y + e, sec).map_or(ph - 1, |q| q.1);
601                    canvas.line(p.0, lo_p, p.0, hi_p, color);
602                    canvas.line(p.0 - 2, lo_p, p.0 + 2, lo_p, color);
603                    canvas.line(p.0 - 2, hi_p, p.0 + 2, hi_p, color);
604                }
605            }
606            fill_band(&mut canvas, &band, color);
607            if (s.smooth || self.smooth) && matches!(mode, LineMode::Line | LineMode::Area) {
608                pts = catmull_rom(&pts);
609            }
610            if mode != LineMode::Scatter && pts.len() > canvas.px_w() as usize * 4 {
611                pts = decimate(&pts);
612            }
613            draw_series(&mut canvas, &pts, mode, color, s.fill_gradient.as_ref());
614        }
615        canvas.render(buf, plot);
616
617        if let Some(ch) = &self.crosshair {
618            if let (Some(c), Some(r)) = (x_cell(ch.x), y_cell(ch.y)) {
619                let themed = self.theme.as_ref().map(|t| ch.with_theme(t));
620                let ch = themed.as_ref().unwrap_or(ch);
621                crosshair::draw(buf, plot, ch, c, r, &self.tooltip_lines(ch));
622            }
623        }
624
625        layout::draw_axes(buf, &a, self.x_axis.style, self.y_axis.style);
626        layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.y_axis.label_style);
627        layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.x_axis.label_style);
628        if y2_reserve > 0 {
629            for y in plot.y..a.axis_row {
630                buf.set_string(plot.right(), y, "│", self.y2_axis.style);
631            }
632            buf.set_string(plot.right(), a.axis_row, "┘", self.x_axis.style);
633            let mut last: Option<u16> = None;
634            for (f, label) in &y2_marks {
635                let row = layout::frac_row(*f, plot.height, ry);
636                if last == Some(row) {
637                    continue;
638                }
639                last = Some(row);
640                buf.set_stringn(
641                    plot.right() + 1,
642                    plot.y + row,
643                    label,
644                    (y2_reserve - 1) as usize,
645                    self.y2_axis.label_style,
646                );
647            }
648        }
649        layout::draw_titles(
650            buf,
651            inner,
652            &a,
653            self.x_axis
654                .title
655                .as_deref()
656                .map(|t| (t, self.x_axis.label_style)),
657            self.y_axis
658                .title
659                .as_deref()
660                .map(|t| (t, self.y_axis.label_style)),
661        );
662        self.draw_legend(buf, plot);
663    }
664
665    fn tooltip_lines(&self, ch: &Crosshair) -> Vec<String> {
666        let mut lines = vec![
667            format!("x {}", format_compact(ch.x)),
668            format!("y {}", format_compact(ch.y)),
669        ];
670        for s in self.series.iter().filter(|s| !s.name.is_empty()) {
671            if let Some((i, _)) =
672                nearest_point(s.data.iter().copied(), (ch.x, 0.0), (1.0, f64::INFINITY))
673            {
674                lines.push(format!("{} {}", s.name, format_compact(s.data[i].1)));
675            }
676        }
677        lines
678    }
679
680    fn draw_legend(&self, buf: &mut Buffer, plot: Rect) {
681        if self.legend == LegendPosition::None {
682            return;
683        }
684        let entries: Vec<(&str, Color)> = self
685            .series
686            .iter()
687            .enumerate()
688            .filter(|(_, s)| !s.name.is_empty())
689            .map(|(i, s)| (s.name.as_str(), self.series_color(i, s)))
690            .collect();
691        let w = entries
692            .iter()
693            .map(|(n, _)| text_width(n) + 2)
694            .max()
695            .unwrap_or(0);
696        if w == 0 || w > plot.width {
697            return;
698        }
699        let x = match self.legend {
700            LegendPosition::TopLeft | LegendPosition::BottomLeft => plot.x,
701            _ => plot.right() - w,
702        };
703        let label = self.legend_style.unwrap_or_else(|| {
704            Style::default().fg(self.theme.as_ref().map_or(Color::Gray, |t| t.muted))
705        });
706        for (i, (name, color)) in entries.iter().enumerate() {
707            let row = i as u16;
708            if row >= plot.height {
709                break;
710            }
711            let y = match self.legend {
712                LegendPosition::BottomLeft | LegendPosition::BottomRight => {
713                    plot.bottom() - 1 - (entries.len() as u16 - 1 - row).min(plot.height - 1)
714                }
715                _ => plot.y + row,
716            };
717            buf.set_string(x, y, "●", Style::default().fg(*color));
718            buf.set_string(x + 2, y, name, label);
719        }
720    }
721}
722
723/// Catmull-Rom spline through `pts` (pixel space), densified for line drawing.
724fn catmull_rom(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
725    if pts.len() < 3 {
726        return pts.to_vec();
727    }
728    let n = pts.len();
729    let mut out = Vec::with_capacity(n * 4);
730    for i in 0..n - 1 {
731        let p0 = pts[i.saturating_sub(1)];
732        let (p1, p2) = (pts[i], pts[i + 1]);
733        let p3 = pts[(i + 2).min(n - 1)];
734        out.push(p1);
735        let span = (p2.0 - p1.0).abs().max((p2.1 - p1.1).abs());
736        let steps = (span / 2).clamp(1, 64);
737        for k in 1..steps {
738            let t = k as f64 / steps as f64;
739            let (t2, t3) = (t * t, t * t * t);
740            let f = |a: i32, b: i32, c: i32, d: i32| {
741                let (a, b, c, d) = (a as f64, b as f64, c as f64, d as f64);
742                (0.5 * (2.0 * b
743                    + (c - a) * t
744                    + (2.0 * a - 5.0 * b + 4.0 * c - d) * t2
745                    + (3.0 * b - a - 3.0 * c + d) * t3))
746                    .round()
747                    .clamp(-20_000.0, 20_000.0) as i32
748            };
749            out.push((f(p0.0, p1.0, p2.0, p3.0), f(p0.1, p1.1, p2.1, p3.1)));
750        }
751    }
752    out.push(pts[n - 1]);
753    out
754}
755
756/// Dotted shading between `(px, lo_py, hi_py)` samples.
757fn fill_band(canvas: &mut Canvas, band: &[(i32, i32, i32)], color: Color) {
758    let (pw, ph) = (canvas.px_w(), canvas.px_h());
759    let column = |px: i32, a: i32, b: i32, canvas: &mut Canvas| {
760        if !(0..pw).contains(&px) {
761            return;
762        }
763        for py in a.min(b).max(0)..=a.max(b).min(ph - 1) {
764            if (px + py) % 2 == 0 {
765                canvas.set(px, py, color);
766            }
767        }
768    };
769    if band.len() == 1 {
770        column(band[0].0, band[0].1, band[0].2, canvas);
771    }
772    for w in band.windows(2) {
773        let (l, r) = if w[0].0 <= w[1].0 {
774            (w[0], w[1])
775        } else {
776            (w[1], w[0])
777        };
778        for px in l.0.max(0)..=r.0.min(pw - 1) {
779            let t = if r.0 == l.0 {
780                0.0
781            } else {
782                (px - l.0) as f64 / (r.0 - l.0) as f64
783            };
784            let lerp = |a: i32, b: i32| (a as f64 + t * (b - a) as f64).round() as i32;
785            column(px, lerp(l.1, r.1), lerp(l.2, r.2), canvas);
786        }
787    }
788}
789
790/// Collapse x-sorted points to at most 4 per pixel column (first, min, max,
791/// last, in original order), which draws the same pixels as the full series
792/// but with far fewer segments/fills. Unsorted input is returned unchanged.
793fn decimate(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
794    if pts.windows(2).any(|w| w[1].0 < w[0].0) {
795        return pts.to_vec();
796    }
797    let mut out = Vec::with_capacity(pts.len() / 8 + 8);
798    let mut i = 0;
799    while i < pts.len() {
800        let x = pts[i].0;
801        let mut j = i;
802        let (mut lo, mut hi) = (i, i);
803        while j < pts.len() && pts[j].0 == x {
804            if pts[j].1 < pts[lo].1 {
805                lo = j;
806            }
807            if pts[j].1 > pts[hi].1 {
808                hi = j;
809            }
810            j += 1;
811        }
812        let mut keep = [i, lo, hi, j - 1];
813        keep.sort_unstable();
814        let mut last = usize::MAX;
815        for k in keep {
816            if k != last {
817                out.push(pts[k]);
818                last = k;
819            }
820        }
821        i = j;
822    }
823    out
824}
825
826fn draw_series(
827    canvas: &mut Canvas,
828    pts: &[(i32, i32)],
829    mode: LineMode,
830    color: Color,
831    grad: Option<&Gradient>,
832) {
833    let bottom = canvas.px_h() - 1;
834    match mode {
835        LineMode::Scatter => {
836            for &(x, y) in pts {
837                canvas.blob(x, y, color);
838            }
839        }
840        LineMode::Line | LineMode::Area | LineMode::Step => {
841            if mode == LineMode::Area {
842                for w in pts.windows(2) {
843                    fill_segment(canvas, w[0], w[1], bottom, color, grad);
844                }
845            }
846            if pts.len() == 1 {
847                canvas.set(pts[0].0, pts[0].1, color);
848            }
849            for w in pts.windows(2) {
850                let ((x0, y0), (x1, y1)) = (w[0], w[1]);
851                if mode == LineMode::Step {
852                    canvas.line(x0, y0, x1, y0, color);
853                    canvas.line(x1, y0, x1, y1, color);
854                } else {
855                    canvas.line(x0, y0, x1, y1, color);
856                }
857            }
858        }
859    }
860}
861
862fn fill_segment(
863    canvas: &mut Canvas,
864    a: (i32, i32),
865    b: (i32, i32),
866    bottom: i32,
867    color: Color,
868    grad: Option<&Gradient>,
869) {
870    let (lo, hi) = if a.0 <= b.0 { (a, b) } else { (b, a) };
871    let start = lo.0.max(0);
872    let end = hi.0.min(canvas.px_w() - 1);
873    // stipple (every other dot) only where a cell has >1 dot per axis
874    let (rx, ry) = canvas.marker().resolution();
875    let (sx, sy) = (if rx > 1 { 2 } else { 1 }, if ry > 1 { 2 } else { 1 });
876    for px in start..=end {
877        let t = if hi.0 == lo.0 {
878            0.0
879        } else {
880            (px - lo.0) as f64 / (hi.0 - lo.0) as f64
881        };
882        let py = (lo.1 as f64 + t * (hi.1 - lo.1) as f64).round() as i32;
883        for yy in py.max(0)..=bottom {
884            if px % sx == 0 && yy % sy == 0 {
885                let c = match grad {
886                    Some(g) if bottom > 0 => g.color_at((bottom - yy) as f64 / bottom as f64),
887                    _ => color,
888                };
889                canvas.set(px, yy, c);
890            }
891        }
892    }
893}
894
895impl LineChart {
896    fn render_into(&self, area: Rect, buf: &mut Buffer) {
897        self.render_inner(area, buf);
898    }
899}
900
901widget_impls!(LineChart);
902
903#[cfg(feature = "theme")]
904impl tui_nuances::Themed for LineChart {
905    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
906        self.theme(theme)
907    }
908}
909
910#[cfg(test)]
911mod tests {
912    use super::*;
913    use ratatui::widgets::Widget;
914
915    fn chart() -> LineChart {
916        LineChart::new(vec![
917            Series::new("a").values([1.0, 3.0, 2.0, 5.0]),
918            Series::new("b").data([(0.0, 0.0), (3.0, 4.0)]),
919        ])
920    }
921
922    #[test]
923    fn bounds_auto() {
924        let ((x0, x1), (y0, y1)) = chart().bounds();
925        assert_eq!((x0, x1), (0.0, 3.0));
926        assert!(y0 <= 0.0 && y1 >= 5.0);
927    }
928
929    #[test]
930    fn bounds_fixed_and_empty() {
931        let c = LineChart::default().x_axis(Axis::new().bounds(2.0, 4.0));
932        assert_eq!(c.bounds().0, (2.0, 4.0));
933        assert_eq!(c.bounds().1, (0.0, 1.0));
934    }
935
936    #[test]
937    fn bounds_single_point_padded() {
938        let c = LineChart::new(vec![Series::new("p").data([(1.0, 1.0)])]);
939        let ((x0, x1), (y0, y1)) = c.bounds();
940        assert!(x1 > x0 && y1 > y0);
941    }
942
943    #[test]
944    fn nan_points_ignored() {
945        let c = LineChart::new(vec![Series::new("p").data([
946            (f64::NAN, 1.0),
947            (1.0, 2.0),
948            (2.0, 4.0),
949        ])]);
950        assert_eq!(c.bounds().0, (1.0, 2.0));
951    }
952
953    #[test]
954    fn series_helpers() {
955        let s = Series::new("x")
956            .values([1.0, 2.0])
957            .color(Color::Red)
958            .mode(LineMode::Step);
959        assert_eq!(s.name(), "x");
960        assert_eq!(s.len(), 2);
961        assert!(!s.is_empty());
962        assert!(Series::new("e").is_empty());
963    }
964
965    #[test]
966    fn renders_without_panic_all_modes() {
967        for mode in [
968            LineMode::Line,
969            LineMode::Step,
970            LineMode::Area,
971            LineMode::Scatter,
972        ] {
973            for marker in [
974                Marker::Braille,
975                Marker::HalfBlock,
976                Marker::Block,
977                Marker::Dot,
978            ] {
979                let area = Rect::new(0, 0, 50, 14);
980                let mut buf = Buffer::empty(area);
981                chart()
982                    .mode(mode)
983                    .marker(marker)
984                    .x_axis(Axis::new().title("x").grid(true))
985                    .y_axis(Axis::new().title("y").grid(true))
986                    .block(Block::bordered().title("t"))
987                    .render(area, &mut buf);
988            }
989        }
990    }
991
992    #[test]
993    fn tiny_area_is_safe() {
994        for (w, h) in [(0, 0), (1, 1), (5, 3), (9, 4)] {
995            let area = Rect::new(0, 0, w, h);
996            let mut buf = Buffer::empty(area);
997            chart().render(area, &mut buf);
998        }
999    }
1000
1001    #[test]
1002    fn draws_data_and_legend() {
1003        let area = Rect::new(0, 0, 40, 12);
1004        let mut buf = Buffer::empty(area);
1005        chart().render(area, &mut buf);
1006        let text: String = (0..12)
1007            .flat_map(|y| (0..40).map(move |x| (x, y)))
1008            .map(|p| buf[p].symbol().to_string())
1009            .collect();
1010        assert!(text.chars().any(|c| ('\u{2801}'..='\u{28ff}').contains(&c)));
1011        assert!(text.contains('●'));
1012        assert!(text.contains('└'));
1013    }
1014
1015    #[test]
1016    fn legend_none_hides() {
1017        let area = Rect::new(0, 0, 40, 12);
1018        let mut buf = Buffer::empty(area);
1019        chart().legend(LegendPosition::None).render(area, &mut buf);
1020        let text: String = (0..12)
1021            .flat_map(|y| (0..40).map(move |x| (x, y)))
1022            .map(|p| buf[p].symbol().to_string())
1023            .collect();
1024        assert!(!text.contains('●'));
1025    }
1026
1027    fn text_of(buf: &Buffer, w: u16, h: u16) -> String {
1028        (0..h)
1029            .flat_map(|y| (0..w).map(move |x| (x, y)))
1030            .map(|p| buf[p].symbol().to_string())
1031            .collect()
1032    }
1033
1034    #[test]
1035    fn log_bounds_decades_and_labels() {
1036        let c = LineChart::new(vec![Series::new("a").data([
1037            (0.0, 3.0),
1038            (1.0, 4500.0),
1039            (2.0, -1.0),
1040        ])])
1041        .y_log(true);
1042        assert_eq!(c.bounds().1, (1.0, 10_000.0));
1043        let m = c.y_marks((1.0, 10_000.0));
1044        assert_eq!(m.first().unwrap().1, "1");
1045        assert_eq!(m.last().unwrap().1, "10000");
1046        assert!((m[2].0 - 0.5).abs() < 1e-9);
1047        assert_eq!(LineChart::default().y_log(true).bounds().1, (1.0, 10.0));
1048    }
1049
1050    #[test]
1051    fn secondary_axis_bounds_and_render() {
1052        let c = LineChart::new(vec![
1053            Series::new("a").values([1.0, 2.0]),
1054            Series::new("b").values([100.0, 900.0]).secondary_axis(true),
1055        ]);
1056        assert!(c.bounds().1 .1 < 10.0);
1057        let b2 = c.y2_bounds().unwrap();
1058        assert!(b2.1 >= 900.0);
1059        let area = Rect::new(0, 0, 40, 10);
1060        let mut buf = Buffer::empty(area);
1061        c.render(area, &mut buf);
1062        assert!(text_of(&buf, 40, 10).contains('┘'));
1063        assert!(LineChart::default().y2_bounds().is_none());
1064    }
1065
1066    #[test]
1067    fn err_band_extend_bounds() {
1068        let c = LineChart::new(vec![Series::new("a")
1069            .values([1.0, 2.0])
1070            .y_err([10.0, 10.0])]);
1071        assert!(c.bounds().1 .1 >= 12.0);
1072        let c = LineChart::new(vec![Series::new("a")
1073            .values([1.0, 2.0])
1074            .band([(-5.0, 1.0), (0.0, 3.0)])]);
1075        assert!(c.bounds().1 .0 <= -5.0);
1076    }
1077
1078    #[test]
1079    fn catmull_densifies() {
1080        let p = catmull_rom(&[(0, 0), (20, 10), (40, 0), (60, 10)]);
1081        assert!(p.len() > 4);
1082        assert_eq!(p[0], (0, 0));
1083        assert_eq!(*p.last().unwrap(), (60, 10));
1084        assert_eq!(catmull_rom(&[(1, 1)]), vec![(1, 1)]);
1085    }
1086
1087    #[test]
1088    fn nearest_finds_point() {
1089        let n = chart().nearest(3.0, 4.0).unwrap();
1090        assert_eq!((n.series, n.index), (1, 1));
1091        assert!(LineChart::default().nearest(0.0, 0.0).is_none());
1092    }
1093
1094    #[test]
1095    fn features_render_safely_everywhere() {
1096        let c = LineChart::new(vec![
1097            Series::new("a")
1098                .values([1.0, 0.0, f64::NAN, 5.0])
1099                .y_err([0.5, f64::NAN, 1.0])
1100                .smooth(true),
1101            Series::new("b")
1102                .values([10.0, 20.0, 5.0])
1103                .band([(1.0, 30.0), (2.0, 40.0), (0.0, 9.0)])
1104                .secondary_axis(true),
1105        ])
1106        .y_log(true)
1107        .annotation(Annotation::hline(2.0).text("lim"))
1108        .annotation(Annotation::x_region(0.5, 1.5))
1109        .crosshair(Some(Crosshair::new(1.0, 2.0)));
1110        for (w, h) in [(0, 0), (1, 1), (5, 3), (12, 6), (60, 20)] {
1111            let area = Rect::new(0, 0, w, h);
1112            let mut buf = Buffer::empty(area);
1113            (&c).render(area, &mut buf);
1114        }
1115    }
1116
1117    #[test]
1118    fn crosshair_draws_tooltip() {
1119        let area = Rect::new(0, 0, 50, 16);
1120        let mut buf = Buffer::empty(area);
1121        chart()
1122            .crosshair(Some(Crosshair::new(1.0, 2.0)))
1123            .render(area, &mut buf);
1124        let t = text_of(&buf, 50, 16);
1125        assert!(t.contains('┼'));
1126        assert!(t.contains("x 1"));
1127    }
1128
1129    #[cfg(feature = "theme")]
1130    #[test]
1131    fn crosshair_uses_theme_colors() {
1132        let th = Theme::dracula();
1133        let area = Rect::new(0, 0, 50, 16);
1134        let mut buf = Buffer::empty(area);
1135        chart()
1136            .theme(&th)
1137            .crosshair(Some(Crosshair::new(1.0, 2.0)))
1138            .render(area, &mut buf);
1139        assert!(buf
1140            .content()
1141            .iter()
1142            .any(|c| c.symbol() == "┼" && c.fg == th.crosshair));
1143        let mut buf = Buffer::empty(area);
1144        let own = Style::default().fg(Color::Red);
1145        chart()
1146            .theme(&th)
1147            .crosshair(Some(Crosshair::new(1.0, 2.0).style(own)))
1148            .render(area, &mut buf);
1149        assert!(buf
1150            .content()
1151            .iter()
1152            .any(|c| c.symbol() == "┼" && c.fg == Color::Red));
1153    }
1154
1155    #[test]
1156    fn decimate_keeps_extremes_and_order() {
1157        let pts = vec![(0, 5), (0, 1), (0, 9), (0, 4), (1, 2), (2, 3)];
1158        let d = decimate(&pts);
1159        assert_eq!(d, vec![(0, 5), (0, 1), (0, 9), (0, 4), (1, 2), (2, 3)]);
1160        let unsorted = vec![(3, 1), (1, 1)];
1161        assert_eq!(decimate(&unsorted), unsorted);
1162    }
1163}