1use crate::{
2 calc::Calc,
3 unit::{self, *},
4 Spacing, Style, StyleUpdater, Unit,
5};
6use derive_rich::Rich;
7
8#[derive(Rich, Clone, Debug, PartialEq, From, Default)]
21pub struct Margin {
22 #[rich(write, write(option))]
23 pub top: Option<Length>,
24 #[rich(write, write(option))]
25 pub right: Option<Length>,
26 #[rich(write, write(option))]
27 pub bottom: Option<Length>,
28 #[rich(write, write(option))]
29 pub left: Option<Length>,
30}
31
32impl From<i32> for Margin {
33 fn from(source: i32) -> Self {
34 Self::default().all(px(source))
35 }
36}
37
38impl From<Length> for Margin {
39 fn from(source: Length) -> Self {
40 Self::default().all(source)
41 }
42}
43
44impl From<unit::Length> for Margin {
45 fn from(source: unit::Length) -> Self {
46 Self::default().all(source)
47 }
48}
49
50impl From<Percent> for Margin {
51 fn from(source: Percent) -> Self {
52 Self::default().all(source)
53 }
54}
55
56impl<X, Y> From<(X, Y)> for Margin
57where
58 X: Into<Length>,
59 Y: Into<Length>,
60{
61 fn from((x, y): (X, Y)) -> Self {
62 Self::default().x(x).y(y)
63 }
64}
65
66impl StyleUpdater for Margin {
67 fn update_style(self, style: Style) -> Style {
68 style
69 .try_insert("margin-top", self.top)
70 .try_insert("margin-right", self.right)
71 .try_insert("margin-bottom", self.bottom)
72 .try_insert("margin-left", self.left)
73 }
74}
75
76impl Spacing for Margin {
77 type Unit = Length;
78
79 fn left(mut self, value: impl Into<Self::Unit>) -> Self {
80 self.left = Some(value.into());
81 self
82 }
83
84 fn right(mut self, value: impl Into<Self::Unit>) -> Self {
85 self.right = Some(value.into());
86 self
87 }
88
89 fn top(mut self, value: impl Into<Self::Unit>) -> Self {
90 self.top = Some(value.into());
91 self
92 }
93
94 fn bottom(mut self, value: impl Into<Self::Unit>) -> Self {
95 self.bottom = Some(value.into());
96 self
97 }
98}
99
100impl Unit for Length {
101 fn zero() -> Self {
102 0.0.into()
103 }
104
105 fn full() -> Self {
106 1.0.into()
107 }
108
109 fn half() -> Self {
110 0.5.into()
111 }
112}
113
114#[derive(Clone, Debug, PartialEq, Display, From)]
115pub enum Length {
116 #[display(fmt = "auto")]
117 Auto,
118 #[display(fmt = "inherit")]
119 Inherit,
120 #[display(fmt = "initial")]
121 Initial,
122 #[from]
123 Length(unit::Length),
124 #[from(forward)]
125 Percent(Percent),
126}
127
128impl From<Calc> for Length {
129 fn from(source: Calc) -> Self {
130 Length::Length(source.into())
131 }
132}