Skip to main content

lumen_dioxus/motion/
effects.rs

1//! Decorative surface effects and keyed layout motion: `VisualEffect` and `MotionGroup`.
2// cspell:words onfocusout onpointerenter onpointerleave
3
4use std::rc::Rc;
5
6use dioxus::prelude::*;
7
8use super::shared::{js_number, merge_style, use_motion_support};
9use crate::class::compose;
10
11/// The effect a [`VisualEffect`] draws.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum VisualEffectVariant {
15    /// A soft multi-color mesh gradient.
16    #[default]
17    Mesh,
18    /// Drifting aurora bands.
19    Aurora,
20    /// A glow that follows the pointer.
21    Spotlight,
22    /// Film grain.
23    Grain,
24    /// An animated gradient border.
25    Border,
26    /// Strokes that draw in.
27    Draw,
28    /// Layered depth shading.
29    Depth,
30}
31
32impl VisualEffectVariant {
33    /// The `data-ui-visual-effect` value.
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Mesh => "mesh",
37            Self::Aurora => "aurora",
38            Self::Spotlight => "spotlight",
39            Self::Grain => "grain",
40            Self::Border => "border",
41            Self::Draw => "draw",
42            Self::Depth => "depth",
43        }
44    }
45}
46
47/// Clamps an effect intensity to `0..=1`; non-finite values become 0.5, like
48/// `normalizeLumenEffectIntensity`.
49pub(crate) fn normalize_effect_intensity(value: f64) -> f64 {
50    if value.is_finite() {
51        value.clamp(0.0, 1.0)
52    } else {
53        0.5
54    }
55}
56
57/// The spotlight position inside a box: the pointer offset clamped to the box, in pixels.
58pub(crate) fn spotlight_offset(pointer: f64, start: f64, size: f64) -> String {
59    let size = if size.is_finite() { size.max(0.0) } else { 0.0 };
60    let offset = (pointer - start).max(0.0).min(size);
61
62    format!("{}px", js_number(offset))
63}
64
65/// Client-space bounds of the effect root: left, top, width, height.
66type Bounds = (f64, f64, f64, f64);
67
68/// Props for [`VisualEffect`].
69#[derive(Props, Clone, PartialEq)]
70pub struct VisualEffectProps {
71    /// Runs the effect's ambient animation.
72    #[props(default)]
73    pub animated: bool,
74    /// Strength, clamped to `0..=1`.
75    #[props(default = 0.5, into)]
76    pub intensity: f64,
77    /// The effect to draw.
78    #[props(default)]
79    pub variant: VisualEffectVariant,
80    /// Inline style; the intensity is appended to it.
81    #[props(into)]
82    pub style: Option<String>,
83    /// Extra classes appended after the Lumen class.
84    #[props(into)]
85    pub class: Option<String>,
86    /// Any other `<div>` or global attribute.
87    #[props(extends = GlobalAttributes, extends = div)]
88    pub attributes: Vec<Attribute>,
89    /// Content drawn over the effect.
90    pub children: Element,
91}
92
93/// A decorative effect layer behind its content.
94///
95/// The spotlight variant follows mouse and pen pointers on the web and desktop, and resets to the
96/// center when the pointer leaves or focus moves out. Dioxus Native has no pointer or mounted
97/// events yet, so its spotlight rests in the center.
98#[component]
99pub fn VisualEffect(props: VisualEffectProps) -> Element {
100    let support = use_motion_support();
101    let mut root = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
102    let mut bounds = use_hook(|| CopyValue::new(None::<Bounds>));
103    let mut spotlight = use_signal(|| None::<(String, String)>);
104    let tracks = props.variant == VisualEffectVariant::Spotlight;
105
106    let refresh_bounds = move || {
107        if let Some(element) = root.peek().clone() {
108            spawn(async move {
109                if let Ok(rect) = element.get_client_rect().await {
110                    bounds.set(Some((
111                        rect.origin.x,
112                        rect.origin.y,
113                        rect.size.width,
114                        rect.size.height,
115                    )));
116                }
117            });
118        }
119    };
120
121    let mut reset = move || {
122        if tracks {
123            spotlight.set(Some(("50%".to_string(), "50%".to_string())));
124        }
125    };
126
127    let intensity = js_number(normalize_effect_intensity(props.intensity));
128    let own = match spotlight() {
129        Some((x, y)) => format!(
130            "--ui-effect-intensity: {intensity}; --ui-spotlight-x: {x}; --ui-spotlight-y: {y}"
131        ),
132        None => format!("--ui-effect-intensity: {intensity}"),
133    };
134
135    let style = merge_style(props.style.as_deref(), &own);
136    let class = compose([Some("ui-visual-effect"), props.class.as_deref()]);
137
138    rsx! {
139        div {
140            class,
141            "data-ui-effect-animated": "{props.animated}",
142            "data-ui-visual-effect": props.variant.as_str(),
143            style,
144            onmounted: move |event| root.set(Some(event.data())),
145            onpointerenter: move |_| {
146                if tracks {
147                    refresh_bounds();
148                }
149            },
150            onpointermove: move |event| {
151                if !tracks || event.pointer_type() == "touch" || support.peek().reduced() {
152                    return;
153                }
154
155                let point = event.client_coordinates();
156
157                match *bounds.peek() {
158                    Some((left, top, width, height)) => spotlight.set(Some((
159                        spotlight_offset(point.x, left, width),
160                        spotlight_offset(point.y, top, height),
161                    ))),
162                    None => refresh_bounds(),
163                }
164            },
165            onpointerleave: move |_| reset(),
166            onfocusout: move |_| reset(),
167            ..props.attributes,
168            {props.children}
169        }
170    }
171}
172
173/// Animation length of a [`MotionGroup`] reflow.
174#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
175#[non_exhaustive]
176pub enum MotionGroupDuration {
177    /// `--ui-duration-fast`.
178    Fast,
179    /// `--ui-duration`.
180    #[default]
181    Standard,
182    /// `--ui-duration-slow`.
183    Slow,
184}
185
186impl MotionGroupDuration {
187    /// The token name suffix.
188    pub fn as_str(self) -> &'static str {
189        match self {
190            Self::Fast => "fast",
191            Self::Standard => "standard",
192            Self::Slow => "slow",
193        }
194    }
195}
196
197/// Props for [`MotionGroup`].
198#[derive(Props, Clone, PartialEq)]
199pub struct MotionGroupProps {
200    /// Reflow animation length in lumen-react's browser runtime.
201    #[props(default)]
202    pub duration: MotionGroupDuration,
203    /// Fades children in and out in lumen-react's browser runtime.
204    #[props(default = true)]
205    pub enter_exit: bool,
206    /// Extra classes appended after the Lumen class.
207    #[props(into)]
208    pub class: Option<String>,
209    /// Any other `<div>` or global attribute.
210    #[props(extends = GlobalAttributes, extends = div)]
211    pub attributes: Vec<Attribute>,
212    /// Children keyed with `data-ui-motion-key`.
213    pub children: Element,
214}
215
216/// A container whose keyed children (`data-ui-motion-key`) keep their identity across updates.
217///
218/// It renders the same markup as lumen-react. The FLIP reorder, enter, and exit animation is a
219/// browser runtime built on `MutationObserver` and Web Animations that lumen-dioxus does not run,
220/// so children move to their new places at once, as they do in React under reduced motion.
221#[component]
222pub fn MotionGroup(props: MotionGroupProps) -> Element {
223    let class = compose([Some("ui-motion-group"), props.class.as_deref()]);
224
225    rsx! {
226        div {
227            class,
228            "data-ui-motion-group": "true",
229            ..props.attributes,
230            {props.children}
231        }
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::{normalize_effect_intensity, spotlight_offset};
238
239    #[test]
240    fn intensity_clamps_like_lumen_core() {
241        assert!((normalize_effect_intensity(3.0) - 1.0).abs() < f64::EPSILON);
242        assert!(normalize_effect_intensity(-1.0).abs() < f64::EPSILON);
243        assert!((normalize_effect_intensity(f64::INFINITY) - 0.5).abs() < f64::EPSILON);
244    }
245
246    #[test]
247    fn spotlight_stays_inside_the_box() {
248        assert_eq!(spotlight_offset(150.0, 100.0, 200.0), "50px");
249        assert_eq!(spotlight_offset(50.0, 100.0, 200.0), "0px");
250        assert_eq!(spotlight_offset(500.0, 100.0, 200.0), "200px");
251        assert_eq!(spotlight_offset(500.0, 100.0, f64::NAN), "0px");
252    }
253}