glyph_ui 0.1.0

TUI library utilizing the Elm architecture
Documentation
//! Add padding around a view

use euclid::{Rect, Size2D};

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

/// The view itself
pub struct View<V> {
    inner: V,
    left: u16,
    right: u16,
    top: u16,
    bottom: u16,
}

impl<V> View<V> {
    pub fn new(view: V, l: u16, r: u16, t: u16, b: u16) -> Self {
        Self {
            inner: view,
            left: l,
            right: r,
            top: t,
            bottom: b,
        }
    }
}

/// Shorthand for [`View::new()`]
///
/// [`View::new()`] View::new
pub fn new<V>(view: V, l: u16, r: u16, t: u16, b: u16) -> View<V> {
    View::new(view, l, r, t, b)
}

impl<T, M, V> ViewTrait<T, M> for View<V>
where
    V: ViewTrait<T, M>,
{
    fn draw(&self, printer: &Printer, focused: bool) {
        let p_size = printer.size();

        let sub = printer
            .to_sub_area(Rect::new(
                (self.left, self.top).into(),
                (
                    p_size.width - self.left - self.right,
                    p_size.height - self.top - self.bottom,
                )
                    .into(),
            ))
            .unwrap();

        self.inner.draw(&sub, focused);
    }

    fn width(&self) -> Size2D<u16, Cell> {
        let (width, height) = self.inner.width().to_tuple();
        (
            width.saturating_add(self.left).saturating_add(self.right),
            height.saturating_add(self.top).saturating_add(self.bottom),
        )
            .into()
    }

    fn height(&self) -> Size2D<u16, Cell> {
        let (width, height) = self.inner.height().to_tuple();
        (
            width.saturating_add(self.left).saturating_add(self.right),
            height.saturating_add(self.top).saturating_add(self.bottom),
        )
            .into()
    }

    fn layout(&self, constraint: Size2D<u16, Cell>) -> Size2D<u16, Cell> {
        let constraint = (
            constraint.width - self.left - self.right,
            constraint.height - self.top - self.bottom,
        )
            .into();

        let inner_size = self.inner.layout(constraint);

        (
            inner_size.width + self.left + self.right,
            inner_size.height + self.top + self.bottom,
        )
            .into()
    }

    fn event(
        &mut self,
        event: &Event<T>,
        focused: bool,
    ) -> Box<dyn Iterator<Item = M>> {
        self.inner.event(event, focused)
    }

    fn interactive(&self) -> bool {
        self.inner.interactive()
    }
}

pub trait ViewExt {
    fn pad(self, l: u16, r: u16, t: u16, b: u16) -> View<Self>
    where
        Self: Sized,
    {
        View::new(self, l, r, t, b)
    }
}

impl<V> ViewExt for V {}