Skip to main content

ftui_widgets/
progress.rs

1#![forbid(unsafe_code)]
2
3//! Progress bar widget.
4
5use crate::block::Block;
6use crate::{
7    MeasurableWidget, SizeConstraints, Widget, apply_style, clear_text_area, clear_text_row,
8};
9use ftui_core::geometry::{Rect, Size};
10use ftui_render::cell::{Cell, PackedRgba};
11use ftui_render::frame::Frame;
12use ftui_style::Style;
13use ftui_text::display_width;
14
15/// How a [`ProgressBar`] fills: a known fraction, or an animated marquee for
16/// work of unknown duration.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum ProgressMode {
19    /// Fill proportional to the bar's `ratio` (the default).
20    #[default]
21    Determinate,
22    /// A fixed-width segment sweeps across the bar; `ratio` is ignored. The
23    /// caller supplies the animation `phase` (a tick or frame counter), so the
24    /// widget stays a stateless [`Widget`] and its output is deterministic.
25    Indeterminate {
26        /// Animation phase, typically a monotonically increasing tick count.
27        phase: u64,
28    },
29}
30
31/// A widget to display a progress bar.
32#[derive(Debug, Clone, Default)]
33pub struct ProgressBar<'a> {
34    block: Option<Block<'a>>,
35    ratio: f64,
36    label: Option<&'a str>,
37    style: Style,
38    gauge_style: Style,
39    mode: ProgressMode,
40}
41
42impl<'a> ProgressBar<'a> {
43    /// Create a new progress bar with default settings.
44    #[must_use]
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Set the surrounding block.
50    #[must_use]
51    pub fn block(mut self, block: Block<'a>) -> Self {
52        self.block = Some(block);
53        self
54    }
55
56    /// Set the progress ratio (clamped to 0.0..=1.0).
57    #[must_use]
58    pub fn ratio(mut self, ratio: f64) -> Self {
59        self.ratio = if ratio.is_nan() {
60            0.0
61        } else {
62            ratio.clamp(0.0, 1.0)
63        };
64        self
65    }
66
67    /// Set the centered label text.
68    #[must_use]
69    pub fn label(mut self, label: &'a str) -> Self {
70        self.label = Some(label);
71        self
72    }
73
74    /// Set the base style.
75    #[must_use]
76    pub fn style(mut self, style: Style) -> Self {
77        self.style = style;
78        self
79    }
80
81    /// Set the filled portion style.
82    #[must_use]
83    pub fn gauge_style(mut self, style: Style) -> Self {
84        self.gauge_style = style;
85        self
86    }
87
88    /// Switch to indeterminate mode with the given animation `phase`.
89    ///
90    /// In this mode a fixed-width segment sweeps across the bar and `ratio` is
91    /// ignored; the label (if any) is still drawn. The caller supplies `phase`
92    /// — usually a tick or frame counter driven from `Cmd::Tick`/`Every` — so
93    /// the widget remains a stateless [`Widget`] (like [`Sparkline`], unlike the
94    /// stateful `Spinner`) and renders deterministically for a given phase.
95    ///
96    /// [`Sparkline`]: crate::sparkline::Sparkline
97    #[must_use]
98    pub fn indeterminate(mut self, phase: u64) -> Self {
99        self.mode = ProgressMode::Indeterminate { phase };
100        self
101    }
102
103    /// Set the fill mode explicitly.
104    #[must_use]
105    pub fn mode(mut self, mode: ProgressMode) -> Self {
106        self.mode = mode;
107        self
108    }
109
110    /// Whether the bar is in indeterminate (marquee) mode.
111    #[must_use]
112    pub fn is_indeterminate(&self) -> bool {
113        matches!(self.mode, ProgressMode::Indeterminate { .. })
114    }
115
116    /// The visible `[start, end)` columns of the marquee segment for a bar of
117    /// `inner_width` cells at animation `phase`, or `None` when the width is 0.
118    ///
119    /// The segment is `max(3, inner_width / 5)` cells wide and its period is
120    /// `inner_width + seg`, so it enters from the left, crosses, and leaves at
121    /// the right before wrapping. The returned range is always clamped inside
122    /// `[0, inner_width)` (it may be empty while the segment is off-screen).
123    #[must_use]
124    pub fn marquee_span(inner_width: u16, phase: u64) -> Option<(u16, u16)> {
125        if inner_width == 0 {
126            return None;
127        }
128        let width = u64::from(inner_width);
129        let seg = (width / 5).max(3);
130        let period = width + seg;
131        let pos = (phase % period) as i64 - seg as i64;
132        let start = pos.max(0);
133        let end = (pos + seg as i64).clamp(0, width as i64);
134        Some((start as u16, end as u16))
135    }
136
137    /// A short label of the current mode, for the render span.
138    #[cfg(feature = "tracing")]
139    fn mode_label(&self) -> &'static str {
140        match self.mode {
141            ProgressMode::Determinate => "determinate",
142            ProgressMode::Indeterminate { .. } => "indeterminate",
143        }
144    }
145}
146
147impl<'a> Widget for ProgressBar<'a> {
148    fn render(&self, area: Rect, frame: &mut Frame) {
149        if frame.a11y_enabled() {
150            frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
151        }
152        #[cfg(feature = "tracing")]
153        let _span = tracing::debug_span!(
154            "widget_render",
155            widget = "ProgressBar",
156            x = area.x,
157            y = area.y,
158            w = area.width,
159            h = area.height,
160            mode = self.mode_label()
161        )
162        .entered();
163
164        let deg = frame.buffer.degradation;
165
166        // Skeleton+: skip entirely
167        if !deg.render_content() {
168            return;
169        }
170
171        // EssentialOnly: just show text, no bar. Determinate shows a
172        // percentage; indeterminate has none, so it shows the label or "...".
173        if !deg.render_decorative() {
174            clear_text_area(frame, area, Style::default());
175            let text = match self.mode {
176                ProgressMode::Determinate => format!("{}%", (self.ratio * 100.0) as u8),
177                ProgressMode::Indeterminate { .. } => {
178                    self.label.map_or_else(|| "...".to_string(), String::from)
179                }
180            };
181            crate::draw_text_span(frame, area.x, area.y, &text, Style::default(), area.right());
182            return;
183        }
184
185        let base_style = if deg.apply_styling() {
186            self.style
187        } else {
188            Style::default()
189        };
190
191        clear_text_area(frame, area, base_style);
192
193        let bar_area = match &self.block {
194            Some(b) => {
195                b.render(area, frame);
196                b.inner(area)
197            }
198            None => area,
199        };
200
201        if bar_area.is_empty() {
202            return;
203        }
204
205        // The gauge-styled columns: a left-anchored fill in determinate mode,
206        // or the swept marquee segment in indeterminate mode. The determinate
207        // range is byte-for-byte what it was before this branch existed.
208        let (fill_start, fill_end) = match self.mode {
209            ProgressMode::Determinate => {
210                let max_width = bar_area.width as f64;
211                let filled_width = if self.ratio >= 1.0 {
212                    bar_area.width
213                } else {
214                    (max_width * self.ratio).floor() as u16
215                };
216                (0, filled_width)
217            }
218            ProgressMode::Indeterminate { phase } => {
219                Self::marquee_span(bar_area.width, phase).unwrap_or((0, 0))
220            }
221        };
222
223        // Draw filled part
224        let gauge_style = if deg.apply_styling() {
225            self.gauge_style
226        } else {
227            // At NoStyling, use '#' as fill char instead of background color
228            Style::default()
229        };
230        let fill_char = if deg.apply_styling() { ' ' } else { '#' };
231
232        for y in bar_area.top()..bar_area.bottom() {
233            for x in fill_start..fill_end {
234                let cell_x = bar_area.left().saturating_add(x);
235                if cell_x < bar_area.right() {
236                    let mut cell = Cell::from_char(fill_char);
237                    crate::apply_style(&mut cell, gauge_style);
238                    frame.buffer.set_fast(cell_x, y, cell);
239                }
240            }
241        }
242
243        // Draw label (centered)
244        let label_style = if deg.apply_styling() {
245            self.style
246        } else {
247            Style::default()
248        };
249        if let Some(label) = self.label {
250            let label_width = display_width(label);
251            let label_x = bar_area
252                .left()
253                .saturating_add(((bar_area.width as usize).saturating_sub(label_width) / 2) as u16);
254            let label_y = bar_area.top().saturating_add(bar_area.height / 2);
255
256            crate::draw_text_span(
257                frame,
258                label_x,
259                label_y,
260                label,
261                label_style,
262                bar_area.right(),
263            );
264        }
265    }
266}
267
268impl MeasurableWidget for ProgressBar<'_> {
269    fn measure(&self, _available: Size) -> SizeConstraints {
270        // ProgressBar fills available width, has fixed height of 1 (or block inner height)
271        let (block_width, block_height) = self
272            .block
273            .as_ref()
274            .map(|b| {
275                let inner = b.inner(Rect::new(0, 0, 100, 100));
276                let w_overhead = 100u16.saturating_sub(inner.width);
277                let h_overhead = 100u16.saturating_sub(inner.height);
278                (w_overhead, h_overhead)
279            })
280            .unwrap_or((0, 0));
281
282        // Minimum: 1 cell for bar + block overhead
283        // Preferred: fills available width, 1 row + block overhead
284        let min_width = 1u16.saturating_add(block_width);
285        let min_height = 1u16.saturating_add(block_height);
286
287        SizeConstraints {
288            min: Size::new(min_width, min_height),
289            preferred: Size::new(min_width, min_height), // Fills width, so preferred = min
290            max: None,                                   // Can grow to fill available space
291        }
292    }
293
294    fn has_intrinsic_size(&self) -> bool {
295        // ProgressBar fills width, so it doesn't have true intrinsic width
296        // but it does have intrinsic height
297        true
298    }
299}
300
301// ---------------------------------------------------------------------------
302// Accessibility
303// ---------------------------------------------------------------------------
304
305impl ftui_a11y::Accessible for ProgressBar<'_> {
306    fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
307        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
308
309        let id = crate::a11y_node_id(area);
310        // Indeterminate bars have no meaningful value: omit value_now (like an
311        // ARIA indeterminate progressbar) and describe them as "in progress".
312        let state = if self.is_indeterminate() {
313            A11yState {
314                value_text: Some("in progress".to_string()),
315                ..A11yState::default()
316            }
317        } else {
318            let pct = (self.ratio * 100.0).round() as u32;
319            A11yState {
320                value_now: Some(self.ratio),
321                value_min: Some(0.0),
322                value_max: Some(1.0),
323                value_text: Some(format!("{pct}%")),
324                ..A11yState::default()
325            }
326        };
327        let name = self.label.map_or_else(
328            || {
329                state
330                    .value_text
331                    .clone()
332                    .unwrap_or_else(|| "progress".to_string())
333            },
334            String::from,
335        );
336
337        vec![
338            A11yNodeInfo::new(id, A11yRole::ProgressBar, area)
339                .with_name(name)
340                .with_state(state),
341        ]
342    }
343}
344
345// ---------------------------------------------------------------------------
346// MiniBar
347// ---------------------------------------------------------------------------
348
349/// Color thresholds for [`MiniBar`].
350#[derive(Debug, Clone, Copy)]
351pub struct MiniBarColors {
352    pub high: PackedRgba,
353    pub mid: PackedRgba,
354    pub low: PackedRgba,
355    pub critical: PackedRgba,
356}
357
358impl MiniBarColors {
359    pub fn new(high: PackedRgba, mid: PackedRgba, low: PackedRgba, critical: PackedRgba) -> Self {
360        Self {
361            high,
362            mid,
363            low,
364            critical,
365        }
366    }
367}
368
369impl Default for MiniBarColors {
370    fn default() -> Self {
371        Self {
372            high: PackedRgba::rgb(64, 200, 120),
373            mid: PackedRgba::rgb(255, 180, 64),
374            low: PackedRgba::rgb(80, 200, 240),
375            critical: PackedRgba::rgb(160, 160, 160),
376        }
377    }
378}
379
380/// Thresholds for mapping values to colors.
381#[derive(Debug, Clone, Copy)]
382pub struct MiniBarThresholds {
383    pub high: f64,
384    pub mid: f64,
385    pub low: f64,
386}
387
388impl Default for MiniBarThresholds {
389    fn default() -> Self {
390        Self {
391            high: 0.75,
392            mid: 0.50,
393            low: 0.25,
394        }
395    }
396}
397
398/// Compact progress indicator for dashboard-style metrics.
399#[derive(Debug, Clone)]
400pub struct MiniBar {
401    value: f64,
402    width: u16,
403    show_percent: bool,
404    style: Style,
405    filled_char: char,
406    empty_char: char,
407    colors: MiniBarColors,
408    thresholds: MiniBarThresholds,
409}
410
411impl MiniBar {
412    /// Create a new MiniBar with value in the 0.0..=1.0 range.
413    pub fn new(value: f64, width: u16) -> Self {
414        Self {
415            value,
416            width,
417            show_percent: false,
418            style: Style::new(),
419            filled_char: '█',
420            empty_char: '░',
421            colors: MiniBarColors::default(),
422            thresholds: MiniBarThresholds::default(),
423        }
424    }
425
426    /// Override the value (clamped to 0.0..=1.0).
427    #[must_use]
428    pub fn value(mut self, value: f64) -> Self {
429        self.value = value;
430        self
431    }
432
433    /// Override the displayed width.
434    #[must_use]
435    pub fn width(mut self, width: u16) -> Self {
436        self.width = width;
437        self
438    }
439
440    /// Enable or disable percentage text.
441    #[must_use]
442    pub fn show_percent(mut self, show: bool) -> Self {
443        self.show_percent = show;
444        self
445    }
446
447    /// Set the base style for the bar.
448    #[must_use]
449    pub fn style(mut self, style: Style) -> Self {
450        self.style = style;
451        self
452    }
453
454    /// Override the filled block character.
455    #[must_use]
456    pub fn filled_char(mut self, ch: char) -> Self {
457        self.filled_char = ch;
458        self
459    }
460
461    /// Override the empty block character.
462    #[must_use]
463    pub fn empty_char(mut self, ch: char) -> Self {
464        self.empty_char = ch;
465        self
466    }
467
468    /// Override the color thresholds.
469    #[must_use]
470    pub fn thresholds(mut self, thresholds: MiniBarThresholds) -> Self {
471        self.thresholds = thresholds;
472        self
473    }
474
475    /// Override the color palette.
476    #[must_use]
477    pub fn colors(mut self, colors: MiniBarColors) -> Self {
478        self.colors = colors;
479        self
480    }
481
482    /// Map a value to a color using default thresholds.
483    pub fn color_for_value(value: f64) -> PackedRgba {
484        let v = if value.is_finite() { value } else { 0.0 };
485        let v = v.clamp(0.0, 1.0);
486        let thresholds = MiniBarThresholds::default();
487        let colors = MiniBarColors::default();
488        if v > thresholds.high {
489            colors.high
490        } else if v > thresholds.mid {
491            colors.mid
492        } else if v > thresholds.low {
493            colors.low
494        } else {
495            colors.critical
496        }
497    }
498
499    /// Render the bar as a string (for testing/debugging).
500    pub fn render_string(&self) -> String {
501        let width = self.width as usize;
502        if width == 0 {
503            return String::new();
504        }
505        let filled = self.filled_cells(width);
506        let empty = width.saturating_sub(filled);
507        let mut out = String::with_capacity(width);
508        out.extend(std::iter::repeat_n(self.filled_char, filled));
509        out.extend(std::iter::repeat_n(self.empty_char, empty));
510        out
511    }
512
513    fn normalized_value(&self) -> f64 {
514        if self.value.is_finite() {
515            self.value.clamp(0.0, 1.0)
516        } else {
517            0.0
518        }
519    }
520
521    fn filled_cells(&self, width: usize) -> usize {
522        if width == 0 {
523            return 0;
524        }
525        let v = self.normalized_value();
526        let filled = (v * width as f64).round() as usize;
527        filled.min(width)
528    }
529
530    fn color_for_value_with_palette(&self, value: f64) -> PackedRgba {
531        let v = if value.is_finite() { value } else { 0.0 };
532        let v = v.clamp(0.0, 1.0);
533        if v > self.thresholds.high {
534            self.colors.high
535        } else if v > self.thresholds.mid {
536            self.colors.mid
537        } else if v > self.thresholds.low {
538            self.colors.low
539        } else {
540            self.colors.critical
541        }
542    }
543}
544
545impl Widget for MiniBar {
546    fn render(&self, area: Rect, frame: &mut Frame) {
547        #[cfg(feature = "tracing")]
548        let _span = tracing::debug_span!(
549            "widget_render",
550            widget = "MiniBar",
551            x = area.x,
552            y = area.y,
553            w = area.width,
554            h = area.height
555        )
556        .entered();
557
558        if area.is_empty() {
559            return;
560        }
561
562        let deg = frame.buffer.degradation;
563        if !deg.render_content() {
564            return;
565        }
566
567        let base_style = if deg.apply_styling() {
568            self.style
569        } else {
570            Style::default()
571        };
572        clear_text_row(frame, area, base_style);
573
574        let value = self.normalized_value();
575
576        if !deg.render_decorative() {
577            if self.show_percent {
578                let pct = format!("{:3.0}%", value * 100.0);
579                let pct_width = display_width(&pct) as u16;
580                if area.width >= pct_width {
581                    let text_x = area.right().saturating_sub(pct_width);
582                    crate::draw_text_span(
583                        frame,
584                        text_x,
585                        area.y,
586                        &pct,
587                        Style::default(),
588                        area.right(),
589                    );
590                } else {
591                    crate::draw_text_span(
592                        frame,
593                        area.x,
594                        area.y,
595                        pct.trim_start(),
596                        Style::default(),
597                        area.right(),
598                    );
599                }
600            }
601            return;
602        }
603
604        let mut bar_width = self.width.min(area.width) as usize;
605        let mut render_percent = false;
606        let mut percent_text = String::new();
607        let mut percent_only_text = String::new();
608        let percent_width = if self.show_percent {
609            percent_text = format!(" {:3.0}%", value * 100.0);
610            percent_only_text = percent_text.trim_start().to_owned();
611            render_percent = true;
612            display_width(&percent_text) as u16
613        } else {
614            0
615        };
616
617        if render_percent {
618            if area.width <= percent_width {
619                bar_width = 0;
620            } else {
621                let available = area.width - percent_width;
622                bar_width = bar_width.min(available as usize);
623            }
624        }
625
626        if bar_width == 0 {
627            if render_percent {
628                crate::draw_text_span(
629                    frame,
630                    area.x,
631                    area.y,
632                    &percent_only_text,
633                    Style::default(),
634                    area.right(),
635                );
636            }
637            return;
638        }
639
640        let color = self.color_for_value_with_palette(value);
641        let filled = self.filled_cells(bar_width);
642
643        for i in 0..bar_width {
644            let x = area.x + i as u16;
645            if x >= area.right() {
646                break;
647            }
648            let ch = if i < filled {
649                self.filled_char
650            } else {
651                self.empty_char
652            };
653            let mut cell = Cell::from_char(ch);
654            if deg.apply_styling() {
655                apply_style(&mut cell, self.style);
656                if i < filled {
657                    cell.fg = color;
658                }
659            }
660            frame.buffer.set_fast(x, area.y, cell);
661        }
662
663        if render_percent {
664            let text_x = area.x + bar_width as u16;
665            crate::draw_text_span(
666                frame,
667                text_x,
668                area.y,
669                &percent_text,
670                Style::default(),
671                area.right(),
672            );
673        }
674    }
675}
676
677impl MeasurableWidget for MiniBar {
678    fn measure(&self, _available: Size) -> SizeConstraints {
679        // MiniBar has fixed dimensions
680        let percent_width = if self.show_percent { 5 } else { 0 }; // " XXX%"
681        let total_width = self.width.saturating_add(percent_width);
682
683        SizeConstraints {
684            min: Size::new(1, 1), // At least show something
685            preferred: Size::new(total_width, 1),
686            max: Some(Size::new(total_width, 1)), // Fixed size
687        }
688    }
689
690    fn has_intrinsic_size(&self) -> bool {
691        self.width > 0
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698    use ftui_render::cell::PackedRgba;
699    use ftui_render::grapheme_pool::GraphemePool;
700
701    fn cell_at(frame: &Frame, x: u16, y: u16) -> Cell {
702        let cell = frame.buffer.get(x, y).copied();
703        assert!(cell.is_some(), "test cell should exist at ({x},{y})");
704        cell.unwrap()
705    }
706
707    fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
708        (0..width)
709            .map(|x| {
710                frame
711                    .buffer
712                    .get(x, y)
713                    .and_then(|cell| cell.content.as_char())
714                    .unwrap_or(' ')
715            })
716            .collect()
717    }
718
719    // --- Builder tests ---
720
721    #[test]
722    fn default_progress_bar() {
723        let pb = ProgressBar::new();
724        assert_eq!(pb.ratio, 0.0);
725        assert!(pb.label.is_none());
726        assert!(pb.block.is_none());
727    }
728
729    #[test]
730    fn ratio_clamped_above_one() {
731        let pb = ProgressBar::new().ratio(1.5);
732        assert_eq!(pb.ratio, 1.0);
733    }
734
735    #[test]
736    fn ratio_clamped_below_zero() {
737        let pb = ProgressBar::new().ratio(-0.5);
738        assert_eq!(pb.ratio, 0.0);
739    }
740
741    #[test]
742    fn ratio_normal_range() {
743        let pb = ProgressBar::new().ratio(0.5);
744        assert!((pb.ratio - 0.5).abs() < f64::EPSILON);
745    }
746
747    #[test]
748    fn builder_label() {
749        let pb = ProgressBar::new().label("50%");
750        assert_eq!(pb.label, Some("50%"));
751    }
752
753    // --- Rendering tests ---
754
755    #[test]
756    fn render_zero_area() {
757        let pb = ProgressBar::new().ratio(0.5);
758        let area = Rect::new(0, 0, 0, 0);
759        let mut pool = GraphemePool::new();
760        let mut frame = Frame::new(1, 1, &mut pool);
761        Widget::render(&pb, area, &mut frame);
762        // Should not panic
763    }
764
765    #[test]
766    fn render_zero_ratio_no_fill() {
767        let gauge_style = Style::new().bg(PackedRgba::RED);
768        let pb = ProgressBar::new().ratio(0.0).gauge_style(gauge_style);
769        let area = Rect::new(0, 0, 10, 1);
770        let mut pool = GraphemePool::new();
771        let mut frame = Frame::new(10, 1, &mut pool);
772        Widget::render(&pb, area, &mut frame);
773
774        // No cells should have the gauge style bg
775        for x in 0..10 {
776            let cell = cell_at(&frame, x, 0);
777            assert_ne!(
778                cell.bg,
779                PackedRgba::RED,
780                "cell at x={x} should not have gauge bg"
781            );
782        }
783    }
784
785    #[test]
786    fn render_full_ratio_fills_all() {
787        let gauge_style = Style::new().bg(PackedRgba::GREEN);
788        let pb = ProgressBar::new().ratio(1.0).gauge_style(gauge_style);
789        let area = Rect::new(0, 0, 10, 1);
790        let mut pool = GraphemePool::new();
791        let mut frame = Frame::new(10, 1, &mut pool);
792        Widget::render(&pb, area, &mut frame);
793
794        // All cells should have gauge bg
795        for x in 0..10 {
796            let cell = cell_at(&frame, x, 0);
797            assert_eq!(
798                cell.bg,
799                PackedRgba::GREEN,
800                "cell at x={x} should have gauge bg"
801            );
802        }
803    }
804
805    #[test]
806    fn render_half_ratio() {
807        let gauge_style = Style::new().bg(PackedRgba::BLUE);
808        let pb = ProgressBar::new().ratio(0.5).gauge_style(gauge_style);
809        let area = Rect::new(0, 0, 10, 1);
810        let mut pool = GraphemePool::new();
811        let mut frame = Frame::new(10, 1, &mut pool);
812        Widget::render(&pb, area, &mut frame);
813
814        // About 5 cells should be filled (10 * 0.5 = 5)
815        let filled_count = (0..10)
816            .filter(|&x| cell_at(&frame, x, 0).bg == PackedRgba::BLUE)
817            .count();
818        assert_eq!(filled_count, 5);
819    }
820
821    #[test]
822    fn render_multi_row_bar() {
823        let gauge_style = Style::new().bg(PackedRgba::RED);
824        let pb = ProgressBar::new().ratio(1.0).gauge_style(gauge_style);
825        let area = Rect::new(0, 0, 5, 3);
826        let mut pool = GraphemePool::new();
827        let mut frame = Frame::new(5, 3, &mut pool);
828        Widget::render(&pb, area, &mut frame);
829
830        // All 3 rows should be filled
831        for y in 0..3 {
832            for x in 0..5 {
833                let cell = cell_at(&frame, x, y);
834                assert_eq!(
835                    cell.bg,
836                    PackedRgba::RED,
837                    "cell at ({x},{y}) should have gauge bg"
838                );
839            }
840        }
841    }
842
843    #[test]
844    fn render_with_label_centered() {
845        let pb = ProgressBar::new().ratio(0.5).label("50%");
846        let area = Rect::new(0, 0, 10, 1);
847        let mut pool = GraphemePool::new();
848        let mut frame = Frame::new(10, 1, &mut pool);
849        Widget::render(&pb, area, &mut frame);
850
851        // Label "50%" is 3 chars wide, centered in 10 = starts at x=3
852        // (10 - 3) / 2 = 3
853        let c = frame.buffer.get(3, 0).and_then(|c| c.content.as_char());
854        assert_eq!(c, Some('5'));
855        let c = frame.buffer.get(4, 0).and_then(|c| c.content.as_char());
856        assert_eq!(c, Some('0'));
857        let c = frame.buffer.get(5, 0).and_then(|c| c.content.as_char());
858        assert_eq!(c, Some('%'));
859    }
860
861    #[test]
862    fn render_with_block() {
863        let pb = ProgressBar::new()
864            .ratio(1.0)
865            .gauge_style(Style::new().bg(PackedRgba::GREEN))
866            .block(Block::bordered());
867        // Block::bordered() includes 1 cell padding on each side, so we need
868        // at least 5 rows to have a 1-row inner content area.
869        let area = Rect::new(0, 0, 10, 5);
870        let mut pool = GraphemePool::new();
871        let mut frame = Frame::new(10, 5, &mut pool);
872        Widget::render(&pb, area, &mut frame);
873
874        // Inner area is 6x1 (borders + padding take 2 on each side)
875        // All inner cells should have gauge bg
876        for x in 2..8 {
877            let cell = cell_at(&frame, x, 2);
878            assert_eq!(
879                cell.bg,
880                PackedRgba::GREEN,
881                "inner cell at x={x} should have gauge bg"
882            );
883        }
884    }
885
886    // --- Degradation tests ---
887
888    #[test]
889    fn degradation_skeleton_skips_entirely() {
890        use ftui_render::budget::DegradationLevel;
891
892        let pb = ProgressBar::new()
893            .ratio(0.5)
894            .gauge_style(Style::new().bg(PackedRgba::GREEN));
895        let area = Rect::new(0, 0, 10, 1);
896        let mut pool = GraphemePool::new();
897        let mut frame = Frame::new(10, 1, &mut pool);
898        frame.buffer.degradation = DegradationLevel::Skeleton;
899        Widget::render(&pb, area, &mut frame);
900
901        // Nothing should be rendered
902        for x in 0..10 {
903            assert!(
904                cell_at(&frame, x, 0).is_empty(),
905                "cell at x={x} should be empty at Skeleton"
906            );
907        }
908    }
909
910    #[test]
911    fn degradation_essential_only_shows_percentage() {
912        use ftui_render::budget::DegradationLevel;
913
914        let pb = ProgressBar::new()
915            .ratio(0.5)
916            .gauge_style(Style::new().bg(PackedRgba::GREEN));
917        let area = Rect::new(0, 0, 10, 1);
918        let mut pool = GraphemePool::new();
919        let mut frame = Frame::new(10, 1, &mut pool);
920        frame.buffer.degradation = DegradationLevel::EssentialOnly;
921        Widget::render(&pb, area, &mut frame);
922
923        // Should show "50%" text, no gauge bar
924        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
925        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some('0'));
926        assert_eq!(cell_at(&frame, 2, 0).content.as_char(), Some('%'));
927        // No gauge background color
928        assert_ne!(cell_at(&frame, 0, 0).bg, PackedRgba::GREEN);
929    }
930
931    #[test]
932    fn degradation_full_renders_bar() {
933        use ftui_render::budget::DegradationLevel;
934
935        let pb = ProgressBar::new()
936            .ratio(1.0)
937            .gauge_style(Style::new().bg(PackedRgba::BLUE));
938        let area = Rect::new(0, 0, 10, 1);
939        let mut pool = GraphemePool::new();
940        let mut frame = Frame::new(10, 1, &mut pool);
941        frame.buffer.degradation = DegradationLevel::Full;
942        Widget::render(&pb, area, &mut frame);
943
944        // All cells should have gauge bg
945        for x in 0..10 {
946            assert_eq!(
947                cell_at(&frame, x, 0).bg,
948                PackedRgba::BLUE,
949                "cell at x={x} should have gauge bg at Full"
950            );
951        }
952    }
953
954    #[test]
955    fn render_no_styling_ratio_shrink_clears_stale_fill() {
956        use ftui_render::budget::DegradationLevel;
957
958        let area = Rect::new(0, 0, 10, 1);
959        let mut pool = GraphemePool::new();
960        let mut frame = Frame::new(10, 1, &mut pool);
961        frame.buffer.degradation = DegradationLevel::NoStyling;
962
963        Widget::render(&ProgressBar::new().ratio(0.8), area, &mut frame);
964        Widget::render(&ProgressBar::new().ratio(0.2), area, &mut frame);
965
966        assert_eq!(raw_row_text(&frame, 0, 10), "##        ");
967    }
968
969    #[test]
970    fn degradation_essential_only_clears_previous_bar_content() {
971        use ftui_render::budget::DegradationLevel;
972
973        let pb = ProgressBar::new().ratio(0.5);
974        let area = Rect::new(0, 0, 10, 1);
975        let mut pool = GraphemePool::new();
976        let mut frame = Frame::new(10, 1, &mut pool);
977
978        Widget::render(&pb, area, &mut frame);
979        frame.buffer.degradation = DegradationLevel::EssentialOnly;
980        Widget::render(&pb, area, &mut frame);
981
982        assert_eq!(raw_row_text(&frame, 0, 10), "50%       ");
983    }
984
985    // --- MiniBar tests ---
986
987    #[test]
988    fn minibar_zero_is_empty() {
989        let bar = MiniBar::new(0.0, 10);
990        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
991        assert_eq!(filled, 0);
992    }
993
994    #[test]
995    fn minibar_full_is_complete() {
996        let bar = MiniBar::new(1.0, 10);
997        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
998        assert_eq!(filled, 10);
999    }
1000
1001    #[test]
1002    fn minibar_half_is_half() {
1003        let bar = MiniBar::new(0.5, 10);
1004        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1005        assert!((4..=6).contains(&filled));
1006    }
1007
1008    #[test]
1009    fn minibar_color_thresholds() {
1010        let high = MiniBar::color_for_value(0.80);
1011        let mid = MiniBar::color_for_value(0.60);
1012        let low = MiniBar::color_for_value(0.30);
1013        let crit = MiniBar::color_for_value(0.10);
1014        assert_ne!(high, mid);
1015        assert_ne!(mid, low);
1016        assert_ne!(low, crit);
1017    }
1018
1019    #[test]
1020    fn minibar_respects_width() {
1021        for width in [5, 10, 20] {
1022            let bar = MiniBar::new(0.5, width);
1023            assert_eq!(bar.render_string().chars().count(), width as usize);
1024        }
1025    }
1026
1027    // --- MeasurableWidget tests ---
1028
1029    #[test]
1030    fn progress_bar_measure_has_intrinsic_size() {
1031        let pb = ProgressBar::new();
1032        assert!(pb.has_intrinsic_size());
1033    }
1034
1035    #[test]
1036    fn progress_bar_measure_min_size() {
1037        let pb = ProgressBar::new();
1038        let c = pb.measure(Size::MAX);
1039
1040        assert_eq!(c.min.width, 1);
1041        assert_eq!(c.min.height, 1);
1042        assert!(c.max.is_none()); // Fills available width
1043    }
1044
1045    #[test]
1046    fn progress_bar_measure_with_block() {
1047        let pb = ProgressBar::new().block(Block::bordered());
1048        let c = pb.measure(Size::MAX);
1049
1050        // Block adds chrome (borders + padding) = 4 on each axis.
1051        assert_eq!(c.min.width, 5);
1052        assert_eq!(c.min.height, 5);
1053    }
1054
1055    #[test]
1056    fn minibar_measure_fixed_width() {
1057        let bar = MiniBar::new(0.5, 10);
1058        let c = bar.measure(Size::MAX);
1059
1060        assert_eq!(c.preferred.width, 10);
1061        assert_eq!(c.preferred.height, 1);
1062        assert_eq!(c.max, Some(Size::new(10, 1)));
1063    }
1064
1065    #[test]
1066    fn minibar_measure_with_percent() {
1067        let bar = MiniBar::new(0.5, 10).show_percent(true);
1068        let c = bar.measure(Size::MAX);
1069
1070        // Width = 10 + 5 (" XXX%") = 15
1071        assert_eq!(c.preferred.width, 15);
1072        assert_eq!(c.preferred.height, 1);
1073    }
1074
1075    #[test]
1076    fn minibar_measure_has_intrinsic_size() {
1077        let bar = MiniBar::new(0.5, 10);
1078        assert!(bar.has_intrinsic_size());
1079
1080        let zero_width = MiniBar::new(0.5, 0);
1081        assert!(!zero_width.has_intrinsic_size());
1082    }
1083
1084    // ── Edge-case tests (bd-3b82x) ──────────────────────────
1085
1086    #[test]
1087    fn ratio_nan_clamped_to_zero() {
1088        let pb = ProgressBar::new().ratio(f64::NAN);
1089        // We now safely handle NaN in the ratio setter to avoid clamping panic.
1090        // The render path uses floor() which handles NaN → 0
1091        let mut pool = GraphemePool::new();
1092        let mut frame = Frame::new(10, 1, &mut pool);
1093        let area = Rect::new(0, 0, 10, 1);
1094        Widget::render(&pb, area, &mut frame);
1095    }
1096
1097    #[test]
1098    fn ratio_infinity_clamped() {
1099        let pb = ProgressBar::new().ratio(f64::INFINITY);
1100        assert_eq!(pb.ratio, 1.0);
1101
1102        let pb_neg = ProgressBar::new().ratio(f64::NEG_INFINITY);
1103        assert_eq!(pb_neg.ratio, 0.0);
1104    }
1105
1106    #[test]
1107    fn label_wider_than_area() {
1108        let pb = ProgressBar::new()
1109            .ratio(0.5)
1110            .label("This is a very long label text");
1111        let mut pool = GraphemePool::new();
1112        let mut frame = Frame::new(10, 1, &mut pool);
1113        let area = Rect::new(0, 0, 5, 1);
1114        Widget::render(&pb, area, &mut frame); // Should not panic, truncated
1115    }
1116
1117    #[test]
1118    fn label_on_multi_row_bar_vertically_centered() {
1119        let pb = ProgressBar::new().ratio(0.5).label("X");
1120        let mut pool = GraphemePool::new();
1121        let mut frame = Frame::new(10, 5, &mut pool);
1122        let area = Rect::new(0, 0, 10, 5);
1123        Widget::render(&pb, area, &mut frame);
1124        // label_y = top + height/2 = 0 + 2 = 2
1125        let c = frame.buffer.get(4, 2).and_then(|c| c.content.as_char());
1126        assert_eq!(c, Some('X'));
1127    }
1128
1129    #[test]
1130    fn empty_label_renders_no_text() {
1131        let pb = ProgressBar::new().ratio(0.5).label("");
1132        let mut pool = GraphemePool::new();
1133        let mut frame = Frame::new(10, 1, &mut pool);
1134        let area = Rect::new(0, 0, 10, 1);
1135        Widget::render(&pb, area, &mut frame); // Should not panic
1136    }
1137
1138    #[test]
1139    fn progress_bar_clone_and_debug() {
1140        let pb = ProgressBar::new().ratio(0.5).label("test");
1141        let cloned = pb.clone();
1142        assert!((cloned.ratio - 0.5).abs() < f64::EPSILON);
1143        assert_eq!(cloned.label, Some("test"));
1144        let dbg = format!("{:?}", pb);
1145        assert!(dbg.contains("ProgressBar"));
1146    }
1147
1148    #[test]
1149    fn progress_bar_default_trait() {
1150        let pb = ProgressBar::default();
1151        assert_eq!(pb.ratio, 0.0);
1152        assert!(pb.label.is_none());
1153    }
1154
1155    #[test]
1156    fn render_width_one() {
1157        let pb = ProgressBar::new()
1158            .ratio(1.0)
1159            .gauge_style(Style::new().bg(PackedRgba::RED));
1160        let mut pool = GraphemePool::new();
1161        let mut frame = Frame::new(1, 1, &mut pool);
1162        let area = Rect::new(0, 0, 1, 1);
1163        Widget::render(&pb, area, &mut frame);
1164        assert_eq!(cell_at(&frame, 0, 0).bg, PackedRgba::RED);
1165    }
1166
1167    #[test]
1168    fn render_ratio_just_above_zero() {
1169        let pb = ProgressBar::new()
1170            .ratio(0.01)
1171            .gauge_style(Style::new().bg(PackedRgba::GREEN));
1172        let mut pool = GraphemePool::new();
1173        let mut frame = Frame::new(100, 1, &mut pool);
1174        let area = Rect::new(0, 0, 100, 1);
1175        Widget::render(&pb, area, &mut frame);
1176        // floor(100 * 0.01) = 1 cell filled
1177        assert_eq!(cell_at(&frame, 0, 0).bg, PackedRgba::GREEN);
1178        assert_ne!(cell_at(&frame, 1, 0).bg, PackedRgba::GREEN);
1179    }
1180
1181    // --- MiniBar edge cases ---
1182
1183    #[test]
1184    fn minibar_nan_value_treated_as_zero() {
1185        let bar = MiniBar::new(f64::NAN, 10);
1186        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1187        assert_eq!(filled, 0);
1188    }
1189
1190    #[test]
1191    fn minibar_infinity_clamped_to_full() {
1192        let bar = MiniBar::new(f64::INFINITY, 10);
1193        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1194        assert_eq!(filled, 0); // NaN/Inf → normalized_value returns 0.0
1195    }
1196
1197    #[test]
1198    fn minibar_negative_value() {
1199        let bar = MiniBar::new(-0.5, 10);
1200        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1201        assert_eq!(filled, 0);
1202    }
1203
1204    #[test]
1205    fn minibar_value_above_one() {
1206        let bar = MiniBar::new(1.5, 10);
1207        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1208        assert_eq!(filled, 10); // clamped to 1.0
1209    }
1210
1211    #[test]
1212    fn minibar_width_zero() {
1213        let bar = MiniBar::new(0.5, 0);
1214        assert_eq!(bar.render_string(), "");
1215    }
1216
1217    #[test]
1218    fn minibar_width_one() {
1219        let bar = MiniBar::new(1.0, 1);
1220        let s = bar.render_string();
1221        assert_eq!(s.chars().count(), 1);
1222        assert_eq!(s.chars().next(), Some('█'));
1223    }
1224
1225    #[test]
1226    fn minibar_custom_chars() {
1227        let bar = MiniBar::new(0.5, 4).filled_char('#').empty_char('-');
1228        let s = bar.render_string();
1229        assert!(s.contains('#'));
1230        assert!(s.contains('-'));
1231        assert_eq!(s.chars().count(), 4);
1232    }
1233
1234    #[test]
1235    fn minibar_value_and_width_setters() {
1236        let bar = MiniBar::new(0.0, 5).value(1.0).width(3);
1237        assert_eq!(bar.render_string().chars().count(), 3);
1238        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1239        assert_eq!(filled, 3);
1240    }
1241
1242    #[test]
1243    fn minibar_color_boundary_exactly_at_high() {
1244        // Default high threshold is 0.75; at exactly 0.75, value is NOT > 0.75
1245        let at_thresh = MiniBar::color_for_value(0.75);
1246        let above = MiniBar::color_for_value(0.76);
1247        let defaults = MiniBarColors::default();
1248        assert_eq!(above, defaults.high);
1249        assert_eq!(at_thresh, defaults.mid); // not above high threshold
1250    }
1251
1252    #[test]
1253    fn minibar_color_boundary_exactly_at_mid() {
1254        let at_thresh = MiniBar::color_for_value(0.50);
1255        let defaults = MiniBarColors::default();
1256        assert_eq!(at_thresh, defaults.low); // not above mid threshold
1257    }
1258
1259    #[test]
1260    fn minibar_color_boundary_exactly_at_low() {
1261        let at_thresh = MiniBar::color_for_value(0.25);
1262        let defaults = MiniBarColors::default();
1263        assert_eq!(at_thresh, defaults.critical); // not above low threshold
1264    }
1265
1266    #[test]
1267    fn minibar_color_for_value_nan() {
1268        let c = MiniBar::color_for_value(f64::NAN);
1269        let defaults = MiniBarColors::default();
1270        assert_eq!(c, defaults.critical); // NaN → 0.0 → critical
1271    }
1272
1273    #[test]
1274    fn minibar_colors_new() {
1275        let r = PackedRgba::rgb(255, 0, 0);
1276        let g = PackedRgba::rgb(0, 255, 0);
1277        let b = PackedRgba::rgb(0, 0, 255);
1278        let w = PackedRgba::rgb(255, 255, 255);
1279        let colors = MiniBarColors::new(r, g, b, w);
1280        assert_eq!(colors.high, r);
1281        assert_eq!(colors.mid, g);
1282        assert_eq!(colors.low, b);
1283        assert_eq!(colors.critical, w);
1284    }
1285
1286    #[test]
1287    fn minibar_custom_thresholds_and_colors() {
1288        let colors = MiniBarColors::new(
1289            PackedRgba::rgb(1, 1, 1),
1290            PackedRgba::rgb(2, 2, 2),
1291            PackedRgba::rgb(3, 3, 3),
1292            PackedRgba::rgb(4, 4, 4),
1293        );
1294        let thresholds = MiniBarThresholds {
1295            high: 0.9,
1296            mid: 0.5,
1297            low: 0.1,
1298        };
1299        let bar = MiniBar::new(0.95, 10).colors(colors).thresholds(thresholds);
1300        let c = bar.color_for_value_with_palette(0.95);
1301        assert_eq!(c, PackedRgba::rgb(1, 1, 1));
1302    }
1303
1304    #[test]
1305    fn minibar_clone_and_debug() {
1306        let bar = MiniBar::new(0.5, 10).show_percent(true);
1307        let cloned = bar.clone();
1308        assert_eq!(cloned.render_string(), bar.render_string());
1309        let dbg = format!("{:?}", bar);
1310        assert!(dbg.contains("MiniBar"));
1311    }
1312
1313    #[test]
1314    fn minibar_render_zero_area() {
1315        let bar = MiniBar::new(0.5, 10);
1316        let mut pool = GraphemePool::new();
1317        let mut frame = Frame::new(10, 1, &mut pool);
1318        let area = Rect::new(0, 0, 0, 0);
1319        Widget::render(&bar, area, &mut frame); // Should not panic
1320    }
1321
1322    #[test]
1323    fn minibar_render_with_percent_narrow() {
1324        let bar = MiniBar::new(0.5, 10).show_percent(true);
1325        let mut pool = GraphemePool::new();
1326        let mut frame = Frame::new(5, 1, &mut pool);
1327        // Area smaller than bar_width + percent_width
1328        let area = Rect::new(0, 0, 5, 1);
1329        Widget::render(&bar, area, &mut frame); // Should adapt or truncate
1330    }
1331
1332    #[test]
1333    fn minibar_render_percent_only_no_bar_room() {
1334        let bar = MiniBar::new(0.5, 10).show_percent(true);
1335        let mut pool = GraphemePool::new();
1336        let mut frame = Frame::new(5, 1, &mut pool);
1337        // Area of width 5, percent takes 5 (" XXX%"), bar_width gets 0
1338        let area = Rect::new(0, 0, 5, 1);
1339        Widget::render(&bar, area, &mut frame);
1340        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
1341    }
1342
1343    #[test]
1344    fn minibar_render_percent_only_starts_with_digits_in_tight_widths() {
1345        let bar = MiniBar::new(0.5, 10).show_percent(true);
1346        let mut pool = GraphemePool::new();
1347        let mut frame = Frame::new(2, 1, &mut pool);
1348        Widget::render(&bar, Rect::new(0, 0, 2, 1), &mut frame);
1349
1350        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
1351        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some('0'));
1352    }
1353
1354    #[test]
1355    fn minibar_essential_only_percent_starts_with_digits_in_tight_widths() {
1356        use ftui_render::budget::DegradationLevel;
1357
1358        let bar = MiniBar::new(0.5, 10).show_percent(true);
1359        let mut pool = GraphemePool::new();
1360        let mut frame = Frame::new(2, 1, &mut pool);
1361        frame.buffer.degradation = DegradationLevel::EssentialOnly;
1362        Widget::render(&bar, Rect::new(0, 0, 2, 1), &mut frame);
1363
1364        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
1365        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some('0'));
1366    }
1367
1368    #[test]
1369    fn minibar_essential_only_right_aligns_percent_when_width_allows() {
1370        use ftui_render::budget::DegradationLevel;
1371
1372        let bar = MiniBar::new(0.5, 10).show_percent(true);
1373        let mut pool = GraphemePool::new();
1374        let mut frame = Frame::new(7, 1, &mut pool);
1375        frame.buffer.degradation = DegradationLevel::EssentialOnly;
1376        Widget::render(&bar, Rect::new(0, 0, 7, 1), &mut frame);
1377
1378        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some(' '));
1379        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some(' '));
1380        assert_eq!(cell_at(&frame, 2, 0).content.as_char(), Some(' '));
1381        assert_eq!(cell_at(&frame, 3, 0).content.as_char(), Some(' '));
1382        assert_eq!(cell_at(&frame, 4, 0).content.as_char(), Some('5'));
1383        assert_eq!(cell_at(&frame, 5, 0).content.as_char(), Some('0'));
1384        assert_eq!(cell_at(&frame, 6, 0).content.as_char(), Some('%'));
1385    }
1386
1387    #[test]
1388    fn minibar_essential_only_clears_previous_bar_content() {
1389        use ftui_render::budget::DegradationLevel;
1390
1391        let bar = MiniBar::new(0.5, 10).show_percent(true);
1392        let area = Rect::new(0, 0, 7, 1);
1393        let mut pool = GraphemePool::new();
1394        let mut frame = Frame::new(7, 1, &mut pool);
1395
1396        Widget::render(&bar, area, &mut frame);
1397        frame.buffer.degradation = DegradationLevel::EssentialOnly;
1398        Widget::render(&bar, area, &mut frame);
1399
1400        assert_eq!(raw_row_text(&frame, 0, 7), "    50%");
1401    }
1402
1403    #[test]
1404    fn minibar_thresholds_default_values() {
1405        let t = MiniBarThresholds::default();
1406        assert!((t.high - 0.75).abs() < f64::EPSILON);
1407        assert!((t.mid - 0.50).abs() < f64::EPSILON);
1408        assert!((t.low - 0.25).abs() < f64::EPSILON);
1409    }
1410
1411    #[test]
1412    fn minibar_colors_default_not_all_same() {
1413        let c = MiniBarColors::default();
1414        assert_ne!(c.high, c.mid);
1415        assert_ne!(c.mid, c.low);
1416        assert_ne!(c.low, c.critical);
1417    }
1418
1419    #[test]
1420    fn minibar_colors_copy() {
1421        let c = MiniBarColors::default();
1422        let c2 = c; // Copy
1423        assert_eq!(c.high, c2.high);
1424    }
1425
1426    #[test]
1427    fn minibar_thresholds_copy() {
1428        let t = MiniBarThresholds::default();
1429        let t2 = t; // Copy
1430        assert!((t.high - t2.high).abs() < f64::EPSILON);
1431    }
1432
1433    #[test]
1434    fn minibar_style_setter() {
1435        let bar = MiniBar::new(0.5, 10).style(Style::new().bold());
1436        let dbg = format!("{:?}", bar);
1437        assert!(dbg.contains("MiniBar"));
1438    }
1439
1440    mod indeterminate_tests {
1441        use super::*;
1442        use proptest::prelude::*;
1443
1444        /// Render `pb` to a `width`x1 frame and return, for each column, whether
1445        /// its background is `bg` (i.e. it is a gauge-filled cell).
1446        fn gauge_cols(pb: &ProgressBar, width: u16, bg: PackedRgba) -> Vec<bool> {
1447            let mut pool = GraphemePool::new();
1448            let mut frame = Frame::new(width, 1, &mut pool);
1449            Widget::render(pb, Rect::new(0, 0, width, 1), &mut frame);
1450            (0..width).map(|x| cell_at(&frame, x, 0).bg == bg).collect()
1451        }
1452
1453        #[test]
1454        fn indeterminate_marquee_wraps() {
1455            // width 40, seg = 40/5 = 8, period = 48.
1456            assert_eq!(ProgressBar::marquee_span(40, 0), Some((0, 0)));
1457            assert_eq!(ProgressBar::marquee_span(40, 3), Some((0, 3)));
1458            assert_eq!(ProgressBar::marquee_span(40, 7), Some((0, 7)));
1459            assert_eq!(ProgressBar::marquee_span(40, 8), Some((0, 8)));
1460            assert_eq!(ProgressBar::marquee_span(40, 20), Some((12, 20)));
1461            assert_eq!(ProgressBar::marquee_span(40, 47), Some((39, 40)));
1462            // Wraps at inner_width + seg = 48.
1463            assert_eq!(ProgressBar::marquee_span(40, 48), Some((0, 0)));
1464            assert_eq!(
1465                ProgressBar::marquee_span(40, 48 + 8),
1466                ProgressBar::marquee_span(40, 8)
1467            );
1468        }
1469
1470        #[test]
1471        fn indeterminate_width_one_and_zero() {
1472            // Zero width has no span.
1473            assert_eq!(ProgressBar::marquee_span(0, 5), None);
1474            // Width 1 (seg clamps to 3) stays inside [0, 1] for every phase.
1475            for phase in 0..10u64 {
1476                let (start, end) = ProgressBar::marquee_span(1, phase).expect("width 1");
1477                assert!(start <= end && end <= 1, "phase {phase}: {start}..{end}");
1478            }
1479            // Rendering width 1 must not panic.
1480            let pb = ProgressBar::new()
1481                .indeterminate(3)
1482                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1483            let _ = gauge_cols(&pb, 1, PackedRgba::BLUE);
1484        }
1485
1486        #[test]
1487        fn determinate_unchanged_by_mode_default() {
1488            let pb = ProgressBar::new()
1489                .ratio(0.5)
1490                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1491            assert!(!pb.is_indeterminate());
1492            let cols = gauge_cols(&pb, 40, PackedRgba::BLUE);
1493            // 0.5 * 40 = 20 cells filled from the left, exactly as before.
1494            assert!(cols[..20].iter().all(|&f| f), "left half filled");
1495            assert!(cols[20..].iter().all(|&f| !f), "right half empty");
1496        }
1497
1498        #[test]
1499        fn indeterminate_render_highlights_marquee() {
1500            let pb = ProgressBar::new()
1501                .indeterminate(8)
1502                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1503            assert!(pb.is_indeterminate());
1504            // phase 8 -> span (0, 8): cols 0..8 highlighted, the rest not.
1505            let cols = gauge_cols(&pb, 40, PackedRgba::BLUE);
1506            assert!(cols[..8].iter().all(|&f| f), "marquee segment filled");
1507            assert!(cols[8..].iter().all(|&f| !f), "rest of bar empty");
1508        }
1509
1510        #[test]
1511        fn indeterminate_ignores_ratio() {
1512            // The marquee is identical whatever the ratio is set to.
1513            let high = ProgressBar::new()
1514                .indeterminate(8)
1515                .ratio(0.9)
1516                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1517            let low = ProgressBar::new()
1518                .indeterminate(8)
1519                .ratio(0.1)
1520                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1521            assert_eq!(
1522                gauge_cols(&high, 40, PackedRgba::BLUE),
1523                gauge_cols(&low, 40, PackedRgba::BLUE)
1524            );
1525        }
1526
1527        proptest! {
1528            #![proptest_config(ProptestConfig::with_cases(1000))]
1529
1530            /// The marquee span is `None` iff the width is 0; otherwise it is a
1531            /// non-empty-to-empty range clamped inside the bar and no wider than
1532            /// the segment.
1533            #[test]
1534            fn marquee_span_always_inside_area(width in 0u16..=200, phase in any::<u64>()) {
1535                match ProgressBar::marquee_span(width, phase) {
1536                    None => prop_assert_eq!(width, 0),
1537                    Some((start, end)) => {
1538                        prop_assert_ne!(width, 0);
1539                        prop_assert!(start <= end);
1540                        prop_assert!(end <= width);
1541                        let seg = (u64::from(width) / 5).max(3);
1542                        prop_assert!(u64::from(end - start) <= seg);
1543                    }
1544                }
1545            }
1546        }
1547    }
1548}