use std::collections::BTreeMap;
use std::ops::Range;
use understory_virtual_list::{ScrollAlign, SparsePrefixSumExtentModel, VirtualList};
use crate::core::keyboard::{Key, KeyState, NamedKey};
use crate::core::{
AccessCtx, AccessEvent, ChildrenIds, ComposeCtx, EventCtx, KeyboardEvent, LayoutCtx,
MeasureCtx, NewWidget, PaintCtx, PointerEvent, PointerScrollEvent, PropertiesMut,
PropertiesRef, RegisterCtx, TextEvent, Update, UpdateCtx, Widget, WidgetMut, WidgetPod,
};
use crate::dpi::PhysicalPosition;
use crate::imaging::Painter;
use crate::kurbo::{Axis, Size};
use crate::layout::{LenDef, LenReq, Length, SizeDef};
use crate::util::debug_panic;
#[derive(Debug)]
pub struct VirtualScrollFetchAction {
old_active: Range<usize>,
target: Range<usize>,
}
#[derive(Debug)]
pub struct VirtualScrollScrollAction {
range_in_viewport: Range<usize>,
}
#[derive(Debug)]
pub enum VirtualScrollAction {
Fetch(VirtualScrollFetchAction),
Scroll(VirtualScrollScrollAction),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[expect(missing_docs, reason = "self explanatory")]
pub enum ScrollDirection {
TopToBottom,
BottomToTop,
LeftToRight,
RightToLeft,
}
pub struct VirtualScroll {
virtual_list: VirtualList<SparsePrefixSumExtentModel<f64>>,
active_range: Range<usize>,
action_handled: bool,
warned_not_dense: bool,
missed_actions_count: u32,
items: BTreeMap<usize, WidgetPod<dyn Widget>>,
anchor_index: usize,
range_in_viewport: Range<usize>,
start_at: f64,
end_at: f64,
direction: ScrollDirection,
scrolling: bool,
}
impl std::fmt::Debug for VirtualScroll {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VirtualScroll")
.field("virtual_list", &self.virtual_list)
.field("active_range", &self.active_range)
.field("action_handled", &self.action_handled)
.field("warned_not_dense", &self.warned_not_dense)
.field("missed_actions_count", &self.missed_actions_count)
.field("items", &self.items.keys().collect::<Vec<_>>())
.field("anchor_index", &self.anchor_index)
.field("range_in_viewport", &self.range_in_viewport)
.field("start_at", &self.start_at)
.field("end_at", &self.end_at)
.field("direction", &self.direction)
.field("scrolling", &self.scrolling)
.finish()
}
}
const DEFAULT_MEAN_ITEM_LENGTH: f64 = 180.;
impl VirtualScroll {
pub fn new(initial_anchor: usize, len: usize) -> Self {
let mut virtual_list = VirtualList::new(
SparsePrefixSumExtentModel::new(DEFAULT_MEAN_ITEM_LENGTH, len),
0.,
0.,
);
virtual_list.scroll_to_index(initial_anchor, ScrollAlign::Start);
Self {
virtual_list,
active_range: initial_anchor..initial_anchor,
action_handled: true,
warned_not_dense: false,
missed_actions_count: 0,
items: BTreeMap::default(),
anchor_index: initial_anchor,
range_in_viewport: initial_anchor..initial_anchor,
start_at: 0.,
end_at: 1.,
direction: ScrollDirection::TopToBottom,
scrolling: false,
}
}
#[track_caller]
pub fn with_len(mut self, len: usize) -> Self {
self.virtual_list.set_len(len);
self
}
pub fn with_start_end(mut self, start_at: f64, end_at: f64) -> Self {
self.start_at = start_at;
self.end_at = end_at;
self
}
pub fn with_direction(mut self, direction: ScrollDirection) -> Self {
self.direction = direction;
self
}
pub fn with_scrolling(mut self, scrolling: bool) -> Self {
self.scrolling = scrolling;
self
}
}
impl VirtualScroll {
#[expect(
clippy::len_without_is_empty,
reason = "The only time the VirtualScroll unloads all children is when given an empty valid range."
)]
pub fn len(&self) -> usize {
self.items.len()
}
pub fn scroll_by(&mut self, delta: f64) -> bool {
self.virtual_list
.scroll_by(-self.direction.appropriate(delta));
self.needs_layout()
}
fn needs_layout(&mut self) -> bool {
self.virtual_list.clamp_scroll_to_content();
let scroll_offset = self.virtual_list.scroll_offset();
let offset_of_anchor = self.virtual_list.offset_of(self.anchor_index);
scroll_offset < offset_of_anchor
|| scroll_offset >= offset_of_anchor + self.virtual_list.extent_of(self.anchor_index)
}
fn scroll_offset_from_anchor(&mut self) -> f64 {
self.virtual_list.scroll_offset() - self.virtual_list.offset_of(self.anchor_index)
}
}
impl VirtualScrollFetchAction {
pub fn old_active(&self) -> &Range<usize> {
&self.old_active
}
pub fn target(&self) -> &Range<usize> {
&self.target
}
}
impl VirtualScrollScrollAction {
pub fn range_in_viewport(&self) -> &Range<usize> {
&self.range_in_viewport
}
}
impl ScrollDirection {
fn axis(self) -> Axis {
match self {
Self::TopToBottom | Self::BottomToTop => Axis::Vertical,
Self::LeftToRight | Self::RightToLeft => Axis::Horizontal,
}
}
fn is_reverse(self) -> bool {
matches!(self, Self::BottomToTop | Self::RightToLeft)
}
fn appropriate(self, delta: f64) -> f64 {
if self.is_reverse() { -delta } else { delta }
}
}
impl VirtualScroll {
pub fn will_handle_action(this: &mut WidgetMut<'_, Self>, action: &VirtualScrollFetchAction) {
if this.widget.active_range != action.old_active {
debug_panic!(
"Handling a VirtualScrollFetchAction with the wrong range; got {:?}, expected {:?} for widget {}.\n\
Maybe this has been routed to the wrong `VirtualScroll`?",
action.old_active,
this.widget.active_range,
this.ctx.widget_id(),
);
}
this.widget.action_handled = true;
if this.widget.missed_actions_count > 0 {
this.widget.missed_actions_count = 1;
}
this.widget.active_range = action.target.clone();
this.ctx.request_layout();
}
#[track_caller]
pub fn add_child(this: &mut WidgetMut<'_, Self>, idx: usize, child: NewWidget<dyn Widget>) {
debug_assert!(
this.widget.action_handled,
"You must call `will_handle_action` before `add_child`."
);
debug_assert!(
this.widget.active_range.contains(&idx),
"`add_child` should only be called with an index requested by the controller."
);
this.ctx.children_changed();
if this.widget.items.insert(idx, child.to_pod()).is_some() {
tracing::warn!("Tried to add child {idx} twice to VirtualScroll");
};
}
#[track_caller]
pub fn remove_child(this: &mut WidgetMut<'_, Self>, idx: usize) {
debug_assert!(
this.widget.action_handled,
"You must call `will_handle_action` before `remove_child`."
);
debug_assert!(
!this.widget.active_range.contains(&idx),
"`remove_child` should only be called with an index which is not active."
);
let child = this.widget.items.remove(&idx);
if let Some(child) = child {
this.ctx.remove_child(child);
} else if !this.widget.warned_not_dense {
tracing::error!(
"Tried to remove child ({idx}) which has already been removed or was never added."
);
}
}
#[track_caller]
pub fn child_mut<'t>(
this: &'t mut WidgetMut<'_, Self>,
idx: usize,
) -> WidgetMut<'t, dyn Widget> {
let Some(child) = this.widget.items.get_mut(&idx) else {
panic!(
"`VirtualScroll::child_mut` called with non-present index {idx}.\nActive range is {:?}.",
this.widget.active_range
)
};
this.ctx.get_mut(child)
}
pub fn set_len(this: &mut WidgetMut<'_, Self>, len: usize) {
this.widget.virtual_list.set_len(len);
this.ctx.request_layout();
}
pub fn set_start(this: &mut WidgetMut<'_, Self>, start_at: f64) {
this.widget.start_at = start_at;
this.ctx.request_layout();
}
pub fn set_end(this: &mut WidgetMut<'_, Self>, end_at: f64) {
this.widget.end_at = end_at;
this.ctx.request_layout();
}
pub fn set_direction(this: &mut WidgetMut<'_, Self>, direction: ScrollDirection) {
this.widget.direction = direction;
this.ctx.request_layout();
}
pub fn set_scrolling(this: &mut WidgetMut<'_, Self>, scrolling: bool) {
this.widget.scrolling = scrolling;
this.ctx.request_render();
}
pub fn scroll_to(this: &mut WidgetMut<'_, Self>, idx: usize) {
this.widget.anchor_index = idx;
this.widget
.virtual_list
.scroll_to_index(idx, ScrollAlign::Start);
this.ctx.request_layout();
}
}
impl Widget for VirtualScroll {
type Action = VirtualScrollAction;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
if let PointerEvent::Scroll(PointerScrollEvent { delta, .. }) = event {
let content_box = ctx.content_box();
let scale_factor = ctx.scale_factor();
let line_px = PhysicalPosition {
x: 120.0 * scale_factor,
y: 120.0 * scale_factor,
};
let page_px = PhysicalPosition {
x: content_box.width() * scale_factor,
y: content_box.height() * scale_factor,
};
let delta_px = delta
.to_pixel_delta(line_px, page_px)
.to_logical::<f64>(scale_factor);
let delta = -match (self.direction.axis(), delta_px.x == 0., delta_px.y == 0.) {
(Axis::Horizontal, false, _) | (Axis::Vertical, _, true) => delta_px.x,
(Axis::Horizontal, true, _) | (Axis::Vertical, _, false) => delta_px.y,
};
if self.scroll_by(-delta) {
ctx.request_layout();
}
ctx.request_compose();
}
}
fn on_text_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &TextEvent,
) {
const DELTA_PAGE: f64 = 2000.;
const DELTA_LINE: f64 = 20.;
let TextEvent::Keyboard(KeyboardEvent {
state: KeyState::Down,
key: Key::Named(key),
..
}) = event
else {
return;
};
let delta = match (key, self.direction.axis()) {
(NamedKey::PageDown, _) => Some((DELTA_PAGE, true)),
(NamedKey::PageUp, _) => Some((-DELTA_PAGE, true)),
(NamedKey::ArrowDown, Axis::Vertical) => Some((DELTA_LINE, false)),
(NamedKey::ArrowUp, Axis::Vertical) => Some((-DELTA_LINE, false)),
(NamedKey::ArrowLeft, Axis::Horizontal) => Some((DELTA_LINE, false)),
(NamedKey::ArrowRight, Axis::Horizontal) => Some((-DELTA_LINE, false)),
_ => None,
};
if let Some((delta, direct)) = delta {
self.virtual_list.scroll_by(if direct {
delta
} else {
self.direction.appropriate(delta)
});
if self.needs_layout() {
ctx.request_layout();
}
ctx.request_compose();
ctx.set_handled();
}
}
fn on_access_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &AccessEvent,
) {
let backscroll = match event.action {
accesskit::Action::ScrollLeft | accesskit::Action::ScrollUp => true,
accesskit::Action::ScrollRight | accesskit::Action::ScrollDown => false,
_ => return,
};
let delta = match event.data {
Some(accesskit::ActionData::ScrollUnit(accesskit::ScrollUnit::Page)) => {
ctx.content_box().size().get_coord(self.direction.axis())
}
_ => self.virtual_list.extent_of(self.anchor_index),
};
if self.scroll_by(if backscroll { delta } else { -delta }) {
ctx.request_layout();
}
ctx.request_compose();
ctx.set_handled();
}
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
for child in self.items.values_mut() {
ctx.register_child(child);
}
}
fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
if let Update::RequestPanToChild(target) = event {
let content_box_length = ctx.content_box().size().get_coord(self.direction.axis());
let target = target.get_coords(self.direction.axis());
let new_pos =
super::compute_pan_range(0.0..content_box_length, target.0..target.1).start;
self.virtual_list.scroll_by(new_pos);
if self.needs_layout() {
ctx.request_layout();
}
ctx.request_compose();
}
}
fn measure(
&mut self,
_ctx: &mut MeasureCtx<'_>,
_props: &PropertiesRef<'_>,
_axis: Axis,
len_req: LenReq,
_cross_length: Option<Length>,
) -> Length {
const DEFAULT_LENGTH: Length = Length::const_px(100.);
match len_req {
LenReq::MinContent | LenReq::MaxContent => DEFAULT_LENGTH,
LenReq::FitContent(space) => space,
}
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
ctx.set_clip_path(size.to_rect());
let offset_of_anchor_re_viewport = self.scroll_offset_from_anchor();
let mut total_children_length = 0.;
let mut total_children_count = 0_usize;
self.virtual_list.model_mut().clear();
for (idx, child) in &mut self.items {
let auto_size = SizeDef::fit(size).with(self.direction.axis(), LenDef::MaxContent);
let child_size = ctx.compute_size(child, auto_size, size.into());
ctx.run_layout(child, child_size);
let child_length = child_size.get_coord(self.direction.axis());
self.virtual_list.model_mut().set_extent(*idx, child_length);
total_children_length += child_length;
total_children_count += 1;
}
if total_children_length != 0. && total_children_count != 0 {
self.virtual_list
.model_mut()
.set_default_extent(total_children_length / total_children_count as f64);
}
let main_axis_length = size.get_coord(self.direction.axis());
let start_at = self.start_at * main_axis_length;
let end_at = self.end_at * main_axis_length;
self.virtual_list.set_viewport_extent(end_at - start_at);
self.virtual_list
.set_overscan(main_axis_length + start_at, main_axis_length * 3. - end_at);
let offset_of_anchor = self.virtual_list.offset_of(self.anchor_index);
self.virtual_list
.set_scroll_offset(offset_of_anchor_re_viewport + offset_of_anchor);
self.virtual_list.clamp_scroll_to_content();
self.anchor_index = self.virtual_list.viewport_range().start;
if self.action_handled && self.active_range != self.virtual_list.materialized_range() {
ctx.submit_action::<VirtualScrollAction>(VirtualScrollAction::Fetch(
VirtualScrollFetchAction {
old_active: self.active_range.clone(),
target: self.virtual_list.materialized_range(),
},
));
self.action_handled = false;
}
let offset_of_anchor = self.virtual_list.offset_of(self.anchor_index);
for (idx, child) in &mut self.items {
if self.virtual_list.materialized_range().contains(idx) {
let pos = self.virtual_list.offset_of(*idx) - offset_of_anchor;
let placed_pos = if self.direction.is_reverse() {
-pos - self.virtual_list.extent_of(*idx)
} else {
pos
};
ctx.place_child(child, self.direction.axis().pack_point(placed_pos, 0.));
} else {
ctx.set_stashed(child, true);
}
}
}
fn compose(&mut self, ctx: &mut ComposeCtx<'_>) {
let content_length = ctx.content_box().size().get_coord(self.direction.axis());
let offset = self.scroll_offset_from_anchor() - self.start_at * content_length;
let offset = if self.direction.is_reverse() {
content_length - self.direction.appropriate(offset)
} else {
-self.direction.appropriate(offset)
};
let translation = self.direction.axis().pack_vec2(offset, 0.);
for idx in self.active_range.clone() {
if let Some(child) = self.items.get_mut(&idx) {
if self.scrolling {
ctx.set_animated_child_scroll_translation(child, translation);
} else {
ctx.set_child_scroll_translation(child, translation);
}
}
}
let range_in_viewport = self.virtual_list.viewport_range();
if std::mem::replace(&mut self.range_in_viewport, range_in_viewport.clone())
!= range_in_viewport
{
ctx.submit_action::<VirtualScrollAction>(VirtualScrollAction::Scroll(
VirtualScrollScrollAction { range_in_viewport },
));
}
}
fn paint(
&mut self,
_ctx: &mut PaintCtx<'_>,
_props: &PropertiesRef<'_>,
_painter: &mut Painter<'_>,
) {
if !self.action_handled {
if self.missed_actions_count == 0 {
tracing::warn!(
"VirtualScroll got to painting without its action (i.e. it's request for items to be loaded) being handled.\n\
This means that there was a delay in handling its action for some reason.\n\
Maybe your driver only handles one action at a time?"
);
}
if self.missed_actions_count > 10 {
debug_panic!(
"VirtualScroll's action is being missed repeatedly being handled.\n\
Note that to handle an action, you must call `VirtualScroll::will_handle_action` with the action."
);
self.action_handled = true;
}
self.missed_actions_count += 1;
}
}
fn accessibility_role(&self) -> accesskit::Role {
accesskit::Role::ScrollView
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
node: &mut accesskit::Node,
) {
node.set_clips_children();
node.set_orientation(match self.direction.axis() {
Axis::Horizontal => accesskit::Orientation::Horizontal,
Axis::Vertical => accesskit::Orientation::Vertical,
});
if self.anchor_index != 0 && self.anchor_index != usize::MAX {
let pos = (self.anchor_index as f64) * self.virtual_list.model().default_extent()
+ self.scroll_offset_from_anchor();
match self.direction.axis() {
Axis::Horizontal => node.set_scroll_x(pos),
Axis::Vertical => node.set_scroll_y(pos),
}
}
if self.anchor_index != 0 || self.scroll_offset_from_anchor() > 0. {
node.add_action(match self.direction {
ScrollDirection::TopToBottom => accesskit::Action::ScrollUp,
ScrollDirection::BottomToTop => accesskit::Action::ScrollDown,
ScrollDirection::LeftToRight => accesskit::Action::ScrollLeft,
ScrollDirection::RightToLeft => accesskit::Action::ScrollRight,
});
}
let viewport = self.virtual_list.viewport_strip();
let at_end = viewport.end == self.virtual_list.len()
&& viewport.content_extent
- viewport.after_extent
- self.virtual_list.scroll_offset()
- self.virtual_list.viewport_extent()
!= 0.;
if !at_end {
node.add_action(match self.direction {
ScrollDirection::TopToBottom => accesskit::Action::ScrollDown,
ScrollDirection::BottomToTop => accesskit::Action::ScrollUp,
ScrollDirection::LeftToRight => accesskit::Action::ScrollRight,
ScrollDirection::RightToLeft => accesskit::Action::ScrollLeft,
});
}
node.add_child_action(accesskit::Action::ScrollIntoView);
}
fn children_ids(&self) -> ChildrenIds {
self.items.values().map(|pod| pod.id()).collect()
}
fn accepts_text_input(&self) -> bool {
false
}
fn accepts_focus(&self) -> bool {
true
}
fn get_debug_text(&self) -> Option<String> {
Some(format!("{self:#?}"))
}
}
#[cfg(test)]
mod tests {
use crate::core::{NewWidget, Widget, WidgetId, WidgetMut};
use crate::kurbo::Vec2;
use crate::parley::StyleProperty;
use crate::testing::{TestHarness, assert_render_snapshot};
use crate::theme::test_property_set;
use crate::widgets::Label;
use super::*;
#[test]
fn sensible_driver() {
let widget = VirtualScroll::new(0, usize::MAX).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (100, 200));
let virtual_scroll_tag = harness.root_tag();
let virtual_scroll_id = harness.root_id();
fn driver(action: VirtualScrollFetchAction, mut scroll: WidgetMut<'_, VirtualScroll>) {
VirtualScroll::will_handle_action(&mut scroll, &action);
for idx in action.old_active.clone() {
if !action.target.contains(&idx) {
VirtualScroll::remove_child(&mut scroll, idx);
}
}
for idx in action.target {
if !action.old_active.contains(&idx) {
VirtualScroll::add_child(
&mut scroll,
idx,
NewWidget::new(
Label::new(format!("{idx}")).with_style(StyleProperty::FontSize(30.)),
)
.erased(),
);
}
}
}
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
assert_render_snapshot!(harness, "virtual_scroll_basic");
harness.edit_root_widget(|mut scroll| {
VirtualScroll::scroll_to(&mut scroll, 100);
});
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
assert_render_snapshot!(harness, "virtual_scroll_moved");
harness.mouse_move_to(virtual_scroll_tag);
harness.mouse_wheel(Vec2 { x: 0., y: 25. });
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
assert_render_snapshot!(harness, "virtual_scroll_scrolled");
}
#[test]
fn small_gaps() {
let widget = VirtualScroll::new(0, usize::MAX).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (100, 200));
let virtual_scroll_tag = harness.root_tag();
let virtual_scroll_id = harness.root_id();
fn driver(action: VirtualScrollFetchAction, mut scroll: WidgetMut<'_, VirtualScroll>) {
VirtualScroll::will_handle_action(&mut scroll, &action);
for idx in action.old_active.clone() {
if !action.target.contains(&idx) {
VirtualScroll::remove_child(&mut scroll, idx);
}
}
for idx in action.target {
if !action.old_active.contains(&idx) && idx % 2 == 0 {
VirtualScroll::add_child(
&mut scroll,
idx,
NewWidget::new(
Label::new(format!("{idx}")).with_style(StyleProperty::FontSize(30.)),
)
.erased(),
);
}
}
}
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
harness.edit_root_widget(|mut scroll| {
VirtualScroll::scroll_to(&mut scroll, 100);
});
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
harness.mouse_move_to(virtual_scroll_tag);
harness.mouse_wheel(Vec2 { x: 0., y: 200. });
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
}
#[test]
fn big_gaps() {
let widget = VirtualScroll::new(0, usize::MAX).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (100, 200));
let virtual_scroll_tag = harness.root_tag();
let virtual_scroll_id = harness.root_id();
fn driver(action: VirtualScrollFetchAction, mut scroll: WidgetMut<'_, VirtualScroll>) {
VirtualScroll::will_handle_action(&mut scroll, &action);
for idx in action.old_active.clone() {
if !action.target.contains(&idx) {
VirtualScroll::remove_child(&mut scroll, idx);
}
}
for idx in action.target {
if !action.old_active.contains(&idx) && idx % 100 == 1 {
VirtualScroll::add_child(
&mut scroll,
idx,
NewWidget::new(
Label::new(format!("{idx}")).with_style(StyleProperty::FontSize(30.)),
)
.erased(),
);
}
}
}
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
harness.edit_root_widget(|mut scroll| {
VirtualScroll::scroll_to(&mut scroll, 200);
});
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
harness.mouse_move_to(virtual_scroll_tag);
harness.mouse_wheel(Vec2 { x: 0., y: 200. });
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
}
#[test]
fn degenerate_driver() {
let widget = VirtualScroll::new(0, usize::MAX).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (100, 200));
let virtual_scroll_tag = harness.root_tag();
let virtual_scroll_id = harness.root_id();
fn driver(action: VirtualScrollFetchAction, mut scroll: WidgetMut<'_, VirtualScroll>) {
VirtualScroll::will_handle_action(&mut scroll, &action);
for idx in action.old_active.clone() {
if !action.target.contains(&idx) {
VirtualScroll::remove_child(&mut scroll, idx);
}
}
for idx in action.target {
if !action.old_active.contains(&idx) && idx < 5 {
VirtualScroll::add_child(
&mut scroll,
idx,
NewWidget::new(
Label::new(format!("{idx}")).with_style(StyleProperty::FontSize(30.)),
)
.erased(),
);
}
}
}
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
harness.edit_root_widget(|mut scroll| {
VirtualScroll::scroll_to(&mut scroll, 200);
});
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
harness.mouse_move_to(virtual_scroll_tag);
harness.mouse_wheel(Vec2 { x: 0., y: 200. });
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
}
#[test]
fn limited_down() {
const MAX: usize = 10;
let widget = VirtualScroll::new(100, MAX).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (100, 200));
let virtual_scroll_tag = harness.root_tag();
let virtual_scroll_id = harness.root_id();
fn driver(action: VirtualScrollFetchAction, mut scroll: WidgetMut<'_, VirtualScroll>) {
VirtualScroll::will_handle_action(&mut scroll, &action);
for idx in action.old_active.clone() {
if !action.target.contains(&idx) {
VirtualScroll::remove_child(&mut scroll, idx);
}
}
for idx in action.target {
if !action.old_active.contains(&idx) {
assert!(
idx < MAX,
"Virtual Scroll controller should never request an invalid id. Requested {idx}"
);
VirtualScroll::add_child(
&mut scroll,
idx,
NewWidget::new(
Label::new(idx.to_string()).with_style(StyleProperty::FontSize(30.)),
)
.erased(),
);
}
}
}
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
assert_render_snapshot!(harness, "virtual_scroll_limited_up_bottom");
let (original_range, original_scroll) = {
let widget = harness.root_widget();
tracing::debug!(widget = ?(&*widget));
assert_eq!(
widget.range_in_viewport.end, MAX,
"Virtual Scroll controller should fix the last item to the end of the viewport"
);
(
widget.active_range.clone(),
widget.virtual_list.scroll_offset(),
)
};
harness.mouse_move_to(virtual_scroll_tag);
harness.mouse_wheel(Vec2 { x: 0., y: 40. });
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
{
let widget = harness.root_widget();
tracing::debug!(widget = ?(&*widget));
assert_ne!(widget.range_in_viewport.end, MAX);
assert_eq!(widget.active_range, original_range);
}
harness.mouse_wheel(Vec2 { x: 0., y: -45. });
drive_to_fixpoint(&mut harness, virtual_scroll_id, driver);
assert_render_snapshot!(harness, "virtual_scroll_limited_up_bottom");
{
let widget = harness.root_widget();
assert_eq!(widget.range_in_viewport.end, MAX);
assert_eq!(
widget.virtual_list.scroll_offset(),
original_scroll,
"Should be scrolled as far as possible (which is the same as we originally were)"
);
}
}
fn drive_to_fixpoint(
harness: &mut TestHarness<VirtualScroll>,
virtual_scroll_id: WidgetId,
mut f: impl FnMut(VirtualScrollFetchAction, WidgetMut<'_, VirtualScroll>),
) {
let mut iteration = 0;
let mut old_active = None;
loop {
iteration += 1;
if iteration > 1000 {
panic!("Took too long to reach fixpoint");
}
let Some((action, id)) = harness.pop_action::<VirtualScrollAction>() else {
break;
};
let VirtualScrollAction::Fetch(action) = action else {
continue;
};
assert_eq!(
id, virtual_scroll_id,
"Only widget in tree should give action"
);
if let Some(old_active) = old_active.take() {
assert_eq!(action.old_active, old_active);
}
old_active = Some(action.target.clone());
assert_ne!(
action.target, action.old_active,
"Shouldn't have sent an update if the target hasn't changed"
);
harness.edit_root_widget(|scroll| {
f(action, scroll);
});
}
}
}