Skip to main content

blit_widget/scroll/
mod.rs

1pub use self::{
2    area::{Scroll, ScrollBar, ScrollContent},
3    list::{Rows, ScrollList, ScrollListState},
4};
5
6mod area;
7mod list;
8
9use core::time::Duration;
10
11use blit::{
12    Animation, AnimationOptions, Axis, Id, Layout, LayoutCx, NodeId, Point, Scalar, Scope, Ui,
13    internal::animator::Animator, state::Local,
14};
15
16use crate::{Context, interact};
17
18/// persistent scroll position and motion
19#[derive(Debug, Default)]
20pub struct ScrollState<T> {
21    /// scroll position which may temporarily be outside the scrollable range after a request
22    pub offset: T,
23    pub content_extent: T,
24    pub viewport_extent: T,
25    inertia: Inertia,
26    request: Request<T>,
27}
28
29#[derive(Debug, Default)]
30struct Inertia {
31    velocity: f32,
32    tracking: bool,
33    last_frame: Option<Duration>,
34    remainder: f32,
35    sample_time: Option<Duration>,
36    pending_delta: f32,
37}
38
39impl<T: Scalar> ScrollState<T> {
40    pub fn new() -> Self {
41        Self::default()
42    }
43
44    pub fn maximum_offset(&self) -> T {
45        (self.content_extent - self.viewport_extent).max(T::ZERO)
46    }
47
48    pub fn scroll_by(&mut self, amount: T) {
49        self.scroll_to(self.offset.endpoint(amount));
50    }
51
52    /// queues an offset resolved against the scroll area's measured limits
53    /// retargeting carries existing request velocity
54    pub fn scroll_to(&mut self, offset: T) {
55        self.inertia.stop();
56        self.request.target = Goal::Offset(offset);
57    }
58
59    /// queues a node of the scroll content to reveal within the viewport
60    pub fn reveal(&mut self, target: Id) {
61        self.inertia.stop();
62        self.request.target = Goal::Node(target);
63        self.request.missed = false;
64    }
65
66    /// sets the offset immediately without animation
67    pub fn jump_to(&mut self, offset: T) {
68        self.stop();
69        self.offset = offset;
70    }
71
72    pub fn stop(&mut self) {
73        self.inertia.stop();
74        self.request = Request::default();
75    }
76
77    pub fn is_moving(&self) -> bool {
78        match self.request.target {
79            Goal::None => self.inertia.velocity != 0.0,
80            Goal::Offset(_) | Goal::Node(_) => true,
81        }
82    }
83}
84
85impl Inertia {
86    fn stop(&mut self) {
87        self.remainder = 0.0;
88        self.velocity = 0.0;
89        self.tracking = false;
90        self.sample_time = None;
91        self.pending_delta = 0.0;
92    }
93
94    fn pixel_delta<T: Scalar>(&mut self, amount: f32) -> T {
95        let delta = amount + self.remainder;
96        let whole = if amount == 0.0 { T::ZERO } else { T::from_f32(delta) };
97        self.remainder = delta - whole.to_f32();
98        whole
99    }
100}
101
102#[derive(Debug, Default)]
103struct Request<T> {
104    target: Goal<T>,
105    animator: Option<Animator<T, 1>>,
106    // the node target was missing from the previous build, which may have added it
107    missed: bool,
108}
109
110#[derive(Clone, Copy, Debug, Default)]
111enum Goal<T> {
112    #[default]
113    None,
114    Offset(T),
115    Node(Id),
116}
117
118#[derive(Clone, Copy)]
119struct ScrollLayout<T> {
120    axis: Axis,
121    offset: T,
122    viewport_extent: T,
123    scrollbar: Scrollbar<T>,
124}
125
126#[derive(Clone, Copy)]
127struct ThumbProgress {
128    position: f32,
129    visible_fraction: f32,
130}
131
132#[derive(Clone, Copy, Default)]
133enum ScrollItem {
134    #[default]
135    Content,
136    Track,
137    Thumb,
138}
139
140impl<C: Context<Scalar = T>, T: Scalar> Layout<C> for ScrollLayout<T> {
141    type Item = ScrollItem;
142
143    fn fit(&self, ui: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> blit::Fit<T> {
144        let (Some(content), bars) = scroll_parts(ui) else {
145            return blit::Fit::ZERO;
146        };
147        let mut extent = ui.fit(content, axis);
148        if axis == self.axis {
149            extent.min = T::ZERO;
150        } else if !self.scrollbar.floating
151            && let Some((track, _)) = bars
152        {
153            let track_fit = ui.fit(track, axis);
154            extent.min = extent.min.endpoint(track_fit.min);
155            extent.natural = extent.natural.endpoint(track_fit.natural);
156        }
157        extent
158    }
159
160    fn distribute(&self, ui: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: T) {
161        let (Some(content), bars) = scroll_parts(ui) else {
162            return;
163        };
164        if axis == self.axis {
165            let content_extent = ui.set_extent(content, ui.fit(content, axis).natural);
166            let maximum = (content_extent - extent).max(T::ZERO);
167            let offset = self.offset.clamp(T::ZERO, maximum);
168            if extent != self.viewport_extent || offset != self.offset {
169                ui.request_frame();
170            }
171            ui.set_offset(content, -offset);
172            if let Some((track, thumb)) = bars {
173                if maximum > T::ZERO {
174                    let progress = ThumbProgress {
175                        position: offset.to_f32() / maximum.to_f32(),
176                        visible_fraction: if content_extent > T::ZERO {
177                            extent.to_f32() / content_extent.to_f32()
178                        } else {
179                            1.0
180                        },
181                    };
182                    self.scrollbar.distribute_main(ui, extent, progress, track, thumb);
183                } else {
184                    // move past the clipped viewport so non-zero min constraints stay hidden
185                    ui.set_extent(track, T::ZERO);
186                    ui.set_offset(track, extent);
187                    ui.set_extent(thumb, T::ZERO);
188                    ui.set_offset(thumb, extent);
189                }
190            }
191        } else {
192            let thickness = bars.map_or(T::ZERO, |(track, _)| ui.fit(track, axis).natural.min(extent));
193            let gutter = if self.scrollbar.floating { T::ZERO } else { thickness };
194            ui.set_extent(content, (extent - gutter).max(T::ZERO));
195            ui.set_offset(content, T::ZERO);
196            if let Some((track, thumb)) = bars {
197                self.scrollbar.distribute_cross(ui, extent, thickness, track, thumb);
198            }
199        }
200    }
201}
202
203fn scroll_parts<C: Context>(ui: &LayoutCx<'_, C, ScrollItem>) -> (Option<NodeId>, Option<(NodeId, NodeId)>) {
204    let (mut content, mut track, mut thumb) = (None, None, None);
205    for child in ui.children() {
206        match *ui.item(child) {
207            ScrollItem::Content => content = Some(child),
208            ScrollItem::Track => track = Some(child),
209            ScrollItem::Thumb => thumb = Some(child),
210        }
211    }
212    (content, track.zip(thumb))
213}
214
215#[derive(Clone, Copy)]
216struct Scrollbar<T> {
217    minimum: T,
218    floating: bool,
219}
220
221impl<T: Scalar> Scrollbar<T> {
222    fn distribute_main<C: Context<Scalar = T>, I: 'static>(
223        &self,
224        ui: &mut LayoutCx<'_, C, I>,
225        extent: T,
226        progress: ThumbProgress,
227        track: NodeId,
228        thumb: NodeId,
229    ) {
230        ui.set_extent(track, extent);
231        ui.set_offset(track, T::ZERO);
232        let thumb_extent = T::from_f32(extent.to_f32() * progress.visible_fraction)
233            .max(self.minimum.max(T::ZERO))
234            .min(extent);
235        let thumb_extent = ui.set_extent(thumb, thumb_extent);
236        let thumb_offset = T::from_f32(progress.position * (extent - thumb_extent).max(T::ZERO).to_f32());
237        ui.set_offset(thumb, thumb_offset);
238    }
239
240    fn distribute_cross<C: Context<Scalar = T>, I: 'static>(
241        &self,
242        ui: &mut LayoutCx<'_, C, I>,
243        extent: T,
244        thickness: T,
245        track: NodeId,
246        thumb: NodeId,
247    ) {
248        let thickness = ui.set_extent(track, thickness);
249        ui.set_offset(track, extent - thickness);
250        ui.set_extent(thumb, thickness);
251        ui.set_offset(thumb, extent - thickness);
252    }
253}
254
255/// updates scroll input and motion returning thumb activity and viewport availability
256/// uses the content and thumb children for geometry when present
257fn update<C: Context, S: Local>(
258    state: &mut ScrollState<C::Scalar>,
259    ui: &mut Ui<'_, C, S>,
260    parts: Scope,
261    axis: Axis,
262    scroll_speed: f32,
263    inertia_friction: f32,
264) -> (bool, bool) {
265    let viewport_known = if let Some(area) = ui.area() {
266        state.viewport_extent = axis.extent(area.size());
267        true
268    } else {
269        false
270    };
271    let content_id = ui.resolve(parts, CONTENT);
272    if let Some(area) = ui.node(content_id).area() {
273        state.content_extent = axis.extent(area.size());
274    }
275
276    let motion = content_input(ui, axis);
277    if motion.active || motion.deactivated || motion.delta != Point::ZERO {
278        state.request = Request::default();
279    }
280    let maximum = state.maximum_offset();
281    let (thumb_active, scrollbar) = scrollbar_input(&mut state.inertia, ui, parts, axis, state.viewport_extent);
282    if let Some(action) = scrollbar {
283        state.request = Request::default();
284        match action {
285            ScrollbarInput::Thumb(delta) => move_by(state, delta * maximum.to_f32()),
286            ScrollbarInput::Track(position) => {
287                state.offset = C::Scalar::from_f32(position * maximum.to_f32()).clamp(C::Scalar::ZERO, maximum);
288                state.inertia.remainder = 0.0;
289            }
290            ScrollbarInput::Idle => {}
291        }
292    } else {
293        let delta = content_motion(&mut state.inertia, ui, axis, scroll_speed, inertia_friction, motion);
294        move_by(state, delta);
295    }
296    (thumb_active, viewport_known)
297}
298
299enum ScrollbarInput {
300    Thumb(f32),
301    Track(f32),
302    Idle,
303}
304
305fn scrollbar_input<C: Context, S: Local>(
306    state: &mut Inertia,
307    ui: &mut Ui<'_, C, S>,
308    scroll: Scope,
309    axis: Axis,
310    viewport_extent: C::Scalar,
311) -> (bool, Option<ScrollbarInput>) {
312    let thumb_id = ui.resolve(scroll, THUMB);
313    let track_id = ui.resolve(scroll, TRACK);
314    let (thumb_area, thumb, thumb_drag) = {
315        let mut part = ui.node(thumb_id);
316        (
317            part.area(),
318            part.interact(interact::press()),
319            part.interact(interact::drag()),
320        )
321    };
322    let (track_area, track, track_drag) = {
323        let mut part = ui.node(track_id);
324        (
325            part.area(),
326            part.interact(interact::press()),
327            part.interact(interact::drag()),
328        )
329    };
330    let active = thumb.active || track.active || thumb_drag.active || track_drag.active;
331    // cancelled drags leave the offset alone
332    let thumb_moved = thumb_drag.active || thumb_drag.released;
333    let track_delta = match axis {
334        Axis::Horizontal => track_drag.delta.x,
335        Axis::Vertical => track_drag.delta.y,
336    };
337    let track_moved = track_drag.active || track_drag.released && track_delta != C::Scalar::ZERO;
338    if !thumb_moved && !track.activated && !track_moved {
339        return (active, None);
340    }
341    state.last_frame = Some(ui.time());
342    let extent = thumb_area.map_or(C::Scalar::ZERO, |area| axis.extent(area.size()));
343    let travel = viewport_extent - extent;
344    state.velocity = 0.0;
345    state.tracking = false;
346    if travel <= C::Scalar::ZERO {
347        return (active, Some(ScrollbarInput::Idle));
348    }
349    let travel = travel.to_f32();
350    let action = if thumb_moved {
351        let delta = match axis {
352            Axis::Horizontal => thumb_drag.delta.x,
353            Axis::Vertical => thumb_drag.delta.y,
354        };
355        ScrollbarInput::Thumb(delta.to_f32() / travel)
356    } else {
357        let pointer = if track_moved {
358            Some(track_drag.position)
359        } else {
360            track.contact.and_then(|id| ui.contact_position(id))
361        };
362        match (track_area, pointer) {
363            (Some(track), Some(pointer)) => {
364                let position = match axis {
365                    Axis::Horizontal => pointer.x - track.x,
366                    Axis::Vertical => pointer.y - track.y,
367                };
368                ScrollbarInput::Track(((position.to_f32() - extent.to_f32() / 2.0) / travel).clamp(0.0, 1.0))
369            }
370            _ => ScrollbarInput::Idle,
371        }
372    };
373    (active, Some(action))
374}
375
376/// wheel scrolling and touch panning over the content
377fn content_input<C: Context, S: Local>(ui: &mut Ui<'_, C, S>, axis: Axis) -> interact::scroll::Response {
378    let scroll = ui.interact(interact::scroll().axis(axis));
379    let pan = ui.interact(interact::drag().axis(axis).touch_only(true));
380    if !pan.active && !pan.deactivated {
381        return scroll;
382    }
383    // touches pan the content, moving it against the finger
384    interact::scroll::Response {
385        active: pan.active,
386        activated: pan.activated,
387        deactivated: pan.deactivated,
388        released: pan.released,
389        delta: Point::new(-pan.delta.x.to_f32(), -pan.delta.y.to_f32()),
390        continuous: true,
391    }
392}
393
394fn content_motion<C: Context, S: Local>(
395    state: &mut Inertia,
396    ui: &mut Ui<'_, C, S>,
397    axis: Axis,
398    scroll_speed: f32,
399    inertia_friction: f32,
400    motion: interact::scroll::Response,
401) -> f32 {
402    let now = ui.time();
403    let previous = state.last_frame.replace(now);
404    let elapsed = previous.map_or(0.0, |previous| now.saturating_sub(previous).as_secs_f32());
405    if matches!(ui.input(), blit::input::Input::Touch { phase: blit::input::TouchPhase::Down, position, .. }
406        if ui.area().is_some_and(|area| area.contains(*position)))
407    {
408        state.stop();
409        state.sample_time = Some(now);
410        return 0.0;
411    }
412    let moving = motion.active || motion.deactivated || motion.delta != Point::ZERO;
413    let delta = match axis {
414        Axis::Horizontal => motion.delta.x,
415        Axis::Vertical => motion.delta.y,
416    };
417    let mut direct_delta = delta * scroll_speed;
418    if motion.continuous {
419        if motion.activated || motion.deactivated && !motion.released {
420            state.velocity = 0.0;
421            state.pending_delta = 0.0;
422        }
423        if motion.activated {
424            if matches!(ui.input(), blit::input::Input::Touch { .. }) {
425                let distance = libm::hypotf(motion.delta.x, motion.delta.y);
426                if distance > 0.0 {
427                    direct_delta *= (1.0 - C::SLOP.to_f32() / distance).max(0.0);
428                }
429            } else {
430                state.sample_time = previous;
431            }
432        }
433        state.tracking = motion.active;
434    } else if moving {
435        state.velocity = 0.0;
436        state.tracking = false;
437    }
438
439    if motion.continuous && (motion.active || motion.released) {
440        let sample_time = state.sample_time.get_or_insert(previous.unwrap_or(now));
441        let sample_elapsed = now.saturating_sub(*sample_time).as_secs_f32();
442        if delta != 0.0 {
443            state.pending_delta += delta * scroll_speed;
444            if sample_elapsed > 0.0 {
445                let velocity = (state.pending_delta / sample_elapsed).clamp(-MAX_SCROLL_VELOCITY, MAX_SCROLL_VELOCITY);
446                state.velocity = if state.velocity == 0.0 {
447                    velocity
448                } else {
449                    (state.velocity + velocity) * 0.5
450                };
451                state.pending_delta = 0.0;
452                *sample_time = now;
453            }
454        } else if sample_elapsed >= 0.1 {
455            state.velocity = 0.0;
456        }
457    }
458
459    if !state.tracking && state.velocity != 0.0 {
460        let elapsed = if moving { 0.0 } else { elapsed };
461        let decay = libm::expf(-inertia_friction * elapsed);
462        let delta = state.velocity * (1.0 - decay) / inertia_friction;
463        state.velocity *= decay;
464        direct_delta += delta;
465        if state.velocity.abs() < MIN_SCROLL_VELOCITY {
466            state.velocity = 0.0;
467        } else {
468            ui.request_frame();
469        }
470    }
471    direct_delta
472}
473
474fn animate<C: Context, S: Local>(
475    state: &mut ScrollState<C::Scalar>,
476    ui: &mut Ui<'_, C, S>,
477    animation: Animation,
478    viewport_known: bool,
479) {
480    let request = &mut state.request;
481    let target = match request.target {
482        // the widget that holds the content turns a node goal into an offset first
483        Goal::None | Goal::Node(_) => return,
484        _ if !viewport_known => {
485            ui.request_frame();
486            return;
487        }
488        Goal::Offset(offset) => offset,
489    };
490    request.target = Goal::Offset(target);
491    // bounds here describe the previous frame, so clamping a destination now would
492    // stop at the old end when content is appended and scrolled to in the same frame
493    // bound the moving position, then pass the original destination to layout when motion ends
494    // layout clamps it to the new content size and the next update clamps state.offset
495    let maximum = (state.content_extent - state.viewport_extent).max(C::Scalar::ZERO);
496    let goal = if target.is_finite() {
497        target
498    } else {
499        target.clamp(C::Scalar::ZERO, maximum)
500    };
501    let animator = request
502        .animator
503        .get_or_insert_with(|| Animator::new([state.offset], Animation::default()));
504    animator.advance([goal], [true], animation, AnimationOptions::default(), ui.time(), true);
505    let offset = animator.clamp(0, C::Scalar::ZERO, maximum, ui.time());
506    if animator.is_active() {
507        state.offset = offset;
508        ui.request_frame();
509    } else {
510        state.offset = target;
511        *request = Request::default();
512    }
513}
514
515fn move_by<T: Scalar>(state: &mut ScrollState<T>, amount: f32) {
516    let maximum = state.maximum_offset();
517    let whole = state.inertia.pixel_delta(amount);
518    let offset = state.offset.endpoint(whole);
519    state.offset = offset.clamp(T::ZERO, maximum);
520    if state.offset != offset
521        || (state.offset == T::ZERO && state.inertia.remainder < 0.0)
522        || (state.offset == maximum && state.inertia.remainder > 0.0)
523    {
524        state.inertia.remainder = 0.0;
525        state.inertia.velocity = 0.0;
526    }
527}
528
529// children of a scroll node, keyed in its own scope
530const CONTENT: u8 = 0;
531const TRACK: u8 = 1;
532const THUMB: u8 = 2;
533const MIN_SCROLL_VELOCITY: f32 = 5.0;
534const MAX_SCROLL_VELOCITY: f32 = 12_000.0;
535
536#[cfg(test)]
537mod tests {
538    use std::cell::Cell;
539
540    use blit::{Constraints, FrameInfo, Size, Spring, Tree, input::Input};
541
542    use super::*;
543    use crate::test::TestContext;
544
545    #[test]
546    fn release_preserves_recent_velocity() {
547        for gap in [0, 16, 33, 100, 500] {
548            let mut tree = Tree::default();
549            let mut inertia = Inertia {
550                velocity: 1000.0,
551                tracking: true,
552                last_frame: Some(Duration::from_millis(64)),
553                sample_time: Some(Duration::from_millis(64)),
554                ..Inertia::default()
555            };
556            tree.build(
557                &mut TestContext,
558                FrameInfo::new(Size::uniform(200.0)),
559                Duration::from_millis(64 + gap),
560                Input::None,
561                |mut ui: Ui<'_, TestContext>| {
562                    content_motion(
563                        &mut inertia,
564                        &mut ui,
565                        Axis::Vertical,
566                        1.0,
567                        2.5,
568                        interact::scroll::Response {
569                            continuous: true,
570                            released: true,
571                            deactivated: true,
572                            ..Default::default()
573                        },
574                    );
575                },
576            );
577            assert_eq!(inertia.velocity, if gap < 100 { 1000.0 } else { 0.0 });
578        }
579    }
580
581    #[test]
582    fn touch_motion_stops_and_survives_batched_release() {
583        use blit::input::TouchPhase;
584
585        for held in [false, true] {
586            let mut tree = Tree::default();
587            let mut state = ScrollState::<f32>::new();
588            let mut step = |millis, phase: Option<TouchPhase>, y| {
589                tree.build(
590                    &mut TestContext,
591                    FrameInfo::new(Size::uniform(200.0)),
592                    Duration::from_millis(millis),
593                    phase.map_or(Input::None, |phase| Input::Touch {
594                        id: 1,
595                        position: Point::new(50.0, y),
596                        phase,
597                    }),
598                    |ui: Ui<'_, TestContext>| {
599                        Scroll::new(&mut state)
600                            .begin(ui)
601                            .content(|mut ui| {
602                                ui.measure(|_, bounds| bounds.constrain(Size::new(200.0, 4000.0)));
603                            })
604                            .scrollbar(|_| {}, |_, _| {})
605                    },
606                );
607                tree.layout(&mut TestContext);
608                (state.offset, state.is_moving())
609            };
610            step(0, None, 0.0);
611            step(16, None, 0.0);
612            step(32, Some(TouchPhase::Down), 180.0);
613            let (offset, _) = step(48, Some(TouchPhase::Move), 150.0);
614            assert!((offset - 24.0).abs() < 0.001);
615            if held {
616                assert!(!step(500, Some(TouchPhase::Up), 150.0).1);
617                assert_eq!(step(516, None, 0.0).0, offset);
618            } else {
619                assert!(step(48, Some(TouchPhase::Up), 130.0).1);
620                let (coasting, _) = step(64, None, 0.0);
621                assert!(coasting > offset + 20.0);
622                assert_eq!(step(80, Some(TouchPhase::Down), 100.0), (coasting, false));
623                assert_eq!(step(96, None, 0.0), (coasting, false));
624            }
625        }
626    }
627
628    #[test]
629    fn scrollbars_appear_on_overflow_and_floating_ones_leave_the_content_width() {
630        for (floating, height, width) in [(false, 400.0, 199.0), (true, 400.0, 200.0), (false, 100.0, 199.0)] {
631            let mut tree = Tree::default();
632            let mut state = ScrollState::<f32>::new();
633            let mut step = || {
634                crate::test::step(&mut tree, Input::None, |ui: Ui<'_, TestContext>| {
635                    let (area, track) = (Cell::new(None), Cell::new(None));
636                    Scroll::new(&mut state)
637                        .floating(floating)
638                        .begin(ui)
639                        .content(|mut ui| {
640                            area.set(ui.area());
641                            ui.measure(move |_, bounds| Size::new(bounds.max.width, height))
642                        })
643                        .scrollbar(
644                            |ui| {
645                                track.set(ui.area());
646                                ui.constrain(Constraints {
647                                    min: Size::uniform(1.0),
648                                    max: Size::uniform(f32::INFINITY),
649                                });
650                            },
651                            |_, _| {},
652                        );
653                    (area.get(), track.get())
654                })
655            };
656            step();
657            let (area, track) = step();
658            assert_eq!(area.unwrap().width, width);
659            let track = track.unwrap();
660            assert_eq!(track.y < 200.0 && track.height > 0.0, height > 200.0);
661        }
662    }
663
664    #[test]
665    fn requests_and_focus_reveal_content() {
666        let mut tree = Tree::default();
667        let mut state = ScrollState::<f32>::new();
668        let focused = Cell::new(None);
669        let target = Cell::new(None);
670        let mut step = |state: &mut ScrollState<f32>| {
671            for _ in 0..3 {
672                crate::test::step(&mut tree, Input::None, |ui: Ui<'_, TestContext>| {
673                    Scroll::new(state)
674                        .begin(ui)
675                        .content(|ui| {
676                            let mut rows = ui.layout(crate::layout::flex::column());
677                            for index in 10..20u8 {
678                                let mut row = rows.child_in(Scope::ROOT, index);
679                                if index == 17 {
680                                    target.set(Some(row.id()));
681                                }
682                                row.interact(interact::focus());
683                                if focused.get() == Some(index) {
684                                    row.focus();
685                                }
686                                row.measure(|_, bounds| bounds.constrain(Size::new(200.0, 100.0)));
687                            }
688                        })
689                        .scrollbar(|_| {}, |_, _| {})
690                });
691            }
692            state.offset
693        };
694        step(&mut state);
695        state.reveal(target.get().unwrap());
696        assert_eq!(step(&mut state), 600.0);
697        assert!(!state.is_moving());
698        // a focus change reveals once, so scrolling away from a row that stays focused sticks
699        state.scroll_to(0.0);
700        step(&mut state);
701        focused.set(Some(17));
702        assert_eq!(step(&mut state), 600.0);
703        state.scroll_to(0.0);
704        assert_eq!(step(&mut state), 0.0);
705    }
706
707    #[test]
708    fn animated_requests_retarget_bound_and_settle() {
709        let mut tree = Tree::default();
710        let mut state = ScrollState {
711            content_extent: 1000.0,
712            viewport_extent: 100.0,
713            ..ScrollState::default()
714        };
715        let spring = Spring::new(0.500, 0.3).rest(0.01, 0.01);
716        let mut step = |state: &mut ScrollState<f32>, animation: Animation, millis| {
717            tree.build(
718                &mut TestContext,
719                FrameInfo::new(Size::uniform(100.0)),
720                Duration::from_millis(millis),
721                Input::None,
722                |mut ui: Ui<'_, TestContext>| animate(state, &mut ui, animation, true),
723            );
724            tree.layout(&mut TestContext);
725        };
726        state.scroll_to(500.0);
727        step(&mut state, spring.into(), 0);
728        step(&mut state, spring.into(), 30);
729        let moving = state.offset;
730        assert!(moving > 0.0 && moving < 500.0);
731        state.scroll_to(0.0);
732        step(&mut state, spring.into(), 30);
733        assert_eq!(state.offset, moving);
734        step(&mut state, spring.into(), 31);
735        assert!(state.offset > moving);
736        state.scroll_to(10_000.0);
737        step(&mut state, spring.into(), 31);
738        step(&mut state, spring.into(), 2000);
739        move_by(&mut state, 0.0);
740        assert_eq!(state.offset, 900.0);
741        assert!(!state.is_moving());
742        assert!(state.request.animator.is_none());
743        state.scroll_to(300.0);
744        step(&mut state, Animation::default(), 2000);
745        assert_eq!(state.offset, 300.0);
746        assert!(!tree.has_pending_redraw());
747    }
748}