Skip to main content

fc_ui/capabilities/navigation/
view_router.rs

1//! ViewRouter - A view stack manager with animated page transitions for multi-screen desktop apps.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5use std::time::Duration;
6
7use crate::capabilities::motion::animations::easings;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum PageTransition {
11    SlideLeft,
12    SlideRight,
13    SlideUp,
14    SlideDown,
15    Fade,
16    None,
17}
18
19impl PageTransition {
20    fn reverse(&self) -> Self {
21        match self {
22            Self::SlideLeft => Self::SlideRight,
23            Self::SlideRight => Self::SlideLeft,
24            Self::SlideUp => Self::SlideDown,
25            Self::SlideDown => Self::SlideUp,
26            Self::Fade => Self::Fade,
27            Self::None => Self::None,
28        }
29    }
30}
31
32struct ViewEntry {
33    id: SharedString,
34    render: Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>,
35}
36
37pub struct ViewRouterState {
38    stack: Vec<ViewEntry>,
39    previous_render: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>>,
40    transition: PageTransition,
41    active_transition: Option<PageTransition>,
42    version: usize,
43    is_transitioning: bool,
44    duration: Duration,
45}
46
47impl Default for ViewRouterState {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl ViewRouterState {
54    pub fn new() -> Self {
55        Self {
56            stack: Vec::new(),
57            previous_render: None,
58            transition: PageTransition::SlideLeft,
59            active_transition: None,
60            version: 0,
61            is_transitioning: false,
62            duration: Duration::from_millis(300),
63        }
64    }
65
66    pub fn push(
67        &mut self,
68        id: impl Into<SharedString>,
69        render: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
70        cx: &mut Context<Self>,
71    ) {
72        self.previous_render = self.stack.last().map(|e| e.render.clone());
73
74        self.stack.push(ViewEntry {
75            id: id.into(),
76            render: Rc::new(render),
77        });
78
79        self.begin_transition(self.transition, cx);
80    }
81
82    pub fn pop(&mut self, cx: &mut Context<Self>) {
83        if self.stack.len() <= 1 {
84            return;
85        }
86
87        self.previous_render = self.stack.last().map(|e| e.render.clone());
88        self.stack.pop();
89        self.begin_transition(self.transition.reverse(), cx);
90    }
91
92    pub fn replace(
93        &mut self,
94        id: impl Into<SharedString>,
95        render: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
96        cx: &mut Context<Self>,
97    ) {
98        self.previous_render = self.stack.last().map(|e| e.render.clone());
99
100        if !self.stack.is_empty() {
101            self.stack.pop();
102        }
103
104        self.stack.push(ViewEntry {
105            id: id.into(),
106            render: Rc::new(render),
107        });
108
109        self.begin_transition(self.transition, cx);
110    }
111
112    fn begin_transition(&mut self, transition: PageTransition, cx: &mut Context<Self>) {
113        if matches!(transition, PageTransition::None) {
114            self.previous_render = None;
115            cx.notify();
116            return;
117        }
118
119        self.active_transition = Some(transition);
120        self.version += 1;
121        self.is_transitioning = true;
122        cx.notify();
123
124        let duration = self.duration;
125        let version = self.version;
126        cx.spawn(async move |this, cx| {
127            cx.background_executor().timer(duration).await;
128            _ = this.update(cx, |this, cx| {
129                if this.version != version {
130                    return;
131                }
132                this.is_transitioning = false;
133                this.previous_render = None;
134                this.active_transition = None;
135                cx.notify();
136            });
137        })
138        .detach();
139    }
140
141    pub fn current_id(&self) -> Option<SharedString> {
142        self.stack.last().map(|e| e.id.clone())
143    }
144
145    pub fn can_go_back(&self) -> bool {
146        self.stack.len() > 1
147    }
148
149    pub fn depth(&self) -> usize {
150        self.stack.len()
151    }
152
153    pub fn set_transition(&mut self, transition: PageTransition) {
154        self.transition = transition;
155    }
156
157    pub fn set_duration(&mut self, duration: Duration) {
158        self.duration = duration;
159    }
160}
161
162#[derive(IntoElement)]
163pub struct ViewRouter {
164    id: ElementId,
165    state: Entity<ViewRouterState>,
166    transition_override: Option<PageTransition>,
167    style: StyleRefinement,
168}
169
170impl ViewRouter {
171    pub fn new(id: impl Into<ElementId>, state: Entity<ViewRouterState>) -> Self {
172        Self {
173            id: id.into(),
174            state,
175            transition_override: None,
176            style: StyleRefinement::default(),
177        }
178    }
179
180    pub fn transition(mut self, transition: PageTransition) -> Self {
181        self.transition_override = Some(transition);
182        self
183    }
184}
185
186impl Styled for ViewRouter {
187    fn style(&mut self) -> &mut StyleRefinement {
188        &mut self.style
189    }
190}
191
192impl RenderOnce for ViewRouter {
193    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
194        let user_style = self.style;
195
196        let (version, duration, transition, current_render, previous_render) = {
197            let state = self.state.read(cx);
198            let trans = self
199                .transition_override
200                .or(state.active_transition)
201                .unwrap_or(PageTransition::Fade);
202            let prev = if state.is_transitioning {
203                state.previous_render.clone()
204            } else {
205                None
206            };
207            (
208                state.version,
209                state.duration,
210                trans,
211                state.stack.last().map(|e| e.render.clone()),
212                prev,
213            )
214        };
215
216        let current_content = current_render.map(|f| f(window, cx));
217        let previous_content = previous_render.map(|f| f(window, cx));
218
219        let id = self.id;
220
221        let mut container = div().size_full().overflow_hidden().relative();
222
223        if let Some(old) = previous_content {
224            let exit_id = ElementId::Name(format!("{}-exit-{}", id, version).into());
225            let enter_id = ElementId::Name(format!("{}-enter-{}", id, version).into());
226
227            container = container.child(render_exit(old, exit_id, transition, duration));
228
229            container = container.when_some(current_content, |this, new| {
230                this.child(render_enter(new, enter_id, transition, duration))
231            });
232        } else {
233            container = container.when_some(current_content, |this, content| {
234                this.child(div().size_full().child(content))
235            });
236        }
237
238        container.map(|this| {
239            let mut d = this;
240            d.style().refine(&user_style);
241            d
242        })
243    }
244}
245
246fn render_exit(
247    content: AnyElement,
248    anim_id: ElementId,
249    transition: PageTransition,
250    duration: Duration,
251) -> impl IntoElement {
252    div()
253        .absolute()
254        .inset_0()
255        .size_full()
256        .child(content)
257        .with_animation(anim_id, anim(duration), move |el, delta| {
258            apply_exit(el, delta, transition)
259        })
260}
261
262fn render_enter(
263    content: AnyElement,
264    anim_id: ElementId,
265    transition: PageTransition,
266    duration: Duration,
267) -> impl IntoElement {
268    div()
269        .size_full()
270        .child(content)
271        .with_animation(anim_id, anim(duration), move |el, delta| {
272            apply_enter(el, delta, transition)
273        })
274}
275
276fn anim(duration: Duration) -> Animation {
277    Animation::new(duration).with_easing(easings::ease_out_cubic)
278}
279
280fn apply_exit(el: Div, delta: f32, transition: PageTransition) -> Div {
281    let progress = delta;
282    match transition {
283        PageTransition::SlideLeft => el.left(px(-300.0 * progress)).opacity(1.0 - progress),
284        PageTransition::SlideRight => el.left(px(300.0 * progress)).opacity(1.0 - progress),
285        PageTransition::SlideUp => el.top(px(-300.0 * progress)).opacity(1.0 - progress),
286        PageTransition::SlideDown => el.top(px(300.0 * progress)).opacity(1.0 - progress),
287        PageTransition::Fade => el.opacity(1.0 - progress),
288        PageTransition::None => el,
289    }
290}
291
292fn apply_enter(el: Div, delta: f32, transition: PageTransition) -> Div {
293    let progress = delta;
294    match transition {
295        PageTransition::SlideLeft => el.left(px(300.0 * (1.0 - progress))).opacity(progress),
296        PageTransition::SlideRight => el.left(px(-300.0 * (1.0 - progress))).opacity(progress),
297        PageTransition::SlideUp => el.top(px(300.0 * (1.0 - progress))).opacity(progress),
298        PageTransition::SlideDown => el.top(px(-300.0 * (1.0 - progress))).opacity(progress),
299        PageTransition::Fade => el.opacity(progress),
300        PageTransition::None => el,
301    }
302}