bevy/examples/ui/core_widgets_observers.rs
Joona Aalto e5dc177b4b
Rename Trigger to On (#19596)
# Objective

Currently, the observer API looks like this:

```rust
app.add_observer(|trigger: Trigger<Explode>| {
    info!("Entity {} exploded!", trigger.target());
});
```

Future plans for observers also include "multi-event observers" with a
trigger that looks like this (see [Cart's
example](https://github.com/bevyengine/bevy/issues/14649#issuecomment-2960402508)):

```rust
trigger: Trigger<(
    OnAdd<Pressed>,
    OnRemove<Pressed>,
    OnAdd<InteractionDisabled>,
    OnRemove<InteractionDisabled>,
    OnInsert<Hovered>,
)>,
```

In scenarios like this, there is a lot of repetition of `On`. These are
expected to be very high-traffic APIs especially in UI contexts, so
ergonomics and readability are critical.

By renaming `Trigger` to `On`, we can make these APIs read more cleanly
and get rid of the repetition:

```rust
app.add_observer(|trigger: On<Explode>| {
    info!("Entity {} exploded!", trigger.target());
});
```

```rust
trigger: On<(
    Add<Pressed>,
    Remove<Pressed>,
    Add<InteractionDisabled>,
    Remove<InteractionDisabled>,
    Insert<Hovered>,
)>,
```

Names like `On<Add<Pressed>>` emphasize the actual event listener nature
more than `Trigger<OnAdd<Pressed>>`, and look cleaner. This *also* frees
up the `Trigger` name if we want to use it for the observer event type,
splitting them out from buffered events (bikeshedding this is out of
scope for this PR though).

For prior art:
[`bevy_eventlistener`](https://github.com/aevyrie/bevy_eventlistener)
used
[`On`](https://docs.rs/bevy_eventlistener/latest/bevy_eventlistener/event_listener/struct.On.html)
for its event listener type. Though in our case, the observer is the
event listener, and `On` is just a type containing information about the
triggered event.

## Solution

Steal from `bevy_event_listener` by @aevyrie and use `On`.

- Rename `Trigger` to `On`
- Rename `OnAdd` to `Add`
- Rename `OnInsert` to `Insert`
- Rename `OnReplace` to `Replace`
- Rename `OnRemove` to `Remove`
- Rename `OnDespawn` to `Despawn`

## Discussion

### Naming Conflicts??

Using a name like `Add` might initially feel like a very bad idea, since
it risks conflict with `core::ops::Add`. However, I don't expect this to
be a big problem in practice.

- You rarely need to actually implement the `Add` trait, especially in
modules that would use the Bevy ECS.
- In the rare cases where you *do* get a conflict, it is very easy to
fix by just disambiguating, for example using `ops::Add`.
- The `Add` event is a struct while the `Add` trait is a trait (duh), so
the compiler error should be very obvious.

For the record, renaming `OnAdd` to `Add`, I got exactly *zero* errors
or conflicts within Bevy itself. But this is of course not entirely
representative of actual projects *using* Bevy.

You might then wonder, why not use `Added`? This would conflict with the
`Added` query filter, so it wouldn't work. Additionally, the current
naming convention for observer events does not use past tense.

### Documentation

This does make documentation slightly more awkward when referring to
`On` or its methods. Previous docs often referred to `Trigger::target`
or "sends a `Trigger`" (which is... a bit strange anyway), which would
now be `On::target` and "sends an observer `Event`".

You can see the diff in this PR to see some of the effects. I think it
should be fine though, we may just need to reword more documentation to
read better.
2025-06-12 18:22:33 +00:00

304 lines
8.3 KiB
Rust

//! This example illustrates how to create widgets using the `bevy_core_widgets` widget set.
use bevy::{
color::palettes::basic::*,
core_widgets::{CoreButton, CoreWidgetsPlugin},
ecs::system::SystemId,
input_focus::{
tab_navigation::{TabGroup, TabIndex},
InputDispatchPlugin,
},
picking::hover::Hovered,
prelude::*,
ui::{InteractionDisabled, Pressed},
winit::WinitSettings,
};
fn main() {
App::new()
.add_plugins((DefaultPlugins, CoreWidgetsPlugin, InputDispatchPlugin))
// Only run the app when there is user input. This will significantly reduce CPU/GPU use.
.insert_resource(WinitSettings::desktop_app())
.add_systems(Startup, setup)
.add_observer(on_add_pressed)
.add_observer(on_remove_pressed)
.add_observer(on_add_disabled)
.add_observer(on_remove_disabled)
.add_observer(on_change_hover)
.add_systems(Update, toggle_disabled)
.run();
}
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
/// Marker which identifies buttons with a particular style, in this case the "Demo style".
#[derive(Component)]
struct DemoButton;
fn on_add_pressed(
trigger: On<Add, Pressed>,
mut buttons: Query<
(
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut text_query: Query<&mut Text>,
) {
if let Ok((hovered, disabled, mut color, mut border_color, children)) =
buttons.get_mut(trigger.target().unwrap())
{
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
disabled,
hovered.get(),
true,
&mut color,
&mut border_color,
&mut text,
);
}
}
fn on_remove_pressed(
trigger: On<Remove, Pressed>,
mut buttons: Query<
(
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut text_query: Query<&mut Text>,
) {
if let Ok((hovered, disabled, mut color, mut border_color, children)) =
buttons.get_mut(trigger.target().unwrap())
{
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
disabled,
hovered.get(),
false,
&mut color,
&mut border_color,
&mut text,
);
}
}
fn on_add_disabled(
trigger: On<Add, InteractionDisabled>,
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut text_query: Query<&mut Text>,
) {
if let Ok((pressed, hovered, mut color, mut border_color, children)) =
buttons.get_mut(trigger.target().unwrap())
{
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
true,
hovered.get(),
pressed,
&mut color,
&mut border_color,
&mut text,
);
}
}
fn on_remove_disabled(
trigger: On<Remove, InteractionDisabled>,
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut text_query: Query<&mut Text>,
) {
if let Ok((pressed, hovered, mut color, mut border_color, children)) =
buttons.get_mut(trigger.target().unwrap())
{
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
false,
hovered.get(),
pressed,
&mut color,
&mut border_color,
&mut text,
);
}
}
fn on_change_hover(
trigger: On<Insert, Hovered>,
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut text_query: Query<&mut Text>,
) {
if let Ok((pressed, hovered, disabled, mut color, mut border_color, children)) =
buttons.get_mut(trigger.target().unwrap())
{
if children.is_empty() {
return;
}
let Ok(mut text) = text_query.get_mut(children[0]) else {
return;
};
set_button_style(
disabled,
hovered.get(),
pressed,
&mut color,
&mut border_color,
&mut text,
);
}
}
fn set_button_style(
disabled: bool,
hovered: bool,
pressed: bool,
color: &mut BackgroundColor,
border_color: &mut BorderColor,
text: &mut Text,
) {
match (disabled, hovered, pressed) {
// Disabled button
(true, _, _) => {
**text = "Disabled".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(GRAY);
}
// Pressed and hovered button
(false, true, true) => {
**text = "Press".to_string();
*color = PRESSED_BUTTON.into();
border_color.set_all(RED);
}
// Hovered, unpressed button
(false, true, false) => {
**text = "Hover".to_string();
*color = HOVERED_BUTTON.into();
border_color.set_all(WHITE);
}
// Unhovered button (either pressed or not).
(false, false, _) => {
**text = "Button".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(BLACK);
}
}
}
fn setup(mut commands: Commands, assets: Res<AssetServer>) {
let on_click = commands.register_system(|| {
info!("Button clicked!");
});
// ui camera
commands.spawn(Camera2d);
commands.spawn(button(&assets, on_click));
}
fn button(asset_server: &AssetServer, on_click: SystemId) -> impl Bundle {
(
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
display: Display::Flex,
flex_direction: FlexDirection::Column,
..default()
},
TabGroup::default(),
children![
(
Node {
width: Val::Px(150.0),
height: Val::Px(65.0),
border: UiRect::all(Val::Px(5.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
DemoButton,
CoreButton {
on_click: Some(on_click),
},
Hovered::default(),
TabIndex(0),
BorderColor::all(Color::BLACK),
BorderRadius::MAX,
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Button"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)]
),
Text::new("Press 'D' to toggle button disabled state"),
],
)
}
fn toggle_disabled(
input: Res<ButtonInput<KeyCode>>,
mut interaction_query: Query<(Entity, Has<InteractionDisabled>), With<CoreButton>>,
mut commands: Commands,
) {
if input.just_pressed(KeyCode::KeyD) {
for (entity, disabled) in &mut interaction_query {
// disabled.0 = !disabled.0;
if disabled {
info!("Button enabled");
commands.entity(entity).remove::<InteractionDisabled>();
} else {
info!("Button disabled");
commands.entity(entity).insert(InteractionDisabled);
}
}
}
}