Skip to main content

cranpose_ui/widgets/
animated_visibility.rs

1//! Enter and exit transitions, and `AnimatedVisibility`.
2//!
3//! Mirrors Jetpack Compose's `EnterTransition`/`ExitTransition` from
4//! `androidx.compose.animation`: fades, slides along either axis by a
5//! fraction of the content's own size or across the container's edge, and
6//! scales, combined with `+`.
7
8use cranpose_animation::AnimationType;
9use cranpose_ui_graphics::Size;
10
11use crate::{
12    composable,
13    modifier::GraphicsLayer,
14    widgets::animated_content::{ContentTransform, SeekableAnimatedContent},
15};
16
17/// Which way content slides across the edge of an
18/// [`AnimatedContent`](crate::AnimatedContent) — Compose's
19/// `AnimatedContentTransitionScope.SlideDirection`.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum SlideDirection {
22    /// Toward the left edge.
23    Left,
24    /// Toward the right edge.
25    Right,
26    /// Toward the top edge.
27    Up,
28    /// Toward the bottom edge.
29    Down,
30    /// Toward the start edge: the left one, or the right one in a
31    /// right-to-left layout.
32    Start,
33    /// Toward the end edge: the right one, or the left one in a
34    /// right-to-left layout.
35    End,
36}
37
38impl SlideDirection {
39    fn is_vertical(self) -> bool {
40        matches!(self, Self::Up | Self::Down)
41    }
42
43    /// Whether the direction points toward smaller coordinates.
44    fn is_backward(self, rtl: bool) -> bool {
45        match self {
46            Self::Left | Self::Up => true,
47            Self::Right | Self::Down => false,
48            Self::Start => !rtl,
49            Self::End => rtl,
50        }
51    }
52}
53
54/// How far content slides along one axis at full strength.
55#[derive(Clone, Copy, Debug, PartialEq)]
56enum Slide {
57    /// A fraction of the content's own extent.
58    Fraction(f32),
59    /// Across the container's edge: content that comes starts just past the
60    /// edge it comes from, and content that goes ends just past the edge it
61    /// heads to.
62    Container {
63        towards: SlideDirection,
64        entering: bool,
65    },
66}
67
68impl Slide {
69    /// The offset of content whose extent is `own` in a container of extent
70    /// `container`, where content rests at the start.
71    fn offset(self, own: f32, container: f32, rtl: bool) -> f32 {
72        match self {
73            Slide::Fraction(fraction) => fraction * own,
74            Slide::Container { towards, entering } => {
75                if entering == towards.is_backward(rtl) {
76                    container
77                } else {
78                    -own
79                }
80            }
81        }
82    }
83
84    fn uses_direction(self) -> bool {
85        matches!(
86            self,
87            Slide::Container {
88                towards: SlideDirection::Start | SlideDirection::End,
89                ..
90            }
91        )
92    }
93}
94
95/// What container slides measure from: the container's size, and whether
96/// its layout reads right to left.
97#[derive(Clone, Copy, Debug, Default, PartialEq)]
98pub(crate) struct ContainerFrame {
99    pub(crate) size: Size,
100    pub(crate) rtl: bool,
101}
102
103/// What a transition does to its content at full strength; progress `1.0`
104/// shows the content at rest.
105#[derive(Clone, Copy, Debug, Default, PartialEq)]
106pub(crate) struct TransitionEffects {
107    fade: bool,
108    slide_x: Option<Slide>,
109    slide_y: Option<Slide>,
110    scale: Option<f32>,
111}
112
113impl TransitionEffects {
114    fn merged(self, other: Self) -> Self {
115        Self {
116            fade: self.fade || other.fade,
117            slide_x: self.slide_x.or(other.slide_x),
118            slide_y: self.slide_y.or(other.slide_y),
119            scale: self.scale.or(other.scale),
120        }
121    }
122
123    /// Whether a slide toward the start or the end needs the layout
124    /// direction.
125    pub(crate) fn uses_direction(self) -> bool {
126        self.slide_x.is_some_and(Slide::uses_direction)
127    }
128
129    /// The layer that shows content of `size` in `container` at `progress`
130    /// of the way to rest.
131    pub(crate) fn layer(
132        self,
133        progress: f32,
134        size: Size,
135        container: ContainerFrame,
136    ) -> GraphicsLayer {
137        let away = 1.0 - progress;
138        let offset = |slide: Option<Slide>, own: f32, extent: f32| {
139            slide.map_or(0.0, |slide| slide.offset(own, extent, container.rtl) * away)
140        };
141        GraphicsLayer {
142            alpha: if self.fade {
143                progress.clamp(0.0, 1.0)
144            } else {
145                1.0
146            },
147            translation_x: offset(self.slide_x, size.width, container.size.width),
148            translation_y: offset(self.slide_y, size.height, container.size.height),
149            scale: self
150                .scale
151                .map_or(1.0, |scale| scale + (1.0 - scale) * progress),
152            ..GraphicsLayer::default()
153        }
154    }
155}
156
157/// Defines how content appears.
158///
159/// Mirrors Jetpack Compose's `EnterTransition`. Transitions are combined
160/// with `+`, like Compose's `fadeIn() + slideInVertically()`.
161#[derive(Clone, Copy, Debug, PartialEq)]
162pub struct EnterTransition {
163    effects: TransitionEffects,
164    animation: Option<AnimationType>,
165}
166
167impl EnterTransition {
168    /// An empty enter transition: content appears without any effect.
169    ///
170    /// Mirrors Jetpack Compose: `EnterTransition.None`.
171    pub fn none() -> Self {
172        Self {
173            effects: TransitionEffects::default(),
174            animation: None,
175        }
176    }
177
178    /// Use a custom animation spec for this transition. In Compose the spec
179    /// is a parameter of each transition factory (e.g.
180    /// `fadeIn(animationSpec = tween(300))`); here it is a builder method:
181    /// `fade_in().with_animation(tween(300, Easing::LinearEasing))`.
182    pub fn with_animation(mut self, animation: AnimationType) -> Self {
183        self.animation = Some(animation);
184        self
185    }
186
187    /// This transition for the content that comes in, and `exit` for the
188    /// content that goes, as an [`AnimatedContent`](crate::AnimatedContent)
189    /// change. Compose's `enter togetherWith exit`.
190    pub fn together_with(self, exit: ExitTransition) -> ContentTransform {
191        ContentTransform {
192            enter: self,
193            exit,
194            size_transform: None,
195        }
196    }
197
198    pub(crate) fn effects(&self) -> TransitionEffects {
199        self.effects
200    }
201
202    pub(crate) fn animation(&self) -> AnimationType {
203        self.animation.unwrap_or_default()
204    }
205}
206
207impl std::ops::Add for EnterTransition {
208    type Output = Self;
209
210    fn add(self, other: Self) -> Self {
211        Self {
212            effects: self.effects.merged(other.effects),
213            animation: self.animation.or(other.animation),
214        }
215    }
216}
217
218/// Defines how content disappears.
219///
220/// Mirrors Jetpack Compose's `ExitTransition`. Transitions are combined
221/// with `+`, like Compose's `fadeOut() + slideOutVertically()`.
222#[derive(Clone, Copy, Debug, PartialEq)]
223pub struct ExitTransition {
224    effects: TransitionEffects,
225    animation: Option<AnimationType>,
226}
227
228impl ExitTransition {
229    /// An empty exit transition: content disappears without any effect.
230    ///
231    /// Mirrors Jetpack Compose: `ExitTransition.None`.
232    pub fn none() -> Self {
233        Self {
234            effects: TransitionEffects::default(),
235            animation: None,
236        }
237    }
238
239    /// Use a custom animation spec for this transition (see
240    /// [`EnterTransition::with_animation`]).
241    pub fn with_animation(mut self, animation: AnimationType) -> Self {
242        self.animation = Some(animation);
243        self
244    }
245
246    pub(crate) fn effects(&self) -> TransitionEffects {
247        self.effects
248    }
249
250    pub(crate) fn animation(&self) -> AnimationType {
251        self.animation.unwrap_or_default()
252    }
253}
254
255impl std::ops::Add for ExitTransition {
256    type Output = Self;
257
258    fn add(self, other: Self) -> Self {
259        Self {
260            effects: self.effects.merged(other.effects),
261            animation: self.animation.or(other.animation),
262        }
263    }
264}
265
266/// Fades in the content of an [`AnimatedVisibility`], from transparent to
267/// fully opaque.
268///
269/// Mirrors Jetpack Compose: `fadeIn()`.
270pub fn fade_in() -> EnterTransition {
271    enter(TransitionEffects {
272        fade: true,
273        ..TransitionEffects::default()
274    })
275}
276
277/// Fades out the content of an [`AnimatedVisibility`], from fully opaque to
278/// transparent.
279///
280/// Mirrors Jetpack Compose: `fadeOut()`.
281pub fn fade_out() -> ExitTransition {
282    exit(TransitionEffects {
283        fade: true,
284        ..TransitionEffects::default()
285    })
286}
287
288/// Slides in the content vertically from `initial_offset_fraction` of its
289/// own height (negative values start above the resting position, mirroring
290/// Compose's default of `-fullHeight / 2`).
291///
292/// Mirrors Jetpack Compose: `slideInVertically { fullHeight -> ... }`, with
293/// the offset expressed as a fraction of the content height instead of a
294/// lambda over the measured height.
295pub fn slide_in_vertically(initial_offset_fraction: f32) -> EnterTransition {
296    enter(TransitionEffects {
297        slide_y: Some(Slide::Fraction(initial_offset_fraction)),
298        ..TransitionEffects::default()
299    })
300}
301
302/// Slides out the content vertically towards `target_offset_fraction` of
303/// its own height.
304///
305/// Mirrors Jetpack Compose: `slideOutVertically { fullHeight -> ... }`, with
306/// the offset expressed as a fraction of the content height instead of a
307/// lambda over the measured height.
308pub fn slide_out_vertically(target_offset_fraction: f32) -> ExitTransition {
309    exit(TransitionEffects {
310        slide_y: Some(Slide::Fraction(target_offset_fraction)),
311        ..TransitionEffects::default()
312    })
313}
314
315/// Slides in the content horizontally from `initial_offset_fraction` of its
316/// own width: `1.0` starts one width to the right, `-1.0` one to the left.
317///
318/// Mirrors Jetpack Compose: `slideInHorizontally { fullWidth -> ... }`.
319pub fn slide_in_horizontally(initial_offset_fraction: f32) -> EnterTransition {
320    enter(TransitionEffects {
321        slide_x: Some(Slide::Fraction(initial_offset_fraction)),
322        ..TransitionEffects::default()
323    })
324}
325
326/// Slides out the content horizontally towards `target_offset_fraction` of
327/// its own width.
328///
329/// Mirrors Jetpack Compose: `slideOutHorizontally { fullWidth -> ... }`.
330pub fn slide_out_horizontally(target_offset_fraction: f32) -> ExitTransition {
331    exit(TransitionEffects {
332        slide_x: Some(Slide::Fraction(target_offset_fraction)),
333        ..TransitionEffects::default()
334    })
335}
336
337/// Slides in the content across the container's edge `towards` a
338/// direction: toward [`SlideDirection::Left`] it comes from just past the
339/// container's right edge. The container is the
340/// [`AnimatedContent`](crate::AnimatedContent) it changes in.
341///
342/// Mirrors Jetpack Compose: `slideIntoContainer(towards)`, with the full
343/// slide of Compose's default `initialOffset`.
344pub fn slide_into_container(towards: SlideDirection) -> EnterTransition {
345    enter(container_slide(towards, true))
346}
347
348/// Slides out the content across the container's edge `towards` a
349/// direction: toward [`SlideDirection::Left`] it ends just past the
350/// container's left edge.
351///
352/// Mirrors Jetpack Compose: `slideOutOfContainer(towards)`, with the full
353/// slide of Compose's default `targetOffset`.
354pub fn slide_out_of_container(towards: SlideDirection) -> ExitTransition {
355    exit(container_slide(towards, false))
356}
357
358fn container_slide(towards: SlideDirection, entering: bool) -> TransitionEffects {
359    let slide = Some(Slide::Container { towards, entering });
360    if towards.is_vertical() {
361        TransitionEffects {
362            slide_y: slide,
363            ..TransitionEffects::default()
364        }
365    } else {
366        TransitionEffects {
367            slide_x: slide,
368            ..TransitionEffects::default()
369        }
370    }
371}
372
373/// Scales in the content from `initial_scale` of its size, about its
374/// centre.
375///
376/// Mirrors Jetpack Compose: `scaleIn(initialScale)`.
377pub fn scale_in(initial_scale: f32) -> EnterTransition {
378    enter(TransitionEffects {
379        scale: Some(initial_scale),
380        ..TransitionEffects::default()
381    })
382}
383
384/// Scales out the content towards `target_scale` of its size, about its
385/// centre.
386///
387/// Mirrors Jetpack Compose: `scaleOut(targetScale)`.
388pub fn scale_out(target_scale: f32) -> ExitTransition {
389    exit(TransitionEffects {
390        scale: Some(target_scale),
391        ..TransitionEffects::default()
392    })
393}
394
395fn enter(effects: TransitionEffects) -> EnterTransition {
396    EnterTransition {
397        effects,
398        animation: None,
399    }
400}
401
402fn exit(effects: TransitionEffects) -> ExitTransition {
403    ExitTransition {
404        effects,
405        animation: None,
406    }
407}
408
409/// Animates the appearance and disappearance of its content when `visible`
410/// changes.
411///
412/// Mirrors Jetpack Compose:
413/// `AnimatedVisibility(visible, enter = ..., exit = ...) { ... }`.
414///
415/// Compose semantics: content that is visible on first composition appears
416/// without an animation; when `visible` turns `false` the content stays
417/// composed for the whole exit transition and leaves the composition once it
418/// completes, keeping its size until then; toggling `visible`
419/// mid-transition retargets the running animation from its current value.
420/// The animation moves the content's layer only: nothing recomposes while it
421/// runs.
422///
423/// Divergence from Compose: enter and exit each drive a single shared
424/// progress (instead of one `Transition` animation per effect), so all
425/// effects of a combined transition share one animation spec.
426#[composable]
427pub fn AnimatedVisibility<F>(
428    visible: bool,
429    enter: EnterTransition,
430    exit: ExitTransition,
431    mut content: F,
432) where
433    F: FnMut() + 'static,
434{
435    SeekableAnimatedContent(
436        visible,
437        None,
438        move |_, &shown| {
439            if shown {
440                enter.together_with(ExitTransition::none().with_animation(enter.animation()))
441            } else {
442                EnterTransition::none()
443                    .with_animation(exit.animation())
444                    .together_with(exit)
445            }
446        },
447        move |shown| {
448            if shown {
449                content();
450            }
451        },
452    );
453}