glyph_ui 0.1.0

TUI library utilizing the Elm architecture
Documentation
//! Display text with line wrapping

use std::{borrow::Cow, convert::TryInto};

use euclid::Size2D;
use unicode_segmentation::UnicodeSegmentation;

use crate::{event::Event, unit::Cell, Printer, View as ViewTrait};

/// The view itself
pub struct View<'a> {
    inner: &'a str,
}

impl<'a> View<'a> {
    pub fn new(s: &'a str) -> Self {
        Self {
            inner: s,
        }
    }

    fn size_and_lines(
        &self,
        width_constraint: u16,
    ) -> (Size2D<u16, Cell>, Vec<Cow<'_, str>>) {
        let lines = textwrap::wrap(&self.inner, width_constraint as usize);

        // Calculate cell length taken by the longest line
        let max_width = lines
            .iter()
            .map(|x| x.graphemes(true).count())
            .max()
            .unwrap_or(0)
            .try_into()
            .unwrap_or(0);

        let rows = lines.iter().count().try_into().unwrap_or(0);

        ((max_width, rows).into(), lines)
    }
}

/// Shorthand for [`View::new()`]
///
/// [`View::new()`]: View::new
pub fn new(s: &str) -> View<'_> {
    View::new(s)
}

impl<T, M> ViewTrait<T, M> for View<'_>
where
    M: 'static,
{
    fn draw(&self, printer: &Printer, _focused: bool) {
        let (size, lines) = self.size_and_lines(printer.size().width);

        for (line, row) in lines.iter().zip(0..size.height) {
            printer.print(&line, (0, row)).unwrap();
        }
    }

    fn width(&self) -> Size2D<u16, Cell> {
        let longest_word_len: u16 = self
            .inner
            .split_whitespace()
            .map(|w| w.graphemes(true).count())
            .max()
            .unwrap_or(0)
            .try_into()
            .expect("u16 overflow");

        self.size_and_lines(longest_word_len).0
    }

    fn height(&self) -> Size2D<u16, Cell> {
        let longest_line_len = self
            .inner
            .lines()
            .map(|l| l.graphemes(true).count())
            .max()
            .unwrap_or(0)
            .try_into()
            .expect("u16 overflow");

        self.size_and_lines(longest_line_len).0
    }

    fn layout(&self, constraint: Size2D<u16, Cell>) -> Size2D<u16, Cell> {
        self.size_and_lines(constraint.width).0
    }

    fn event(&mut self, _: &Event<T>, _: bool) -> Box<dyn Iterator<Item = M>> {
        Box::new(std::iter::empty())
    }

    fn interactive(&self) -> bool {
        false
    }
}