From 639e0c2656f0e8eac305670ac50bbc713291b052 Mon Sep 17 00:00:00 2001 From: Andreas Steding Date: Tue, 23 Feb 2021 20:41:15 +0100 Subject: [PATCH] implemented title alignment --- src/widgets/block.rs | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/widgets/block.rs b/src/widgets/block.rs index 70610134..e3ceadf1 100644 --- a/src/widgets/block.rs +++ b/src/widgets/block.rs @@ -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. /// @@ -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> { @@ -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, } } } @@ -109,6 +119,11 @@ impl<'a> Block<'a> { 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 { let mut inner = area; @@ -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 @@ -204,7 +220,29 @@ 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, + ); + } + } } } }