dioxus-motion 0.3.3

Animations library for Dioxus.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# Dioxus Motion 🚀

[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/wheregmis/dioxus-motion/blob/main/LICENSE)
[![Crates.io](https://img.shields.io/crates/v/dioxus-motion.svg)](https://crates.io/crates/dioxus-motion)
[![Docs](https://docs.rs/dioxus-motion/badge.svg)](https://docs.rs/dioxus-motion/0.1.4/dioxus_motion/)

A lightweight, cross-platform animation library for Dioxus, designed to bring smooth, flexible animations to your Rust web, desktop, and mobile applications.

## ⚠️ Important Note

This repository follows Dioxus's main branch for the latest features and improvements. For production use, we recommend using the stable version from [crates.io](https://crates.io/crates/dioxus-motion) instead of directly depending on the repository.

```toml
# Recommended: Stable version from crates.io
dioxus-motion = "0.3.1"

# Development version: Follows Dioxus main branch
dioxus-motion = { git = "https://github.com/wheregmis/dioxus-motion.git", branch = "main" }
```

## 🎯 Live Examples

<img src="example.gif" width="100%" height="400" />

Visit our [Example Website](https://wheregmis.github.io/dioxus-motion/) to see these animations in action:

## 🚀 Page Transitions

```rust
use dioxus_motion::prelude::*;

#[derive(Routable, Clone, Debug, PartialEq, MotionTransitions )]
#[rustfmt::skip]
enum Route {
    #[layout(NavBar)]
        #[route("/")]
        #[transition(Fade)]
        Home {},
        #[route("/slide-left")]
        #[transition(ZoomIn)]
        SlideLeft {},
        #[route("/slide-right")]
        SlideRight {},
        #[route("/slide-up")]
        SlideUp {},
        #[route("/slide-down")]
        SlideDown {},
        #[route("/fade")]
        Fade {},
    #[end_layout]
    #[route("/:..route")]
    PageNotFound { route: Vec<String> },
}
```

And replace all your `Outlet::<Route> {}` with `AnimatedOutlet::<Route> {}` and place the layout containing OutletRouter on top with something like this

```rust
#[component]
fn NavBar() -> Element {
    rsx! {
        nav { id: "navbar take it",
            Link { to: Route::Home {}, "Home" }
            Link { to: Route::SlideLeft {}, "Blog" }
        }
        AnimatedOutlet::<Route> {}
    }
}
```

Each route can have its own transition effect:

- `Fade`: Smooth opacity transition
- `ZoomIn`: Scale and fade combination
- `SlideLeft`: Horizontal slide animation
- [And more!]https://github.com/wheregmis/dioxus-motion/blob/main/src/transitions/page_transitions.rs
- Also, add transitions feature to support page transitions. [Example]https://github.com/wheregmis/animated_router/blob/main/src/main.rs which was translated from router [example]https://github.com/DioxusLabs/dioxus/blob/main/examples/router.rs of Dioxus. More detailed guide will be updated soon.

### Quick Value Animation Example

```rust
use dioxus_motion::prelude::*;

#[component]
fn PulseEffect() -> Element {
    let scale = use_motion(1.0f32);

    use_effect(move || {
        scale.animate_to(
            1.2,
            AnimationConfig::new(AnimationMode::Spring(Spring {
                stiffness: 100.0,
                damping: 5.0,
                mass: 0.5,
                velocity: 1.0
            }))
            .with_loop(LoopMode::Infinite)
        );
    });

    rsx! {
        div {
            class: "w-20 h-20 bg-blue-500 rounded-full",
            style: "transform: scale({scale.get_value()})"
        }
    }
}
```

### Animation Sequences Example

Chain multiple animations together with different configurations:

```rust
let scale = use_motion(1.0f32);

// Create a bouncy sequence
let sequence = AnimationSequence::new()
    .then(
        1.2, // Scale up
        AnimationConfig::new(AnimationMode::Spring(Spring {
            stiffness: 400.0,
            damping: 10.0,
            mass: 1.0,
            velocity: 5.0,
        }))
    )
    .then(
        0.8, // Scale down
        AnimationConfig::new(AnimationMode::Spring(Spring {
            stiffness: 300.0,
            damping: 15.0,
            mass: 1.0,
            velocity: -2.0,
        }))
    )
    .then(
        1.0, // Return to original
        AnimationConfig::new(AnimationMode::Spring(Spring::default()))
    );

// Start the sequence
scale.animate_sequence(sequence);
// Each step in the sequence can have its own timing, easing, and spring physics configuration. Sequences can also be looped or chained with other animations.
```

## ✨ Features

- **🔧 Simplified Animatable Trait**: Uses standard Rust operators (`+`, `-`, `*`) instead of custom methods
- **🌍 Cross-Platform Support**: Works on web, desktop, and mobile
- **⚙️ Flexible Animation Configuration**: Spring physics and tween animations
- **📊 Custom Easing Functions**: Built-in and custom easing support
- **🧩 Modular Feature Setup**: Choose only what you need
- **💡 Simple, Intuitive API**: Easy to learn and use
- **🎬 Page Transitions**: Smooth route transitions with the `transitions` feature

## 🛠 Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
dioxus-motion = { version = "0.3.0", optional = true, default-features = false }

[features]
default = ["web"]
web = ["dioxus/web", "dioxus-motion/web"]
desktop = ["dioxus/desktop", "dioxus-motion/desktop"]
mobile = ["dioxus/mobile", "dioxus-motion/desktop"]
```

If you want to use page transiton dependency will look like,

```toml
[dependencies]
dioxus-motion = { version = "0.3.0", optional = true, default-features = false }

[features]
default = ["web"]
web = ["dioxus/web", "dioxus-motion/web", "dioxus-motion/transitions"]
desktop = [
    "dioxus/desktop",
    "dioxus-motion/desktop",
    "dioxus-motion/transitions",
]
mobile = ["dioxus/mobile", "dioxus-motion/desktop", "dioxus-motion/transitions"]
```

## 🌐 Platform Support

Choose the right feature for your platform:

- `web`: For web applications using WASM
- `desktop`: For desktop and mobile applications
- `default`: Web support (if no feature specified)

## 🚀 Quick Start

## 🎨 Creating Custom Animatable Types

The simplified `Animatable` trait makes it easy to create custom animatable types:

```rust
use dioxus_motion::prelude::*;

#[derive(Debug, Copy, Clone, PartialEq, Default)]
struct Point3D {
    x: f32,
    y: f32,
    z: f32,
}
// Point3D automatically implements Send + 'static since all fields are Send + 'static

// Implement standard Rust operator traits
impl std::ops::Add for Point3D {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
            z: self.z + other.z,
        }
    }
}

impl std::ops::Sub for Point3D {
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        Self {
            x: self.x - other.x,
            y: self.y - other.y,
            z: self.z - other.z,
        }
    }
}

impl std::ops::Mul<f32> for Point3D {
    type Output = Self;
    fn mul(self, factor: f32) -> Self {
        Self {
            x: self.x * factor,
            y: self.y * factor,
            z: self.z * factor,
        }
    }
}

// Implement Animatable with just two methods!
impl Animatable for Point3D {
    fn interpolate(&self, target: &Self, t: f32) -> Self {
        *self + (*target - *self) * t
    }
    
    fn magnitude(&self) -> f32 {
        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
    }
}

// Now you can animate 3D points!
let mut position = use_motion(Point3D::default());
position.animate_to(
    Point3D { x: 10.0, y: 5.0, z: -2.0 },
    AnimationConfig::new(AnimationMode::Spring(Spring::default()))
);
```

**Previous vs. New Trait Complexity:**
- **Before**: 7 required methods (`zero`, `epsilon`, `magnitude`, `scale`, `add`, `sub`, `interpolate`)
- **After**: 2 required methods (`interpolate`, `magnitude`) + standard Rust operators
- **Result**: ~70% less boilerplate, more idiomatic Rust code!

## 🔄 Migration Guide (v0.3.0)

### Breaking Changes

- **`use_motion<T>` now requires `T: Send + 'static`**: The `use_motion<T>` function now requires types to implement `Send + 'static` in addition to `Animatable`. This enables better thread safety and resource management for animations.

### Migration Steps

- Most built-in types (`f32`, `Transform`, `Color`) already satisfy these bounds
- For custom types, ensure they implement `Send + 'static`:
  - Types with non-Send fields (like `Rc<T>`) will need to be refactored
  - Use `Arc<T>` instead of `Rc<T>` for shared ownership in animatable types
- Minor exports might change so just import `prelude::*` if anything breaks on import

```rust
use dioxus_motion::prelude::*;

// ✅ This works - f32 is Send + 'static
let motion = use_motion(0.0f32);

// ✅ This works - custom type with Send + 'static
#[derive(Copy, Clone, Default)]
struct Point { x: f32, y: f32 } // Send + 'static automatically derived

let point_motion = use_motion(Point::default());

// ❌ This won't compile - Rc<T> is not Send
// let bad_motion = use_motion(std::rc::Rc::new(0.0f32));

// ✅ Use Arc<T> instead for shared ownership
// Note: The type inside Arc must implement Animatable
#[derive(Copy, Clone, Default)]
struct SharedValue { value: f32 }

impl std::ops::Add for SharedValue {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        Self { value: self.value + other.value }
    }
}

impl std::ops::Sub for SharedValue {
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        Self { value: self.value - other.value }
    }
}

impl std::ops::Mul<f32> for SharedValue {
    type Output = Self;
    fn mul(self, factor: f32) -> Self {
        Self { value: self.value * factor }
    }
}

impl dioxus_motion::animations::core::Animatable for SharedValue {
    fn interpolate(&self, target: &Self, t: f32) -> Self {
        Self { value: self.value + (target.value - self.value) * t }
    }
    
    fn magnitude(&self) -> f32 {
        self.value.abs()
    }
}

let shared_motion = use_motion(SharedValue { value: 0.0 });

// ✅ Alternative: Use Arc to share the motion itself (not the value)
let shared_motion_handle = std::sync::Arc::new(use_motion(0.0f32));
// Now you can clone the Arc and share the motion across components
let motion_clone = shared_motion_handle.clone();
```

## 🔄 Migration Guide (v0.2.0)

### Breaking Changes

- Combined `use_value_animation` and `use_transform_animation` into `use_motion`
- New animation configuration API
- Updated spring physics parameters
- Changed transform property names

### New Animation API

```rust
use dioxus_motion::prelude::*;

// Before (v0.1.x)
let mut motion = use_value_animation(Motion::new(0.0).to(100.0));

// After (v0.2.x)
let mut value = use_motion(0.0f32);
value.animate_to(
    100.0,
    AnimationConfig::new(AnimationMode::Tween(Tween {
        duration: Duration::from_secs(2),
        easing: easer::functions::Linear::ease_in_out,
    }))
);

// Before (v0.1.x)
let mut transform = use_transform_animation(Transform::default());

// After (v0.2.x)
let mut transform = use_motion(Transform::default());
transform.animate_to(
    Transform::new(100.0, 0.0, 1.2, 45.0),
    AnimationConfig::new(AnimationMode::Spring(Spring {
        stiffness: 100.0,
        damping: 10.0,
        mass: 1.0,
        ..Default::default()
    }))
);
```

### If you were using transform.get_style(), that function is removed to make the library more generic so I recommend building something like

```rust
    let transform = use_motion(Transform::default());

    let transform_style = use_memo(move || {
        format!(
            "transform: translate({}px, {}px) scale({}) rotate({}deg);",
            transform.get_value().x,
            transform.get_value().y,
            transform.get_value().scale,
            transform.get_value().rotation * 180.0 / std::f32::consts::PI
        )
    });

    // and using the memo in the component
      rsx! {
        div {
            class: "...",
            style: "{transform_style.read()}",
            // ...rest of component...
        }
    }
```

## 🆕 New Features

### Loop Modes

```rust
.with_loop(LoopMode::Infinite)
.with_loop(LoopMode::Times(3))
```

### Animation Delays

```rust
.with_delay(Duration::from_secs(1))
```

### On Complete

```rust
.with_on_complete(|| println!("Animation complete!"))
```

## 🎓 Advanced Guide: Extending Animations

### Implementing the Animatable Trait

[Cube Component Example](https://github.com/wheregmis/dioxus-motion/blob/main/docs/src/old_showcase/components/cube_animation.rs)

The `Animatable` trait allows you to animate any custom type.

Definition of Animatable Trait

```rust
pub trait Animatable: 
    Copy + 'static + Default + 
    std::ops::Add<Output = Self> + 
    std::ops::Sub<Output = Self> + 
    std::ops::Mul<f32, Output = Self> 
{
    fn interpolate(&self, target: &Self, t: f32) -> Self;
    fn magnitude(&self) -> f32;
    fn epsilon() -> f32 { 0.01 } // Default implementation
}
```

Here's how to implement it:

### Custom Position Type

```rust
#[derive(Debug, Copy, Clone)]
struct Position {
    x: f32,
    y: f32,
}

#[derive(Debug, Copy, Clone, PartialEq, Default)]
struct Position {
    x: f32,
    y: f32,
}

// Implement standard Rust operator traits
impl std::ops::Add for Position {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        Self { x: self.x + other.x, y: self.y + other.y }
    }
}

impl std::ops::Sub for Position {
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        Self { x: self.x - other.x, y: self.y - other.y }
    }
}

impl std::ops::Mul<f32> for Position {
    type Output = Self;
    fn mul(self, factor: f32) -> Self {
        Self { x: self.x * factor, y: self.y * factor }
    }
}

// Implement Animatable with just two methods!
impl Animatable for Position {
    fn interpolate(&self, target: &Self, t: f32) -> Self {
        *self + (*target - *self) * t
    }
    
    fn magnitude(&self) -> f32 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
}
```

### Best Practices

- **Default State**: Implement `Default` trait for your type's neutral state
- **Operator Traits**: Implement `Add`, `Sub`, and `Mul<f32>` using standard Rust operators
- **Magnitude**: Return the square root of sum of squares for vector types
- **Interpolate**: Use linear interpolation for smooth transitions
- **Epsilon**: Uses default 0.01, or override with `with_epsilon()` for custom precision

### Common Patterns

#### Circular Values (e.g., angles)

```rust
fn interpolate(&self, target: &Self, t: f32) -> Self {
    let mut diff = target.angle - self.angle;
    // Ensure shortest path
    if diff > PI { diff -= 2.0 * PI; }
    if diff < -PI { diff += 2.0 * PI; }
    Self { angle: self.angle + diff * t }
}
```

#### Normalized Values (e.g., colors)

```rust
fn scale(&self, factor: f32) -> Self {
    Self {
        value: (self.value * factor).clamp(0.0, 1.0)
    }
}
```

## 🌈 Supported Easing Functions

Leverages the `easer` crate, supporting:

- Linear
- Quadratic
- Cubic
- Quartic
- And more!

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch
3. Commit changes
4. Push to the branch
5. Create a Pull Request

## 📄 License

MIT License

## 🐞 Reporting Issues

Please report issues on the GitHub repository with:

- Detailed description
- Minimal reproducible example
- Platform and feature configuration used

## 🌟 Motivation

Bringing elegant, performant motion animations to Rust's web and desktop ecosystems with minimal complexity.