rcus-core 0.2.0

Core types for rcus: retained view tree, style, input, and the host bridge protocol
Documentation
//! The shape of a box: how round its corners are, and what it casts.
//!
//! These are plain values rather than fields on `Style` so they can be reused
//! by anything that draws a box — a renderer, a shadow pass, a test that draws
//! one shape and samples it. Both default to "nothing drawn", which is what
//! keeps every view that never mentions them rendering exactly as it did.

use serde::{Deserialize, Serialize};

use crate::style::Color;

/// Corner radii, smallest to largest. A box uses the `md` value unless it is
/// told otherwise, so a theme sets three and a view picks one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Radius {
    pub sm: f32,
    pub md: f32,
    pub lg: f32,
}

impl Radius {
    /// The radius a box uses when it is not told otherwise.
    pub fn standard(&self) -> f32 {
        self.md
    }

    /// Sets all three sizes at once.
    pub fn uniform(value: f32) -> Self {
        Self {
            sm: value,
            md: value,
            lg: value,
        }
    }
}

/// Accepts either a bare number or an object, because a theme file that sets one
/// radius everywhere should not have to spell out three keys.
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum RadiusRepr {
    Uniform(f32),
    Sized {
        #[serde(default)]
        sm: f32,
        #[serde(default)]
        md: f32,
        #[serde(default)]
        lg: f32,
    },
}

impl<'de> Deserialize<'de> for Radius {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match RadiusRepr::deserialize(deserializer)? {
            RadiusRepr::Uniform(value) => Radius::uniform(value),
            RadiusRepr::Sized { sm, md, lg } => Radius { sm, md, lg },
        })
    }
}

/// A drop shadow: an offset box, blurred, spread outwards and drawn behind.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Shadow {
    pub offset_x: f32,
    pub offset_y: f32,
    /// Edge softness in pixels. Zero is a hard shadow, which is only correct
    /// for an offset of zero.
    pub blur: f32,
    /// Grows the shadow shape before blurring, so a positive spread makes the
    /// shadow larger than the box rather than blurrier.
    pub spread: f32,
    pub color: Color,
}

impl Default for Shadow {
    /// Transparent rather than the framework's opaque default, so a shadow that
    /// was never given a colour is empty by colour as well as by geometry.
    fn default() -> Self {
        Self {
            offset_x: 0.0,
            offset_y: 0.0,
            blur: 0.0,
            spread: 0.0,
            color: Color {
                r: 0.0,
                g: 0.0,
                b: 0.0,
                a: 0.0,
            },
        }
    }
}

impl Shadow {
    /// True when this shadow would draw nothing at all.
    pub fn is_empty(&self) -> bool {
        self.color.a <= 0.0
            || (self.blur == 0.0
                && self.spread == 0.0
                && self.offset_x == 0.0
                && self.offset_y == 0.0)
    }

    /// How far the shadow reaches beyond the box on each side, which is how far
    /// the box's drawable area has to grow to contain it.
    pub fn reach(&self) -> f32 {
        if self.is_empty() {
            0.0
        } else {
            self.blur.abs() + self.spread.abs() + self.offset_x.abs().max(self.offset_y.abs())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_radius_defaults_to_nothing() {
        assert_eq!(
            Radius::default(),
            Radius {
                sm: 0.0,
                md: 0.0,
                lg: 0.0
            }
        );
        assert_eq!(Radius::default().standard(), 0.0);
    }

    #[test]
    fn a_shadow_defaults_to_nothing_and_draws_nothing() {
        let shadow = Shadow::default();
        assert_eq!(
            (shadow.blur, shadow.spread, shadow.color.a),
            (0.0, 0.0, 0.0)
        );
        assert!(shadow.is_empty());
        assert_eq!(shadow.reach(), 0.0, "an empty shadow needs no room");
    }

    #[test]
    fn a_radius_decodes_from_camel_case() {
        let radius: Radius = serde_json::from_str(r#"{"sm":2,"md":6,"lg":10}"#).expect("decodes");
        assert_eq!(
            radius,
            Radius {
                sm: 2.0,
                md: 6.0,
                lg: 10.0
            }
        );
    }

    #[test]
    fn a_missing_radius_field_is_zero_rather_than_an_error() {
        let radius: Radius = serde_json::from_str(r#"{"md":8}"#).expect("decodes");
        assert_eq!(
            radius,
            Radius {
                sm: 0.0,
                md: 8.0,
                lg: 0.0
            }
        );
    }

    #[test]
    fn a_shadow_decodes_from_camel_case() {
        let shadow: Shadow = serde_json::from_str(
            r#"{"offsetX":1,"offsetY":2,"blur":8,"spread":0,"color":{"r":0,"g":0,"b":0,"a":0.5}}"#,
        )
        .expect("decodes");
        assert_eq!(shadow.offset_y, 2.0);
        assert_eq!(shadow.blur, 8.0);
        assert_eq!(shadow.color.a, 0.5);
        assert!(!shadow.is_empty());
    }

    #[test]
    fn a_shadows_reach_covers_its_blur_and_its_largest_offset() {
        let shadow = Shadow {
            offset_x: 0.0,
            offset_y: 4.0,
            blur: 10.0,
            spread: 2.0,
            color: Color::rgba(0.0, 0.0, 0.0, 0.5),
        };
        assert_eq!(shadow.reach(), 16.0, "blur + spread + the bigger offset");
    }

    #[test]
    fn a_fully_transparent_shadow_is_empty_however_far_it_reaches() {
        let shadow = Shadow {
            offset_y: 12.0,
            blur: 24.0,
            color: Color::rgba(0.0, 0.0, 0.0, 0.0),
            ..Shadow::default()
        };
        assert!(shadow.is_empty());
        assert_eq!(shadow.reach(), 0.0);
    }
}