bevy_ui_widgets 0.20.0

Unstyled common widgets for Bevy Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use accesskit::Role;
use bevy_a11y::AccessibilityNode;
use bevy_app::{App, Plugin};
use bevy_ecs::event::EntityEvent;
use bevy_ecs::query::{Has, With, Without};
use bevy_ecs::system::ResMut;
use bevy_ecs::{
    component::Component,
    observer::On,
    reflect::{ReflectComponent, ReflectEvent},
    system::{Commands, Query},
};
use bevy_input::keyboard::{KeyCode, KeyboardInput};
use bevy_input::ButtonState;
use bevy_input_focus::{FocusCause, FocusedInput, InputFocus, InputFocusVisible};
use bevy_picking::events::{
    PointerCancel, PointerClick, PointerDragEnd, PointerPress, PointerRelease,
};
use bevy_reflect::Reflect;
use bevy_ui::{Checkable, Checked, InteractionDisabled, Pressed};

use crate::{ActivateOnPress, ValueChange};
use bevy_ecs::entity::Entity;

/// Headless widget implementation for checkboxes. The [`Checked`] component represents the current
/// state of the checkbox. The widget will emit a [`ValueChange<bool>`] event when clicked, or when
/// the `Enter` or `Space` key is pressed while the checkbox is focused.
///
/// Add the [`checkbox_self_update`] observer watching the entity with this component to automatically add and remove the [`Checked`] component.
///
/// # Toggle switches
///
/// The [`Checkbox`] 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.
///
/// **Note:** For information on how widget state is managed
/// and how to respond to state changes, see the [crate-level documentation].
/// [crate-level documentation]: crate
#[derive(Component, Debug, Default, Clone)]
#[require(AccessibilityNode(accesskit::Node::new(Role::CheckBox)), Checkable)]
#[derive(Reflect)]
#[reflect(Component)]
pub struct Checkbox;

fn checkbox_on_key_input(
    mut ev: On<FocusedInput<KeyboardInput>>,
    q_checkbox: Query<Has<Checked>, (With<Checkbox>, Without<InteractionDisabled>)>,
    mut commands: Commands,
) {
    if let Ok(is_checked) = q_checkbox.get(ev.focused_entity) {
        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);
            commands.trigger(ValueChange {
                source: ev.focused_entity,
                value: !is_checked,
                is_final: true,
            });
        }
    }
}

fn checkbox_on_pointer_click(
    mut click: On<PointerClick>,
    q_checkbox: Query<
        (Has<Checked>, Has<InteractionDisabled>),
        (With<Checkbox>, Without<ActivateOnPress>),
    >,
    mut commands: Commands,
) {
    if let Ok((is_checked, disabled)) = q_checkbox.get(click.entity) {
        click.propagate(false);
        if !disabled {
            commands.trigger(ValueChange {
                source: click.entity,
                value: !is_checked,
                is_final: true,
            });
        }
    }
}

fn checkbox_on_pointer_down(
    mut press: On<PointerPress>,
    mut q_checkbox: Query<
        (
            Entity,
            Has<InteractionDisabled>,
            Has<Checked>,
            Has<Pressed>,
            Has<ActivateOnPress>,
        ),
        With<Checkbox>,
    >,
    focus: Option<ResMut<InputFocus>>,
    focus_visible: Option<ResMut<InputFocusVisible>>,
    mut commands: Commands,
) {
    if let Ok((checkbox, disabled, checked, pressed, activate_on_press)) =
        q_checkbox.get_mut(press.entity)
    {
        // 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.set(press.entity, FocusCause::Pressed);
        }
        if let Some(mut focus_visible) = focus_visible {
            focus_visible.0 = false;
        }

        press.propagate(false);
        if !disabled && !pressed {
            commands.entity(checkbox).insert(Pressed);
            if activate_on_press {
                commands.trigger(ValueChange {
                    source: press.entity,
                    value: !checked,
                    is_final: true,
                });
            }
        }
    }
}

fn checkbox_on_pointer_up(
    mut release: On<PointerRelease>,
    mut q_checkbox: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<Checkbox>>,
    mut commands: Commands,
) {
    if let Ok((checkbox, disabled, pressed)) = q_checkbox.get_mut(release.entity) {
        release.propagate(false);
        if !disabled && pressed {
            commands.entity(checkbox).remove::<Pressed>();
        }
    }
}

fn checkbox_on_pointer_drag_end(
    mut drag_end: On<PointerDragEnd>,
    mut q_checkbox: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<Checkbox>>,
    mut commands: Commands,
) {
    if let Ok((checkbox, disabled, pressed)) = q_checkbox.get_mut(drag_end.entity) {
        drag_end.propagate(false);
        if !disabled && pressed {
            commands.entity(checkbox).remove::<Pressed>();
        }
    }
}

fn checkbox_on_pointer_cancel(
    mut cancel: On<PointerCancel>,
    mut q_checkbox: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<Checkbox>>,
    mut commands: Commands,
) {
    if let Ok((checkbox, disabled, pressed)) = q_checkbox.get_mut(cancel.entity) {
        cancel.propagate(false);
        if !disabled && pressed {
            commands.entity(checkbox).remove::<Pressed>();
        }
    }
}

/// 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_ui_widgets::{Checkbox, SetChecked};
///
/// fn setup(mut commands: Commands) {
///     // Create a checkbox
///     let entity = commands.spawn((
///         Checkbox::default(),
///     )).id();
///
///     // Set to checked
///     commands.trigger(SetChecked { entity, checked: true});
/// }
/// ```
#[derive(EntityEvent, Reflect)]
#[reflect(Event)]
pub struct SetChecked {
    /// The [`Checkbox`] entity to set the "checked" state on.
    pub entity: Entity,
    /// Sets the `checked` state to `true` or `false`.
    pub checked: bool,
}

/// 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_ui_widgets::{Checkbox, ToggleChecked};
///
/// fn setup(mut commands: Commands) {
///     // Create a checkbox
///     let entity = commands.spawn((
///         Checkbox::default(),
///     )).id();
///
///     // Set to checked
///     commands.trigger(ToggleChecked { entity });
/// }
/// ```
#[derive(EntityEvent, Reflect)]
#[reflect(Event)]
pub struct ToggleChecked {
    /// The [`Entity`] of the toggled [`Checkbox`]
    pub entity: Entity,
}

fn checkbox_on_set_checked(
    set_checked: On<SetChecked>,
    q_checkbox: Query<(Has<Checked>, Has<InteractionDisabled>), With<Checkbox>>,
    mut commands: Commands,
) {
    if let Ok((is_checked, disabled)) = q_checkbox.get(set_checked.entity) {
        if disabled {
            return;
        }

        let will_be_checked = set_checked.checked;
        if will_be_checked != is_checked {
            commands.trigger(ValueChange {
                source: set_checked.entity,
                value: will_be_checked,
                is_final: true,
            });
        }
    }
}

fn checkbox_on_toggle_checked(
    toggle_checked: On<ToggleChecked>,
    q_checkbox: Query<(Has<Checked>, Has<InteractionDisabled>), With<Checkbox>>,
    mut commands: Commands,
) {
    if let Ok((is_checked, disabled)) = q_checkbox.get(toggle_checked.entity) {
        if disabled {
            return;
        }

        commands.trigger(ValueChange {
            source: toggle_checked.entity,
            value: !is_checked,
            is_final: true,
        });
    }
}

/// Plugin that adds the observers for the [`Checkbox`] widget.
pub struct CheckboxPlugin;

impl Plugin for CheckboxPlugin {
    fn build(&self, app: &mut App) {
        app.add_observer(checkbox_on_key_input)
            .add_observer(checkbox_on_pointer_click)
            .add_observer(checkbox_on_pointer_down)
            .add_observer(checkbox_on_pointer_up)
            .add_observer(checkbox_on_pointer_drag_end)
            .add_observer(checkbox_on_pointer_cancel)
            .add_observer(checkbox_on_set_checked)
            .add_observer(checkbox_on_toggle_checked);
    }
}

/// Observer function which updates the checkbox value in response to a [`ValueChange`] event.
/// This can be used to make the checkbox automatically update its own state when clicked,
/// as opposed to managing the checkbox state externally.
pub fn checkbox_self_update(value_change: On<ValueChange<bool>>, mut commands: Commands) {
    if value_change.value {
        commands.entity(value_change.source).insert(Checked);
    } else {
        commands.entity(value_change.source).remove::<Checked>();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy_ecs::hierarchy::ChildOf;
    use bevy_input::keyboard::Key;
    use bevy_input::InputPlugin;
    use bevy_input_focus::{
        tab_navigation::{TabIndex, TabNavigationPlugin},
        InputDispatchPlugin, InputFocusPlugin,
    };
    use bevy_math::Vec2;
    use bevy_picking::{backend::HitData, pointer::PointerButton};
    use bevy_picking::{
        events::Pointer,
        pointer::{Location, PointerId},
    };
    use bevy_window::{PrimaryWindow, Window, WindowRef};

    /// Builds a headless app wired the way the `standard_widgets` example is: focus plugins plus the
    /// checkbox observers, with the [`checkbox_self_update`] observer so that a `ValueChange` is
    /// reflected back into the [`Checked`] component (mirroring how the example drives it).
    ///
    /// [`InputDispatchPlugin`] is included so that raw [`KeyboardInput`] messages are dispatched to
    /// the focused entity as `FocusedInput<KeyboardInput>` events (which is how `checkbox_on_key_input`
    /// receives them).
    fn checkbox_app() -> (App, Entity) {
        let mut app = App::new();
        app.add_plugins((
            InputPlugin,
            InputFocusPlugin,
            InputDispatchPlugin,
            TabNavigationPlugin,
            CheckboxPlugin,
        ));
        app.add_observer(checkbox_self_update);
        let window = app
            .world_mut()
            .spawn((Window::default(), PrimaryWindow))
            .id();
        // Resolve initial focus (goes to the primary window).
        app.update();
        (app, window)
    }

    /// A [`Location`] pointing at the primary window; the exact position is irrelevant because these
    /// tests drive the widget observers directly rather than through hit-testing.
    fn window_location(window: Entity) -> Location {
        Location {
            target: bevy_camera::NormalizedRenderTarget::Window(
                WindowRef::Entity(window).normalize(Some(window)).unwrap(),
            ),
            position: Vec2::ZERO,
        }
    }

    fn stub_hit(window: Entity) -> HitData {
        HitData::new(window, 0.0, None, None)
    }

    /// Synthesizes the pointer events a real click produces (`Press` → `Release` → `Click`) on
    /// `target`, mirroring what the picking backend would emit. `target` may be a non-focusable
    /// descendant of the widget; the events bubble up via `ChildOf` just like real pointer events.
    fn click_entity(app: &mut App, target: Entity, window: Entity) {
        let pointer = Pointer::new(PointerId::Mouse, window_location(window));
        let button = PointerButton::Primary;
        app.world_mut().trigger(PointerPress {
            entity: target,
            pointer: pointer.clone(),
            button,
            hit: stub_hit(window),
            count: 1,
        });
        app.world_mut().trigger(PointerRelease {
            entity: target,
            pointer: pointer.clone(),
            button,
            hit: stub_hit(window),
        });
        app.world_mut().trigger(PointerClick {
            entity: target,
            pointer: pointer.clone(),
            button,
            hit: stub_hit(window),
            duration: core::time::Duration::from_millis(10),
            count: 1,
        });
        app.update();
    }

    /// Clicking a checkbox toggles it and gives it focus.
    #[test]
    fn click_toggles_and_focuses_checkbox() {
        let (mut app, window) = checkbox_app();
        let checkbox = app
            .world_mut()
            .spawn((Checkbox, TabIndex(0), ChildOf(window)))
            .id();
        app.update();

        assert!(!app.world().entity(checkbox).contains::<Checked>());

        click_entity(&mut app, checkbox, window);

        assert!(
            app.world().entity(checkbox).contains::<Checked>(),
            "checkbox should toggle to checked on click"
        );
        assert_eq!(
            app.world().resource::<InputFocus>().get(),
            Some(checkbox),
            "checkbox should receive focus on click"
        );

        // A second click toggles it back off.
        click_entity(&mut app, checkbox, window);
        assert!(!app.world().entity(checkbox).contains::<Checked>());
    }

    /// Clicking on a non-focusable child of the checkbox still toggles and
    /// focuses the checkbox root, because both the pointer events and the resulting `AcquireFocus` bubble up to it.
    #[test]
    fn click_on_child_toggles_and_focuses_checkbox_root() {
        let (mut app, window) = checkbox_app();
        let checkbox = app
            .world_mut()
            .spawn((Checkbox, TabIndex(0), ChildOf(window)))
            .id();
        let outer = app.world_mut().spawn(ChildOf(checkbox)).id();
        let inner = app.world_mut().spawn(ChildOf(outer)).id();
        app.update();

        click_entity(&mut app, inner, window);

        assert!(
            app.world().entity(checkbox).contains::<Checked>(),
            "clicking the inner node should toggle the checkbox root"
        );
        assert_eq!(
            app.world().resource::<InputFocus>().get(),
            Some(checkbox),
            "clicking the inner node should focus the checkbox root"
        );
    }

    /// With a checkbox focused, pressing Space toggles it.
    #[test]
    fn space_key_toggles_focused_checkbox() {
        let (mut app, window) = checkbox_app();
        let checkbox = app
            .world_mut()
            .spawn((Checkbox, TabIndex(0), ChildOf(window)))
            .id();
        app.update();

        // Focus the checkbox as Tab navigation would.
        app.world_mut()
            .resource_mut::<InputFocus>()
            .set(checkbox, FocusCause::Navigated);

        // Send a raw Space key press; `InputDispatchPlugin` routes it to the focused entity as a
        // `FocusedInput<KeyboardInput>` event, which `checkbox_on_key_input` handles.
        app.world_mut().write_message(KeyboardInput {
            key_code: KeyCode::Space,
            logical_key: Key::Space,
            state: ButtonState::Pressed,
            text: None,
            repeat: false,
            window,
        });
        app.update();

        assert!(
            app.world().entity(checkbox).contains::<Checked>(),
            "Space should toggle the focused checkbox"
        );
    }

    /// A disabled checkbox does not toggle on click.
    #[test]
    fn disabled_checkbox_does_not_toggle() {
        let (mut app, window) = checkbox_app();
        let checkbox = app
            .world_mut()
            .spawn((Checkbox, InteractionDisabled, TabIndex(0), ChildOf(window)))
            .id();
        app.update();

        click_entity(&mut app, checkbox, window);

        assert!(
            !app.world().entity(checkbox).contains::<Checked>(),
            "a disabled checkbox must not toggle"
        );
    }
}