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;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParticlesDensity {
Low,
#[default]
Medium,
High,
}
impl ParticlesDensity {
pub fn as_str(self) -> &'static str {
match self {
Self::Low => "low",
Self::Medium => "medium",
Self::High => "high",
}
}
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))"];
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;
f64::from_bits(0x3FF0_0000_0000_0000 | (mixed >> 12)) - 1.0
}
}
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);
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),
}
}
#[derive(Props, Clone, PartialEq)]
pub struct ParticlesProps {
#[props(default)]
pub density: ParticlesDensity,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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)
);
}
}