Skip to main content

egui_kit/
transition.rs

1//! View transitions between pages.
2//!
3//! The router keeps the outgoing page alive for the duration of the transition and renders it next
4//! to the incoming one. A [`ViewTransition`] (used in a layout, in place of [`Outlet::show`])
5//! decides where and how opaque each of the two is drawn.
6//!
7//! The transition starts once all `load`s finished, right before the new page is shown. Layouts
8//! shared by both pages stay put: only the layout closest to the page that both routes share
9//! animates.
10
11use core::cell::Cell;
12use std::rc::Rc;
13
14use egui::{Id, Rect, Ui, UiBuilder, Vec2};
15
16use crate::navigation::{Direction, Navigation};
17use crate::page::Outlet;
18
19/// How one of the two pages is drawn in a frame of the transition
20/// (`::view-transition-old` / `::view-transition-new`).
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Layer {
23    /// In points, relative to the outlet.
24    pub offset: Vec2,
25    pub opacity: f32,
26}
27
28impl Layer {
29    pub const VISIBLE: Self = Self {
30        offset: Vec2::ZERO,
31        opacity: 1.0,
32    };
33}
34
35/// The input of a transition effect for one frame.
36#[derive(Debug, Clone)]
37pub struct TransitionFrame {
38    /// Linear progress, from `0.0` to `1.0`. Apply your own easing.
39    pub t: f32,
40    pub direction: Direction,
41    /// The size of the outlet.
42    pub size: Vec2,
43    /// The navigation being animated: where from and to, e.g. to slide by the pages' order in a
44    /// sidebar rather than by the history's direction.
45    pub navigation: Navigation,
46}
47
48type Effect = Rc<dyn Fn(&TransitionFrame) -> (Layer, Layer)>;
49
50/// Animates page changes inside a layout. Use it instead of [`Outlet::show`]:
51///
52/// ```no_run
53/// # use egui_kit::ViewTransition;
54/// # use egui_kit::page::Outlet;
55/// fn layout(ui: &mut egui::Ui, outlet: Outlet) {
56///     ui.heading("My app"); // shared chrome: stays put
57///     ViewTransition::slide().show(ui, outlet);
58/// }
59/// ```
60///
61/// When the user prefers reduced motion (the browser's `prefers-reduced-motion` on the web, or
62/// [`ViewTransition::reduced_motion`]), offsets are dropped and only the fading remains, like the
63/// blog post's `@media (prefers-reduced-motion)` suggestion.
64#[derive(Clone)]
65pub struct ViewTransition {
66    duration: f32,
67    effect: Effect,
68    reduced_motion: Option<bool>,
69}
70
71impl ViewTransition {
72    /// The browser's default: a crossfade.
73    pub fn fade() -> Self {
74        Self::custom(|frame| {
75            let t = ease_in_out(frame.t);
76            (
77                Layer {
78                    opacity: 1.0 - t,
79                    ..Layer::VISIBLE
80                },
81                Layer {
82                    opacity: t,
83                    ..Layer::VISIBLE
84                },
85            )
86        })
87        .duration(0.2)
88    }
89
90    /// The blog post's transition: the old page fades out quickly while sliding away, the new one
91    /// fades in a bit later while sliding in. Mirrored when going back.
92    pub fn slide() -> Self {
93        Self::slide_by(30.0)
94    }
95
96    /// [`ViewTransition::slide`] with a custom distance in points.
97    pub fn slide_by(distance: f32) -> Self {
98        Self::custom(move |frame| {
99            let shift = distance * frame.direction.sign();
100            let t = ease_out(frame.t);
101            let old = Layer {
102                // 90ms of 300ms
103                opacity: 1.0 - (frame.t / 0.3).min(1.0),
104                offset: Vec2::new(-shift * t, 0.0),
105            };
106            let new = Layer {
107                // 210ms after a 90ms delay
108                opacity: ((frame.t - 0.3) / 0.7).clamp(0.0, 1.0),
109                offset: Vec2::new(shift * (1.0 - t), 0.0),
110            };
111            (old, new)
112        })
113        .duration(0.3)
114    }
115
116    /// A full-width push, like navigation stacks on mobile.
117    pub fn push() -> Self {
118        Self::custom(|frame| {
119            let shift = frame.size.x * frame.direction.sign();
120            let t = ease_in_out(frame.t);
121            (
122                Layer {
123                    offset: Vec2::new(-shift * t, 0.0),
124                    opacity: if shift == 0.0 { 1.0 - t } else { 1.0 },
125                },
126                Layer {
127                    offset: Vec2::new(shift * (1.0 - t), 0.0),
128                    opacity: if shift == 0.0 { t } else { 1.0 },
129                },
130            )
131        })
132        .duration(0.35)
133    }
134
135    /// Your own effect: return how the old and the new page are drawn for a frame.
136    pub fn custom(effect: impl Fn(&TransitionFrame) -> (Layer, Layer) + 'static) -> Self {
137        Self {
138            duration: 0.3,
139            effect: Rc::new(effect),
140            reduced_motion: None,
141        }
142    }
143
144    /// In seconds.
145    pub fn duration(mut self, seconds: f32) -> Self {
146        self.duration = seconds;
147        self
148    }
149
150    /// Overrides the reduced-motion preference (by default: the browser's setting on the web,
151    /// off on native).
152    pub fn reduced_motion(mut self, reduced: bool) -> Self {
153        self.reduced_motion = Some(reduced);
154        self
155    }
156
157    /// Shows the outlet, animating from the previous page if this layout is where the current
158    /// navigation transitions.
159    pub fn show(&self, ui: &mut Ui, mut outlet: Outlet<'_>) {
160        outlet.uses_transitions.set(true);
161        let rect = ui.available_rect_before_wrap();
162        let outlet_id = ui.id().with("egui_kit_outlet");
163
164        let frame = outlet.transition.as_deref().and_then(|transition| {
165            let state = transition.state();
166            let now = ui.input(|i| i.time);
167            let started = state.started.get().unwrap_or_else(|| {
168                state.started.set(Some(now));
169                now
170            });
171            state.claimed.set(true);
172            let t = if self.duration > 0.0 {
173                ((now - started) as f32 / self.duration).clamp(0.0, 1.0)
174            } else {
175                1.0
176            };
177            if t >= 1.0 {
178                state.done.set(true);
179                return None;
180            }
181            Some(TransitionFrame {
182                t,
183                direction: transition.direction(),
184                size: rect.size(),
185                navigation: transition.navigation().clone(),
186            })
187        });
188
189        let Some(frame) = frame else {
190            // Same id as during transitions, so widget state survives the end of the animation.
191            let mut page = ui.new_child(UiBuilder::new().id(outlet_id).max_rect(rect));
192            outlet.show(&mut page);
193            ui.advance_cursor_after_rect(page.min_rect());
194            return;
195        };
196
197        ui.ctx().request_repaint();
198        let (mut old, mut new) = (self.effect)(&frame);
199        if self.reduced_motion.unwrap_or_else(prefers_reduced_motion) {
200            old.offset = Vec2::ZERO;
201            new.offset = Vec2::ZERO;
202        }
203        let clip = rect.intersect(ui.clip_rect());
204
205        // The outgoing page is drawn first, so the incoming one ends up on top.
206        let mut previous_ui = layer_ui(ui, outlet_id.with("previous"), rect, clip, old);
207        if let Some(transition) = outlet.transition.as_deref_mut() {
208            transition.render_previous(&mut previous_ui);
209        }
210
211        let mut page = layer_ui(ui, outlet_id, rect, clip, new);
212        outlet.show(&mut page);
213        ui.advance_cursor_after_rect(page.min_rect().translate(-new.offset));
214    }
215}
216
217fn layer_ui(ui: &mut Ui, id: Id, rect: Rect, clip: Rect, layer: Layer) -> Ui {
218    let mut child = ui.new_child(
219        UiBuilder::new()
220            .id(id)
221            .max_rect(rect.translate(layer.offset)),
222    );
223    child.set_clip_rect(clip);
224    child.multiply_opacity(layer.opacity.clamp(0.0, 1.0));
225    child
226}
227
228fn ease_out(t: f32) -> f32 {
229    1.0 - (1.0 - t).powi(3)
230}
231
232fn ease_in_out(t: f32) -> f32 {
233    if t < 0.5 {
234        4.0 * t * t * t
235    } else {
236        1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
237    }
238}
239
240/// Whether the user asked their system for reduced motion (`prefers-reduced-motion: reduce`).
241/// Always `false` on native, where there is no portable way to ask.
242pub fn prefers_reduced_motion() -> bool {
243    #[cfg(target_arch = "wasm32")]
244    {
245        web_sys::window()
246            .and_then(|window| {
247                window
248                    .match_media("(prefers-reduced-motion: reduce)")
249                    .ok()
250                    .flatten()
251            })
252            .is_some_and(|query| query.matches())
253    }
254    #[cfg(not(target_arch = "wasm32"))]
255    {
256        false
257    }
258}
259
260/// Bookkeeping of a running transition, shared with the outlet that runs it.
261#[derive(Default)]
262pub(crate) struct TransitionState {
263    pub(crate) started: Cell<Option<f64>>,
264    /// Whether a [`ViewTransition`] ran it this frame; unclaimed transitions end right away.
265    pub(crate) claimed: Cell<bool>,
266    pub(crate) done: Cell<bool>,
267}
268
269/// What the outlet of the transitioning layout gets on top of the new page.
270pub(crate) struct OutletTransition<'a> {
271    pub(crate) previous: &'a mut dyn FnMut(&mut Ui),
272    pub(crate) state: &'a TransitionState,
273    pub(crate) direction: Direction,
274    pub(crate) navigation: &'a Navigation,
275}
276
277/// [`OutletTransition`] behind a trait object, so an [`Outlet`]'s lifetime doesn't have to match it.
278pub(crate) trait TransitionHandle {
279    fn render_previous(&mut self, ui: &mut Ui);
280    fn state(&self) -> &TransitionState;
281    fn direction(&self) -> Direction;
282    fn navigation(&self) -> &Navigation;
283}
284
285impl TransitionHandle for OutletTransition<'_> {
286    fn render_previous(&mut self, ui: &mut Ui) {
287        (self.previous)(ui);
288    }
289
290    fn state(&self) -> &TransitionState {
291        self.state
292    }
293
294    fn direction(&self) -> Direction {
295        self.direction
296    }
297
298    fn navigation(&self) -> &Navigation {
299        self.navigation
300    }
301}