lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Decorative floating particles.
// cspell:words splitmix

use std::collections::hash_map::RandomState;
use std::hash::BuildHasher;
use std::sync::atomic::{AtomicU64, Ordering};

use dioxus::prelude::*;

use super::shared::{MotionSupport, use_motion_support};
use crate::class::compose;

/// How many particles a [`Particles`] field holds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParticlesDensity {
    /// 15 particles.
    Low,
    /// 25 particles.
    #[default]
    Medium,
    /// 40 particles.
    High,
}

impl ParticlesDensity {
    /// The `data-ui-particles` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
        }
    }

    /// The number of particles, matching lumen-react.
    pub fn count(self) -> usize {
        match self {
            Self::Low => 15,
            Self::Medium => 25,
            Self::High => 40,
        }
    }
}

const PARTICLE_TONES: [&str; 3] = ["var(--brand)", "var(--accent)", "var(--glow, var(--brand))"];

/// A small splitmix64 generator; particles only need decorative variation.
struct ParticleRandom(u64);

impl ParticleRandom {
    fn next(&mut self) -> f64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut mixed = self.0;
        mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        mixed ^= mixed >> 31;

        // 52 random mantissa bits give a value in 1..2.
        f64::from_bits(0x3FF0_0000_0000_0000 | (mixed >> 12)) - 1.0
    }
}

/// The inline style of each particle, generated like `createParticles` in lumen-react.
pub(crate) fn particle_styles(density: ParticlesDensity, seed: u64) -> Vec<String> {
    let mut random = ParticleRandom(seed);

    (0..density.count())
        .map(|_| {
            let size = random.next() * 12.0 + 8.0;
            let left = random.next() * 100.0;
            let top = random.next() * 100.0;
            let delay = random.next() * 8.0;
            let duration = 20.0 + random.next() * 15.0;
            let pick = random.next();
            let tone = if pick < 1.0 / 3.0 {
                PARTICLE_TONES[0]
            } else if pick < 2.0 / 3.0 {
                PARTICLE_TONES[1]
            } else {
                PARTICLE_TONES[2]
            };

            format!(
                "--ui-particle-delay: {delay:.3}s; --ui-particle-duration: {duration:.3}s; --ui-particle-left: {left:.3}%; --ui-particle-size: {size:.3}px; --ui-particle-tone: {tone}; --ui-particle-top: {top:.3}%"
            )
        })
        .collect()
}

static NEXT_FIELD: AtomicU64 = AtomicU64::new(0);

/// A per-field seed: the browser's `Math.random()` when it answered, otherwise the process's
/// random hasher keys mixed with a counter.
fn particle_seed(support: MotionSupport) -> u64 {
    let field = NEXT_FIELD.fetch_add(1, Ordering::Relaxed);

    match support {
        MotionSupport::Browser { random, .. } => random.to_bits() ^ field,
        _ => RandomState::new().hash_one(field),
    }
}

/// Props for [`Particles`].
#[derive(Props, Clone, PartialEq)]
pub struct ParticlesProps {
    /// How many particles drift through the field.
    #[props(default)]
    pub density: ParticlesDensity,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Content placed in the field before the particles.
    pub children: Element,
}

/// A decorative field of drifting particles, hidden from assistive technology.
///
/// Like lumen-react, the first render has no particles; they are generated after mount with
/// fresh positions. They are skipped when a browser reports reduced motion, and Lumen's CSS hides
/// them under `prefers-reduced-motion` wherever the renderer evaluates that query.
#[component]
pub fn Particles(props: ParticlesProps) -> Element {
    let support = use_motion_support();
    let mut seed = use_hook(|| CopyValue::new(None::<u64>));
    let class = compose([Some("ui-particles"), props.class.as_deref()]);
    let current = support();

    if current != MotionSupport::Pending && !current.reduced() && seed.peek().is_none() {
        seed.set(Some(particle_seed(current)));
    }

    let particles =
        (*seed.peek()).map_or_else(Vec::new, |seed| particle_styles(props.density, seed));

    rsx! {
        div {
            aria_hidden: "true",
            class,
            "data-ui-particles": props.density.as_str(),
            ..props.attributes,
            {props.children}
            for (index, style) in particles.into_iter().enumerate() {
                span { key: "{index}", class: "ui-particles__particle", style }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{ParticlesDensity, particle_styles};

    #[test]
    fn densities_match_lumen_react() {
        assert_eq!(particle_styles(ParticlesDensity::Low, 1).len(), 15);
        assert_eq!(particle_styles(ParticlesDensity::Medium, 1).len(), 25);
        assert_eq!(particle_styles(ParticlesDensity::High, 1).len(), 40);
    }

    #[test]
    fn particles_stay_inside_their_ranges() {
        for style in particle_styles(ParticlesDensity::High, 42) {
            let value = |name: &str, unit: &str| -> f64 {
                let start = style.find(name).expect("property") + name.len() + 2;
                let rest = &style[start..];
                rest[..rest.find(unit).expect("unit")]
                    .parse()
                    .expect("number")
            };

            assert!((8.0..=20.0).contains(&value("--ui-particle-size", "px")));
            assert!((0.0..=100.0).contains(&value("--ui-particle-left", "%")));
            assert!((0.0..=100.0).contains(&value("--ui-particle-top", "%")));
            assert!((0.0..=8.0).contains(&value("--ui-particle-delay", "s")));
            assert!((20.0..=35.0).contains(&value("--ui-particle-duration", "s")));
            assert!(style.contains("--ui-particle-tone: var(--"));
        }
    }

    #[test]
    fn seeds_change_the_layout() {
        assert_ne!(
            particle_styles(ParticlesDensity::Low, 1),
            particle_styles(ParticlesDensity::Low, 2)
        );
    }
}