Skip to content

Core Checkbox #19665

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
179 changes: 179 additions & 0 deletions crates/bevy_core_widgets/src/core_checkbox.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
use accesskit::Role;
use bevy_a11y::AccessibilityNode;
use bevy_app::{App, Plugin};
use bevy_ecs::event::{EntityEvent, Event};
use bevy_ecs::query::{Has, Without};
use bevy_ecs::system::{In, ResMut};
use bevy_ecs::{
component::Component,
observer::On,
system::{Commands, Query, SystemId},
};
use bevy_input::keyboard::{KeyCode, KeyboardInput};
use bevy_input::ButtonState;
use bevy_input_focus::{FocusedInput, InputFocus, InputFocusVisible};
use bevy_picking::events::{Click, Pointer};
use bevy_ui::{Checkable, Checked, InteractionDisabled};

/// Headless widget implementation for checkboxes. The [`Checked`] component represents the current
/// state of the checkbox. The `on_change` field is an optional system id that will be run when the
/// checkbox is clicked, or when the `Enter` or `Space` key is pressed while the checkbox is
/// focused. If the `on_change` field is `None`, then instead of calling a callback, the checkbox
/// will update its own [`Checked`] state directly.
///
/// # Toggle switches
///
/// The [`CoreCheckbox`] component can be used to implement other kinds of toggle widgets. If you
/// are going to do a toggle switch, you should override the [`AccessibilityNode`] component with
/// the `Switch` role instead of the `Checkbox` role.
#[derive(Component, Debug, Default)]
#[require(AccessibilityNode(accesskit::Node::new(Role::CheckBox)), Checkable)]
pub struct CoreCheckbox {
/// One-shot system that is run when the checkbox state needs to be changed.
pub on_change: Option<SystemId<In<bool>>>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh nice, I like the piped one shot systems here!

}

fn checkbox_on_key_input(
mut ev: On<FocusedInput<KeyboardInput>>,
q_checkbox: Query<(&CoreCheckbox, Has<Checked>), Without<InteractionDisabled>>,
mut commands: Commands,
) {
if let Ok((checkbox, is_checked)) = q_checkbox.get(ev.target()) {
let event = &ev.event().input;
if event.state == ButtonState::Pressed
&& !event.repeat
&& (event.key_code == KeyCode::Enter || event.key_code == KeyCode::Space)
{
ev.propagate(false);
set_checkbox_state(&mut commands, ev.target(), checkbox, !is_checked);
}
}
}

fn checkbox_on_pointer_click(
mut ev: On<Pointer<Click>>,
q_checkbox: Query<(&CoreCheckbox, Has<Checked>, Has<InteractionDisabled>)>,
focus: Option<ResMut<InputFocus>>,
focus_visible: Option<ResMut<InputFocusVisible>>,
mut commands: Commands,
) {
if let Ok((checkbox, is_checked, disabled)) = q_checkbox.get(ev.target()) {
// Clicking on a button makes it the focused input,
// and hides the focus ring if it was visible.
if let Some(mut focus) = focus {
focus.0 = Some(ev.target());
}
if let Some(mut focus_visible) = focus_visible {
focus_visible.0 = false;
}

ev.propagate(false);
if !disabled {
set_checkbox_state(&mut commands, ev.target(), checkbox, !is_checked);
}
}
}

/// Event which can be triggered on a checkbox to set the checked state. This can be used to control
/// the checkbox via gamepad buttons or other inputs.
///
/// # Example:
///
/// ```
/// use bevy_ecs::system::Commands;
/// use bevy_core_widgets::{CoreCheckbox, SetChecked};
///
/// fn setup(mut commands: Commands) {
/// // Create a checkbox
/// let checkbox = commands.spawn((
/// CoreCheckbox::default(),
/// )).id();
///
/// // Set to checked
/// commands.trigger_targets(SetChecked(true), checkbox);
/// }
/// ```
#[derive(Event, EntityEvent)]
pub struct SetChecked(pub bool);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small nit: This should probably be an enum instead of a boolean.


/// Event which can be triggered on a checkbox to toggle the checked state. This can be used to
/// control the checkbox via gamepad buttons or other inputs.
///
/// # Example:
///
/// ```
/// use bevy_ecs::system::Commands;
/// use bevy_core_widgets::{CoreCheckbox, ToggleChecked};
///
/// fn setup(mut commands: Commands) {
/// // Create a checkbox
/// let checkbox = commands.spawn((
/// CoreCheckbox::default(),
/// )).id();
///
/// // Set to checked
/// commands.trigger_targets(ToggleChecked, checkbox);
/// }
/// ```
#[derive(Event, EntityEvent)]
pub struct ToggleChecked;

fn checkbox_on_set_checked(
mut ev: On<SetChecked>,
q_checkbox: Query<(&CoreCheckbox, Has<Checked>, Has<InteractionDisabled>)>,
mut commands: Commands,
) {
if let Ok((checkbox, is_checked, disabled)) = q_checkbox.get(ev.target()) {
ev.propagate(false);
if disabled {
return;
}

let will_be_checked = ev.event().0;
if will_be_checked != is_checked {
set_checkbox_state(&mut commands, ev.target(), checkbox, will_be_checked);
}
}
}

fn checkbox_on_toggle_checked(
mut ev: On<ToggleChecked>,
q_checkbox: Query<(&CoreCheckbox, Has<Checked>, Has<InteractionDisabled>)>,
mut commands: Commands,
) {
if let Ok((checkbox, is_checked, disabled)) = q_checkbox.get(ev.target()) {
ev.propagate(false);
if disabled {
return;
}

set_checkbox_state(&mut commands, ev.target(), checkbox, !is_checked);
}
}

fn set_checkbox_state(
commands: &mut Commands,
entity: impl Into<bevy_ecs::entity::Entity>,
checkbox: &CoreCheckbox,
new_state: bool,
) {
if let Some(on_change) = checkbox.on_change {
commands.run_system_with(on_change, new_state);
} else if new_state {
commands.entity(entity.into()).insert(Checked);
} else {
commands.entity(entity.into()).remove::<Checked>();
}
}

/// Plugin that adds the observers for the [`CoreCheckbox`] widget.
pub struct CoreCheckboxPlugin;

impl Plugin for CoreCheckboxPlugin {
fn build(&self, app: &mut App) {
app.add_observer(checkbox_on_key_input)
.add_observer(checkbox_on_pointer_click)
.add_observer(checkbox_on_set_checked)
.add_observer(checkbox_on_toggle_checked);
}
}
4 changes: 3 additions & 1 deletion crates/bevy_core_widgets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
// the widget level, like `SliderValue`, should not have the `Core` prefix.

mod core_button;
mod core_checkbox;
mod core_slider;

use bevy_app::{App, Plugin};

pub use core_button::{CoreButton, CoreButtonPlugin};
pub use core_checkbox::{CoreCheckbox, CoreCheckboxPlugin, SetChecked, ToggleChecked};
pub use core_slider::{
CoreSlider, CoreSliderDragState, CoreSliderPlugin, CoreSliderThumb, SetSliderValue,
SliderRange, SliderStep, SliderValue, TrackClick,
Expand All @@ -31,6 +33,6 @@ pub struct CoreWidgetsPlugin;

impl Plugin for CoreWidgetsPlugin {
fn build(&self, app: &mut App) {
app.add_plugins((CoreButtonPlugin, CoreSliderPlugin));
app.add_plugins((CoreButtonPlugin, CoreCheckboxPlugin, CoreSliderPlugin));
}
}
37 changes: 24 additions & 13 deletions crates/bevy_ui/src/interaction_states.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use bevy_a11y::AccessibilityNode;
use bevy_ecs::{
component::Component,
lifecycle::{Add, Insert, Remove},
lifecycle::{Add, Remove},
observer::On,
world::DeferredWorld,
};
Expand Down Expand Up @@ -40,21 +40,17 @@ pub(crate) fn on_remove_disabled(
#[derive(Component, Default, Debug)]
pub struct Pressed;

/// Component that indicates whether a checkbox or radio button is in a checked state.
/// Component that indicates that a widget can be checked.
#[derive(Component, Default, Debug)]
#[component(immutable)]
pub struct Checked(pub bool);
pub struct Checkable;

impl Checked {
/// Returns whether the checkbox or radio button is currently checked.
pub fn get(&self) -> bool {
self.0
}
}
/// Component that indicates whether a checkbox or radio button is in a checked state.
#[derive(Component, Default, Debug)]
pub struct Checked;

pub(crate) fn on_insert_is_checked(trigger: On<Insert, Checked>, mut world: DeferredWorld) {
pub(crate) fn on_add_checkable(trigger: On<Add, Checked>, mut world: DeferredWorld) {
let mut entity = world.entity_mut(trigger.target());
let checked = entity.get::<Checked>().unwrap().get();
let checked = entity.get::<Checked>().is_some();
if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() {
accessibility.set_toggled(match checked {
true => accesskit::Toggled::True,
Expand All @@ -63,7 +59,22 @@ pub(crate) fn on_insert_is_checked(trigger: On<Insert, Checked>, mut world: Defe
}
}

pub(crate) fn on_remove_is_checked(trigger: On<Remove, Checked>, mut world: DeferredWorld) {
pub(crate) fn on_remove_checkable(trigger: On<Add, Checked>, mut world: DeferredWorld) {
// Remove the 'toggled' attribute entirely.
let mut entity = world.entity_mut(trigger.target());
if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() {
accessibility.clear_toggled();
}
}

pub(crate) fn on_add_checked(trigger: On<Add, Checked>, mut world: DeferredWorld) {
let mut entity = world.entity_mut(trigger.target());
if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() {
accessibility.set_toggled(accesskit::Toggled::True);
}
}

pub(crate) fn on_remove_checked(trigger: On<Remove, Checked>, mut world: DeferredWorld) {
let mut entity = world.entity_mut(trigger.target());
if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() {
accessibility.set_toggled(accesskit::Toggled::False);
Expand Down
8 changes: 5 additions & 3 deletions crates/bevy_ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ mod ui_node;
pub use focus::*;
pub use geometry::*;
pub use gradients::*;
pub use interaction_states::{Checked, InteractionDisabled, Pressed};
pub use interaction_states::{Checkable, Checked, InteractionDisabled, Pressed};
pub use layout::*;
pub use measurement::*;
pub use render::*;
Expand Down Expand Up @@ -323,8 +323,10 @@ fn build_text_interop(app: &mut App) {

app.add_observer(interaction_states::on_add_disabled)
.add_observer(interaction_states::on_remove_disabled)
.add_observer(interaction_states::on_insert_is_checked)
.add_observer(interaction_states::on_remove_is_checked);
.add_observer(interaction_states::on_add_checkable)
.add_observer(interaction_states::on_remove_checkable)
.add_observer(interaction_states::on_add_checked)
.add_observer(interaction_states::on_remove_checked);

app.configure_sets(
PostUpdate,
Expand Down
Loading