use bevy_app::{Plugin, PreStartup};
use bevy_ecs::{
component::Component,
entity::Entity,
lifecycle::HookContext,
observer::On,
query::{QueryData, With},
system::{Commands, Query},
world::World,
};
use bevy_picking::events::{Out, Over, Pointer};
use tiny_bail::prelude::*;
use crate::events::TooltipHighlighting;
pub(crate) struct HighlightPlugin;
impl Plugin for HighlightPlugin {
fn build(&self, app: &mut bevy_app::App) {
app.add_systems(PreStartup, setup_component_hooks);
}
}
#[derive(Debug, Component, PartialEq)]
pub struct TooltipHighlightLink(pub String);
#[derive(Debug, Component)]
pub struct TooltipHighlight(pub Vec<String>);
fn setup_component_hooks(world: &mut World) {
world
.register_component_hooks::<TooltipHighlightLink>()
.on_insert(|mut world, HookContext { entity, .. }| {
r!(world.commands().get_entity(entity))
.observe(highlight_activate)
.observe(highlight_deactivate);
});
}
#[derive(QueryData)]
struct HighlightNodesQuery {
entity: Entity,
tooltip_highlight: &'static TooltipHighlight,
}
fn highlight_activate(
hover: On<Pointer<Over>>,
highlight_nodes_link_query: Query<&TooltipHighlightLink>,
highlight_nodes_query: Query<HighlightNodesQuery>,
mut commands: Commands,
) {
let link = r!(highlight_nodes_link_query.get(hover.entity)).0.clone();
for node in highlight_nodes_query
.iter()
.filter(|x| x.tooltip_highlight.0.contains(&link))
{
c!(commands.get_entity(node.entity)).insert(TooltipHighlighting);
}
}
fn highlight_deactivate(
hover: On<Pointer<Out>>,
highlight_nodes_link_query: Query<&TooltipHighlightLink>,
highlight_nodes_query: Query<HighlightNodesQuery, With<TooltipHighlighting>>,
mut commands: Commands,
) {
let link = r!(highlight_nodes_link_query.get(hover.entity)).0.clone();
for node in highlight_nodes_query
.iter()
.filter(|x| x.tooltip_highlight.0.contains(&link))
{
c!(commands.get_entity(node.entity)).remove::<TooltipHighlighting>();
}
}