Skip to main content

lumen_dioxus/motion/
scroll.rs

1//! CSS scroll-driven motion: `Parallax` and `ViewProgress`.
2
3use dioxus::prelude::*;
4
5use super::shared::{js_number, js_round, merge_style};
6use crate::class::compose;
7
8const PARALLAX_DEFAULT_FROM: f64 = -6.0;
9const PARALLAX_DEFAULT_TO: f64 = 6.0;
10const PARALLAX_MAX_OFFSET: f64 = 50.0;
11const PARALLAX_MAX_ZOOM: f64 = 1.5;
12
13/// Keeps two decimals, like `lumen-core`, so inline styles stay short and deterministic.
14fn round_two(value: f64) -> f64 {
15    js_round(value * 100.0) / 100.0
16}
17
18/// Clamps a parallax offset to `-50..=50` percent; a missing or non-finite value uses `fallback`.
19pub(crate) fn normalize_parallax_offset(value: Option<f64>, fallback: f64) -> f64 {
20    match value {
21        Some(value) if value.is_finite() => {
22            round_two(value.clamp(-PARALLAX_MAX_OFFSET, PARALLAX_MAX_OFFSET))
23        }
24        _ => fallback,
25    }
26}
27
28/// Clamps a parallax zoom to `1..=1.5`; a missing or non-finite value means no zoom.
29pub(crate) fn normalize_parallax_zoom(value: Option<f64>) -> f64 {
30    match value {
31        Some(value) if value.is_finite() => round_two(value.clamp(1.0, PARALLAX_MAX_ZOOM)),
32        _ => 1.0,
33    }
34}
35
36/// The custom properties set on the `Parallax` root, like `lumenParallaxStyleProperties`. Zoom is
37/// omitted at 1 so resting children keep `scale: none`.
38pub(crate) fn parallax_properties(from: Option<f64>, to: Option<f64>, zoom: Option<f64>) -> String {
39    let from = normalize_parallax_offset(from, PARALLAX_DEFAULT_FROM);
40    let to = normalize_parallax_offset(to, PARALLAX_DEFAULT_TO);
41    let zoom = normalize_parallax_zoom(zoom);
42    let offsets = format!(
43        "--ui-parallax-from: {}%; --ui-parallax-to: {}%",
44        js_number(from),
45        js_number(to)
46    );
47
48    if (zoom - 1.0).abs() > f64::EPSILON {
49        format!("{offsets}; --ui-parallax-zoom: {}", js_number(zoom))
50    } else {
51        offsets
52    }
53}
54
55/// Props for [`Parallax`].
56#[derive(Props, Clone, PartialEq)]
57pub struct ParallaxProps {
58    /// Clips the moving children to the root's box, for framed images.
59    #[props(default)]
60    pub clip: bool,
61    /// Starting offset as a percentage of each child's height, clamped to -50..=50. Defaults to -6.
62    #[props(into)]
63    pub from: Option<f64>,
64    /// Ending offset as a percentage of each child's height, clamped to -50..=50. Defaults to 6.
65    #[props(into)]
66    pub to: Option<f64>,
67    /// Constant scale, clamped to 1..=1.5, so a clipped image covers its frame while it moves.
68    #[props(into)]
69    pub zoom: Option<f64>,
70    /// Inline style; the parallax properties are appended to it.
71    #[props(into)]
72    pub style: Option<String>,
73    /// Extra classes appended after the Lumen classes.
74    #[props(into)]
75    pub class: Option<String>,
76    /// Any other `<div>` or global attribute.
77    #[props(extends = GlobalAttributes, extends = div)]
78    pub attributes: Vec<Attribute>,
79    /// The children that move.
80    pub children: Element,
81}
82
83/// Moves its direct children while the root crosses the viewport, with a CSS scroll-driven
84/// animation. Decorative only: children rest in place where scroll-driven animations are
85/// unsupported (Dioxus Native today) or motion is reduced.
86#[component]
87pub fn Parallax(props: ParallaxProps) -> Element {
88    let class = compose([
89        Some("ui-parallax"),
90        props.clip.then_some("ui-parallax--clip"),
91        props.class.as_deref(),
92    ]);
93    let style = merge_style(
94        props.style.as_deref(),
95        &parallax_properties(props.from, props.to, props.zoom),
96    );
97
98    rsx! {
99        div { class, style, ..props.attributes, {props.children} }
100    }
101}
102
103/// The part of a viewport pass that [`ViewProgress`] maps to 0..=1.
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
105#[non_exhaustive]
106pub enum ViewProgressRange {
107    /// From the first pixel entering to the last pixel leaving.
108    #[default]
109    Cover,
110    /// While the element is fully inside the viewport.
111    Contain,
112    /// While the element enters.
113    Entry,
114    /// While the element leaves.
115    Exit,
116}
117
118impl ViewProgressRange {
119    /// The class suffix.
120    pub fn as_str(self) -> &'static str {
121        match self {
122            Self::Cover => "cover",
123            Self::Contain => "contain",
124            Self::Entry => "entry",
125            Self::Exit => "exit",
126        }
127    }
128}
129
130/// Props for [`ViewProgress`].
131#[derive(Props, Clone, PartialEq)]
132pub struct ViewProgressProps {
133    /// The part of the pass mapped to 0..=1.
134    #[props(default)]
135    pub range: ViewProgressRange,
136    /// Extra classes appended after the Lumen classes.
137    #[props(into)]
138    pub class: Option<String>,
139    /// Any other `<div>` or global attribute.
140    #[props(extends = GlobalAttributes, extends = div)]
141    pub attributes: Vec<Attribute>,
142    /// Content that reads `--ui-view-progress`.
143    pub children: Element,
144}
145
146/// Scrubs the registered `--ui-view-progress` number from 0 to 1 on its root while it crosses
147/// the viewport. It rests at 1 where scroll-driven animations are unsupported (Dioxus Native
148/// today) or motion is reduced.
149#[component]
150pub fn ViewProgress(props: ViewProgressProps) -> Element {
151    let range = format!("ui-view-progress--{}", props.range.as_str());
152    let class = compose([
153        Some("ui-view-progress"),
154        Some(range.as_str()),
155        props.class.as_deref(),
156    ]);
157
158    rsx! {
159        div { class, ..props.attributes, {props.children} }
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::{normalize_parallax_offset, normalize_parallax_zoom, parallax_properties};
166
167    #[test]
168    fn offsets_clamp_and_round_like_lumen_core() {
169        assert!((normalize_parallax_offset(Some(80.0), 6.0) - 50.0).abs() < f64::EPSILON);
170        assert!((normalize_parallax_offset(Some(-80.0), 6.0) + 50.0).abs() < f64::EPSILON);
171        assert!((normalize_parallax_offset(Some(1.234_56), 6.0) - 1.23).abs() < 1e-9);
172        assert!((normalize_parallax_offset(Some(f64::NAN), 6.0) - 6.0).abs() < f64::EPSILON);
173        assert!((normalize_parallax_offset(None, -6.0) + 6.0).abs() < f64::EPSILON);
174    }
175
176    #[test]
177    fn zoom_clamps_to_its_range() {
178        assert!((normalize_parallax_zoom(Some(3.0)) - 1.5).abs() < f64::EPSILON);
179        assert!((normalize_parallax_zoom(Some(0.2)) - 1.0).abs() < f64::EPSILON);
180        assert!((normalize_parallax_zoom(None) - 1.0).abs() < f64::EPSILON);
181    }
182
183    #[test]
184    fn properties_omit_a_resting_zoom() {
185        assert_eq!(
186            parallax_properties(None, None, None),
187            "--ui-parallax-from: -6%; --ui-parallax-to: 6%"
188        );
189        assert_eq!(
190            parallax_properties(Some(-0.0), Some(12.5), Some(1.2)),
191            "--ui-parallax-from: 0%; --ui-parallax-to: 12.5%; --ui-parallax-zoom: 1.2"
192        );
193    }
194}