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.
This commit is contained in:
Dominique Martinet 2025-08-23 03:11:38 +09:00 committed by GitHub
parent 2d713d723d
commit 564a9d76fc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 9 additions and 9 deletions

View File

@ -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]

View File

@ -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);