Skip to content

Commit

Permalink
Merge pull request #1788 from tarkah/optimization/scrollable-publish
Browse files Browse the repository at this point in the history
Don't publish redundant `on_scroll` offsets
  • Loading branch information
hecrj authored Apr 12, 2023
2 parents adb70d2 + 4125c03 commit 3dc76ca
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions native/src/widget/scrollable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,7 @@ pub fn draw<Renderer>(
}

fn notify_on_scroll<Message>(
state: &State,
state: &mut State,
on_scroll: &Option<Box<dyn Fn(RelativeOffset) -> Message + '_>>,
bounds: Rectangle,
content_bounds: Rectangle,
Expand All @@ -916,7 +916,23 @@ fn notify_on_scroll<Message>(
.absolute(bounds.height, content_bounds.height)
/ (content_bounds.height - bounds.height);

shell.publish(on_scroll(RelativeOffset { x, y }))
let new_offset = RelativeOffset { x, y };

// Don't publish redundant offsets to shell
if let Some(prev_offset) = state.last_notified {
let unchanged = |a: f32, b: f32| {
(a - b).abs() <= f32::EPSILON || (a.is_nan() && b.is_nan())
};

if unchanged(prev_offset.x, new_offset.x)
&& unchanged(prev_offset.y, new_offset.y)
{
return;
}
}

shell.publish(on_scroll(new_offset));
state.last_notified = Some(new_offset);
}
}

Expand All @@ -929,6 +945,7 @@ pub struct State {
offset_x: Offset,
x_scroller_grabbed_at: Option<f32>,
keyboard_modifiers: keyboard::Modifiers,
last_notified: Option<RelativeOffset>,
}

impl Default for State {
Expand All @@ -940,6 +957,7 @@ impl Default for State {
offset_x: Offset::Absolute(0.0),
x_scroller_grabbed_at: None,
keyboard_modifiers: keyboard::Modifiers::default(),
last_notified: None,
}
}
}
Expand Down

0 comments on commit 3dc76ca

Please sign in to comment.