rustom 0.1.0

A library for building rich, stateful terminal user interfaces and dashboards.
Documentation
use crate::buffer::Buffer;
use crate::layout::Rect;
use crate::style::Style;
use crate::text::Line;
use crate::widgets::{Block, Widget};

/// A horizontal row of selectable tab titles separated by a divider.
#[derive(Debug, Default, Clone)]
pub struct Tabs<'a> {
    titles: Vec<Line<'a>>,
    selected: usize,
    block: Option<Block<'a>>,
    style: Style,
    highlight_style: Style,
    divider: String,
}

impl<'a> Tabs<'a> {
    pub fn new<T>(titles: T) -> Tabs<'a>
    where
        T: IntoIterator,
        T::Item: Into<Line<'a>>,
    {
        Tabs {
            titles: titles.into_iter().map(Into::into).collect(),
            selected: 0,
            block: None,
            style: Style::default(),
            highlight_style: Style::default(),
            divider: "|".to_string(),
        }
    }

    pub fn select(mut self, index: usize) -> Tabs<'a> {
        self.selected = index;
        self
    }

    pub fn block(mut self, block: Block<'a>) -> Tabs<'a> {
        self.block = Some(block);
        self
    }

    pub fn style(mut self, style: Style) -> Tabs<'a> {
        self.style = style;
        self
    }

    pub fn highlight_style(mut self, style: Style) -> Tabs<'a> {
        self.highlight_style = style;
        self
    }

    pub fn divider<T: Into<String>>(mut self, divider: T) -> Tabs<'a> {
        self.divider = divider.into();
        self
    }
}

impl<'a> Widget for Tabs<'a> {
    fn render(mut self, area: Rect, buf: &mut Buffer) {
        let tabs_area = if let Some(block) = self.block.take() {
            let inner = block.inner(area);
            block.render(area, buf);
            inner
        } else {
            area
        };
        if tabs_area.area() == 0 {
            return;
        }
        buf.set_style(tabs_area, self.style);

        let mut x = tabs_area.x;
        for (i, title) in self.titles.iter().enumerate() {
            if x >= tabs_area.right() {
                break;
            }
            let style = if i == self.selected {
                self.style.patch(self.highlight_style)
            } else {
                self.style
            };
            for span in &title.spans {
                x = buf.set_stringn(
                    x,
                    tabs_area.y,
                    &span.content,
                    tabs_area.right().saturating_sub(x) as usize,
                    span.style.patch(style),
                );
            }
            if i + 1 < self.titles.len() && x < tabs_area.right() {
                x = buf.set_stringn(
                    x + 1,
                    tabs_area.y,
                    &self.divider,
                    tabs_area.right().saturating_sub(x + 1) as usize,
                    self.style,
                );
                x += 1;
            }
        }
    }
}