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        let deg = frame.buffer.degradation;
364
365        // Skeleton+: skip entirely
366        if !deg.render_content() {
367            return;
368        }
369
370        let base_style = if deg.apply_styling() {
371            self.style
372        } else {
373            Style::default()
374        };
375        clear_text_row(frame, area, base_style);
376
377        if self.data.is_empty() {
378            return;
379        }
380
381        let (min, max) = self.compute_bounds();
382        let range = max - min;
383
384        // Extreme columns are marked only when they fall inside the visible
385        // window (the leftmost `display_count` samples).
386        let extremes = Self::extreme_indices(self.data);
387        let unicode = deg.use_unicode_borders();
388
389        // How many data points can we show?
390        let display_count = (area.width as usize).min(self.data.len());
391
392        for (i, &value) in self.data.iter().take(display_count).enumerate() {
393            let x = area.x + i as u16;
394            let y = area.y;
395
396            if x >= area.right() {
397                break;
398            }
399
400            let bar_idx = self.value_to_bar_index(value, min, max);
401            let (ch, marker_style) = match self.column_marker(i, extremes) {
402                Some((glyph, style, is_max)) => {
403                    (Self::degrade_marker(glyph, is_max, unicode), Some(style))
404                }
405                None => (SPARK_CHARS[bar_idx], None),
406            };
407
408            let mut cell = Cell::from_char(ch);
409
410            // Apply style
411            if deg.apply_styling() {
412                // Apply base style (fg, bg, attrs)
413                crate::apply_style(&mut cell, self.style);
414
415                // Override fg with gradient if configured
416                if let Some((low_color, high_color)) = self.gradient {
417                    let t = if range > 0.0 {
418                        (value - min) / range
419                    } else {
420                        0.5
421                    };
422                    cell.fg = Self::lerp_color(low_color, high_color, t);
423                } else if self.style.fg.is_none() {
424                    // Default to white if no style fg and no gradient
425                    cell.fg = PackedRgba::WHITE;
426                }
427
428                // Merge the marker style over the computed column style, so a
429                // marker recolours the extreme without dropping the gradient.
430                if let Some(style) = marker_style {
431                    crate::apply_style(&mut cell, style);
432                }
433            }
434
435            frame.buffer.set_fast(x, y, cell);
436        }
437    }
438}
439
440impl MeasurableWidget for Sparkline<'_> {
441    fn measure(&self, _available: Size) -> SizeConstraints {
442        if self.data.is_empty() {
443            return SizeConstraints::ZERO;
444        }
445
446        // Sparklines are always 1 row tall
447        // Width is the number of data points
448        let width = self.data.len() as u16;
449
450        SizeConstraints {
451            min: Size::new(1, 1), // At least 1 data point visible
452            preferred: Size::new(width, 1),
453            max: Some(Size::new(width, 1)), // Fixed content size
454        }
455    }
456
457    fn has_intrinsic_size(&self) -> bool {
458        !self.data.is_empty()
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use ftui_render::grapheme_pool::GraphemePool;
466
467    // --- Builder tests ---
468
469    #[test]
470    fn empty_data() {
471        let sparkline = Sparkline::new(&[]);
472        assert_eq!(sparkline.render_to_string(), "");
473    }
474
475    #[test]
476    fn single_value() {
477        let sparkline = Sparkline::new(&[5.0]);
478        // Single value maps to middle bar
479        let s = sparkline.render_to_string();
480        assert_eq!(s.chars().count(), 1);
481    }
482
483    #[test]
484    fn constant_values() {
485        let data = vec![5.0, 5.0, 5.0, 5.0];
486        let sparkline = Sparkline::new(&data);
487        let s = sparkline.render_to_string();
488        // All same height (middle bar)
489        assert_eq!(s.chars().count(), 4);
490        assert!(s.chars().all(|c| c == s.chars().next().unwrap()));
491    }
492
493    #[test]
494    fn ascending_values() {
495        let data: Vec<f64> = (0..9).map(|i| i as f64).collect();
496        let sparkline = Sparkline::new(&data);
497        let s = sparkline.render_to_string();
498        let chars: Vec<char> = s.chars().collect();
499        // First should be lowest, last should be highest
500        assert_eq!(chars[0], ' ');
501        assert_eq!(chars[8], '█');
502    }
503
504    #[test]
505    fn descending_values() {
506        let data: Vec<f64> = (0..9).rev().map(|i| i as f64).collect();
507        let sparkline = Sparkline::new(&data);
508        let s = sparkline.render_to_string();
509        let chars: Vec<char> = s.chars().collect();
510        // First should be highest, last should be lowest
511        assert_eq!(chars[0], '█');
512        assert_eq!(chars[8], ' ');
513    }
514
515    #[test]
516    fn explicit_bounds() {
517        let data = vec![5.0, 5.0, 5.0];
518        let sparkline = Sparkline::new(&data).bounds(0.0, 10.0);
519        let s = sparkline.render_to_string();
520        // 5.0 is at 50%, should be middle bar (▄)
521        let chars: Vec<char> = s.chars().collect();
522        assert_eq!(chars[0], '▄');
523    }
524
525    #[test]
526    fn min_max_explicit() {
527        let data = vec![0.0, 50.0, 100.0];
528        let sparkline = Sparkline::new(&data).min(0.0).max(100.0);
529        let s = sparkline.render_to_string();
530        let chars: Vec<char> = s.chars().collect();
531        assert_eq!(chars[0], ' '); // 0%
532        assert_eq!(chars[1], '▄'); // 50%
533        assert_eq!(chars[2], '█'); // 100%
534    }
535
536    #[test]
537    fn negative_values() {
538        let data = vec![-10.0, 0.0, 10.0];
539        let sparkline = Sparkline::new(&data);
540        let s = sparkline.render_to_string();
541        let chars: Vec<char> = s.chars().collect();
542        assert_eq!(chars[0], ' '); // Lowest
543        assert_eq!(chars[2], '█'); // Highest
544    }
545
546    #[test]
547    fn nan_values_handled() {
548        let data = vec![1.0, f64::NAN, 3.0];
549        let sparkline = Sparkline::new(&data);
550        let s = sparkline.render_to_string();
551        // NaN should render as empty (index 0)
552        let chars: Vec<char> = s.chars().collect();
553        assert_eq!(chars[1], ' ');
554    }
555
556    #[test]
557    fn infinity_values_handled() {
558        let data = vec![f64::NEG_INFINITY, 0.0, f64::INFINITY];
559        let sparkline = Sparkline::new(&data);
560        let s = sparkline.render_to_string();
561        // Infinities should be clamped
562        assert_eq!(s.chars().count(), 3);
563    }
564
565    // --- Rendering tests ---
566
567    #[test]
568    fn render_empty_area() {
569        let data = vec![1.0, 2.0, 3.0];
570        let sparkline = Sparkline::new(&data);
571        let area = Rect::new(0, 0, 0, 0);
572        let mut pool = GraphemePool::new();
573        let mut frame = Frame::new(1, 1, &mut pool);
574        Widget::render(&sparkline, area, &mut frame);
575        // Should not panic
576    }
577
578    #[test]
579    fn render_basic() {
580        let data = vec![0.0, 0.5, 1.0];
581        let sparkline = Sparkline::new(&data).bounds(0.0, 1.0);
582        let area = Rect::new(0, 0, 3, 1);
583        let mut pool = GraphemePool::new();
584        let mut frame = Frame::new(3, 1, &mut pool);
585        Widget::render(&sparkline, area, &mut frame);
586
587        let c0 = frame.buffer.get(0, 0).unwrap().content.as_char();
588        let c1 = frame.buffer.get(1, 0).unwrap().content.as_char();
589        let c2 = frame.buffer.get(2, 0).unwrap().content.as_char();
590
591        assert_eq!(c0, Some(' ')); // 0%
592        assert_eq!(c1, Some('▄')); // 50%
593        assert_eq!(c2, Some('█')); // 100%
594    }
595
596    #[test]
597    fn render_truncates_to_width() {
598        let data: Vec<f64> = (0..100).map(|i| i as f64).collect();
599        let sparkline = Sparkline::new(&data);
600        let area = Rect::new(0, 0, 10, 1);
601        let mut pool = GraphemePool::new();
602        let mut frame = Frame::new(10, 1, &mut pool);
603        Widget::render(&sparkline, area, &mut frame);
604
605        // Should only render first 10 values
606        for x in 0..10 {
607            let cell = frame.buffer.get(x, 0).unwrap();
608            assert!(cell.content.as_char().is_some());
609        }
610    }
611
612    #[test]
613    fn render_with_style() {
614        let data = vec![1.0];
615        let sparkline = Sparkline::new(&data).style(Style::new().fg(PackedRgba::GREEN));
616        let area = Rect::new(0, 0, 1, 1);
617        let mut pool = GraphemePool::new();
618        let mut frame = Frame::new(1, 1, &mut pool);
619        Widget::render(&sparkline, area, &mut frame);
620
621        let cell = frame.buffer.get(0, 0).unwrap();
622        assert_eq!(cell.fg, PackedRgba::GREEN);
623    }
624
625    #[test]
626    fn render_with_gradient() {
627        let data = vec![0.0, 0.5, 1.0];
628        let sparkline = Sparkline::new(&data)
629            .bounds(0.0, 1.0)
630            .gradient(PackedRgba::BLUE, PackedRgba::RED);
631        let area = Rect::new(0, 0, 3, 1);
632        let mut pool = GraphemePool::new();
633        let mut frame = Frame::new(3, 1, &mut pool);
634        Widget::render(&sparkline, area, &mut frame);
635
636        let c0 = frame.buffer.get(0, 0).unwrap();
637        let c2 = frame.buffer.get(2, 0).unwrap();
638
639        // Low value should be blue-ish
640        assert_eq!(c0.fg, PackedRgba::BLUE);
641        // High value should be red-ish
642        assert_eq!(c2.fg, PackedRgba::RED);
643    }
644
645    // --- Degradation tests ---
646
647    #[test]
648    fn degradation_skeleton_skips() {
649        use ftui_render::budget::DegradationLevel;
650
651        let data = vec![1.0, 2.0, 3.0];
652        let sparkline = Sparkline::new(&data).style(Style::new().fg(PackedRgba::GREEN));
653        let area = Rect::new(0, 0, 3, 1);
654        let mut pool = GraphemePool::new();
655        let mut frame = Frame::new(3, 1, &mut pool);
656        frame.buffer.degradation = DegradationLevel::Skeleton;
657        Widget::render(&sparkline, area, &mut frame);
658
659        // All cells should be empty
660        for x in 0..3 {
661            assert!(
662                frame.buffer.get(x, 0).unwrap().is_empty(),
663                "cell at x={x} should be empty at Skeleton"
664            );
665        }
666    }
667
668    #[test]
669    fn degradation_no_styling_renders_without_color() {
670        use ftui_render::budget::DegradationLevel;
671
672        let data = vec![0.5];
673        let sparkline = Sparkline::new(&data)
674            .bounds(0.0, 1.0)
675            .style(Style::new().fg(PackedRgba::GREEN));
676        let area = Rect::new(0, 0, 1, 1);
677        let mut pool = GraphemePool::new();
678        let mut frame = Frame::new(1, 1, &mut pool);
679        frame.buffer.degradation = DegradationLevel::NoStyling;
680        Widget::render(&sparkline, area, &mut frame);
681
682        // Character should be rendered but without custom color
683        let cell = frame.buffer.get(0, 0).unwrap();
684        assert!(cell.content.as_char().is_some());
685        // fg should NOT be green since styling is disabled
686        assert_ne!(cell.fg, PackedRgba::GREEN);
687    }
688
689    #[test]
690    fn render_shorter_data_clears_stale_suffix() {
691        let long = Sparkline::new(&[0.0, 0.5, 1.0, 0.75]).bounds(0.0, 1.0);
692        let short = Sparkline::new(&[1.0]);
693        let area = Rect::new(0, 0, 4, 1);
694        let mut pool = GraphemePool::new();
695        let mut frame = Frame::new(4, 1, &mut pool);
696
697        Widget::render(&long, area, &mut frame);
698        Widget::render(&short, area, &mut frame);
699
700        let row: String = (0..4)
701            .map(|x| {
702                frame
703                    .buffer
704                    .get(x, 0)
705                    .and_then(|cell| cell.content.as_char())
706                    .unwrap_or(' ')
707            })
708            .collect();
709        assert_eq!(row, "▄   ");
710    }
711
712    #[test]
713    fn render_empty_data_clears_stale_sparkline() {
714        let long = Sparkline::new(&[0.0, 0.5, 1.0]).bounds(0.0, 1.0);
715        let empty = Sparkline::new(&[]);
716        let area = Rect::new(0, 0, 3, 1);
717        let mut pool = GraphemePool::new();
718        let mut frame = Frame::new(3, 1, &mut pool);
719
720        Widget::render(&long, area, &mut frame);
721        Widget::render(&empty, area, &mut frame);
722
723        for x in 0..3 {
724            assert_eq!(
725                frame
726                    .buffer
727                    .get(x, 0)
728                    .and_then(|cell| cell.content.as_char()),
729                Some(' ')
730            );
731        }
732    }
733
734    // --- Color interpolation tests ---
735
736    #[test]
737    fn lerp_color_endpoints() {
738        let low = PackedRgba::rgb(0, 0, 0);
739        let high = PackedRgba::rgb(255, 255, 255);
740
741        assert_eq!(Sparkline::lerp_color(low, high, 0.0), low);
742        assert_eq!(Sparkline::lerp_color(low, high, 1.0), high);
743    }
744
745    #[test]
746    fn lerp_color_midpoint() {
747        let low = PackedRgba::rgb(0, 0, 0);
748        let high = PackedRgba::rgb(255, 255, 255);
749        let mid = Sparkline::lerp_color(low, high, 0.5);
750
751        assert_eq!(mid.r(), 128);
752        assert_eq!(mid.g(), 128);
753        assert_eq!(mid.b(), 128);
754    }
755
756    #[test]
757    fn lerp_color_interpolates_alpha() {
758        let low = PackedRgba::rgba(0, 0, 0, 0);
759        let high = PackedRgba::rgba(255, 255, 255, 255);
760        let mid = Sparkline::lerp_color(low, high, 0.5);
761
762        assert_eq!(mid.r(), 128);
763        assert_eq!(mid.g(), 128);
764        assert_eq!(mid.b(), 128);
765        assert_eq!(mid.a(), 128);
766    }
767
768    // --- MeasurableWidget tests ---
769
770    #[test]
771    fn measure_empty_sparkline() {
772        let sparkline = Sparkline::new(&[]);
773        let c = sparkline.measure(Size::MAX);
774        assert_eq!(c, SizeConstraints::ZERO);
775        assert!(!sparkline.has_intrinsic_size());
776    }
777
778    #[test]
779    fn measure_single_value() {
780        let data = [5.0];
781        let sparkline = Sparkline::new(&data);
782        let c = sparkline.measure(Size::MAX);
783
784        assert_eq!(c.preferred.width, 1);
785        assert_eq!(c.preferred.height, 1);
786        assert!(sparkline.has_intrinsic_size());
787    }
788
789    #[test]
790    fn measure_multiple_values() {
791        let data: Vec<f64> = (0..50).map(|i| i as f64).collect();
792        let sparkline = Sparkline::new(&data);
793        let c = sparkline.measure(Size::MAX);
794
795        assert_eq!(c.preferred.width, 50);
796        assert_eq!(c.preferred.height, 1);
797        assert_eq!(c.min.width, 1);
798        assert_eq!(c.min.height, 1);
799    }
800
801    #[test]
802    fn measure_max_equals_preferred() {
803        let data = [1.0, 2.0, 3.0];
804        let sparkline = Sparkline::new(&data);
805        let c = sparkline.measure(Size::MAX);
806
807        assert_eq!(c.max, Some(Size::new(3, 1)));
808    }
809
810    mod marker_tests {
811        use super::*;
812        use proptest::prelude::*;
813
814        fn chars_of(s: &str) -> Vec<char> {
815            s.chars().collect()
816        }
817
818        #[test]
819        fn min_marker_placed_at_first_min() {
820            // First minimum (1.0) is at index 1; the later 1.0 stays a bar.
821            let data = [3.0, 1.0, 2.0, 1.0];
822            let s = Sparkline::new(&data)
823                .with_min_marker('L', Style::default())
824                .render_to_string();
825            let chars = chars_of(&s);
826            assert_eq!(chars[1], 'L');
827            assert_eq!(chars.iter().filter(|&&c| c == 'L').count(), 1);
828        }
829
830        #[test]
831        fn max_marker_placed_at_first_max() {
832            // First maximum (3.0) is at index 1; the later 3.0 stays a bar.
833            let data = [1.0, 3.0, 2.0, 3.0];
834            let s = Sparkline::new(&data)
835                .with_max_marker('H', Style::default())
836                .render_to_string();
837            let chars = chars_of(&s);
838            assert_eq!(chars[1], 'H');
839            assert_eq!(chars.iter().filter(|&&c| c == 'H').count(), 1);
840        }
841
842        #[test]
843        fn markers_respect_explicit_bounds() {
844            // Bounds only scale the bars; markers still track the data extremes.
845            let data = [2.0, 8.0, 5.0];
846            let s = Sparkline::new(&data)
847                .bounds(0.0, 100.0)
848                .with_min_marker('L', Style::default())
849                .with_max_marker('H', Style::default())
850                .render_to_string();
851            let chars = chars_of(&s);
852            assert_eq!(chars[0], 'L', "data min, not the bound min");
853            assert_eq!(chars[1], 'H', "data max, not the bound max");
854        }
855
856        #[test]
857        fn single_sample_gets_max_marker() {
858            let data = [5.0];
859            let both = Sparkline::new(&data)
860                .with_min_marker('L', Style::default())
861                .with_max_marker('H', Style::default())
862                .render_to_string();
863            assert_eq!(both, "H", "a single sample is both extremes; max wins");
864            // Only a min marker still shows on the single sample.
865            let min_only = Sparkline::new(&data)
866                .with_min_marker('L', Style::default())
867                .render_to_string();
868            assert_eq!(min_only, "L");
869        }
870
871        #[test]
872        fn render_to_string_includes_markers() {
873            let data = [1.0, 5.0, 3.0];
874            let s = Sparkline::new(&data)
875                .with_min_marker('v', Style::default())
876                .with_max_marker('^', Style::default())
877                .render_to_string();
878            assert!(s.contains('v') && s.contains('^'), "{s}");
879        }
880
881        #[test]
882        fn empty_data_no_panic() {
883            let sparkline = Sparkline::new(&[])
884                .with_min_marker('L', Style::default())
885                .with_max_marker('H', Style::default());
886            assert_eq!(sparkline.render_to_string(), "");
887            // Rendering empty data to a frame must not panic.
888            let area = Rect::new(0, 0, 3, 1);
889            let mut pool = GraphemePool::new();
890            let mut frame = Frame::new(3, 1, &mut pool);
891            Widget::render(&sparkline, area, &mut frame);
892        }
893
894        #[test]
895        fn nan_samples_are_not_extremes() {
896            let data = [f64::NAN, 5.0, 1.0, f64::NAN];
897            // min at index 2 (1.0), max at index 1 (5.0); NaNs ignored.
898            assert_eq!(Sparkline::extreme_indices(&data), Some((2, 1)));
899            // All-NaN has no extremes.
900            assert_eq!(Sparkline::extreme_indices(&[f64::NAN, f64::NAN]), None);
901            assert_eq!(Sparkline::extreme_indices(&[]), None);
902        }
903
904        #[test]
905        fn marker_outside_window_not_drawn() {
906            // Ascending data: min at 0 (inside a width-5 window), max at 19
907            // (outside it). The window is the leftmost `area.width` samples.
908            let data: Vec<f64> = (0..20).map(|i| i as f64).collect();
909            let sparkline = Sparkline::new(&data)
910                .with_min_marker('L', Style::default())
911                .with_max_marker('H', Style::default());
912            let area = Rect::new(0, 0, 5, 1);
913            let mut pool = GraphemePool::new();
914            let mut frame = Frame::new(5, 1, &mut pool);
915            Widget::render(&sparkline, area, &mut frame);
916
917            assert_eq!(
918                frame.buffer.get(0, 0).unwrap().content.as_char(),
919                Some('L'),
920                "the min is inside the window"
921            );
922            for x in 0..5 {
923                assert_ne!(
924                    frame.buffer.get(x, 0).unwrap().content.as_char(),
925                    Some('H'),
926                    "the max column is outside the window"
927                );
928            }
929        }
930
931        #[test]
932        fn marker_style_merges_over_gradient() {
933            // The max marker sets only a background; the gradient foreground at
934            // that column must survive the merge.
935            let data = [0.0, 10.0];
936            let sparkline = Sparkline::new(&data)
937                .bounds(0.0, 10.0)
938                .gradient(PackedRgba::BLUE, PackedRgba::GREEN)
939                .with_max_marker('H', Style::new().bg(PackedRgba::WHITE));
940            let area = Rect::new(0, 0, 2, 1);
941            let mut pool = GraphemePool::new();
942            let mut frame = Frame::new(2, 1, &mut pool);
943            Widget::render(&sparkline, area, &mut frame);
944
945            let max_cell = frame.buffer.get(1, 0).unwrap();
946            assert_eq!(max_cell.content.as_char(), Some('H'));
947            assert_eq!(max_cell.fg, PackedRgba::GREEN, "gradient fg preserved");
948            assert_eq!(max_cell.bg, PackedRgba::WHITE, "marker bg applied");
949        }
950
951        #[test]
952        fn ascii_degradation_falls_back_to_carets() {
953            use ftui_render::budget::DegradationLevel;
954
955            let data = [1.0, 9.0, 3.0];
956            let sparkline = Sparkline::new(&data)
957                .with_min_marker(SparklineMarkers::DEFAULT_MIN_GLYPH, Style::default())
958                .with_max_marker(SparklineMarkers::DEFAULT_MAX_GLYPH, Style::default());
959            let area = Rect::new(0, 0, 3, 1);
960            let mut pool = GraphemePool::new();
961            let mut frame = Frame::new(3, 1, &mut pool);
962            frame.buffer.degradation = DegradationLevel::SimpleBorders;
963            Widget::render(&sparkline, area, &mut frame);
964
965            assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('^'));
966            assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('v'));
967        }
968
969        #[test]
970        fn no_markers_matches_plain_render() {
971            // With no markers set, render_to_string is byte-identical to the
972            // pre-feature output.
973            let data = [0.0, 4.0, 2.0, 8.0, 3.0];
974            let plain = Sparkline::new(&data).render_to_string();
975            let still_plain = Sparkline::new(&data)
976                .with_markers(SparklineMarkers::default())
977                .render_to_string();
978            assert_eq!(plain, still_plain);
979        }
980
981        #[test]
982        fn sparkline_markers_20x1() {
983            // A 20-wide render with a unique min at column 3 and a unique max at
984            // column 12; both markers land on exactly those columns.
985            let mut data = [5.0f64; 20];
986            data[3] = 0.0;
987            data[12] = 9.0;
988            let sparkline = Sparkline::new(&data)
989                .with_min_marker(SparklineMarkers::DEFAULT_MIN_GLYPH, Style::default())
990                .with_max_marker(SparklineMarkers::DEFAULT_MAX_GLYPH, Style::default());
991            let area = Rect::new(0, 0, 20, 1);
992            let mut pool = GraphemePool::new();
993            let mut frame = Frame::new(20, 1, &mut pool);
994            Widget::render(&sparkline, area, &mut frame);
995
996            let row: String = (0..20)
997                .map(|x| {
998                    frame
999                        .buffer
1000                        .get(x, 0)
1001                        .and_then(|c| c.content.as_char())
1002                        .unwrap_or(' ')
1003                })
1004                .collect();
1005            let chars: Vec<char> = row.chars().collect();
1006            assert_eq!(chars[3], SparklineMarkers::DEFAULT_MIN_GLYPH);
1007            assert_eq!(chars[12], SparklineMarkers::DEFAULT_MAX_GLYPH);
1008            assert_eq!(
1009                chars
1010                    .iter()
1011                    .filter(|&&c| c == SparklineMarkers::DEFAULT_MIN_GLYPH)
1012                    .count(),
1013                1
1014            );
1015            assert_eq!(
1016                chars
1017                    .iter()
1018                    .filter(|&&c| c == SparklineMarkers::DEFAULT_MAX_GLYPH)
1019                    .count(),
1020                1
1021            );
1022        }
1023
1024        proptest! {
1025            #![proptest_config(ProptestConfig::with_cases(512))]
1026
1027            /// `extreme_indices` returns the earliest indices whose values equal
1028            /// the min and max of the (NaN-free) data.
1029            #[test]
1030            fn extreme_indices_finds_earliest_extremes(
1031                data in prop::collection::vec(-100.0f64..100.0, 1..30),
1032            ) {
1033                let (min_i, max_i) = Sparkline::extreme_indices(&data)
1034                    .expect("finite data has extremes");
1035                let dmin = data.iter().copied().fold(f64::INFINITY, f64::min);
1036                let dmax = data.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1037                prop_assert_eq!(data[min_i], dmin);
1038                prop_assert_eq!(data[max_i], dmax);
1039                prop_assert!(data[..min_i].iter().all(|&v| v > dmin), "earliest min");
1040                prop_assert!(data[..max_i].iter().all(|&v| v < dmax), "earliest max");
1041            }
1042        }
1043    }
1044}