diff --git a/src/lib.rs b/src/lib.rs index b453242..ba4becb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,14 +28,14 @@ pub struct ScrollViewport { impl Default for ScrollViewport { fn default() -> Self { - Self { - scroll_speed: 500.0, - } + Self { scroll_speed: 500.0 } } } #[derive(Component, Debug, Reflect)] -pub struct ScrollViewContent(pub Entity); +pub struct ScrollViewContent { + pub pos_y: f32, +} pub fn create_scroll_view(mut commands: Commands, q: Query>) { for e in q.iter() { @@ -44,6 +44,9 @@ pub fn create_scroll_view(mut commands: Commands, q: Query, - mut q: Query<(&Children, &Interaction), With>, - mut content_q: Query<&mut Style, With>, + mut q: Query<(&Children, &Interaction, &Node), With>, + mut content_q: Query<(&mut Style, &mut ScrollViewContent, &Node)>, ) { for evt in motion_evr.read() { - info!("{:?}", evt); - for (children, &interaction) in q.iter_mut() { + for (children, &interaction, node) in q.iter_mut() { if interaction != Interaction::Pressed { continue; } + let container_height = node.size().y; for &child in children.iter() { - if let Ok(mut style) = content_q.get_mut(child) { - style.top = match style.top { - Val::Px(px) => Val::Px(px + evt.delta.y), - _ => Val::Px(0.0), - } + if let Ok(item) = content_q.get_mut(child) { + let mut style = item.0; + let mut scroll = item.1; + let max_scroll = (item.2.size().y - container_height).max(0.0); + scroll.pos_y += evt.delta.y; + scroll.pos_y = scroll.pos_y.clamp(-max_scroll, 0.); + style.top = Val::Px(scroll.pos_y); } } } @@ -92,33 +97,33 @@ fn input_mouse_pressed_move( fn scroll_events( mut scroll_evr: EventReader, - mut q: Query<(&mut Style, &Interaction, &ScrollViewport), With>, + mut q: Query<(&Children, &Interaction, &ScrollViewport, &Node), With>, time: Res