Skip to main content

sequoia_style/
text_style.rs

1use sequoia_core::Color;
2
3#[derive(Clone, Debug, Default, PartialEq)]
4pub struct TextStyle {
5    pub size: Option<f32>,
6
7    pub color: Option<Color>,
8
9    pub weight: Option<u16>,
10
11    pub family: Option<String>,
12
13    pub italic: Option<bool>,
14
15    pub letter_spacing: Option<f32>,
16
17    /// Line height as a multiple of the font size.
18    pub line_height: Option<f32>,
19
20    pub underline: Option<bool>,
21
22    pub strikethrough: Option<bool>,
23}
24
25impl TextStyle {
26    pub const fn new() -> Self {
27        Self {
28            size: None,
29            color: None,
30            weight: None,
31            family: None,
32            italic: None,
33            letter_spacing: None,
34            line_height: None,
35            underline: None,
36            strikethrough: None,
37        }
38    }
39
40    pub const fn size(mut self, size: f32) -> Self {
41        self.size = Some(size);
42        self
43    }
44
45    pub const fn color(mut self, color: Color) -> Self {
46        self.color = Some(color);
47        self
48    }
49
50    pub const fn weight(mut self, weight: u16) -> Self {
51        self.weight = Some(weight);
52        self
53    }
54
55    pub fn family(mut self, family: impl Into<String>) -> Self {
56        self.family = Some(family.into());
57        self
58    }
59
60    pub const fn italic(mut self, on: bool) -> Self {
61        self.italic = Some(on);
62        self
63    }
64
65    pub const fn letter_spacing(mut self, spacing: f32) -> Self {
66        self.letter_spacing = Some(spacing);
67        self
68    }
69
70    pub const fn line_height(mut self, factor: f32) -> Self {
71        self.line_height = Some(factor);
72        self
73    }
74
75    pub const fn underline(mut self, on: bool) -> Self {
76        self.underline = Some(on);
77        self
78    }
79
80    pub const fn strikethrough(mut self, on: bool) -> Self {
81        self.strikethrough = Some(on);
82        self
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn const_composition_keeps_base() {
92        const TITLE: TextStyle = TextStyle::new()
93            .size(20.0)
94            .color(Color::WHITE)
95            .weight(700)
96            .italic(true);
97        assert_eq!(TITLE.size, Some(20.0));
98        assert_eq!(TITLE.color, Some(Color::WHITE));
99        assert_eq!(TITLE.weight, Some(700));
100        assert_eq!(TITLE.italic, Some(true));
101        assert_eq!(TITLE.family, None);
102        assert_eq!(TITLE.underline, None);
103    }
104
105    #[test]
106    fn family_accepts_owned_names() {
107        let family = String::from("SequoiaTest");
108        assert_eq!(TextStyle::new().family(family.clone()).family, Some(family));
109    }
110
111    #[test]
112    fn default_is_empty() {
113        assert_eq!(TextStyle::default(), TextStyle::new());
114    }
115}