Skip to main content

fc_ui/capabilities/effects/
shared_element_transition.rs

1//! Shared element (hero) transition between views.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::time::Duration;
5
6use crate::capabilities::motion::animations::{durations, easings, lerp_pixels};
7
8#[derive(Clone, Copy, Debug)]
9struct ElementBounds {
10    x: Pixels,
11    y: Pixels,
12    width: Pixels,
13    height: Pixels,
14}
15
16impl Default for ElementBounds {
17    fn default() -> Self {
18        Self {
19            x: px(0.0),
20            y: px(0.0),
21            width: px(0.0),
22            height: px(0.0),
23        }
24    }
25}
26
27pub struct SharedElementState {
28    source_bounds: Option<ElementBounds>,
29    target_bounds: Option<ElementBounds>,
30    is_transitioning: bool,
31    progress: f32,
32    version: usize,
33    duration: Duration,
34}
35
36impl SharedElementState {
37    pub fn new(_cx: &mut Context<Self>) -> Self {
38        Self {
39            source_bounds: None,
40            target_bounds: None,
41            is_transitioning: false,
42            progress: 0.0,
43            version: 0,
44            duration: durations::SLOW,
45        }
46    }
47
48    pub fn set_duration(&mut self, duration: Duration) {
49        self.duration = duration;
50    }
51
52    pub fn set_source_bounds(&mut self, bounds: Bounds<Pixels>) {
53        self.source_bounds = Some(ElementBounds {
54            x: bounds.origin.x,
55            y: bounds.origin.y,
56            width: bounds.size.width,
57            height: bounds.size.height,
58        });
59    }
60
61    pub fn set_target_bounds(&mut self, bounds: Bounds<Pixels>) {
62        self.target_bounds = Some(ElementBounds {
63            x: bounds.origin.x,
64            y: bounds.origin.y,
65            width: bounds.size.width,
66            height: bounds.size.height,
67        });
68    }
69
70    pub fn transition_to(&mut self, cx: &mut Context<Self>) {
71        if self.source_bounds.is_none() || self.target_bounds.is_none() {
72            return;
73        }
74
75        self.is_transitioning = true;
76        self.progress = 0.0;
77        self.version += 1;
78        cx.notify();
79
80        let version = self.version;
81        let duration = self.duration;
82        cx.spawn(async move |this, cx| {
83            cx.background_executor().timer(duration).await;
84            _ = this.update(cx, |state, cx| {
85                if state.version != version {
86                    return;
87                }
88                state.is_transitioning = false;
89                state.progress = 1.0;
90                state.source_bounds = state.target_bounds;
91                cx.notify();
92            });
93        })
94        .detach();
95    }
96
97    pub fn is_transitioning(&self) -> bool {
98        self.is_transitioning
99    }
100
101    pub fn progress(&self) -> f32 {
102        self.progress
103    }
104
105    pub fn version(&self) -> usize {
106        self.version
107    }
108}
109
110#[derive(IntoElement)]
111pub struct SharedElementTransition {
112    id: ElementId,
113    state: Entity<SharedElementState>,
114    content: Option<AnyElement>,
115    style: StyleRefinement,
116}
117
118impl SharedElementTransition {
119    pub fn new(id: impl Into<ElementId>, state: Entity<SharedElementState>) -> Self {
120        Self {
121            id: id.into(),
122            state,
123            content: None,
124            style: StyleRefinement::default(),
125        }
126    }
127
128    pub fn content(mut self, element: impl IntoElement) -> Self {
129        self.content = Some(element.into_any_element());
130        self
131    }
132}
133
134impl Styled for SharedElementTransition {
135    fn style(&mut self) -> &mut StyleRefinement {
136        &mut self.style
137    }
138}
139
140impl RenderOnce for SharedElementTransition {
141    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
142        let user_style = self.style;
143        let state = self.state.read(cx);
144        let is_transitioning = state.is_transitioning;
145        let version = state.version;
146        let source = state.source_bounds.unwrap_or_default();
147        let target = state.target_bounds.unwrap_or_default();
148        let duration = state.duration;
149        let content = self.content;
150
151        if is_transitioning {
152            div()
153                .id(self.id.clone())
154                .absolute()
155                .left(source.x)
156                .top(source.y)
157                .w(source.width)
158                .h(source.height)
159                .children(content)
160                .map(|this| {
161                    let mut el = this;
162                    el.style().refine(&user_style);
163                    el
164                })
165                .with_animation(
166                    ElementId::Name(format!("set-{}-{}", self.id, version).into()),
167                    Animation::new(duration).with_easing(easings::ease_in_out_cubic),
168                    move |el, delta| {
169                        let curr_x = lerp_pixels(source.x, target.x, delta);
170                        let curr_y = lerp_pixels(source.y, target.y, delta);
171                        let curr_w = lerp_pixels(source.width, target.width, delta);
172                        let curr_h = lerp_pixels(source.height, target.height, delta);
173
174                        el.left(curr_x).top(curr_y).w(curr_w).h(curr_h)
175                    },
176                )
177                .into_any_element()
178        } else {
179            div()
180                .id(self.id)
181                .children(content)
182                .map(|this| {
183                    let mut el = this;
184                    el.style().refine(&user_style);
185                    el
186                })
187                .into_any_element()
188        }
189    }
190}