Skip to main content

fc_ui/capabilities/motion/
transitions.rs

1//! # Transition Components for Smooth UI Animations
2//!
3//! Declarative transition wrappers that provide smooth, polished animations
4//! for component mounting, unmounting, and state changes.
5//! ## Transition Types
6//!
7//! - **Fade Transitions**: Smooth opacity changes for gentle appearances/disappearances
8//! - **Slide Transitions**: Directional movement with easing for panel transitions
9//! - **Scale Transitions**: Size-based animations for emphasis and focus changes
10//! - **Combined Transitions**: Multi-property animations for complex state changes
11//!
12//! ## Design Principles
13//!
14//! - **Performance First**: Efficient animation scheduling with minimal overhead
15//! - **Declarative API**: Easy-to-use builder pattern for complex animations
16//! - **Consistent Timing**: Standardized durations following modern UI guidelines
17//! - **Natural Motion**: Physically-inspired easing curves for realistic movement
18//! - **Accessibility**: Respects user's motion preferences and provides alternatives
19//!
20//! ## Usage Examples
21//!
22//! ### Basic Transitions
23//! ```rust,ignore
24//! // Fade in component on mount
25//! Transition::fade_normal().child(my_component)
26//!
27//! // Slide panel from left edge
28//! Transition::slide_left().duration(Duration::from_millis(300)).child(panel)
29//! ```
30//!
31//! ### Conditional Rendering
32//! ```rust,ignore
33//! .when(show_modal, |parent| {
34//!     parent.child(
35//!         Transition::scale_up()
36//!             .duration(Duration::from_millis(200))
37//!             .child(modal_content)
38//!     )
39//! })
40//! ```
41//!
42//! ### Complex Transitions
43//! ```rust,ignore
44//! // Combine fade and slide with a custom easing
45//! Transition::new()
46//!     .fade()
47//!     .slide(Direction::Bottom)
48//!     .snappy()
49//!     .duration(Duration::from_millis(400))
50//!     .child(complex_component)
51//! ```
52//!
53
54use gpui::*;
55use std::panic::Location;
56use std::time::Duration;
57
58use crate::capabilities::motion::animations::{durations, easings};
59
60/// Direction for slide transitions
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub enum Direction {
63    /// Slide from top
64    Top,
65    /// Slide from bottom
66    Bottom,
67    /// Slide from left
68    Left,
69    /// Slide from right
70    Right,
71}
72
73/// Transition wrapper component
74///
75/// Wraps a child element and applies animation transitions when it appears.
76#[derive(IntoElement)]
77pub struct Transition {
78    slide_direction: Option<Direction>,
79    slide_distance: Pixels,
80    duration: Duration,
81    easing_fn: fn(f32) -> f32,
82    child: Option<AnyElement>,
83    animation_id: ElementId,
84    apply_fade: bool,
85}
86
87impl Transition {
88    /// Create a new transition
89    ///
90    /// The default animation id is derived from the call site so multiple
91    /// transitions do not share state; override it with [`Transition::id`].
92    #[track_caller]
93    pub fn new() -> Self {
94        let location = Location::caller();
95        let animation_id = ElementId::Name(
96            format!(
97                "transition:{}:{}:{}",
98                location.file(),
99                location.line(),
100                location.column()
101            )
102            .into(),
103        );
104
105        Self {
106            slide_direction: None,
107            slide_distance: px(20.0),
108            duration: durations::NORMAL,
109            easing_fn: easings::ease_out_cubic,
110            child: None,
111            animation_id,
112            apply_fade: false,
113        }
114    }
115
116    /// Set a unique ID for this transition (overrides the call-site-derived id)
117    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
118        self.animation_id = id.into();
119        self
120    }
121
122    /// Apply a fade in transition
123    pub fn fade(mut self) -> Self {
124        self.apply_fade = true;
125        self
126    }
127
128    /// Apply a slide in transition from the specified direction
129    pub fn slide(mut self, direction: Direction) -> Self {
130        self.slide_direction = Some(direction);
131        self
132    }
133
134    /// Set custom slide distance (default: 20px)
135    pub fn distance(mut self, distance: Pixels) -> Self {
136        self.slide_distance = distance;
137        self
138    }
139
140    /// Set the transition duration
141    pub fn duration(mut self, duration: Duration) -> Self {
142        self.duration = duration;
143        self
144    }
145
146    /// Use smooth easing (cubic)
147    pub fn smooth(mut self) -> Self {
148        self.easing_fn = easings::ease_out_cubic;
149        self
150    }
151
152    /// Use spring easing (with bounce)
153    pub fn spring(mut self) -> Self {
154        self.easing_fn = easings::smooth_spring;
155        self
156    }
157
158    /// Use snappy easing (quick with slight overshoot)
159    pub fn snappy(mut self) -> Self {
160        self.easing_fn = easings::ease_out_back;
161        self
162    }
163
164    /// Use linear easing
165    pub fn linear(mut self) -> Self {
166        self.easing_fn = easings::linear;
167        self
168    }
169
170    /// Set the child element to transition
171    pub fn child(mut self, child: impl IntoElement) -> Self {
172        self.child = Some(child.into_any_element());
173        self
174    }
175}
176
177impl Default for Transition {
178    fn default() -> Self {
179        Self::new()
180    }
181}
182
183impl RenderOnce for Transition {
184    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
185        let child = self.child.unwrap_or_else(|| div().into_any_element());
186        let easing_fn = self.easing_fn;
187        let animation_id = self.animation_id.clone();
188        let slide_direction = self.slide_direction;
189        let slide_distance = self.slide_distance;
190        let duration = self.duration;
191        let apply_fade = self.apply_fade;
192
193        if let Some(direction) = slide_direction {
194            div()
195                .id(animation_id.clone())
196                .relative()
197                .child(child)
198                .with_animation(
199                    animation_id,
200                    Animation::new(duration).with_easing(easing_fn),
201                    move |el, delta| {
202                        let offset = slide_distance * (1.0 - delta);
203                        let positioned = match direction {
204                            Direction::Top => el.top(-offset),
205                            Direction::Bottom => el.top(offset),
206                            Direction::Left => el.left(-offset),
207                            Direction::Right => el.left(offset),
208                        };
209                        if apply_fade {
210                            positioned.opacity(delta)
211                        } else {
212                            positioned
213                        }
214                    },
215                )
216        } else {
217            div()
218                .id(animation_id.clone())
219                .relative()
220                .child(child)
221                .with_animation(
222                    animation_id,
223                    Animation::new(duration).with_easing(easing_fn),
224                    |el, delta| el.opacity(delta),
225                )
226        }
227    }
228}
229
230/// Preset transition builders for common use cases
231impl Transition {
232    /// Quick fade in (200ms)
233    #[track_caller]
234    pub fn fade_quick() -> Self {
235        Self::new().fade().duration(durations::FAST)
236    }
237
238    /// Normal fade in (300ms)
239    #[track_caller]
240    pub fn fade_normal() -> Self {
241        Self::new().fade().duration(durations::NORMAL)
242    }
243
244    /// Slow fade in (400ms)
245    #[track_caller]
246    pub fn fade_slow() -> Self {
247        Self::new().fade().duration(durations::SLOW)
248    }
249
250    /// Slide in from bottom with fade (smooth)
251    #[track_caller]
252    pub fn slide_up() -> Self {
253        Self::new()
254            .slide(Direction::Bottom)
255            .fade()
256            .duration(durations::NORMAL)
257    }
258
259    /// Slide in from top with fade
260    #[track_caller]
261    pub fn slide_down() -> Self {
262        Self::new()
263            .slide(Direction::Top)
264            .fade()
265            .duration(durations::NORMAL)
266    }
267
268    /// Slide in from left with fade
269    #[track_caller]
270    pub fn slide_left() -> Self {
271        Self::new()
272            .slide(Direction::Left)
273            .fade()
274            .duration(durations::NORMAL)
275    }
276
277    /// Slide in from right with fade
278    #[track_caller]
279    pub fn slide_right() -> Self {
280        Self::new()
281            .slide(Direction::Right)
282            .fade()
283            .duration(durations::NORMAL)
284    }
285
286    /// Smooth slide up with spring
287    #[track_caller]
288    pub fn slide_up_spring() -> Self {
289        Self::new()
290            .slide(Direction::Bottom)
291            .fade()
292            .spring()
293            .duration(durations::SLOW)
294    }
295
296    /// Fade in with snappy easing (named for a future scale transform: this
297    /// currently applies fade only, no scaling)
298    #[track_caller]
299    pub fn scale_smooth() -> Self {
300        Self::fade_normal().snappy()
301    }
302
303    /// Fade in with spring easing (named for a future scale transform: this
304    /// currently applies fade only, no scaling)
305    #[track_caller]
306    pub fn scale_bounce() -> Self {
307        Self::fade_normal().spring().duration(durations::SLOW)
308    }
309
310    /// Quick fade in with snappy easing (named for a future scale transform:
311    /// this currently applies fade only, no scaling)
312    #[track_caller]
313    pub fn scale_snappy() -> Self {
314        Self::fade_quick().snappy()
315    }
316}