css-style 0.14.1

Typed CSS Style
Documentation
use crate::{
    calc::Calc,
    unit::{self, *},
    Spacing, Style, StyleUpdater, Unit,
};
use derive_rich::Rich;

/// ```
/// use css_style::{prelude::*, unit::px, margin::Length};
///
/// style()
///     // colsure style
///     .and_margin(|conf| {
///         conf.x(Length::Auto) // equal to conf.left(Length::Auto).right(Length::Auto)
///             .y(px(4))
///     })
///     // setter method style
///     .margin((Length::Auto, px(4)));
/// ```
#[derive(Rich, Clone, Debug, PartialEq, From, Default)]
pub struct Margin {
    #[rich(write, write(option))]
    pub top: Option<Length>,
    #[rich(write, write(option))]
    pub right: Option<Length>,
    #[rich(write, write(option))]
    pub bottom: Option<Length>,
    #[rich(write, write(option))]
    pub left: Option<Length>,
}

impl From<i32> for Margin {
    fn from(source: i32) -> Self {
        Self::default().all(px(source))
    }
}

impl From<Length> for Margin {
    fn from(source: Length) -> Self {
        Self::default().all(source)
    }
}

impl From<unit::Length> for Margin {
    fn from(source: unit::Length) -> Self {
        Self::default().all(source)
    }
}

impl From<Percent> for Margin {
    fn from(source: Percent) -> Self {
        Self::default().all(source)
    }
}

impl<X, Y> From<(X, Y)> for Margin
where
    X: Into<Length>,
    Y: Into<Length>,
{
    fn from((x, y): (X, Y)) -> Self {
        Self::default().x(x).y(y)
    }
}

impl StyleUpdater for Margin {
    fn update_style(self, style: Style) -> Style {
        style
            .try_insert("margin-top", self.top)
            .try_insert("margin-right", self.right)
            .try_insert("margin-bottom", self.bottom)
            .try_insert("margin-left", self.left)
    }
}

impl Spacing for Margin {
    type Unit = Length;

    fn left(mut self, value: impl Into<Self::Unit>) -> Self {
        self.left = Some(value.into());
        self
    }

    fn right(mut self, value: impl Into<Self::Unit>) -> Self {
        self.right = Some(value.into());
        self
    }

    fn top(mut self, value: impl Into<Self::Unit>) -> Self {
        self.top = Some(value.into());
        self
    }

    fn bottom(mut self, value: impl Into<Self::Unit>) -> Self {
        self.bottom = Some(value.into());
        self
    }
}

impl Unit for Length {
    fn zero() -> Self {
        0.0.into()
    }

    fn full() -> Self {
        1.0.into()
    }

    fn half() -> Self {
        0.5.into()
    }
}

#[derive(Clone, Debug, PartialEq, Display, From)]
pub enum Length {
    #[display(fmt = "auto")]
    Auto,
    #[display(fmt = "inherit")]
    Inherit,
    #[display(fmt = "initial")]
    Initial,
    #[from]
    Length(unit::Length),
    #[from(forward)]
    Percent(Percent),
}

impl From<Calc> for Length {
    fn from(source: Calc) -> Self {
        Length::Length(source.into())
    }
}