Skip to content
This repository has been archived by the owner on Aug 6, 2023. It is now read-only.

Commit

Permalink
implemented title alignment
Browse files Browse the repository at this point in the history
  • Loading branch information
Andreas Steding committed Feb 23, 2021
1 parent 4e76bfa commit bf34040
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/widgets/block.rs
Expand Up @@ -26,6 +26,13 @@ impl BorderType {
}
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TitleAlignment {
Left,
Center,
Right,
}

/// Base widget to be used with all upper level ones. It may be used to display a box border around
/// the widget and/or add a title.
///
Expand Down Expand Up @@ -54,6 +61,8 @@ pub struct Block<'a> {
border_type: BorderType,
/// Widget style
style: Style,
/// Title alignment
title_alignment: TitleAlignment
}

impl<'a> Default for Block<'a> {
Expand All @@ -64,6 +73,7 @@ impl<'a> Default for Block<'a> {
border_style: Default::default(),
border_type: BorderType::Plain,
style: Default::default(),
title_alignment: TitleAlignment::Left,
}
}
}
Expand Down Expand Up @@ -108,6 +118,11 @@ impl<'a> Block<'a> {
self.border_type = border_type;
self
}

pub fn title_alignment(mut self, title_alignment: TitleAlignment) -> Block<'a> {
self.title_alignment = title_alignment;
self
}

/// Compute the inner area of a block based on its border visibility rules.
pub fn inner(&self, area: Rect) -> Rect {
Expand Down Expand Up @@ -192,6 +207,7 @@ impl<'a> Widget for Block<'a> {
.set_style(self.border_style);
}

// Title
if let Some(title) = self.title {
let lx = if self.borders.intersects(Borders::LEFT) {
1
Expand All @@ -204,7 +220,19 @@ impl<'a> Widget for Block<'a> {
0
};
let width = area.width.saturating_sub(lx).saturating_sub(rx);
buf.set_spans(area.left() + lx, area.top(), &title, width);

// Title alignment
match self.title_alignment {
TitleAlignment::Left => {
buf.set_spans(area.left() + lx, area.top(), &title, width);
}
TitleAlignment::Center => {
buf.set_spans(area.left() + width/2 - (title.width() as u16)/2 + lx, area.top(), &title, width);
}
TitleAlignment::Right => {
buf.set_spans(area.right() - title.width() as u16 - rx, area.top(), &title, width);
}
}
}
}
}
Expand Down

0 comments on commit bf34040

Please sign in to comment.