lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Scroll-triggered entrances: `ScrollReveal` and `RevealGroup`.
// cspell:words onfocusin onvisible

use dioxus::prelude::*;

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

/// Entrance style of a [`ScrollReveal`] or [`RevealGroup`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RevealAnimation {
    /// Opacity only. The [`ScrollReveal`] default.
    #[default]
    Fade,
    /// Rises by the reveal distance while fading in. The [`RevealGroup`] default.
    SlideUp,
    /// Grows from 96% while fading in.
    Scale,
    /// Unmasks from the bottom edge.
    Curtain,
    /// Draws in from the inline start, for rules and dividers.
    Rule,
}

impl RevealAnimation {
    /// The class suffix.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Fade => "fade",
            Self::SlideUp => "slide-up",
            Self::Scale => "scale",
            Self::Curtain => "curtain",
            Self::Rule => "rule",
        }
    }
}

/// Travel of a slide-up reveal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RevealDistance {
    /// A short rise.
    Sm,
    /// The original 1.5rem rise.
    #[default]
    Md,
    /// A long rise.
    Lg,
}

impl RevealDistance {
    /// The class suffix.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Sm => "sm",
            Self::Md => "md",
            Self::Lg => "lg",
        }
    }
}

const DEFAULT_THRESHOLD: f64 = 0.15;

/// Clamps a visibility threshold to `0..=1`, like `normalizeLumenRevealThreshold`; non-finite
/// values fall back to 0.15.
pub(crate) fn normalize_reveal_threshold(value: f64) -> f64 {
    if value.is_finite() {
        value.clamp(0.0, 1.0)
    } else {
        DEFAULT_THRESHOLD
    }
}

fn milliseconds(value: f64) -> String {
    format!("{}ms", js_number(if value > 0.0 { value } else { 0.0 }))
}

/// Props for [`ScrollReveal`].
#[derive(Props, Clone, PartialEq)]
pub struct ScrollRevealProps {
    /// Entrance style.
    #[props(default)]
    pub animation: RevealAnimation,
    /// Milliseconds before the entrance starts; negative values become 0.
    #[props(default, into)]
    pub delay: f64,
    /// Travel for slide-up reveals.
    #[props(default)]
    pub distance: RevealDistance,
    /// Transition length.
    #[props(default)]
    pub duration: MotionDuration,
    /// Reveal only once; when false the content hides again after it leaves the viewport.
    #[props(default = true)]
    pub once: bool,
    /// Visible share, `0..=1`, written to `data-ui-reveal-threshold`.
    #[props(default = DEFAULT_THRESHOLD, into)]
    pub threshold: f64,
    /// Inline style; the reveal delay is appended to it.
    #[props(into)]
    pub style: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Revealed content.
    pub children: Element,
}

/// Fades or slides its content in when it scrolls into view.
///
/// The first render is visible, like lumen-react's server markup. On the web and desktop the
/// element binds after mount and reveals on `onvisible`; on Dioxus Native, and when the user
/// prefers reduced motion, the content shows without animation.
#[component]
pub fn ScrollReveal(props: ScrollRevealProps) -> Element {
    let reveal = use_reveal(props.once, true, None);
    let animation = format!("ui-scroll-reveal-{}", props.animation.as_str());
    let duration = props.duration.class();
    let distance = format!("ui-reveal-distance-{}", props.distance.as_str());
    let class = compose([
        Some("ui-scroll-reveal"),
        Some(animation.as_str()),
        Some(duration.as_str()),
        Some(distance.as_str()),
        props.class.as_deref(),
        reveal.revealed().then_some("is-revealed"),
    ]);
    let style = merge_style(
        props.style.as_deref(),
        &format!("--ui-reveal-delay: {}", milliseconds(props.delay)),
    );

    rsx! {
        div {
            class,
            "data-ui-reveal-once": "{props.once}",
            "data-ui-reveal-threshold": js_number(normalize_reveal_threshold(props.threshold)),
            "data-ui-scroll-reveal": "true",
            "data-ui-scroll-reveal-bound": reveal.bound_attribute(),
            style,
            onvisible: move |event| reveal.on_visible(&event),
            onfocusin: move |_| reveal.on_focus_in(),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`RevealGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct RevealGroupProps {
    /// Entrance style of every child.
    #[props(default = RevealAnimation::SlideUp)]
    pub animation: RevealAnimation,
    /// Milliseconds before the first child starts; negative values become 0.
    #[props(default, into)]
    pub delay: f64,
    /// Travel for slide-up reveals.
    #[props(default)]
    pub distance: RevealDistance,
    /// Transition length of each child.
    #[props(default)]
    pub duration: MotionDuration,
    /// Reveal only once; when false the children hide again after the group leaves the viewport.
    #[props(default = true)]
    pub once: bool,
    /// Milliseconds between children; negative values become 0.
    #[props(default = 80.0, into)]
    pub stagger: f64,
    /// Visible share, `0..=1`, written to `data-ui-reveal-threshold`.
    #[props(default = DEFAULT_THRESHOLD, into)]
    pub threshold: f64,
    /// Inline style; the delay and stagger are appended to it.
    #[props(into)]
    pub style: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The children that enter one after another.
    pub children: Element,
}

/// Numbers every reveal group child with `--ui-reveal-index`, as lumen-react's effect does. It
/// runs in browsers and webviews only; the property is decorative.
const INDEX_CHILDREN: &str = "for (const group of document.querySelectorAll('[data-ui-reveal-group]')) { Array.from(group.children).forEach((child, index) => child.style.setProperty('--ui-reveal-index', String(index))); }";

fn index_reveal_children() {
    let _ = document::eval(INDEX_CHILDREN);
}

/// Reveals its direct children one after another when the group scrolls into view.
///
/// Renders like [`ScrollReveal`]. After binding on the web and desktop, each child receives its
/// `--ui-reveal-index` for the stagger; Dioxus Native shows the children without animation.
#[component]
pub fn RevealGroup(props: RevealGroupProps) -> Element {
    let reveal = use_reveal(props.once, true, Some(index_reveal_children));
    let animation = format!("ui-reveal-group-{}", props.animation.as_str());
    let duration = props.duration.class();
    let distance = format!("ui-reveal-distance-{}", props.distance.as_str());
    let class = compose([
        Some("ui-reveal-group"),
        Some(animation.as_str()),
        Some(duration.as_str()),
        Some(distance.as_str()),
        props.class.as_deref(),
        reveal.revealed().then_some("is-revealed"),
    ]);
    let style = merge_style(
        props.style.as_deref(),
        &format!(
            "--ui-reveal-delay: {}; --ui-reveal-stagger: {}",
            milliseconds(props.delay),
            milliseconds(props.stagger)
        ),
    );

    rsx! {
        div {
            class,
            "data-ui-reveal-group": "true",
            "data-ui-reveal-once": "{props.once}",
            "data-ui-reveal-threshold": js_number(normalize_reveal_threshold(props.threshold)),
            "data-ui-scroll-reveal-bound": reveal.bound_attribute(),
            style,
            onvisible: move |event| reveal.on_visible(&event),
            onfocusin: move |_| reveal.on_focus_in(),
            ..props.attributes,
            {props.children}
        }
    }
}

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

    #[test]
    fn thresholds_clamp_like_lumen_core() {
        assert!((normalize_reveal_threshold(2.0) - 1.0).abs() < f64::EPSILON);
        assert!(normalize_reveal_threshold(-1.0).abs() < f64::EPSILON);
        assert!((normalize_reveal_threshold(f64::NAN) - 0.15).abs() < f64::EPSILON);
    }

    #[test]
    fn delays_never_go_negative() {
        assert_eq!(milliseconds(-20.0), "0ms");
        assert_eq!(milliseconds(120.5), "120.5ms");
        assert_eq!(milliseconds(f64::NAN), "0ms");
    }
}