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