Skip to main content

rcus_core/
boxstyle.rs

1//! The shape of a box: how round its corners are, and what it casts.
2//!
3//! These are plain values rather than fields on `Style` so they can be reused
4//! by anything that draws a box — a renderer, a shadow pass, a test that draws
5//! one shape and samples it. Both default to "nothing drawn", which is what
6//! keeps every view that never mentions them rendering exactly as it did.
7
8use serde::{Deserialize, Serialize};
9
10use crate::style::Color;
11
12/// Corner radii, smallest to largest. A box uses the `md` value unless it is
13/// told otherwise, so a theme sets three and a view picks one.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
15#[serde(rename_all = "camelCase")]
16pub struct Radius {
17    pub sm: f32,
18    pub md: f32,
19    pub lg: f32,
20}
21
22impl Radius {
23    /// The radius a box uses when it is not told otherwise.
24    pub fn standard(&self) -> f32 {
25        self.md
26    }
27
28    /// Sets all three sizes at once.
29    pub fn uniform(value: f32) -> Self {
30        Self {
31            sm: value,
32            md: value,
33            lg: value,
34        }
35    }
36}
37
38/// Accepts either a bare number or an object, because a theme file that sets one
39/// radius everywhere should not have to spell out three keys.
40#[derive(serde::Deserialize)]
41#[serde(untagged)]
42enum RadiusRepr {
43    Uniform(f32),
44    Sized {
45        #[serde(default)]
46        sm: f32,
47        #[serde(default)]
48        md: f32,
49        #[serde(default)]
50        lg: f32,
51    },
52}
53
54impl<'de> Deserialize<'de> for Radius {
55    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
56        Ok(match RadiusRepr::deserialize(deserializer)? {
57            RadiusRepr::Uniform(value) => Radius::uniform(value),
58            RadiusRepr::Sized { sm, md, lg } => Radius { sm, md, lg },
59        })
60    }
61}
62
63/// A drop shadow: an offset box, blurred, spread outwards and drawn behind.
64#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
65#[serde(default, rename_all = "camelCase")]
66pub struct Shadow {
67    pub offset_x: f32,
68    pub offset_y: f32,
69    /// Edge softness in pixels. Zero is a hard shadow, which is only correct
70    /// for an offset of zero.
71    pub blur: f32,
72    /// Grows the shadow shape before blurring, so a positive spread makes the
73    /// shadow larger than the box rather than blurrier.
74    pub spread: f32,
75    pub color: Color,
76}
77
78impl Default for Shadow {
79    /// Transparent rather than the framework's opaque default, so a shadow that
80    /// was never given a colour is empty by colour as well as by geometry.
81    fn default() -> Self {
82        Self {
83            offset_x: 0.0,
84            offset_y: 0.0,
85            blur: 0.0,
86            spread: 0.0,
87            color: Color {
88                r: 0.0,
89                g: 0.0,
90                b: 0.0,
91                a: 0.0,
92            },
93        }
94    }
95}
96
97impl Shadow {
98    /// True when this shadow would draw nothing at all.
99    pub fn is_empty(&self) -> bool {
100        self.color.a <= 0.0
101            || (self.blur == 0.0
102                && self.spread == 0.0
103                && self.offset_x == 0.0
104                && self.offset_y == 0.0)
105    }
106
107    /// How far the shadow reaches beyond the box on each side, which is how far
108    /// the box's drawable area has to grow to contain it.
109    pub fn reach(&self) -> f32 {
110        if self.is_empty() {
111            0.0
112        } else {
113            self.blur.abs() + self.spread.abs() + self.offset_x.abs().max(self.offset_y.abs())
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn a_radius_defaults_to_nothing() {
124        assert_eq!(
125            Radius::default(),
126            Radius {
127                sm: 0.0,
128                md: 0.0,
129                lg: 0.0
130            }
131        );
132        assert_eq!(Radius::default().standard(), 0.0);
133    }
134
135    #[test]
136    fn a_shadow_defaults_to_nothing_and_draws_nothing() {
137        let shadow = Shadow::default();
138        assert_eq!(
139            (shadow.blur, shadow.spread, shadow.color.a),
140            (0.0, 0.0, 0.0)
141        );
142        assert!(shadow.is_empty());
143        assert_eq!(shadow.reach(), 0.0, "an empty shadow needs no room");
144    }
145
146    #[test]
147    fn a_radius_decodes_from_camel_case() {
148        let radius: Radius = serde_json::from_str(r#"{"sm":2,"md":6,"lg":10}"#).expect("decodes");
149        assert_eq!(
150            radius,
151            Radius {
152                sm: 2.0,
153                md: 6.0,
154                lg: 10.0
155            }
156        );
157    }
158
159    #[test]
160    fn a_missing_radius_field_is_zero_rather_than_an_error() {
161        let radius: Radius = serde_json::from_str(r#"{"md":8}"#).expect("decodes");
162        assert_eq!(
163            radius,
164            Radius {
165                sm: 0.0,
166                md: 8.0,
167                lg: 0.0
168            }
169        );
170    }
171
172    #[test]
173    fn a_shadow_decodes_from_camel_case() {
174        let shadow: Shadow = serde_json::from_str(
175            r#"{"offsetX":1,"offsetY":2,"blur":8,"spread":0,"color":{"r":0,"g":0,"b":0,"a":0.5}}"#,
176        )
177        .expect("decodes");
178        assert_eq!(shadow.offset_y, 2.0);
179        assert_eq!(shadow.blur, 8.0);
180        assert_eq!(shadow.color.a, 0.5);
181        assert!(!shadow.is_empty());
182    }
183
184    #[test]
185    fn a_shadows_reach_covers_its_blur_and_its_largest_offset() {
186        let shadow = Shadow {
187            offset_x: 0.0,
188            offset_y: 4.0,
189            blur: 10.0,
190            spread: 2.0,
191            color: Color::rgba(0.0, 0.0, 0.0, 0.5),
192        };
193        assert_eq!(shadow.reach(), 16.0, "blur + spread + the bigger offset");
194    }
195
196    #[test]
197    fn a_fully_transparent_shadow_is_empty_however_far_it_reaches() {
198        let shadow = Shadow {
199            offset_y: 12.0,
200            blur: 24.0,
201            color: Color::rgba(0.0, 0.0, 0.0, 0.0),
202            ..Shadow::default()
203        };
204        assert!(shadow.is_empty());
205        assert_eq!(shadow.reach(), 0.0);
206    }
207}