1use 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#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Layer {
23 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#[derive(Debug, Clone)]
37pub struct TransitionFrame {
38 pub t: f32,
40 pub direction: Direction,
41 pub size: Vec2,
43 pub navigation: Navigation,
46}
47
48type Effect = Rc<dyn Fn(&TransitionFrame) -> (Layer, Layer)>;
49
50#[derive(Clone)]
65pub struct ViewTransition {
66 duration: f32,
67 effect: Effect,
68 reduced_motion: Option<bool>,
69}
70
71impl ViewTransition {
72 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 pub fn slide() -> Self {
93 Self::slide_by(30.0)
94 }
95
96 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 opacity: 1.0 - (frame.t / 0.3).min(1.0),
104 offset: Vec2::new(-shift * t, 0.0),
105 };
106 let new = Layer {
107 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 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 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 pub fn duration(mut self, seconds: f32) -> Self {
146 self.duration = seconds;
147 self
148 }
149
150 pub fn reduced_motion(mut self, reduced: bool) -> Self {
153 self.reduced_motion = Some(reduced);
154 self
155 }
156
157 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 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 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
240pub 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#[derive(Default)]
262pub(crate) struct TransitionState {
263 pub(crate) started: Cell<Option<f64>>,
264 pub(crate) claimed: Cell<bool>,
266 pub(crate) done: Cell<bool>,
267}
268
269pub(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
277pub(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}