Lines
100 %
Functions
Branches
//! The status bar: one row of hotkeys and their labels.
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::Widget;
use crate::{Role, Theme};
/// Hotkey and label pairs on one row: `F1 Help M-x Exit`, the key in the `status-hotkey`
/// role. An item that does not fit the width is left out whole; later, shorter ones still show.
pub struct StatusBar<'a> {
theme: &'a Theme,
items: &'a [(String, String)],
}
impl<'a> StatusBar<'a> {
#[must_use]
pub fn new(theme: &'a Theme, items: &'a [(String, String)]) -> Self {
StatusBar { theme, items }
fn line(&self, width: usize) -> Line<'a> {
let key = self.theme.style(Role::StatusHotkey);
let label = self.theme.style(Role::Status);
let mut spans = Vec::new();
for slot in fit(self.items, width) {
let (hotkey, text) = &self.items[slot.index];
spans.extend([
Span::styled(" ".repeat(slot.gap), label),
Span::styled(hotkey.as_str(), key),
Span::styled(format!(" {text}"), label),
]);
Line::from(spans)
/// The cells of each item shown in `area`, gap excluded, as `(index into items, area)`.
pub fn item_areas(area: Rect, items: &[(String, String)]) -> Vec<(usize, Rect)> {
let mut x = area.x;
let mut areas = Vec::new();
for slot in fit(items, usize::from(area.width)) {
let start = x.saturating_add(u16::try_from(slot.gap).unwrap_or(u16::MAX));
let width = u16::try_from(slot.width - slot.gap).unwrap_or(u16::MAX);
areas.push((
slot.index,
Rect::new(start, area.y, width, 1).intersection(area),
));
x = start.saturating_add(width);
areas
/// An item that fits: its index, the blank columns before it and its width with them.
struct Slot {
index: usize,
gap: usize,
width: usize,
fn fit(items: &[(String, String)], width: usize) -> Vec<Slot> {
let mut used = 0;
let mut slots: Vec<Slot> = Vec::new();
for (index, (hotkey, text)) in items.iter().enumerate() {
let gap = if slots.is_empty() { 1 } else { 2 };
let wide = gap + hotkey.chars().count() + 1 + text.chars().count();
if used + wide > width {
continue;
used += wide;
slots.push(Slot {
index,
gap,
width: wide,
});
slots
impl Widget for StatusBar<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
buf.set_style(area, self.theme.style(Role::Status));
self.line(usize::from(area.width)).render(area, buf);
#[cfg(test)]
mod tests;