1use crate::{Interaction, LayoutNode, Point, Rect};
2use std::{
3 collections::BTreeMap,
4 ops::Range,
5 rc::Rc,
6 time::{Duration, Instant},
7};
8use xrack_runtime::{LayoutDirection, Node, Orientation, PageIdentity, group_index};
9
10const MAX_INTERRUPTED_LAYERS: usize = 32;
11
12struct PageLayer {
13 page: Rc<(Node, LayoutNode)>,
14 offset: f32,
15 visible: Range<f32>,
16 first_frame_direct: bool,
17}
18
19fn visible_slice(offset: f32, slice: Range<f32>) -> Option<Range<f32>> {
20 let start = (slice.start + offset).max(0.0);
21 let end = (slice.end + offset).min(1.0);
22 (start < end).then_some(start..end)
23}
24
25impl PageLayer {
26 fn capture(
27 node: &Node,
28 layout: &LayoutNode,
29 offset: f32,
30 first_frame_direct: bool,
31 ) -> Option<Self> {
32 Some(Self {
33 visible: visible_slice(offset, 0.0..1.0)?,
34 page: Rc::new((node.clone(), layout.clone())),
35 offset,
36 first_frame_direct,
37 })
38 }
39
40 fn moved(&self, delta: f32) -> Option<(f32, Range<f32>)> {
41 Some((
42 self.offset + delta,
43 visible_slice(delta, self.visible.clone())?,
44 ))
45 }
46}
47
48pub struct StackSlide {
50 start: Instant,
51 duration: Duration,
52 direction: f32,
53 orientation: Orientation,
54 progress: f32,
55 initial_progress: f32,
56 previous: Vec<PageLayer>,
57}
58
59impl StackSlide {
60 pub fn incoming_offset(&self) -> f32 {
61 self.direction * (1.0 - self.progress)
62 }
63
64 #[doc(hidden)]
65 pub fn displacement(&self, bounds: Rect, offset: f32) -> Point {
66 match self.orientation {
67 Orientation::Horizontal => Point {
68 x: bounds.width * offset,
69 y: 0.0,
70 },
71 Orientation::Vertical => Point {
72 x: 0.0,
73 y: bounds.height * offset,
74 },
75 }
76 }
77
78 #[doc(hidden)]
79 pub fn slice(&self, bounds: Rect, range: Range<f32>) -> Rect {
80 let start = self.displacement(bounds, range.start);
81 let end = self.displacement(bounds, range.end);
82 match self.orientation {
83 Orientation::Horizontal => {
84 Rect::new(bounds.x + start.x, bounds.y, end.x - start.x, bounds.height)
85 }
86 Orientation::Vertical => {
87 Rect::new(bounds.x, bounds.y + start.y, bounds.width, end.y - start.y)
88 }
89 }
90 }
91
92 pub fn outgoing(&self) -> impl Iterator<Item = (&Node, &LayoutNode, f32, Range<f32>)> {
93 self.outgoing_layers().map(|(page, offset, clip, _)| {
94 let (node, layout) = &**page;
95 (node, layout, offset, clip)
96 })
97 }
98
99 #[doc(hidden)]
101 pub fn outgoing_layers(
102 &self,
103 ) -> impl Iterator<Item = (&Rc<(Node, LayoutNode)>, f32, Range<f32>, bool)> {
104 self.layers().map(|(layer, offset, clip)| {
105 let cacheable = !(layer.first_frame_direct && self.progress == 0.0);
106 (&layer.page, offset, clip, cacheable)
107 })
108 }
109
110 fn layers(&self) -> impl Iterator<Item = (&PageLayer, f32, Range<f32>)> {
111 let delta = -self.direction * self.progress;
112 self.previous.iter().filter_map(move |layer| {
113 let (offset, clip) = layer.moved(delta)?;
114 Some((layer, offset, clip))
115 })
116 }
117}
118
119#[derive(Default)]
121pub struct StackTransitions {
122 slides: BTreeMap<Vec<usize>, StackSlide>,
123}
124
125impl StackTransitions {
126 pub fn active_paths(&self) -> impl Iterator<Item = &[usize]> {
127 self.slides.keys().map(Vec::as_slice)
128 }
129
130 pub fn is_active(&self) -> bool {
131 !self.slides.is_empty()
132 }
133
134 pub fn at(&self, path: &[usize]) -> Option<&StackSlide> {
135 self.slides.get(path)
136 }
137
138 pub fn advance(&mut self, now: Instant) {
140 self.slides.retain(|_, slide| {
141 let elapsed = now.saturating_duration_since(slide.start);
142 let remaining = 1.0 - elapsed.as_secs_f32() / slide.duration.as_secs_f32();
143 slide.progress = 1.0 - (1.0 - slide.initial_progress) * remaining.max(0.0).powi(3);
144 elapsed < slide.duration
145 });
146 }
147
148 pub fn update(
149 &mut self,
150 previous: (&Node, &LayoutNode),
151 next: (&Node, &LayoutNode),
152 now: Instant,
153 ) {
154 self.update_with_input(previous, next, now, None);
155 }
156
157 #[doc(hidden)]
158 pub fn update_with_input(
159 &mut self,
160 previous: (&Node, &LayoutNode),
161 next: (&Node, &LayoutNode),
162 now: Instant,
163 input: Option<&Interaction>,
164 ) {
165 let mut prior = std::mem::take(&mut self.slides);
166 self.collect(previous, next, (now, input), &mut Vec::new(), &mut prior);
167 }
168
169 fn collect(
170 &mut self,
171 (old, old_layout): (&Node, &LayoutNode),
172 (new, new_layout): (&Node, &LayoutNode),
173 (now, input): (Instant, Option<&Interaction>),
174 path: &mut Vec<usize>,
175 prior: &mut BTreeMap<Vec<usize>, StackSlide>,
176 ) {
177 if !old_layout.visible
178 || !new_layout.visible
179 || (old.kind, old.element_id(), old.row_key)
180 != (new.kind, new.element_id(), new.row_key)
181 {
182 return;
183 }
184 if let Some(change) = PageChange::between(old, new, new_layout) {
185 let existing = prior.remove(path);
186 let duration = new.int("transition-duration").unwrap_or(0).max(0) as u64;
187 let bounds = new_layout.bounds;
188 let viewport = new_layout.clip.intersect(bounds);
189 let can_slide = duration > 0
190 && old_layout.bounds == bounds
191 && old_layout.clip == new_layout.clip
192 && (new.kind != "SwipeView"
193 || (old.orientation(), old_layout.layout_direction)
194 == (new.orientation(), new_layout.layout_direction)
195 && old.swipe_preview.as_ref().map(|preview| &preview.handle)
196 == new.swipe_preview.as_ref().map(|preview| &preview.handle))
197 && viewport.width > 0.0
198 && viewport.height > 0.0;
199 if change.changed {
200 if can_slide
201 && let Some(direction) = change.direction
202 && let Some(index) = change.from
203 && let Some(previous) = old.child_at(index).zip(old_layout.child_at(index))
204 {
205 let offset =
206 input.map_or(0.0, |input| input.swipe_commit_fraction(path, old, new));
207 let progress = (offset * direction).max(0.0);
208 let duration = Duration::from_millis(duration).mul_f32(1.0 - progress);
209 if !duration.is_zero() {
210 self.slides.insert(
211 path.clone(),
212 StackSlide {
213 start: now,
214 duration,
215 direction,
216 orientation: change.orientation,
217 progress,
218 initial_progress: progress,
219 previous: outgoing_pages(previous, existing.as_ref()),
220 },
221 );
222 }
223 }
224 return;
225 }
226 if can_slide && let Some(slide) = existing {
227 self.slides.insert(path.clone(), slide);
228 }
229 }
230 for (index, child, layout) in new_layout.children_in_scene_order(new) {
231 let Some(before) = old.child_at(index).zip(old_layout.child_at(index)) else {
232 continue;
233 };
234 path.push(index);
235 self.collect(before, (child, layout), (now, input), path, prior);
236 path.pop();
237 }
238 }
239}
240
241struct PageChange {
242 from: Option<usize>,
243 changed: bool,
244 direction: Option<f32>,
245 orientation: Orientation,
246}
247
248impl PageChange {
249 fn between(old: &Node, new: &Node, layout: &LayoutNode) -> Option<Self> {
250 match new.kind {
251 "StackView" => {
252 let (before, after) = old.stack.as_ref().zip(new.stack.as_ref())?;
253 let backward =
254 after.depth() < before.depth() && before.routes().starts_with(after.routes());
255 Some(Self {
256 from: old.stack_page_index(),
257 changed: before.current() != after.current(),
258 direction: Some(if backward { -1.0 } else { 1.0 }),
259 orientation: Orientation::Horizontal,
260 })
261 }
262 "SwipeView" => {
263 let from = group_index(old);
264 let to = group_index(new);
265 let identity = |node: &Node, slot: Option<usize>| {
266 let slot = slot?;
267 Some(PageIdentity::of(node.child_at(slot)?, slot))
268 };
269 let orientation = new.orientation();
270 let mirrored = orientation == Orientation::Horizontal
271 && layout.layout_direction == LayoutDirection::RightToLeft;
272 Some(Self {
273 from,
274 changed: identity(old, from) != identity(new, to),
275 direction: from.zip(to).and_then(|(from, to)| {
276 (from != to).then_some(if (from < to) != mirrored { 1.0 } else { -1.0 })
277 }),
278 orientation,
279 })
280 }
281 _ => None,
282 }
283 }
284}
285
286fn outgoing_pages(
287 (node, layout): (&Node, &LayoutNode),
288 previous: Option<&StackSlide>,
289) -> Vec<PageLayer> {
290 if let Some(previous) = previous {
291 let mut layers: Vec<_> = previous
292 .layers()
293 .map(|(layer, offset, visible)| PageLayer {
294 page: layer.page.clone(),
295 offset,
296 visible,
297 first_frame_direct: layer.first_frame_direct && previous.progress == 0.0,
298 })
299 .collect();
300 layers.extend(PageLayer::capture(
303 node,
304 layout,
305 previous.incoming_offset(),
306 true,
307 ));
308 if layers.len() <= MAX_INTERRUPTED_LAYERS {
309 return layers;
310 }
311 }
312 PageLayer::capture(node, layout, 0.0, false)
313 .into_iter()
314 .collect()
315}