fc_ui/capabilities/motion/
content_transition.rs1use gpui::*;
2use std::time::Duration;
3
4use crate::capabilities::motion::animations::easings;
5
6#[derive(IntoElement)]
7pub struct ContentTransition {
8 id: ElementId,
9 old_content: Option<AnyElement>,
10 new_content: AnyElement,
11 duration: Duration,
12 transitioning: bool,
13 key: u64,
14}
15
16impl ContentTransition {
17 pub fn new(id: impl Into<ElementId>, content: impl IntoElement) -> Self {
18 Self {
19 id: id.into(),
20 old_content: None,
21 new_content: content.into_any_element(),
22 duration: Duration::from_millis(200),
23 transitioning: false,
24 key: 0,
25 }
26 }
27
28 pub fn key(mut self, key: u64) -> Self {
33 self.key = key;
34 self
35 }
36
37 pub fn duration(mut self, duration: Duration) -> Self {
38 self.duration = duration;
39 self
40 }
41
42 pub fn crossfade_from(mut self, old: impl IntoElement) -> Self {
43 self.old_content = Some(old.into_any_element());
44 self.transitioning = true;
45 self
46 }
47}
48
49impl RenderOnce for ContentTransition {
50 fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
51 let duration = self.duration;
52
53 if self.transitioning {
54 let mut container = div().relative().size_full();
55
56 if let Some(old) = self.old_content {
57 container = container.child(div().absolute().inset_0().child(old).with_animation(
58 ElementId::Name(format!("{}-old-{}", self.id, self.key).into()),
59 Animation::new(duration).with_easing(easings::ease_in_cubic),
60 |el, delta| el.opacity(1.0 - delta),
61 ));
62 }
63
64 container = container.child(div().size_full().child(self.new_content).with_animation(
65 ElementId::Name(format!("{}-new-{}", self.id, self.key).into()),
66 Animation::new(duration).with_easing(easings::ease_out_cubic),
67 |el, delta| el.opacity(delta),
68 ));
69
70 container
71 } else {
72 div().size_full().child(self.new_content)
73 }
74 }
75}
76
77pub struct ContentTransitionState {
78 current_key: u64,
79}
80
81impl ContentTransitionState {
82 pub fn new() -> Self {
83 Self { current_key: 0 }
84 }
85
86 pub fn set_key(&mut self, key: u64) -> bool {
87 if self.current_key != key {
88 self.current_key = key;
89 true
90 } else {
91 false
92 }
93 }
94
95 pub fn key(&self) -> u64 {
96 self.current_key
97 }
98}
99
100impl Default for ContentTransitionState {
101 fn default() -> Self {
102 Self::new()
103 }
104}