1use nativeview_layout::{
4 ScrollAxis, ScrollBoundsLookup, ScrollContainerCtx, ScrollDeltaResult, ScrollInputKind,
5 ScrollOffsets, ScrollPhysicsEngine, ScrollTimestampMs, ScrollTouchPhase, push_unique_node,
6};
7use nativeview_store::{NodeId, NodeStore};
8use nativeview_tables::tables::{OverscrollBehavior, Scroll};
9
10use crate::axis::AxisPhase;
11use crate::behavior::ScrollBehavior;
12use crate::resolve::{
13 is_in_ancestor_chain, reconcile_axis, resolve_bounce, resolve_decay, resolve_smooth_wheel,
14 resolve_snap_target, resolve_spring,
15};
16
17use super::{
18 ActiveScrollEntry, GestureLatch, MAX_ACTIVE_SCROLL_ENTRIES, PoolEntryLen, PooledScrollPhysics,
19};
20
21impl<B: ScrollBehavior> ScrollPhysicsEngine for PooledScrollPhysics<B> {
22 fn on_gesture_start(
23 &mut self,
24 store: &NodeStore,
25 bounds: &dyn ScrollBoundsLookup,
26 start: NodeId,
27 now_ms: ScrollTimestampMs,
28 ) {
29 self.latch = GestureLatch {
30 target: start,
31 active_phase: true,
32 last_event_ms: now_ms,
33 };
34 let reduced = self.reduced_motion;
35 let min_fling = self.behavior.min_fling_velocity();
36 for e in &mut self.entries[..self.entry_len.0] {
37 if is_in_ancestor_chain(store, bounds, start, e.node) {
38 for ax in [&mut e.x, &mut e.y] {
39 if ax.phase.is_animating() {
40 ax.phase = AxisPhase::Dragging;
41 ax.vel = 0.0;
42 ax.start_pos = ax.overscroll;
43 ax.start_vel = 0.0;
44 ax.elapsed_s = 0.0;
45 ax.last_input_ms = now_ms;
46 }
47 }
48 } else {
49 let spring = resolve_spring(&self.behavior, store, e.node);
50 if e.x.phase == AxisPhase::Dragging {
51 let _ = e.x.finish_drag(
52 true,
53 false,
54 reduced,
55 None,
56 min_fling,
57 spring,
58 |_| None,
59 0,
60 );
61 }
62 if e.y.phase == AxisPhase::Dragging {
63 let _ = e.y.finish_drag(
64 true,
65 false,
66 reduced,
67 None,
68 min_fling,
69 spring,
70 |_| None,
71 0,
72 );
73 }
74 }
75 }
76 }
77
78 #[inline]
79 fn latched_target(&self) -> Option<NodeId> {
80 self.latch.active_phase.then_some(self.latch.target)
81 }
82
83 #[inline]
84 fn on_gesture_move(&mut self, now_ms: ScrollTimestampMs) {
85 self.latch.last_event_ms = now_ms;
86 }
87
88 fn on_scroll_delta(
89 &mut self,
90 ctx: &ScrollContainerCtx<'_>,
91 dx: f32,
92 dy: f32,
93 kind: ScrollInputKind,
94 out: &mut ScrollDeltaResult,
95 ) {
96 let mut rem_x = dx;
97 let mut rem_y = dy;
98 let mut next_x = ctx.offset.0;
99 let mut next_y = ctx.offset.1;
100
101 self.apply_axis_delta(
102 ctx,
103 false,
104 kind,
105 &mut rem_x,
106 ctx.offset.1,
107 &mut next_x,
108 &mut out.consumed_x,
109 &mut out.visual_changed,
110 &mut out.clamped_changed,
111 &mut out.auto_overscroll_x,
112 );
113 self.apply_axis_delta(
114 ctx,
115 true,
116 kind,
117 &mut rem_y,
118 next_x,
119 &mut next_y,
120 &mut out.consumed_y,
121 &mut out.visual_changed,
122 &mut out.clamped_changed,
123 &mut out.auto_overscroll_y,
124 );
125
126 out.next_offset = (next_x, next_y);
127 out.remaining = (rem_x, rem_y);
128 self.prune_idle();
129 }
130
131 fn on_outermost_overscroll(
132 &mut self,
133 ctx: &ScrollContainerCtx<'_>,
134 axis: ScrollAxis,
135 rem: f32,
136 kind: ScrollInputKind,
137 ) -> bool {
138 if !rem.is_finite() || rem.abs() <= 1e-4 {
139 return false;
140 }
141 let (touch_phase, now_ms) = match kind {
142 ScrollInputKind::SmoothPixels {
143 phase,
144 timestamp_ms,
145 } => (phase, ScrollTimestampMs::new(timestamp_ms)),
146 _ => return false,
147 };
148 let is_y = axis == ScrollAxis::Y;
149 let is_phased_drag = touch_phase != ScrollTouchPhase::None;
150 let seed_ms = self.seed_ms(is_phased_drag, now_ms);
151 let (pos, max, viewport, ob) = if is_y {
152 (
153 ctx.offset.1,
154 ctx.max_offset.1,
155 ctx.viewport.1,
156 ctx.overscroll_behavior.1,
157 )
158 } else {
159 (
160 ctx.offset.0,
161 ctx.max_offset.0,
162 ctx.viewport.0,
163 ctx.overscroll_behavior.0,
164 )
165 };
166 let Some(rb) = resolve_bounce(&self.behavior, ctx.store, ctx.node, ctx.bounce_requested, ob)
167 else {
168 return false;
169 };
170 let idx = self.get_or_insert_idx(ctx.node, ctx.offset.0, ctx.offset.1, seed_ms);
171 let spring = resolve_spring(&self.behavior, ctx.store, ctx.node);
172 let min_fling = self.behavior.min_fling_velocity();
173 let reduced = self.reduced_motion;
174 let ax = self.entries[idx].axis_mut(is_y);
175 let dt_ms = now_ms.saturating_sub(ax.last_input_ms);
176 ax.sync_bounds(pos, max, viewport, Some(rb), OverscrollBehavior::Auto);
177 let changed = ax.apply_rubber_band_drag(rem, dt_ms);
178 ax.last_input_ms = now_ms;
179 if !is_phased_drag {
180 let _ = ax.finish_drag(true, false, reduced, None, min_fling, spring, |_| None, 0);
181 }
182 self.prune_idle();
183 changed
184 }
185
186 fn on_gesture_end(
187 &mut self,
188 store: &NodeStore,
189 scroll: &mut ScrollOffsets,
190 now_ms: ScrollTimestampMs,
191 cancelled: bool,
192 out_visual: &mut Vec<NodeId>,
193 out_clamped: &mut Vec<NodeId>,
194 ) {
195 let allow_mom = self.synthetic_momentum;
196 let reduced = self.reduced_motion;
197 let min_fling = self.behavior.min_fling_velocity();
198 for idx in 0..self.entry_len.0 {
199 let id = self.entries[idx].node;
200 let decay = resolve_decay(&self.behavior, store, id);
201 let spring = resolve_spring(&self.behavior, store, id);
202 let paused_x = now_ms.saturating_sub(self.entries[idx].x.last_input_ms);
203 let paused_y = now_ms.saturating_sub(self.entries[idx].y.last_input_ms);
204 let snap_x = self.entries[idx].x.finish_drag(
205 cancelled,
206 allow_mom,
207 reduced,
208 decay,
209 min_fling,
210 spring,
211 |q| resolve_snap_target(&self.behavior, store, id, q),
212 paused_x,
213 );
214 let snap_y = self.entries[idx].y.finish_drag(
215 cancelled,
216 allow_mom,
217 reduced,
218 decay,
219 min_fling,
220 spring,
221 |q| resolve_snap_target(&self.behavior, store, id, q),
222 paused_y,
223 );
224 if snap_x || snap_y {
225 let (nx, ny) = (self.entries[idx].x.pos, self.entries[idx].y.pos);
226 scroll.set_raw(id, nx, ny);
227 push_unique_node(out_visual, id);
228 push_unique_node(out_clamped, id);
229 }
230 }
231 self.latch = GestureLatch::default();
232 self.prune_idle();
233 }
234
235 fn step(
236 &mut self,
237 store: &NodeStore,
238 bounds: &dyn ScrollBoundsLookup,
239 scroll: &mut ScrollOffsets,
240 dt_s: f32,
241 out_visual: &mut Vec<NodeId>,
242 out_clamped: &mut Vec<NodeId>,
243 ) -> bool {
244 if self.entry_len.0 == 0 || dt_s <= 0.0 || !dt_s.is_finite() {
245 return self.has_active();
246 }
247 let mut pending_chains =
248 [(NodeId::NULL, false, 0.0f32, 0.0f32); MAX_ACTIVE_SCROLL_ENTRIES * 2];
249 let mut pending_count = 0usize;
250 let min_fling = self.behavior.min_fling_velocity();
251 let mut i = 0usize;
252 while i < self.entry_len.0 {
253 let entry = self.entries[i];
254 let id = entry.node;
255 if !store.is_live(id) || !store.has::<Scroll>(id) {
256 self.swap_remove_entry(i);
257 continue;
258 }
259 let can_chain_x = (entry.x.phase == AxisPhase::Momentum
260 && entry.x.overscroll_behavior == OverscrollBehavior::Auto
261 && entry.x.vel != 0.0)
262 .then(|| Self::find_ancestor_with_room(store, bounds, scroll, id, false, entry.x.vel))
263 .flatten();
264 let can_chain_y = (entry.y.phase == AxisPhase::Momentum
265 && entry.y.overscroll_behavior == OverscrollBehavior::Auto
266 && entry.y.vel != 0.0)
267 .then(|| Self::find_ancestor_with_room(store, bounds, scroll, id, true, entry.y.vel))
268 .flatten();
269
270 let decay = resolve_decay(&self.behavior, store, id);
271 let spring = resolve_spring(&self.behavior, store, id);
272 let wheel = resolve_smooth_wheel(&self.behavior, store, id, self.reduced_motion);
273
274 let (xv, xc, x_chain) = self.entries[i].x.step(
275 dt_s,
276 decay,
277 min_fling,
278 spring,
279 wheel,
280 can_chain_x.is_some(),
281 );
282 let (yv, yc, y_chain) = self.entries[i].y.step(
283 dt_s,
284 decay,
285 min_fling,
286 spring,
287 wheel,
288 can_chain_y.is_some(),
289 );
290 let nx = self.entries[i].x.pos;
291 let ny = self.entries[i].y.pos;
292
293 if xc || yc {
294 scroll.set_raw(id, nx, ny);
295 push_unique_node(out_clamped, id);
296 }
297 if xv || yv {
298 push_unique_node(out_visual, id);
299 }
300
301 if let (Some(anc), Some((v_hit, t_rem))) = (can_chain_x, x_chain)
302 && pending_count < pending_chains.len()
303 {
304 pending_chains[pending_count] = (anc, false, v_hit, t_rem);
305 pending_count += 1;
306 }
307 if let (Some(anc), Some((v_hit, t_rem))) = (can_chain_y, y_chain)
308 && pending_count < pending_chains.len()
309 {
310 pending_chains[pending_count] = (anc, true, v_hit, t_rem);
311 pending_count += 1;
312 }
313 i += 1;
314 }
315 for &(anc, is_y, v_hit, t_rem) in &pending_chains[..pending_count] {
317 self.chain_momentum_to_ancestor(
318 store,
319 bounds,
320 scroll,
321 anc,
322 is_y,
323 v_hit,
324 t_rem,
325 out_visual,
326 out_clamped,
327 );
328 }
329 self.prune_idle();
330 self.has_active()
331 }
332
333 #[inline]
334 fn overscroll(&self, id: NodeId) -> (f32, f32) {
335 if self.entry_len.0 == 0 {
336 return (0.0, 0.0);
337 }
338 self.active_entries()
339 .iter()
340 .find(|e| e.node == id)
341 .map_or((0.0, 0.0), |e| (e.x.overscroll, e.y.overscroll))
342 }
343
344 #[inline]
345 fn has_active(&self) -> bool {
346 self.active_entries().iter().any(ActiveScrollEntry::is_animating)
347 }
348
349 #[inline]
350 fn px_per_line(&self) -> f32 {
351 self.behavior.px_per_line()
352 }
353
354 #[inline]
355 fn cancel_node(&mut self, id: NodeId) {
356 if let Some(idx) = self.entry_idx(id) {
357 self.swap_remove_entry(idx);
358 }
359 if self.latch.target == id {
360 self.latch = GestureLatch::default();
361 }
362 }
363
364 fn reconcile_node(
365 &mut self,
366 id: NodeId,
367 new_pos: (f32, f32),
368 max: (f32, f32),
369 anchor_delta: (f32, f32),
370 explicit_seek: bool,
371 ) {
372 let Some(idx) = self.entry_idx(id) else {
373 return;
374 };
375 if explicit_seek {
376 self.swap_remove_entry(idx);
377 return;
378 }
379 let e = &mut self.entries[idx];
380 reconcile_axis(&mut e.x, new_pos.0, max.0, anchor_delta.0);
381 reconcile_axis(&mut e.y, new_pos.1, max.1, anchor_delta.1);
382 }
383
384 fn prune_missing(&mut self, store: &NodeStore) {
385 let mut i = 0;
386 while i < self.entry_len.0 {
387 let id = self.entries[i].node;
388 if !store.is_live(id) || !store.has::<Scroll>(id) {
389 self.swap_remove_entry(i);
390 } else {
391 i += 1;
392 }
393 }
394 if self.latch.active_phase
395 && (!store.is_live(self.latch.target) || !store.has::<Scroll>(self.latch.target))
396 {
397 self.latch = GestureLatch::default();
398 }
399 }
400
401 #[inline]
402 fn clear(&mut self) {
403 self.entries[..self.entry_len.0].fill(ActiveScrollEntry::default());
404 self.entry_len = PoolEntryLen(0);
405 self.latch = GestureLatch::default();
406 }
407
408 fn set_reduced_motion(
409 &mut self,
410 reduced: bool,
411 scroll: &mut ScrollOffsets,
412 out_visual: &mut Vec<NodeId>,
413 out_clamped: &mut Vec<NodeId>,
414 ) -> bool {
415 self.reduced_motion = reduced;
416 let mut snapped = false;
417 if reduced {
418 for e in &mut self.entries[..self.entry_len.0] {
419 let id = e.node;
420 let mut changed = false;
421 if matches!(e.x.phase, AxisPhase::SmoothWheel | AxisPhase::Snap) {
422 e.x.pos = e.x.target.clamp(0.0, e.x.max);
423 e.x.vel = 0.0;
424 e.x.phase = AxisPhase::Idle;
425 changed = true;
426 }
427 if matches!(e.y.phase, AxisPhase::SmoothWheel | AxisPhase::Snap) {
428 e.y.pos = e.y.target.clamp(0.0, e.y.max);
429 e.y.vel = 0.0;
430 e.y.phase = AxisPhase::Idle;
431 changed = true;
432 }
433 if changed {
434 scroll.set_raw(id, e.x.pos, e.y.pos);
435 push_unique_node(out_visual, id);
436 push_unique_node(out_clamped, id);
437 snapped = true;
438 }
439 }
440 self.prune_idle();
441 }
442 snapped
443 }
444
445 #[inline]
446 fn set_synthetic_momentum(&mut self, enabled: bool) {
447 self.synthetic_momentum = enabled;
448 }
449}