Skip to main content

ftui_widgets/
sparkline.rs

1#![forbid(unsafe_code)]
2
3//! Sparkline widget for compact trend visualization.
4//!
5//! Sparklines render data as a series of 8-level Unicode block characters
6//! (▁▂▃▄▅▆▇█) for visualizing trends in minimal space.
7//!
8//! # Example
9//!
10//! ```ignore
11//! use ftui_widgets::sparkline::Sparkline;
12//!
13//! let data = vec![1.0, 4.0, 2.0, 8.0, 3.0, 6.0, 5.0];
14//! let sparkline = Sparkline::new(&data)
15//!     .style(Style::new().fg(PackedRgba::CYAN));
16//! sparkline.render(area, frame);
17//! ```
18
19use crate::{MeasurableWidget, SizeConstraints, Widget, clear_text_row};
20use ftui_core::geometry::{Rect, Size};
21use ftui_render::cell::{Cell, PackedRgba};
22use ftui_render::frame::Frame;
23use ftui_style::Style;
24
25/// Block characters for sparkline rendering (9 levels: empty + 8 bars).
26const SPARK_CHARS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
27
28/// Optional glyph + style overrides that mark the extreme samples of a
29/// [`Sparkline`].
30///
31/// Each marker replaces the bar glyph at the column of the first minimum or
32/// first maximum sample (ties resolved to the earliest index) and merges its
33/// style over that column's computed style (base + gradient). Markers refer to
34/// the data extremes even when explicit scaling [`bounds`](Sparkline::bounds)
35/// are set. When a single sample is both the min and the max, the max marker
36/// wins. `NaN` samples are never extremes.
37#[derive(Debug, Clone, Copy, Default)]
38pub struct SparklineMarkers {
39    /// Glyph and style for the first minimum sample, if enabled.
40    pub min: Option<(char, Style)>,
41    /// Glyph and style for the first maximum sample, if enabled.
42    pub max: Option<(char, Style)>,
43}
44
45impl SparklineMarkers {
46    /// The conventional maximum marker glyph (down-pointing triangle).
47    pub const DEFAULT_MAX_GLYPH: char = '▾';
48    /// The conventional minimum marker glyph (up-pointing triangle).
49    pub const DEFAULT_MIN_GLYPH: char = '▴';
50}
51
52/// A compact sparkline widget for trend visualization.
53///
54/// Sparklines display a series of values as a row of Unicode block characters,
55/// with height proportional to value. Useful for showing trends in dashboards,
56/// status bars, and data-dense UIs.
57///
58/// # Features
59///
60/// - Auto-scaling: Automatically determines min/max from data if not specified
61/// - Manual bounds: Set explicit min/max for consistent scaling across multiple sparklines
62/// - Color gradient: Optional start/end colors for value-based coloring
63/// - Baseline: Optional baseline value (default 0.0) for distinguishing positive/negative
64///
65/// # Block Characters
66///
67/// Uses 9 levels of height: empty space plus 8 bar heights (▁▂▃▄▅▆▇█)
68#[derive(Debug, Clone)]
69pub struct Sparkline<'a> {
70    /// Data values to display.
71    data: &'a [f64],
72    /// Optional minimum value (auto-detected if None).
73    min: Option<f64>,
74    /// Optional maximum value (auto-detected if None).
75    max: Option<f64>,
76    /// Base style for all characters.
77    style: Style,
78    /// Optional gradient: (low_color, high_color).
79    gradient: Option<(PackedRgba, PackedRgba)>,
80    /// Baseline value (default 0.0) - values at baseline show as empty.
81    baseline: f64,
82    /// Optional min/max marker glyphs and styles.
83    markers: SparklineMarkers,
84}
85
86impl<'a> Sparkline<'a> {
87    /// Create a new sparkline from data slice.
88    #[must_use]
89    pub fn new(data: &'a [f64]) -> Self {
90        Self {
91            data,
92            min: None,
93            max: None,
94            style: Style::default(),
95            gradient: None,
96            baseline: 0.0,
97            markers: SparklineMarkers::default(),
98        }
99    }
100
101    /// Set explicit minimum value for scaling.
102    ///
103    /// If not set, minimum is auto-detected from data.
104    #[must_use]
105    pub fn min(mut self, min: f64) -> Self {
106        self.min = Some(min);
107        self
108    }
109
110    /// Set explicit maximum value for scaling.
111    ///
112    /// If not set, maximum is auto-detected from data.
113    #[must_use]
114    pub fn max(mut self, max: f64) -> Self {
115        self.max = Some(max);
116        self
117    }
118
119    /// Set min and max bounds together.
120    #[must_use]
121    pub fn bounds(mut self, min: f64, max: f64) -> Self {
122        self.min = Some(min);
123        self.max = Some(max);
124        self
125    }
126
127    /// Mark the first minimum sample with `ch`, merging `style` over the
128    /// column's computed style.
129    ///
130    /// The marker tracks the data minimum, independent of any explicit
131    /// [`bounds`](Self::bounds). Ties resolve to the earliest sample; `NaN`
132    /// samples are never extremes. Under an ASCII-only degradation level a
133    /// non-ASCII glyph falls back to `^`. See [`SparklineMarkers`].
134    #[must_use]
135    pub fn with_min_marker(mut self, ch: char, style: Style) -> Self {
136        self.markers.min = Some((ch, style));
137        self
138    }
139
140    /// Mark the first maximum sample with `ch`, merging `style` over the
141    /// column's computed style.
142    ///
143    /// The marker tracks the data maximum, independent of any explicit
144    /// [`bounds`](Self::bounds). Ties resolve to the earliest sample; `NaN`
145    /// samples are never extremes; and a single sample (both min and max) shows
146    /// the max marker. Under an ASCII-only degradation level a non-ASCII glyph
147    /// falls back to `v`. See [`SparklineMarkers`].
148    #[must_use]
149    pub fn with_max_marker(mut self, ch: char, style: Style) -> Self {
150        self.markers.max = Some((ch, style));
151        self
152    }
153
154    /// Set both markers at once.
155    #[must_use]
156    pub fn with_markers(mut self, markers: SparklineMarkers) -> Self {
157        self.markers = markers;
158        self
159    }
160
161    /// The configured markers.
162    #[must_use]
163    pub fn markers(&self) -> SparklineMarkers {
164        self.markers
165    }
166
167    /// The indices of the first minimum and first maximum samples, ignoring
168    /// `NaN`. Returns `None` when there is no finite sample (empty or all-NaN).
169    /// Ties resolve to the earliest index.
170    fn extreme_indices(data: &[f64]) -> Option<(usize, usize)> {
171        let mut min_idx = None;
172        let mut max_idx = None;
173        let mut min_val = f64::INFINITY;
174        let mut max_val = f64::NEG_INFINITY;
175        for (i, &v) in data.iter().enumerate() {
176            if v.is_nan() {
177                continue;
178            }
179            if v < min_val {
180                min_val = v;
181                min_idx = Some(i);
182            }
183            if v > max_val {
184                max_val = v;
185                max_idx = Some(i);
186            }
187        }
188        match (min_idx, max_idx) {
189            (Some(min), Some(max)) => Some((min, max)),
190            _ => None,
191        }
192    }
193
194    /// The marker glyph, style, and whether it is the max marker for column
195    /// `index`, or `None` when this column carries no marker. Max wins when a
196    /// single sample is both extremes.
197    fn column_marker(
198        &self,
199        index: usize,
200        extremes: Option<(usize, usize)>,
201    ) -> Option<(char, Style, bool)> {
202        let (min_i, max_i) = extremes?;
203        if index == max_i
204            && let Some((ch, style)) = self.markers.max
205        {
206            Some((ch, style, true))
207        } else if index == min_i
208            && let Some((ch, style)) = self.markers.min
209        {
210            Some((ch, style, false))
211        } else {
212            None
213        }
214    }
215
216    /// Apply the crate's ASCII degradation to a marker glyph: a non-ASCII glyph
217    /// becomes `v` (max) or `^` (min) when Unicode borders are disabled.
218    fn degrade_marker(ch: char, is_max: bool, unicode: bool) -> char {
219        if unicode || ch.is_ascii() {
220            ch
221        } else if is_max {
222            'v'
223        } else {
224            '^'
225        }
226    }
227
228    /// A short label of which markers are enabled, for the render span.
229    #[cfg(feature = "tracing")]
230    fn markers_label(&self) -> &'static str {
231        match (self.markers.min.is_some(), self.markers.max.is_some()) {
232            (true, true) => "both",
233            (true, false) => "min",
234            (false, true) => "max",
235            (false, false) => "none",
236        }
237    }
238
239    /// Set the base style (foreground color, etc.).
240    #[must_use]
241    pub fn style(mut self, style: Style) -> Self {
242        self.style = style;
243        self
244    }
245
246    /// Set a color gradient from low to high values.
247    ///
248    /// Low values get `low_color`, high values get `high_color`,
249    /// with linear interpolation between.
250    #[must_use]
251    pub fn gradient(mut self, low_color: PackedRgba, high_color: PackedRgba) -> Self {
252        self.gradient = Some((low_color, high_color));
253        self
254    }
255
256    /// Set the baseline value.
257    ///
258    /// Values at or below baseline show as empty space.
259    /// Default is 0.0.
260    #[must_use]
261    pub fn baseline(mut self, baseline: f64) -> Self {
262        self.baseline = baseline;
263        self
264    }
265
266    /// Compute the min/max bounds from data or explicit settings.
267    fn compute_bounds(&self) -> (f64, f64) {
268        let data_min = self
269            .min
270            .unwrap_or_else(|| self.data.iter().copied().fold(f64::INFINITY, f64::min));
271        let data_max = self
272            .max
273            .unwrap_or_else(|| self.data.iter().copied().fold(f64::NEG_INFINITY, f64::max));
274
275        // Ensure min <= max; handle edge cases
276        let min = if data_min.is_finite() { data_min } else { 0.0 };
277        let max = if data_max.is_finite() { data_max } else { 1.0 };
278
279        if min >= max {
280            // All values are the same; create a range around the value
281            (min - 0.5, max + 0.5)
282        } else {
283            (min, max)
284        }
285    }
286
287    /// Map a value to a bar index (0-8).
288    fn value_to_bar_index(&self, value: f64, min: f64, max: f64) -> usize {
289        if !value.is_finite() {
290            return 0;
291        }
292
293        if value <= self.baseline {
294            return 0;
295        }
296
297        let range = max - min;
298        if range <= 0.0 {
299            return 4; // Middle bar for flat data
300        }
301
302        let normalized = (value - min) / range;
303        let clamped = normalized.clamp(0.0, 1.0);
304        // Map 0.0 -> 0, 1.0 -> 8
305        (clamped * 8.0).round() as usize
306    }
307
308    /// Interpolate between two colors based on t (0.0 to 1.0).
309    fn lerp_color(low: PackedRgba, high: PackedRgba, t: f64) -> PackedRgba {
310        let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) } as f32;
311        let r = (low.r() as f32 * (1.0 - t) + high.r() as f32 * t).round() as u8;
312        let g = (low.g() as f32 * (1.0 - t) + high.g() as f32 * t).round() as u8;
313        let b = (low.b() as f32 * (1.0 - t) + high.b() as f32 * t).round() as u8;
314        let a = (low.a() as f32 * (1.0 - t) + high.a() as f32 * t).round() as u8;
315        PackedRgba::rgba(r, g, b, a)
316    }
317
318    /// Render the sparkline as a string (for testing/debugging).
319    pub fn render_to_string(&self) -> String {
320        if self.data.is_empty() {
321            return String::new();
322        }
323
324        let (min, max) = self.compute_bounds();
325        let extremes = Self::extreme_indices(self.data);
326        self.data
327            .iter()
328            .enumerate()
329            .map(|(i, &v)| match self.column_marker(i, extremes) {
330                // Text mode renders the glyph as chosen (no ASCII degradation).
331                Some((ch, _style, _is_max)) => ch,
332                None => SPARK_CHARS[self.value_to_bar_index(v, min, max)],
333            })
334            .collect()
335    }
336}
337
338impl Default for Sparkline<'_> {
339    fn default() -> Self {
340        Self::new(&[])
341    }
342}
343
344impl Widget for Sparkline<'_> {
345    fn render(&self, area: Rect, frame: &mut Frame) {
346        #[cfg(feature = "tracing")]
347        let _span = tracing::debug_span!(
348            "widget_render",
349            widget = "Sparkline",
350            x = area.x,
351            y = area.y,
352            w = area.width,
353            h = area.height,
354            data_len = self.data.len(),
355            markers = self.markers_label()
356        )
357        .entered();
358
359        if area.is_empty() {
360            return;
361        }
362
363        // Sparkline is decorative — skip under EssentialOnly and above.
364        if !frame.should_render_widget(false) {
365            return;
366        }
367
368        let deg = frame.buffer.degradation;
369
370        // Skeleton+: skip entirely
371        if !deg.render_content() {
372            return;
373        }
374
375        let base_style = if deg.apply_styling() {
376            self.style
377        } else {
378            Style::default()
379        };
380        clear_text_row(frame, area, base_style);
381
382        if self.data.is_empty() {
383            return;
384        }
385
386        let (min, max) = self.compute_bounds();
387        let range = max - min;
388
389        // Extreme columns are marked only when they fall inside the visible
390        // window (the leftmost `display_count` samples).
391        let extremes = Self::extreme_indices(self.data);
392        let unicode = deg.use_unicode_borders();
393
394        // How many data points can we show?
395        let display_count = (area.width as usize).min(self.data.len());
396
397        for (i, &value) in self.data.iter().take(display_count).enumerate() {
398            let x = area.x + i as u16;
399            let y = area.y;
400
401            if x >= area.right() {
402                break;
403            }
404
405            let bar_idx = self.value_to_bar_index(value, min, max);
406            let (ch, marker_style) = match self.column_marker(i, extremes) {
407                Some((glyph, style, is_max)) => {
408                    (Self::degrade_marker(glyph, is_max, unicode), Some(style))
409                }
410                None => (SPARK_CHARS[bar_idx], None),
411            };
412
413            let mut cell = Cell::from_char(ch);
414
415            // Apply style
416            if deg.apply_styling() {
417                // Apply base style (fg, bg, attrs)
418                crate::apply_style(&mut cell, self.style);
419
420                // Override fg with gradient if configured
421                if let Some((low_color, high_color)) = self.gradient {
422                    let t = if range > 0.0 {
423                        (value - min) / range
424                    } else {
425                        0.5
426                    };
427                    cell.fg = Self::lerp_color(low_color, high_color, t);
428                } else if self.style.fg.is_none() {
429                    // Default to white if no style fg and no gradient
430                    cell.fg = PackedRgba::WHITE;
431                }
432
433                // Merge the marker style over the computed column style, so a
434                // marker recolours the extreme without dropping the gradient.
435                if let Some(style) = marker_style {
436                    crate::apply_style(&mut cell, style);
437                }
438            }
439
440            frame.buffer.set_fast(x, y, cell);
441        }
442    }
443}
444
445impl MeasurableWidget for Sparkline<'_> {
446    fn measure(&self, _available: Size) -> SizeConstraints {
447        if self.data.is_empty() {
448            return SizeConstraints::ZERO;
449        }
450
451        // Sparklines are always 1 row tall
452        // Width is the number of data points, saturated: `as u16` wrapped
453        // 65,536 points to a width of 0, below the minimum of 1.
454        let width = u16::try_from(self.data.len()).unwrap_or(u16::MAX);
455
456        SizeConstraints {
457            min: Size::new(1, 1), // At least 1 data point visible
458            preferred: Size::new(width, 1),
459            max: Some(Size::new(width, 1)), // Fixed content size
460        }
461    }
462
463    fn has_intrinsic_size(&self) -> bool {
464        !self.data.is_empty()
465    }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use ftui_render::grapheme_pool::GraphemePool;
472
473    // --- Builder tests ---
474
475    #[test]
476    fn empty_data() {
477        let sparkline = Sparkline::new(&[]);
478        assert_eq!(sparkline.render_to_string(), "");
479    }
480
481    #[test]
482    fn single_value() {
483        let sparkline = Sparkline::new(&[5.0]);
484        // Single value maps to middle bar
485        let s = sparkline.render_to_string();
486        assert_eq!(s.chars().count(), 1);
487    }
488
489    #[test]
490    fn constant_values() {
491        let data = vec![5.0, 5.0, 5.0, 5.0];
492        let sparkline = Sparkline::new(&data);
493        let s = sparkline.render_to_string();
494        // All same height (middle bar)
495        assert_eq!(s.chars().count(), 4);
496        assert!(s.chars().all(|c| c == s.chars().next().unwrap()));
497    }
498
499    #[test]
500    fn ascending_values() {
501        let data: Vec<f64> = (0..9).map(|i| i as f64).collect();
502        let sparkline = Sparkline::new(&data);
503        let s = sparkline.render_to_string();
504        let chars: Vec<char> = s.chars().collect();
505        // First should be lowest, last should be highest
506        assert_eq!(chars[0], ' ');
507        assert_eq!(chars[8], '█');
508    }
509
510    #[test]
511    fn descending_values() {
512        let data: Vec<f64> = (0..9).rev().map(|i| i as f64).collect();
513        let sparkline = Sparkline::new(&data);
514        let s = sparkline.render_to_string();
515        let chars: Vec<char> = s.chars().collect();
516        // First should be highest, last should be lowest
517        assert_eq!(chars[0], '█');
518        assert_eq!(chars[8], ' ');
519    }
520
521    #[test]
522    fn explicit_bounds() {
523        let data = vec![5.0, 5.0, 5.0];
524        let sparkline = Sparkline::new(&data).bounds(0.0, 10.0);
525        let s = sparkline.render_to_string();
526        // 5.0 is at 50%, should be middle bar (▄)
527        let chars: Vec<char> = s.chars().collect();
528        assert_eq!(chars[0], '▄');
529    }
530
531    #[test]
532    fn min_max_explicit() {
533        let data = vec![0.0, 50.0, 100.0];
534        let sparkline = Sparkline::new(&data).min(0.0).max(100.0);
535        let s = sparkline.render_to_string();
536        let chars: Vec<char> = s.chars().collect();
537        assert_eq!(chars[0], ' '); // 0%
538        assert_eq!(chars[1], '▄'); // 50%
539        assert_eq!(chars[2], '█'); // 100%
540    }
541
542    #[test]
543    fn negative_values() {
544        let data = vec![-10.0, 0.0, 10.0];
545        let sparkline = Sparkline::new(&data);
546        let s = sparkline.render_to_string();
547        let chars: Vec<char> = s.chars().collect();
548        assert_eq!(chars[0], ' '); // Lowest
549        assert_eq!(chars[2], '█'); // Highest
550    }
551
552    #[test]
553    fn nan_values_handled() {
554        let data = vec![1.0, f64::NAN, 3.0];
555        let sparkline = Sparkline::new(&data);
556        let s = sparkline.render_to_string();
557        // NaN should render as empty (index 0)
558        let chars: Vec<char> = s.chars().collect();
559        assert_eq!(chars[1], ' ');
560    }
561
562    #[test]
563    fn infinity_values_handled() {
564        let data = vec![f64::NEG_INFINITY, 0.0, f64::INFINITY];
565        let sparkline = Sparkline::new(&data);
566        let s = sparkline.render_to_string();
567        // Infinities should be clamped
568        assert_eq!(s.chars().count(), 3);
569    }
570
571    // --- Rendering tests ---
572
573    #[test]
574    fn render_empty_area() {
575        let data = vec![1.0, 2.0, 3.0];
576        let sparkline = Sparkline::new(&data);
577        let area = Rect::new(0, 0, 0, 0);
578        let mut pool = GraphemePool::new();
579        let mut frame = Frame::new(1, 1, &mut pool);
580        Widget::render(&sparkline, area, &mut frame);
581        // Should not panic
582    }
583
584    #[test]
585    fn render_basic() {
586        let data = vec![0.0, 0.5, 1.0];
587        let sparkline = Sparkline::new(&data).bounds(0.0, 1.0);
588        let area = Rect::new(0, 0, 3, 1);
589        let mut pool = GraphemePool::new();
590        let mut frame = Frame::new(3, 1, &mut pool);
591        Widget::render(&sparkline, area, &mut frame);
592
593        let c0 = frame.buffer.get(0, 0).unwrap().content.as_char();
594        let c1 = frame.buffer.get(1, 0).unwrap().content.as_char();
595        let c2 = frame.buffer.get(2, 0).unwrap().content.as_char();
596
597        assert_eq!(c0, Some(' ')); // 0%
598        assert_eq!(c1, Some('▄')); // 50%
599        assert_eq!(c2, Some('█')); // 100%
600    }
601
602    #[test]
603    fn render_truncates_to_width() {
604        let data: Vec<f64> = (0..100).map(|i| i as f64).collect();
605        let sparkline = Sparkline::new(&data);
606        let area = Rect::new(0, 0, 10, 1);
607        let mut pool = GraphemePool::new();
608        let mut frame = Frame::new(10, 1, &mut pool);
609        Widget::render(&sparkline, area, &mut frame);
610
611        // Should only render first 10 values
612        for x in 0..10 {
613            let cell = frame.buffer.get(x, 0).unwrap();
614            assert!(cell.content.as_char().is_some());
615        }
616    }
617
618    #[test]
619    fn render_with_style() {
620        let data = vec![1.0];
621        let sparkline = Sparkline::new(&data).style(Style::new().fg(PackedRgba::GREEN));
622        let area = Rect::new(0, 0, 1, 1);
623        let mut pool = GraphemePool::new();
624        let mut frame = Frame::new(1, 1, &mut pool);
625        Widget::render(&sparkline, area, &mut frame);
626
627        let cell = frame.buffer.get(0, 0).unwrap();
628        assert_eq!(cell.fg, PackedRgba::GREEN);
629    }
630
631    #[test]
632    fn render_with_gradient() {
633        let data = vec![0.0, 0.5, 1.0];
634        let sparkline = Sparkline::new(&data)
635            .bounds(0.0, 1.0)
636            .gradient(PackedRgba::BLUE, PackedRgba::RED);
637        let area = Rect::new(0, 0, 3, 1);
638        let mut pool = GraphemePool::new();
639        let mut frame = Frame::new(3, 1, &mut pool);
640        Widget::render(&sparkline, area, &mut frame);
641
642        let c0 = frame.buffer.get(0, 0).unwrap();
643        let c2 = frame.buffer.get(2, 0).unwrap();
644
645        // Low value should be blue-ish
646        assert_eq!(c0.fg, PackedRgba::BLUE);
647        // High value should be red-ish
648        assert_eq!(c2.fg, PackedRgba::RED);
649    }
650
651    // --- Degradation tests ---
652
653    #[test]
654    fn degradation_skeleton_skips() {
655        use ftui_render::budget::DegradationLevel;
656
657        let data = vec![1.0, 2.0, 3.0];
658        let sparkline = Sparkline::new(&data).style(Style::new().fg(PackedRgba::GREEN));
659        let area = Rect::new(0, 0, 3, 1);
660        let mut pool = GraphemePool::new();
661        let mut frame = Frame::new(3, 1, &mut pool);
662        frame.buffer.degradation = DegradationLevel::Skeleton;
663        Widget::render(&sparkline, area, &mut frame);
664
665        // All cells should be empty
666        for x in 0..3 {
667            assert!(
668                frame.buffer.get(x, 0).unwrap().is_empty(),
669                "cell at x={x} should be empty at Skeleton"
670            );
671        }
672    }
673
674    #[test]
675    fn degradation_no_styling_renders_without_color() {
676        use ftui_render::budget::DegradationLevel;
677
678        let data = vec![0.5];
679        let sparkline = Sparkline::new(&data)
680            .bounds(0.0, 1.0)
681            .style(Style::new().fg(PackedRgba::GREEN));
682        let area = Rect::new(0, 0, 1, 1);
683        let mut pool = GraphemePool::new();
684        let mut frame = Frame::new(1, 1, &mut pool);
685        frame.buffer.degradation = DegradationLevel::NoStyling;
686        Widget::render(&sparkline, area, &mut frame);
687
688        // Character should be rendered but without custom color
689        let cell = frame.buffer.get(0, 0).unwrap();
690        assert!(cell.content.as_char().is_some());
691        // fg should NOT be green since styling is disabled
692        assert_ne!(cell.fg, PackedRgba::GREEN);
693    }
694
695    #[test]
696    fn render_shorter_data_clears_stale_suffix() {
697        let long = Sparkline::new(&[0.0, 0.5, 1.0, 0.75]).bounds(0.0, 1.0);
698        let short = Sparkline::new(&[1.0]);
699        let area = Rect::new(0, 0, 4, 1);
700        let mut pool = GraphemePool::new();
701        let mut frame = Frame::new(4, 1, &mut pool);
702
703        Widget::render(&long, area, &mut frame);
704        Widget::render(&short, area, &mut frame);
705
706        let row: String = (0..4)
707            .map(|x| {
708                frame
709                    .buffer
710                    .get(x, 0)
711                    .and_then(|cell| cell.content.as_char())
712                    .unwrap_or(' ')
713            })
714            .collect();
715        assert_eq!(row, "▄   ");
716    }
717
718    #[test]
719    fn render_empty_data_clears_stale_sparkline() {
720        let long = Sparkline::new(&[0.0, 0.5, 1.0]).bounds(0.0, 1.0);
721        let empty = Sparkline::new(&[]);
722        let area = Rect::new(0, 0, 3, 1);
723        let mut pool = GraphemePool::new();
724        let mut frame = Frame::new(3, 1, &mut pool);
725
726        Widget::render(&long, area, &mut frame);
727        Widget::render(&empty, area, &mut frame);
728
729        for x in 0..3 {
730            assert_eq!(
731                frame
732                    .buffer
733                    .get(x, 0)
734                    .and_then(|cell| cell.content.as_char()),
735                Some(' ')
736            );
737        }
738    }
739
740    // --- Color interpolation tests ---
741
742    #[test]
743    fn lerp_color_endpoints() {
744        let low = PackedRgba::rgb(0, 0, 0);
745        let high = PackedRgba::rgb(255, 255, 255);
746
747        assert_eq!(Sparkline::lerp_color(low, high, 0.0), low);
748        assert_eq!(Sparkline::lerp_color(low, high, 1.0), high);
749    }
750
751    #[test]
752    fn lerp_color_midpoint() {
753        let low = PackedRgba::rgb(0, 0, 0);
754        let high = PackedRgba::rgb(255, 255, 255);
755        let mid = Sparkline::lerp_color(low, high, 0.5);
756
757        assert_eq!(mid.r(), 128);
758        assert_eq!(mid.g(), 128);
759        assert_eq!(mid.b(), 128);
760    }
761
762    #[test]
763    fn lerp_color_interpolates_alpha() {
764        let low = PackedRgba::rgba(0, 0, 0, 0);
765        let high = PackedRgba::rgba(255, 255, 255, 255);
766        let mid = Sparkline::lerp_color(low, high, 0.5);
767
768        assert_eq!(mid.r(), 128);
769        assert_eq!(mid.g(), 128);
770        assert_eq!(mid.b(), 128);
771        assert_eq!(mid.a(), 128);
772    }
773
774    // --- MeasurableWidget tests ---
775
776    #[test]
777    fn measure_empty_sparkline() {
778        let sparkline = Sparkline::new(&[]);
779        let c = sparkline.measure(Size::MAX);
780        assert_eq!(c, SizeConstraints::ZERO);
781        assert!(!sparkline.has_intrinsic_size());
782    }
783
784    #[test]
785    fn measure_single_value() {
786        let data = [5.0];
787        let sparkline = Sparkline::new(&data);
788        let c = sparkline.measure(Size::MAX);
789
790        assert_eq!(c.preferred.width, 1);
791        assert_eq!(c.preferred.height, 1);
792        assert!(sparkline.has_intrinsic_size());
793    }
794
795    #[test]
796    fn measure_multiple_values() {
797        let data: Vec<f64> = (0..50).map(|i| i as f64).collect();
798        let sparkline = Sparkline::new(&data);
799        let c = sparkline.measure(Size::MAX);
800
801        assert_eq!(c.preferred.width, 50);
802        assert_eq!(c.preferred.height, 1);
803        assert_eq!(c.min.width, 1);
804        assert_eq!(c.min.height, 1);
805    }
806
807    #[test]
808    fn measure_max_equals_preferred() {
809        let data = [1.0, 2.0, 3.0];
810        let sparkline = Sparkline::new(&data);
811        let c = sparkline.measure(Size::MAX);
812
813        assert_eq!(c.max, Some(Size::new(3, 1)));
814    }
815
816    #[test]
817    fn measure_saturates_past_u16_data_points() {
818        // `len() as u16` measured 65,536 points as 0 wide, below min 1.
819        for len in [65_536, 65_537, 200_000] {
820            let data = vec![1.0; len];
821            let c = Sparkline::new(&data).measure(Size::MAX);
822            assert_eq!(c.preferred, Size::new(u16::MAX, 1), "{len}");
823            assert!(c.min.width <= c.preferred.width, "{len}");
824        }
825    }
826
827    mod marker_tests {
828        use super::*;
829        use proptest::prelude::*;
830
831        fn chars_of(s: &str) -> Vec<char> {
832            s.chars().collect()
833        }
834
835        #[test]
836        fn min_marker_placed_at_first_min() {
837            // First minimum (1.0) is at index 1; the later 1.0 stays a bar.
838            let data = [3.0, 1.0, 2.0, 1.0];
839            let s = Sparkline::new(&data)
840                .with_min_marker('L', Style::default())
841                .render_to_string();
842            let chars = chars_of(&s);
843            assert_eq!(chars[1], 'L');
844            assert_eq!(chars.iter().filter(|&&c| c == 'L').count(), 1);
845        }
846
847        #[test]
848        fn max_marker_placed_at_first_max() {
849            // First maximum (3.0) is at index 1; the later 3.0 stays a bar.
850            let data = [1.0, 3.0, 2.0, 3.0];
851            let s = Sparkline::new(&data)
852                .with_max_marker('H', Style::default())
853                .render_to_string();
854            let chars = chars_of(&s);
855            assert_eq!(chars[1], 'H');
856            assert_eq!(chars.iter().filter(|&&c| c == 'H').count(), 1);
857        }
858
859        #[test]
860        fn markers_respect_explicit_bounds() {
861            // Bounds only scale the bars; markers still track the data extremes.
862            let data = [2.0, 8.0, 5.0];
863            let s = Sparkline::new(&data)
864                .bounds(0.0, 100.0)
865                .with_min_marker('L', Style::default())
866                .with_max_marker('H', Style::default())
867                .render_to_string();
868            let chars = chars_of(&s);
869            assert_eq!(chars[0], 'L', "data min, not the bound min");
870            assert_eq!(chars[1], 'H', "data max, not the bound max");
871        }
872
873        #[test]
874        fn single_sample_gets_max_marker() {
875            let data = [5.0];
876            let both = Sparkline::new(&data)
877                .with_min_marker('L', Style::default())
878                .with_max_marker('H', Style::default())
879                .render_to_string();
880            assert_eq!(both, "H", "a single sample is both extremes; max wins");
881            // Only a min marker still shows on the single sample.
882            let min_only = Sparkline::new(&data)
883                .with_min_marker('L', Style::default())
884                .render_to_string();
885            assert_eq!(min_only, "L");
886        }
887
888        #[test]
889        fn render_to_string_includes_markers() {
890            let data = [1.0, 5.0, 3.0];
891            let s = Sparkline::new(&data)
892                .with_min_marker('v', Style::default())
893                .with_max_marker('^', Style::default())
894                .render_to_string();
895            assert!(s.contains('v') && s.contains('^'), "{s}");
896
897            // Same 20-sample dataset as the snapshot test:
898            let data20 = [
899                3.0, 7.0, 2.0, 9.0, 4.0, 1.0, 6.0, 8.0, 5.0, 7.0, 3.0, 9.0, 2.0, 6.0, 4.0, 8.0,
900                1.0, 5.0, 7.0, 3.0,
901            ];
902            let s20 = Sparkline::new(&data20)
903                .with_min_marker(SparklineMarkers::DEFAULT_MIN_GLYPH, Style::default())
904                .with_max_marker(SparklineMarkers::DEFAULT_MAX_GLYPH, Style::default())
905                .render_to_string();
906            let chars20: Vec<char> = s20.chars().collect();
907            assert_eq!(chars20.len(), 20);
908            assert_eq!(chars20[3], SparklineMarkers::DEFAULT_MAX_GLYPH);
909            assert_eq!(chars20[5], SparklineMarkers::DEFAULT_MIN_GLYPH);
910        }
911
912        #[test]
913        fn extreme_indices_pure_fn() {
914            // Ties choose earliest index
915            assert_eq!(
916                Sparkline::extreme_indices(&[1.0, 1.0, 5.0, 5.0]),
917                Some((0, 2))
918            );
919            // NaNs are ignored
920            assert_eq!(
921                Sparkline::extreme_indices(&[f64::NAN, 2.0, f64::NAN]),
922                Some((1, 1))
923            );
924            // All-NaN or empty returns None
925            assert_eq!(Sparkline::extreme_indices(&[f64::NAN]), None);
926            assert_eq!(Sparkline::extreme_indices(&[]), None);
927        }
928
929        #[test]
930        fn empty_data_no_panic() {
931            let sparkline = Sparkline::new(&[])
932                .with_min_marker('L', Style::default())
933                .with_max_marker('H', Style::default());
934            assert_eq!(sparkline.render_to_string(), "");
935            // Rendering empty data to a frame must not panic.
936            let area = Rect::new(0, 0, 3, 1);
937            let mut pool = GraphemePool::new();
938            let mut frame = Frame::new(3, 1, &mut pool);
939            Widget::render(&sparkline, area, &mut frame);
940        }
941
942        #[test]
943        fn nan_samples_are_not_extremes() {
944            let data = [f64::NAN, 5.0, 1.0, f64::NAN];
945            // min at index 2 (1.0), max at index 1 (5.0); NaNs ignored.
946            assert_eq!(Sparkline::extreme_indices(&data), Some((2, 1)));
947            // All-NaN has no extremes.
948            assert_eq!(Sparkline::extreme_indices(&[f64::NAN, f64::NAN]), None);
949            assert_eq!(Sparkline::extreme_indices(&[]), None);
950        }
951
952        #[test]
953        fn marker_outside_window_not_drawn() {
954            // Ascending data: min at 0 (inside a width-5 window), max at 19
955            // (outside it). The window is the leftmost `area.width` samples.
956            let data: Vec<f64> = (0..20).map(|i| i as f64).collect();
957            let sparkline = Sparkline::new(&data)
958                .with_min_marker('L', Style::default())
959                .with_max_marker('H', Style::default());
960            let area = Rect::new(0, 0, 5, 1);
961            let mut pool = GraphemePool::new();
962            let mut frame = Frame::new(5, 1, &mut pool);
963            Widget::render(&sparkline, area, &mut frame);
964
965            assert_eq!(
966                frame.buffer.get(0, 0).unwrap().content.as_char(),
967                Some('L'),
968                "the min is inside the window"
969            );
970            for x in 0..5 {
971                assert_ne!(
972                    frame.buffer.get(x, 0).unwrap().content.as_char(),
973                    Some('H'),
974                    "the max column is outside the window"
975                );
976            }
977        }
978
979        #[test]
980        fn sparkline_skips_render_under_essential_only() {
981            use ftui_render::budget::DegradationLevel;
982
983            let data = [1.0, 5.0, 3.0];
984            let sparkline = Sparkline::new(&data);
985            let area = Rect::new(0, 0, 3, 1);
986
987            // Full: renders characters (not blank)
988            let mut pool_full = GraphemePool::new();
989            let mut frame_full = Frame::new(3, 1, &mut pool_full);
990            frame_full.set_degradation(DegradationLevel::Full);
991            Widget::render(&sparkline, area, &mut frame_full);
992            assert_eq!(
993                frame_full.buffer.get(1, 0).unwrap().content.as_char(),
994                Some('█')
995            );
996
997            // EssentialOnly: leaves area blank
998            let mut pool_ess = GraphemePool::new();
999            let mut frame_ess = Frame::new(3, 1, &mut pool_ess);
1000            frame_ess.set_degradation(DegradationLevel::EssentialOnly);
1001            Widget::render(&sparkline, area, &mut frame_ess);
1002            for x in 0..3 {
1003                let cell = frame_ess.buffer.get(x, 0).unwrap();
1004                assert!(cell.content.is_empty());
1005            }
1006        }
1007
1008        #[test]
1009        fn marker_style_merges_over_gradient() {
1010            // The max marker sets only a background; the gradient foreground at
1011            // that column must survive the merge.
1012            let data = [0.0, 10.0];
1013            let sparkline = Sparkline::new(&data)
1014                .bounds(0.0, 10.0)
1015                .gradient(PackedRgba::BLUE, PackedRgba::GREEN)
1016                .with_max_marker('H', Style::new().bg(PackedRgba::WHITE));
1017            let area = Rect::new(0, 0, 2, 1);
1018            let mut pool = GraphemePool::new();
1019            let mut frame = Frame::new(2, 1, &mut pool);
1020            Widget::render(&sparkline, area, &mut frame);
1021
1022            let max_cell = frame.buffer.get(1, 0).unwrap();
1023            assert_eq!(max_cell.content.as_char(), Some('H'));
1024            assert_eq!(max_cell.fg, PackedRgba::GREEN, "gradient fg preserved");
1025            assert_eq!(max_cell.bg, PackedRgba::WHITE, "marker bg applied");
1026        }
1027
1028        #[test]
1029        fn ascii_degradation_falls_back_to_carets() {
1030            use ftui_render::budget::DegradationLevel;
1031
1032            let data = [1.0, 9.0, 3.0];
1033            let sparkline = Sparkline::new(&data)
1034                .with_min_marker(SparklineMarkers::DEFAULT_MIN_GLYPH, Style::default())
1035                .with_max_marker(SparklineMarkers::DEFAULT_MAX_GLYPH, Style::default());
1036            let area = Rect::new(0, 0, 3, 1);
1037            let mut pool = GraphemePool::new();
1038            let mut frame = Frame::new(3, 1, &mut pool);
1039            frame.buffer.degradation = DegradationLevel::SimpleBorders;
1040            Widget::render(&sparkline, area, &mut frame);
1041
1042            assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('^'));
1043            assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('v'));
1044        }
1045
1046        #[test]
1047        fn no_markers_matches_plain_render() {
1048            // With no markers set, render_to_string is byte-identical to the
1049            // pre-feature output.
1050            let data = [0.0, 4.0, 2.0, 8.0, 3.0];
1051            let plain = Sparkline::new(&data).render_to_string();
1052            let still_plain = Sparkline::new(&data)
1053                .with_markers(SparklineMarkers::default())
1054                .render_to_string();
1055            assert_eq!(plain, still_plain);
1056        }
1057
1058        #[test]
1059        fn sparkline_markers_20x1() {
1060            // A 20-wide render with min first at index 5 and max first at index 3.
1061            // Ties (max also at 11, min also at 16) are resolved to earliest.
1062            let data = [
1063                3.0, 7.0, 2.0, 9.0, 4.0, 1.0, 6.0, 8.0, 5.0, 7.0, 3.0, 9.0, 2.0, 6.0, 4.0, 8.0,
1064                1.0, 5.0, 7.0, 3.0,
1065            ];
1066            let sparkline = Sparkline::new(&data)
1067                .with_min_marker(SparklineMarkers::DEFAULT_MIN_GLYPH, Style::default())
1068                .with_max_marker(SparklineMarkers::DEFAULT_MAX_GLYPH, Style::default());
1069            let area = Rect::new(0, 0, 20, 1);
1070            let mut pool = GraphemePool::new();
1071            let mut frame = Frame::new(20, 1, &mut pool);
1072            Widget::render(&sparkline, area, &mut frame);
1073
1074            let row: String = (0..20)
1075                .map(|x| {
1076                    frame
1077                        .buffer
1078                        .get(x, 0)
1079                        .and_then(|c| c.content.as_char())
1080                        .unwrap_or(' ')
1081                })
1082                .collect();
1083            let chars: Vec<char> = row.chars().collect();
1084            assert_eq!(chars[3], SparklineMarkers::DEFAULT_MAX_GLYPH);
1085            assert_eq!(chars[5], SparklineMarkers::DEFAULT_MIN_GLYPH);
1086            assert_eq!(
1087                chars
1088                    .iter()
1089                    .filter(|&&c| c == SparklineMarkers::DEFAULT_MIN_GLYPH)
1090                    .count(),
1091                1
1092            );
1093            assert_eq!(
1094                chars
1095                    .iter()
1096                    .filter(|&&c| c == SparklineMarkers::DEFAULT_MAX_GLYPH)
1097                    .count(),
1098                1
1099            );
1100        }
1101
1102        proptest! {
1103            #![proptest_config(ProptestConfig::with_cases(512))]
1104
1105            /// `extreme_indices` returns the earliest indices whose values equal
1106            /// the min and max of the (NaN-free) data.
1107            #[test]
1108            fn extreme_indices_finds_earliest_extremes(
1109                data in prop::collection::vec(-100.0f64..100.0, 1..30),
1110            ) {
1111                let (min_i, max_i) = Sparkline::extreme_indices(&data)
1112                    .expect("finite data has extremes");
1113                let dmin = data.iter().copied().fold(f64::INFINITY, f64::min);
1114                let dmax = data.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1115                prop_assert_eq!(data[min_i], dmin);
1116                prop_assert_eq!(data[max_i], dmax);
1117                prop_assert!(data[..min_i].iter().all(|&v| v > dmin), "earliest min");
1118                prop_assert!(data[..max_i].iter().all(|&v| v < dmax), "earliest max");
1119            }
1120        }
1121    }
1122}