lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Decorative surface effects and keyed layout motion: `VisualEffect` and `MotionGroup`.
// cspell:words onfocusout onpointerenter onpointerleave

use std::rc::Rc;

use dioxus::prelude::*;

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

/// The effect a [`VisualEffect`] draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum VisualEffectVariant {
    /// A soft multi-color mesh gradient.
    #[default]
    Mesh,
    /// Drifting aurora bands.
    Aurora,
    /// A glow that follows the pointer.
    Spotlight,
    /// Film grain.
    Grain,
    /// An animated gradient border.
    Border,
    /// Strokes that draw in.
    Draw,
    /// Layered depth shading.
    Depth,
}

impl VisualEffectVariant {
    /// The `data-ui-visual-effect` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Mesh => "mesh",
            Self::Aurora => "aurora",
            Self::Spotlight => "spotlight",
            Self::Grain => "grain",
            Self::Border => "border",
            Self::Draw => "draw",
            Self::Depth => "depth",
        }
    }
}

/// Clamps an effect intensity to `0..=1`; non-finite values become 0.5, like
/// `normalizeLumenEffectIntensity`.
pub(crate) fn normalize_effect_intensity(value: f64) -> f64 {
    if value.is_finite() {
        value.clamp(0.0, 1.0)
    } else {
        0.5
    }
}

/// The spotlight position inside a box: the pointer offset clamped to the box, in pixels.
pub(crate) fn spotlight_offset(pointer: f64, start: f64, size: f64) -> String {
    let size = if size.is_finite() { size.max(0.0) } else { 0.0 };
    let offset = (pointer - start).max(0.0).min(size);

    format!("{}px", js_number(offset))
}

/// Client-space bounds of the effect root: left, top, width, height.
type Bounds = (f64, f64, f64, f64);

/// Props for [`VisualEffect`].
#[derive(Props, Clone, PartialEq)]
pub struct VisualEffectProps {
    /// Runs the effect's ambient animation.
    #[props(default)]
    pub animated: bool,
    /// Strength, clamped to `0..=1`.
    #[props(default = 0.5, into)]
    pub intensity: f64,
    /// The effect to draw.
    #[props(default)]
    pub variant: VisualEffectVariant,
    /// Inline style; the intensity is appended to it.
    #[props(into)]
    pub style: Option<String>,
    /// 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 drawn over the effect.
    pub children: Element,
}

/// A decorative effect layer behind its content.
///
/// The spotlight variant follows mouse and pen pointers on the web and desktop, and resets to the
/// center when the pointer leaves or focus moves out. Dioxus Native has no pointer or mounted
/// events yet, so its spotlight rests in the center.
#[component]
pub fn VisualEffect(props: VisualEffectProps) -> Element {
    let support = use_motion_support();
    let mut root = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
    let mut bounds = use_hook(|| CopyValue::new(None::<Bounds>));
    let mut spotlight = use_signal(|| None::<(String, String)>);
    let tracks = props.variant == VisualEffectVariant::Spotlight;

    let refresh_bounds = move || {
        if let Some(element) = root.peek().clone() {
            spawn(async move {
                if let Ok(rect) = element.get_client_rect().await {
                    bounds.set(Some((
                        rect.origin.x,
                        rect.origin.y,
                        rect.size.width,
                        rect.size.height,
                    )));
                }
            });
        }
    };

    let mut reset = move || {
        if tracks {
            spotlight.set(Some(("50%".to_string(), "50%".to_string())));
        }
    };

    let intensity = js_number(normalize_effect_intensity(props.intensity));
    let own = match spotlight() {
        Some((x, y)) => format!(
            "--ui-effect-intensity: {intensity}; --ui-spotlight-x: {x}; --ui-spotlight-y: {y}"
        ),
        None => format!("--ui-effect-intensity: {intensity}"),
    };

    let style = merge_style(props.style.as_deref(), &own);
    let class = compose([Some("ui-visual-effect"), props.class.as_deref()]);

    rsx! {
        div {
            class,
            "data-ui-effect-animated": "{props.animated}",
            "data-ui-visual-effect": props.variant.as_str(),
            style,
            onmounted: move |event| root.set(Some(event.data())),
            onpointerenter: move |_| {
                if tracks {
                    refresh_bounds();
                }
            },
            onpointermove: move |event| {
                if !tracks || event.pointer_type() == "touch" || support.peek().reduced() {
                    return;
                }

                let point = event.client_coordinates();

                match *bounds.peek() {
                    Some((left, top, width, height)) => spotlight.set(Some((
                        spotlight_offset(point.x, left, width),
                        spotlight_offset(point.y, top, height),
                    ))),
                    None => refresh_bounds(),
                }
            },
            onpointerleave: move |_| reset(),
            onfocusout: move |_| reset(),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Animation length of a [`MotionGroup`] reflow.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MotionGroupDuration {
    /// `--ui-duration-fast`.
    Fast,
    /// `--ui-duration`.
    #[default]
    Standard,
    /// `--ui-duration-slow`.
    Slow,
}

impl MotionGroupDuration {
    /// The token name suffix.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Fast => "fast",
            Self::Standard => "standard",
            Self::Slow => "slow",
        }
    }
}

/// Props for [`MotionGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct MotionGroupProps {
    /// Reflow animation length in lumen-react's browser runtime.
    #[props(default)]
    pub duration: MotionGroupDuration,
    /// Fades children in and out in lumen-react's browser runtime.
    #[props(default = true)]
    pub enter_exit: bool,
    /// 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>,
    /// Children keyed with `data-ui-motion-key`.
    pub children: Element,
}

/// A container whose keyed children (`data-ui-motion-key`) keep their identity across updates.
///
/// It renders the same markup as lumen-react. The FLIP reorder, enter, and exit animation is a
/// browser runtime built on `MutationObserver` and Web Animations that lumen-dioxus does not run,
/// so children move to their new places at once, as they do in React under reduced motion.
#[component]
pub fn MotionGroup(props: MotionGroupProps) -> Element {
    let class = compose([Some("ui-motion-group"), props.class.as_deref()]);

    rsx! {
        div {
            class,
            "data-ui-motion-group": "true",
            ..props.attributes,
            {props.children}
        }
    }
}

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

    #[test]
    fn intensity_clamps_like_lumen_core() {
        assert!((normalize_effect_intensity(3.0) - 1.0).abs() < f64::EPSILON);
        assert!(normalize_effect_intensity(-1.0).abs() < f64::EPSILON);
        assert!((normalize_effect_intensity(f64::INFINITY) - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn spotlight_stays_inside_the_box() {
        assert_eq!(spotlight_offset(150.0, 100.0, 200.0), "50px");
        assert_eq!(spotlight_offset(50.0, 100.0, 200.0), "0px");
        assert_eq!(spotlight_offset(500.0, 100.0, 200.0), "200px");
        assert_eq!(spotlight_offset(500.0, 100.0, f64::NAN), "0px");
    }
}