Skip to main content

lumen_dioxus/motion/
particles.rs

1//! Decorative floating particles.
2// cspell:words splitmix
3
4use std::collections::hash_map::RandomState;
5use std::hash::BuildHasher;
6use std::sync::atomic::{AtomicU64, Ordering};
7
8use dioxus::prelude::*;
9
10use super::shared::{MotionSupport, use_motion_support};
11use crate::class::compose;
12
13/// How many particles a [`Particles`] field holds.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum ParticlesDensity {
17    /// 15 particles.
18    Low,
19    /// 25 particles.
20    #[default]
21    Medium,
22    /// 40 particles.
23    High,
24}
25
26impl ParticlesDensity {
27    /// The `data-ui-particles` value.
28    pub fn as_str(self) -> &'static str {
29        match self {
30            Self::Low => "low",
31            Self::Medium => "medium",
32            Self::High => "high",
33        }
34    }
35
36    /// The number of particles, matching lumen-react.
37    pub fn count(self) -> usize {
38        match self {
39            Self::Low => 15,
40            Self::Medium => 25,
41            Self::High => 40,
42        }
43    }
44}
45
46const PARTICLE_TONES: [&str; 3] = ["var(--brand)", "var(--accent)", "var(--glow, var(--brand))"];
47
48/// A small splitmix64 generator; particles only need decorative variation.
49struct ParticleRandom(u64);
50
51impl ParticleRandom {
52    fn next(&mut self) -> f64 {
53        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
54        let mut mixed = self.0;
55        mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
56        mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
57        mixed ^= mixed >> 31;
58
59        // 52 random mantissa bits give a value in 1..2.
60        f64::from_bits(0x3FF0_0000_0000_0000 | (mixed >> 12)) - 1.0
61    }
62}
63
64/// The inline style of each particle, generated like `createParticles` in lumen-react.
65pub(crate) fn particle_styles(density: ParticlesDensity, seed: u64) -> Vec<String> {
66    let mut random = ParticleRandom(seed);
67
68    (0..density.count())
69        .map(|_| {
70            let size = random.next() * 12.0 + 8.0;
71            let left = random.next() * 100.0;
72            let top = random.next() * 100.0;
73            let delay = random.next() * 8.0;
74            let duration = 20.0 + random.next() * 15.0;
75            let pick = random.next();
76            let tone = if pick < 1.0 / 3.0 {
77                PARTICLE_TONES[0]
78            } else if pick < 2.0 / 3.0 {
79                PARTICLE_TONES[1]
80            } else {
81                PARTICLE_TONES[2]
82            };
83
84            format!(
85                "--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}%"
86            )
87        })
88        .collect()
89}
90
91static NEXT_FIELD: AtomicU64 = AtomicU64::new(0);
92
93/// A per-field seed: the browser's `Math.random()` when it answered, otherwise the process's
94/// random hasher keys mixed with a counter.
95fn particle_seed(support: MotionSupport) -> u64 {
96    let field = NEXT_FIELD.fetch_add(1, Ordering::Relaxed);
97
98    match support {
99        MotionSupport::Browser { random, .. } => random.to_bits() ^ field,
100        _ => RandomState::new().hash_one(field),
101    }
102}
103
104/// Props for [`Particles`].
105#[derive(Props, Clone, PartialEq)]
106pub struct ParticlesProps {
107    /// How many particles drift through the field.
108    #[props(default)]
109    pub density: ParticlesDensity,
110    /// Extra classes appended after the Lumen class.
111    #[props(into)]
112    pub class: Option<String>,
113    /// Any other `<div>` or global attribute.
114    #[props(extends = GlobalAttributes, extends = div)]
115    pub attributes: Vec<Attribute>,
116    /// Content placed in the field before the particles.
117    pub children: Element,
118}
119
120/// A decorative field of drifting particles, hidden from assistive technology.
121///
122/// Like lumen-react, the first render has no particles; they are generated after mount with
123/// fresh positions. They are skipped when a browser reports reduced motion, and Lumen's CSS hides
124/// them under `prefers-reduced-motion` wherever the renderer evaluates that query.
125#[component]
126pub fn Particles(props: ParticlesProps) -> Element {
127    let support = use_motion_support();
128    let mut seed = use_hook(|| CopyValue::new(None::<u64>));
129    let class = compose([Some("ui-particles"), props.class.as_deref()]);
130    let current = support();
131
132    if current != MotionSupport::Pending && !current.reduced() && seed.peek().is_none() {
133        seed.set(Some(particle_seed(current)));
134    }
135
136    let particles =
137        (*seed.peek()).map_or_else(Vec::new, |seed| particle_styles(props.density, seed));
138
139    rsx! {
140        div {
141            aria_hidden: "true",
142            class,
143            "data-ui-particles": props.density.as_str(),
144            ..props.attributes,
145            {props.children}
146            for (index, style) in particles.into_iter().enumerate() {
147                span { key: "{index}", class: "ui-particles__particle", style }
148            }
149        }
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::{ParticlesDensity, particle_styles};
156
157    #[test]
158    fn densities_match_lumen_react() {
159        assert_eq!(particle_styles(ParticlesDensity::Low, 1).len(), 15);
160        assert_eq!(particle_styles(ParticlesDensity::Medium, 1).len(), 25);
161        assert_eq!(particle_styles(ParticlesDensity::High, 1).len(), 40);
162    }
163
164    #[test]
165    fn particles_stay_inside_their_ranges() {
166        for style in particle_styles(ParticlesDensity::High, 42) {
167            let value = |name: &str, unit: &str| -> f64 {
168                let start = style.find(name).expect("property") + name.len() + 2;
169                let rest = &style[start..];
170                rest[..rest.find(unit).expect("unit")]
171                    .parse()
172                    .expect("number")
173            };
174
175            assert!((8.0..=20.0).contains(&value("--ui-particle-size", "px")));
176            assert!((0.0..=100.0).contains(&value("--ui-particle-left", "%")));
177            assert!((0.0..=100.0).contains(&value("--ui-particle-top", "%")));
178            assert!((0.0..=8.0).contains(&value("--ui-particle-delay", "s")));
179            assert!((20.0..=35.0).contains(&value("--ui-particle-duration", "s")));
180            assert!(style.contains("--ui-particle-tone: var(--"));
181        }
182    }
183
184    #[test]
185    fn seeds_change_the_layout() {
186        assert_ne!(
187            particle_styles(ParticlesDensity::Low, 1),
188            particle_styles(ParticlesDensity::Low, 2)
189        );
190    }
191}