From 564a9d76fc9d49e046915b95c518a9cfbcd5ecc2 Mon Sep 17 00:00:00 2001 From: Dominique Martinet Date: Sat, 23 Aug 2025 03:11:38 +0900 Subject: [PATCH] fix(line-gauge): pad default label to display 3 numbers (#2053) Display the default label of the LineGauge widget padded to fill 3 cells. This makes it so that the label doesn't shift around when going from a single digit to double / triple digits. To maintain the existing behavior, use a custom label by calling `.label()` on the LineGauge. --- ratatui-widgets/src/gauge.rs | 4 ++-- ratatui/tests/widgets_gauge.rs | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/ratatui-widgets/src/gauge.rs b/ratatui-widgets/src/gauge.rs index 9fe115c5..fd158cb1 100644 --- a/ratatui-widgets/src/gauge.rs +++ b/ratatui-widgets/src/gauge.rs @@ -431,7 +431,7 @@ impl Widget for &LineGauge<'_> { } let ratio = self.ratio; - let default_label = Line::from(format!("{:.0}%", ratio * 100.0)); + let default_label = Line::from(format!("{:3.0}%", ratio * 100.0)); let label = self.label.as_ref().unwrap_or(&default_label); let (col, row) = buf.set_line(gauge_area.left(), gauge_area.top(), label, gauge_area.width); let start = col + 1; @@ -602,7 +602,7 @@ mod tests { let line_gauge = LineGauge::default().ratio(0.5); // This should not panic, even if the buffer is too small to render the line gauge. line_gauge.render(buffer.area, &mut buffer); - assert_eq!(buffer, Buffer::with_lines(["5"])); + assert_eq!(buffer, Buffer::with_lines([" "])); } #[test] diff --git a/ratatui/tests/widgets_gauge.rs b/ratatui/tests/widgets_gauge.rs index 8699384f..04f99a00 100644 --- a/ratatui/tests/widgets_gauge.rs +++ b/ratatui/tests/widgets_gauge.rs @@ -233,20 +233,20 @@ fn widgets_line_gauge_renders() { }) .unwrap(); let mut expected = Buffer::with_lines([ - "43% ────────────────", + " 43% ───────────────", "┌Gauge 2───────────┐", - "│21% ━━━━━━━━━━━━━━│", + "│ 21% ━━━━━━━━━━━━━│", "└──────────────────┘", - "50% ──────── ", - "80% ████████████░░░░", + " 50% ─────── ", + " 80% ████████████░░░", ]); - for col in 4..10 { + for col in 5..11 { expected[(col, 0)].set_fg(Color::Green); } - for col in 10..20 { + for col in 11..20 { expected[(col, 0)].set_fg(Color::White); } - for col in 5..7 { + for col in 6..8 { expected[(col, 2)].set_fg(Color::Green); } terminal.backend().assert_buffer(&expected);