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::{Alignment, Line, Text};
use crate::widgets::{Block, Widget};

/// Controls whether a `Paragraph` wraps long lines to fit its width.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Wrap {
    /// Trim leading whitespace from wrapped lines.
    pub trim: bool,
}

/// A widget that draws (optionally wrapped, optionally scrolled) styled
/// text inside an optional surrounding `Block`.
#[derive(Debug, Default, Clone)]
pub struct Paragraph<'a> {
    text: Text<'a>,
    block: Option<Block<'a>>,
    style: Style,
    wrap: Option<Wrap>,
    alignment: Alignment,
    scroll: (u16, u16),
}

impl<'a> Paragraph<'a> {
    pub fn new<T>(text: T) -> Paragraph<'a>
    where
        T: Into<Text<'a>>,
    {
        Paragraph {
            text: text.into(),
            block: None,
            style: Style::default(),
            wrap: None,
            alignment: Alignment::Left,
            scroll: (0, 0),
        }
    }

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

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

    pub fn wrap(mut self, wrap: Wrap) -> Paragraph<'a> {
        self.wrap = Some(wrap);
        self
    }

    pub fn alignment(mut self, alignment: Alignment) -> Paragraph<'a> {
        self.alignment = alignment;
        self
    }

    /// Scrolls the rendered text by `(x, y)` cells; `y` scrolls vertically
    /// through wrapped lines, `x` scrolls horizontally when not wrapping.
    pub fn scroll(mut self, offset: (u16, u16)) -> Paragraph<'a> {
        self.scroll = offset;
        self
    }

    /// Returns how many display lines this paragraph would occupy at the
    /// given width, taking wrapping into account. Useful for computing
    /// scroll bounds before rendering.
    pub fn line_count(&self, width: u16) -> usize {
        if let Some(wrap) = self.wrap {
            self.text
                .lines
                .iter()
                .map(|l| wrapped_lines(l, width, wrap.trim).len().max(1))
                .sum()
        } else {
            self.text.lines.len()
        }
    }
}

/// Greedily wraps a single line of spans onto multiple display lines no
/// wider than `width`, splitting on whitespace boundaries when possible and
/// falling back to a hard break for single words wider than the area.
fn wrapped_lines<'a>(line: &Line<'a>, width: u16, trim: bool) -> Vec<Line<'a>> {
    if width == 0 {
        return vec![line.clone()];
    }
    let width = width as usize;
    let flat: String = line
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<Vec<_>>()
        .join("");
    let style = line.spans.first().map(|s| s.style).unwrap_or_default();

    let mut out = Vec::new();
    let mut current = String::new();
    let mut current_width = 0usize;

    for word in flat.split_inclusive(' ') {
        let trimmed = word.trim_end();
        let w = unicode_width::UnicodeWidthStr::width(trimmed);
        if current_width > 0 && current_width + unicode_width::UnicodeWidthStr::width(word) > width
        {
            out.push(Line::styled(
                if trim {
                    current.trim_end().to_string()
                } else {
                    current.clone()
                },
                style,
            ));
            current.clear();
            current_width = 0;
        }
        if w > width {
            // Word alone is wider than the area: hard break it.
            for ch in trimmed.chars() {
                if current_width + 1 > width {
                    out.push(Line::styled(current.clone(), style));
                    current.clear();
                    current_width = 0;
                }
                current.push(ch);
                current_width += 1;
            }
        } else {
            current.push_str(word);
            current_width += unicode_width::UnicodeWidthStr::width(word);
        }
    }
    if !current.is_empty() || out.is_empty() {
        out.push(Line::styled(
            if trim {
                current.trim_end().to_string()
            } else {
                current
            },
            style,
        ));
    }
    out
}

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

        let lines: Vec<Line<'a>> = if let Some(wrap) = self.wrap {
            self.text
                .lines
                .iter()
                .flat_map(|l| wrapped_lines(l, text_area.width, wrap.trim))
                .collect()
        } else {
            self.text.lines.clone()
        };

        let (scroll_x, scroll_y) = self.scroll;
        for (row, line) in lines.iter().skip(scroll_y as usize).enumerate() {
            if row as u16 >= text_area.height {
                break;
            }
            let y = text_area.y + row as u16;
            let alignment = line.alignment.unwrap_or(self.alignment);
            let line_width = line.width() as u16;
            let x = match alignment {
                Alignment::Left => text_area.x,
                Alignment::Center => {
                    text_area.x + text_area.width.saturating_sub(line_width) / 2
                }
                Alignment::Right => text_area.x + text_area.width.saturating_sub(line_width),
            };
            let mut cx = x.saturating_sub(scroll_x);
            for span in &line.spans {
                cx = buf.set_stringn(
                    cx,
                    y,
                    &span.content,
                    text_area.right().saturating_sub(cx) as usize,
                    span.style,
                );
            }
        }
    }
}