1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
use crate::{
    css,
    unit::{self, *},
    Style, StyleUpdater,
};
use derive_rich::Rich;

/// ```
/// use css_style::{css, Style, unit::px};
///
/// Style::default()
///     .and_padding(|conf| {
///         conf.x(px(2)) // equal to conf.left(css::Auto).right(css::Auto)
///             .y(px(4))
///     });
/// ```
#[derive(Rich, Clone, Debug, PartialEq, From, Default)]
pub struct Padding {
    #[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<Length> for Padding {
    fn from(source: Length) -> Self {
        Self::default().all(source)
    }
}

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

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

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

impl Padding {
    pub fn all(self, value: impl Into<Length>) -> Self {
        let value = value.into();
        self.right(value.clone())
            .top(value.clone())
            .left(value.clone())
            .bottom(value)
    }

    pub fn zero(self) -> Self {
        self.all(px(0.))
    }

    pub fn x(self, value: impl Into<Length>) -> Self {
        let value = value.into();
        self.left(value.clone()).right(value)
    }

    pub fn y(self, value: impl Into<Length>) -> Self {
        let value = value.into();
        self.top(value.clone()).bottom(value)
    }

    pub fn horizontal(self, value: impl Into<Length>) -> Self {
        self.y(value)
    }

    pub fn vertical(self, value: impl Into<Length>) -> Self {
        self.x(value)
    }

    pub fn full(self) -> Self {
        self.all(1.)
    }

    pub fn half(self) -> Self {
        self.all(0.5)
    }
}

#[derive(Clone, Debug, PartialEq, Display, From)]
pub enum Length {
    #[from]
    Length(unit::Length),
    #[from(forward)]
    Percent(Percent),
    #[from]
    Inherit(css::Inherit),
}