You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tui-rs/src/widgets/tabs.rs

121 lines
3.1 KiB
Rust

8 years ago
use unicode_width::UnicodeWidthStr;
use widgets::{Block, Widget};
use buffer::Buffer;
use layout::Rect;
use style::Style;
8 years ago
use symbols::line;
8 years ago
/// A widget to display available tabs in a multiple panels context.
///
/// # Examples
///
/// ```
/// # extern crate tui;
/// # use tui::widgets::{Block, border, Tabs};
8 years ago
/// # use tui::style::{Style, Color};
8 years ago
/// # fn main() {
/// Tabs::default()
/// .block(Block::default().title("Tabs").borders(border::ALL))
/// .titles(&["Tab1", "Tab2", "Tab3", "Tab4"])
8 years ago
/// .style(Style::default().fg(Color::White))
/// .highlight_style(Style::default().fg(Color::Yellow));
8 years ago
/// # }
/// ```
8 years ago
pub struct Tabs<'a> {
8 years ago
/// A block to wrap this widget in if necessary
8 years ago
block: Option<Block<'a>>,
8 years ago
/// One title for each tab
8 years ago
titles: &'a [&'a str],
8 years ago
/// The index of the selected tabs
8 years ago
selected: usize,
/// The style used to draw the text
style: Style,
/// The style used to display the selected item
highlight_style: Style,
8 years ago
}
impl<'a> Default for Tabs<'a> {
fn default() -> Tabs<'a> {
Tabs {
block: None,
titles: &[],
selected: 0,
style: Default::default(),
highlight_style: Default::default(),
8 years ago
}
}
}
impl<'a> Tabs<'a> {
pub fn block(&mut self, block: Block<'a>) -> &mut Tabs<'a> {
self.block = Some(block);
self
}
pub fn titles(&mut self, titles: &'a [&'a str]) -> &mut Tabs<'a> {
self.titles = titles;
self
}
pub fn select(&mut self, selected: usize) -> &mut Tabs<'a> {
self.selected = selected;
self
}
pub fn style(&mut self, style: Style) -> &mut Tabs<'a> {
self.style = style;
8 years ago
self
}
pub fn highlight_style(&mut self, style: Style) -> &mut Tabs<'a> {
self.highlight_style = style;
8 years ago
self
}
}
impl<'a> Widget for Tabs<'a> {
fn draw(&mut self, area: &Rect, buf: &mut Buffer) {
8 years ago
let tabs_area = match self.block {
Some(ref mut b) => {
8 years ago
b.draw(area, buf);
8 years ago
b.inner(area)
}
None => *area,
};
8 years ago
if tabs_area.height < 1 {
return;
}
self.background(&tabs_area, buf, self.style.bg);
8 years ago
let mut x = tabs_area.left();
for (title, style) in self.titles
.iter()
.enumerate()
.map(|(i, t)| if i == self.selected {
(t, &self.highlight_style)
} else {
(t, &self.style)
}) {
8 years ago
x += 1;
if x > tabs_area.right() {
break;
} else {
buf.set_string(x, tabs_area.top(), title, style);
8 years ago
x += title.width() as u16 + 1;
if x >= tabs_area.right() {
8 years ago
break;
} else {
buf.get_mut(x, tabs_area.top())
.set_symbol(line::VERTICAL)
.set_fg(self.style.fg)
.set_bg(self.style.bg);
8 years ago
x += 1;
}
}
}
}
}