lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! CSS scroll-driven motion: `Parallax` and `ViewProgress`.

use dioxus::prelude::*;

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

const PARALLAX_DEFAULT_FROM: f64 = -6.0;
const PARALLAX_DEFAULT_TO: f64 = 6.0;
const PARALLAX_MAX_OFFSET: f64 = 50.0;
const PARALLAX_MAX_ZOOM: f64 = 1.5;

/// Keeps two decimals, like `lumen-core`, so inline styles stay short and deterministic.
fn round_two(value: f64) -> f64 {
    js_round(value * 100.0) / 100.0
}

/// Clamps a parallax offset to `-50..=50` percent; a missing or non-finite value uses `fallback`.
pub(crate) fn normalize_parallax_offset(value: Option<f64>, fallback: f64) -> f64 {
    match value {
        Some(value) if value.is_finite() => {
            round_two(value.clamp(-PARALLAX_MAX_OFFSET, PARALLAX_MAX_OFFSET))
        }
        _ => fallback,
    }
}

/// Clamps a parallax zoom to `1..=1.5`; a missing or non-finite value means no zoom.
pub(crate) fn normalize_parallax_zoom(value: Option<f64>) -> f64 {
    match value {
        Some(value) if value.is_finite() => round_two(value.clamp(1.0, PARALLAX_MAX_ZOOM)),
        _ => 1.0,
    }
}

/// The custom properties set on the `Parallax` root, like `lumenParallaxStyleProperties`. Zoom is
/// omitted at 1 so resting children keep `scale: none`.
pub(crate) fn parallax_properties(from: Option<f64>, to: Option<f64>, zoom: Option<f64>) -> String {
    let from = normalize_parallax_offset(from, PARALLAX_DEFAULT_FROM);
    let to = normalize_parallax_offset(to, PARALLAX_DEFAULT_TO);
    let zoom = normalize_parallax_zoom(zoom);
    let offsets = format!(
        "--ui-parallax-from: {}%; --ui-parallax-to: {}%",
        js_number(from),
        js_number(to)
    );

    if (zoom - 1.0).abs() > f64::EPSILON {
        format!("{offsets}; --ui-parallax-zoom: {}", js_number(zoom))
    } else {
        offsets
    }
}

/// Props for [`Parallax`].
#[derive(Props, Clone, PartialEq)]
pub struct ParallaxProps {
    /// Clips the moving children to the root's box, for framed images.
    #[props(default)]
    pub clip: bool,
    /// Starting offset as a percentage of each child's height, clamped to -50..=50. Defaults to -6.
    #[props(into)]
    pub from: Option<f64>,
    /// Ending offset as a percentage of each child's height, clamped to -50..=50. Defaults to 6.
    #[props(into)]
    pub to: Option<f64>,
    /// Constant scale, clamped to 1..=1.5, so a clipped image covers its frame while it moves.
    #[props(into)]
    pub zoom: Option<f64>,
    /// Inline style; the parallax properties 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 move.
    pub children: Element,
}

/// Moves its direct children while the root crosses the viewport, with a CSS scroll-driven
/// animation. Decorative only: children rest in place where scroll-driven animations are
/// unsupported (Dioxus Native today) or motion is reduced.
#[component]
pub fn Parallax(props: ParallaxProps) -> Element {
    let class = compose([
        Some("ui-parallax"),
        props.clip.then_some("ui-parallax--clip"),
        props.class.as_deref(),
    ]);
    let style = merge_style(
        props.style.as_deref(),
        &parallax_properties(props.from, props.to, props.zoom),
    );

    rsx! {
        div { class, style, ..props.attributes, {props.children} }
    }
}

/// The part of a viewport pass that [`ViewProgress`] maps to 0..=1.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ViewProgressRange {
    /// From the first pixel entering to the last pixel leaving.
    #[default]
    Cover,
    /// While the element is fully inside the viewport.
    Contain,
    /// While the element enters.
    Entry,
    /// While the element leaves.
    Exit,
}

impl ViewProgressRange {
    /// The class suffix.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Cover => "cover",
            Self::Contain => "contain",
            Self::Entry => "entry",
            Self::Exit => "exit",
        }
    }
}

/// Props for [`ViewProgress`].
#[derive(Props, Clone, PartialEq)]
pub struct ViewProgressProps {
    /// The part of the pass mapped to 0..=1.
    #[props(default)]
    pub range: ViewProgressRange,
    /// 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>,
    /// Content that reads `--ui-view-progress`.
    pub children: Element,
}

/// Scrubs the registered `--ui-view-progress` number from 0 to 1 on its root while it crosses
/// the viewport. It rests at 1 where scroll-driven animations are unsupported (Dioxus Native
/// today) or motion is reduced.
#[component]
pub fn ViewProgress(props: ViewProgressProps) -> Element {
    let range = format!("ui-view-progress--{}", props.range.as_str());
    let class = compose([
        Some("ui-view-progress"),
        Some(range.as_str()),
        props.class.as_deref(),
    ]);

    rsx! {
        div { class, ..props.attributes, {props.children} }
    }
}

#[cfg(test)]
mod tests {
    use super::{normalize_parallax_offset, normalize_parallax_zoom, parallax_properties};

    #[test]
    fn offsets_clamp_and_round_like_lumen_core() {
        assert!((normalize_parallax_offset(Some(80.0), 6.0) - 50.0).abs() < f64::EPSILON);
        assert!((normalize_parallax_offset(Some(-80.0), 6.0) + 50.0).abs() < f64::EPSILON);
        assert!((normalize_parallax_offset(Some(1.234_56), 6.0) - 1.23).abs() < 1e-9);
        assert!((normalize_parallax_offset(Some(f64::NAN), 6.0) - 6.0).abs() < f64::EPSILON);
        assert!((normalize_parallax_offset(None, -6.0) + 6.0).abs() < f64::EPSILON);
    }

    #[test]
    fn zoom_clamps_to_its_range() {
        assert!((normalize_parallax_zoom(Some(3.0)) - 1.5).abs() < f64::EPSILON);
        assert!((normalize_parallax_zoom(Some(0.2)) - 1.0).abs() < f64::EPSILON);
        assert!((normalize_parallax_zoom(None) - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn properties_omit_a_resting_zoom() {
        assert_eq!(
            parallax_properties(None, None, None),
            "--ui-parallax-from: -6%; --ui-parallax-to: 6%"
        );
        assert_eq!(
            parallax_properties(Some(-0.0), Some(12.5), Some(1.2)),
            "--ui-parallax-from: 0%; --ui-parallax-to: 12.5%; --ui-parallax-zoom: 1.2"
        );
    }
}