use crate::prelude::{button::update_buttons, *}; use bevy::{input::mouse::*, picking::hover::HoverMap}; pub mod components; pub mod consts; pub mod ui; pub mod utils; pub struct UiPlugin; impl Plugin for UiPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, scroll_events); app.add_observer(on_scroll_handler); app.add_systems(Update, update_buttons); } } fn scroll_events( mut mouse_wheel_reader: MessageReader, hover_map: Res, keyboard_input: Res>, mut commands: Commands, ) { for mouse_wheel in mouse_wheel_reader.read() { let mut delta = -Vec2::new(mouse_wheel.x, mouse_wheel.y); if mouse_wheel.unit == MouseScrollUnit::Line { delta *= LINE_HEIGHT; } if keyboard_input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]) { std::mem::swap(&mut delta.x, &mut delta.y); } for pointer_map in hover_map.values() { for entity in pointer_map.keys().copied() { commands.trigger(components::Scroll { entity, delta }); } } } } fn on_scroll_handler( mut scroll: On, mut query: Query<(&mut ScrollPosition, &Node, &ComputedNode)>, ) { let Ok((mut scroll_position, node, computed)) = query.get_mut(scroll.entity) else { return; }; let max_offset = (computed.content_size() - computed.size()) * computed.inverse_scale_factor(); let delta = &mut scroll.delta; if node.overflow.x == OverflowAxis::Scroll && delta.x != 0. { // Is this node already scrolled all the way in the direction of the scroll? let max = if delta.x > 0. { scroll_position.x >= max_offset.x } else { scroll_position.x <= 0. }; if !max { scroll_position.x += delta.x; // Consume the X portion of the scroll delta. delta.x = 0.; } } if node.overflow.y == OverflowAxis::Scroll && delta.y != 0. { // Is this node already scrolled all the way in the direction of the scroll? let max = if delta.y > 0. { scroll_position.y >= max_offset.y } else { scroll_position.y <= 0. }; if !max { scroll_position.y += delta.y; // Consume the Y portion of the scroll delta. delta.y = 0.; } } // Stop propagating when the delta is fully consumed. if *delta == Vec2::ZERO { scroll.propagate(false); } }