bevy_pages 0.1.0

A lightweight and elegant framework to upgrade your Bevy UI experience.
Documentation
use crate::element::ElementId;
use bevy::prelude::{Changed, Commands, Entity, Event, Query};
use bevy::ui::Interaction;

pub(crate) fn interactions(
    mut commands: Commands,
    entities: Query<(Entity, &Interaction, Option<&ElementId>), Changed<Interaction>>,
) {
    for (e, i, id) in entities {
        if matches!(i, Interaction::Pressed) {
            commands.trigger(ElementClick {
                entity: e,
                id: id.cloned(),
            });
        } else if matches!(i, Interaction::Hovered) {
            commands.trigger(ElementHover {
                entity: e,
                id: id.cloned(),
            });
        }
    }
}

/// An event triggered when a clickable element like a button is clicked.
#[derive(Clone, PartialEq, Eq, Debug, Hash, Event)]
pub struct ElementClick {
    /// The entity behind the target element.
    pub entity: Entity,
    /// The element ID of the target element.
    pub id: Option<ElementId>,
}

impl ElementClick {
    /// Returns [true] if the target element ID matches the given ID.
    pub fn matches_id(&self, id: impl Into<ElementId>) -> bool {
        self.id.as_ref().map(|i| *i == id.into()).unwrap_or(false)
    }
}

/// An event triggered when the mouse hovers over an interactable element like a button.
#[derive(Clone, PartialEq, Eq, Debug, Hash, Event)]
pub struct ElementHover {
    /// The entity behind the target element.
    pub entity: Entity,
    /// The element ID of the target element.
    pub id: Option<ElementId>,
}

impl ElementHover {
    /// Returns [true] if the target element ID matches the given ID.
    pub fn matches_id(&self, id: impl Into<ElementId>) -> bool {
        self.id.as_ref().map(|i| *i == id.into()).unwrap_or(false)
    }
}

/// An event triggered when an element is spawned.
#[derive(Clone, PartialEq, Eq, Debug, Hash, Event)]
pub struct ElementSpawn {
    /// The entity behind the target element.
    pub entity: Entity,
    /// The element ID of the target element.
    pub id: Option<ElementId>,
}

impl ElementSpawn {
    /// Returns [true] if the target element ID matches the given ID.
    pub fn matches_id(&self, id: impl Into<ElementId>) -> bool {
        self.id.as_ref().map(|i| *i == id.into()).unwrap_or(false)
    }
}