Skip to main content

dioxus_dnd/
animate.rs

1//! Drop animations. **Experimental** - this module is the one part of the
2//! crate whose behavior depends on browser paint timing rather than pure
3//! logic; validate it in your target renderer and tune `duration` to taste.
4//!
5//! [`FlipItem`] implements the FLIP technique (First–Last–Invert–Play) for
6//! reorder transitions: when your list order changes, each item measures
7//! where it moved from, renders instantly *back* at its old position via a
8//! transform, then releases the transform with a CSS transition - so tiles
9//! appear to glide to their new slots.
10//!
11//! You drive it with an `epoch` counter: bump it whenever order changes.
12//!
13//! ```text
14//! let mut items = use_signal(|| vec![/* … */]);
15//! let mut epoch = use_signal(|| 0usize);
16//! rsx! {
17//!     SortableList {
18//!         len: items.read().len(),
19//!         render: move |ix: usize| rsx! {
20//!             FlipItem { epoch: epoch(), Row { item: items.read()[ix].clone() } }
21//!         },
22//!         on_sort: move |ev: SortEvent| {
23//!             apply_sort(&mut items.write(), ev);
24//!             epoch += 1;
25//!         },
26//!     }
27//! }
28//! ```
29//!
30//! **Snap-back on cancel** needs no Rust at all - it's a CSS recipe. Pointer
31//! drags via `Draggable` use your `DragOverlay`; give the overlay's child
32//! `transition: transform 150ms ease` and render it conditionally on
33//! `dnd.dragging()` - reverting your item's `data-dragging` styles with a
34//! transition produces the settle effect.
35
36use std::rc::Rc;
37
38use dioxus::html::MountedData;
39use dioxus::prelude::*;
40
41use crate::core::{Point, Rect};
42
43/// FLIP animation phase.
44#[derive(Debug, Clone, Copy, PartialEq, Default)]
45enum FlipPhase {
46    /// At rest (transition armed, no transform).
47    #[default]
48    Rest,
49    /// Rendered at the *old* position via an instant inverse transform.
50    Invert(Point),
51}
52
53/// Wraps one list/grid item and glides it to its new position whenever
54/// `epoch` changes. See the module docs for the driving pattern.
55#[component]
56pub fn FlipItem(
57    /// Bump this whenever the surrounding order changes.
58    epoch: usize,
59    /// Transition duration in milliseconds.
60    #[props(default = 200.0)]
61    duration: f64,
62    /// CSS easing function.
63    #[props(default = "ease".to_string())]
64    easing: String,
65    #[props(extends = div, extends = GlobalAttributes)] attributes: Vec<Attribute>,
66    children: Element,
67) -> Element {
68    let mounted = use_signal(|| None::<Rc<MountedData>>);
69    let prev = use_signal(|| None::<Rect>);
70    let mut phase = use_signal(FlipPhase::default);
71
72    // First & Last & Invert: on every epoch change, measure the new
73    // position, and if the item moved, snap an inverse transform on.
74    use_effect(use_reactive!(|epoch| {
75        let _ = epoch;
76        let Some(m) = mounted.peek().clone() else {
77            return;
78        };
79        let mut prev = prev;
80        spawn(async move {
81            if let Ok(r) = m.get_client_rect().await {
82                let now = Rect::new(r.origin.x, r.origin.y, r.size.width, r.size.height);
83                if let Some(old) = *prev.peek() {
84                    let dx = old.x - now.x;
85                    let dy = old.y - now.y;
86                    if dx != 0.0 || dy != 0.0 {
87                        phase.set(FlipPhase::Invert(Point::new(dx, dy)));
88                    }
89                }
90                prev.set(Some(now));
91            }
92        });
93    }));
94
95    // Play: once the inverted frame has committed, release the transform;
96    // the armed CSS transition glides the item home. (Effects run after the
97    // render commits, giving the browser a painted "old position" frame.)
98    use_effect(move || {
99        if matches!(phase(), FlipPhase::Invert(_)) {
100            phase.set(FlipPhase::Rest);
101        }
102    });
103
104    let style = match phase() {
105        FlipPhase::Invert(d) => {
106            format!(
107                "transform: translate({}px, {}px); transition: none;",
108                d.x, d.y
109            )
110        }
111        FlipPhase::Rest => {
112            format!("transform: none; transition: transform {duration}ms {easing};")
113        }
114    };
115
116    rsx! {
117        div {
118            style: "{style}",
119            onmounted: move |evt: Event<MountedData>| {
120                let mut mounted = mounted;
121                mounted.set(Some(evt.data()));
122            },
123            ..attributes,
124            {children}
125        }
126    }
127}