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
483
484
use accesskit::Role;
use bevy_a11y::AccessibilityNode;
use bevy_app::{App, Plugin};
use bevy_ecs::{
    component::Component,
    entity::Entity,
    hierarchy::{ChildOf, Children},
    observer::On,
    query::{Has, With, Without},
    reflect::ReflectComponent,
    system::{Commands, Query},
};
use bevy_input::keyboard::{KeyCode, KeyboardInput};
use bevy_input::ButtonState;
use bevy_input_focus::FocusedInput;
use bevy_picking::events::{
    PointerCancel, PointerClick, PointerDragEnd, PointerPress, PointerRelease,
};
use bevy_reflect::Reflect;
use bevy_ui::{Checkable, Checked, InteractionDisabled, Pressed};

use crate::{ActivateOnPress, ValueChange};

/// Headless widget implementation for a "radio button group". This component is used to group
/// multiple [`RadioButton`] components together, allowing them to behave as a single unit. It
/// implements the tab navigation logic and keyboard shortcuts for radio buttons.
///
/// The [`RadioGroup`] component does not have any state itself, and makes no assumptions about
/// what, if any, value is associated with each radio button, or what Rust type that value might be.
/// Instead, the output of the group is a [`ValueChange`] event whose payload is the entity id of
/// the selected button. This event is emitted whenever a radio button is clicked, or when using
/// the arrow keys while the radio group is focused. The app can then derive the selected value from
/// this using app-specific means, such as accessing a component on the individual buttons.
///
/// The [`RadioGroup`] doesn't actually set the [`Checked`] states directly, that is presumed to
/// happen by the app or via some external data-binding scheme. Typically, each button would be
/// associated with a particular constant value, and would be checked whenever that value is equal
/// to the group's value. This also means that as long as each button's associated value is unique
/// within the group, it should never be the case that more than one button is selected at a time.
///
/// **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, Clone, Default)]
#[require(AccessibilityNode(accesskit::Node::new(Role::RadioGroup)))]
#[derive(Reflect)]
#[reflect(Component)]
pub struct RadioGroup;

/// Headless widget implementation for radio buttons. They can be used independently,
/// but enclosing them in a [`RadioGroup`] widget allows them to behave as a single,
/// mutually exclusive unit.
///
/// According to the WAI-ARIA best practices document, radio buttons should not be focusable,
/// but rather the enclosing group should be focusable.
/// See <https://www.w3.org/WAI/ARIA/apg/patterns/radio>/
///
/// The widget emits a [`ValueChange<bool>`] event with the value `true` whenever it becomes checked,
/// either through a mouse click or when a [`RadioGroup`] checks the widget.
/// If the [`RadioButton`] is focusable, it can also be checked using the `Enter` or `Space` keys,
/// in which case the event will likewise be emitted.
#[derive(Component, Debug, Clone, Default)]
#[require(AccessibilityNode(accesskit::Node::new(Role::RadioButton)), Checkable)]
#[derive(Reflect)]
#[reflect(Component)]
pub struct RadioButton;

fn radio_group_on_key_input(
    mut ev: On<FocusedInput<KeyboardInput>>,
    q_group: Query<(), With<RadioGroup>>,
    q_radio: Query<(Has<Checked>, Has<InteractionDisabled>), With<RadioButton>>,
    q_children: Query<&Children>,
    mut commands: Commands,
) {
    if q_group.contains(ev.focused_entity) {
        let event = &ev.event().input;
        if event.state == ButtonState::Pressed
            && !event.repeat
            && matches!(
                event.key_code,
                KeyCode::ArrowUp
                    | KeyCode::ArrowDown
                    | KeyCode::ArrowLeft
                    | KeyCode::ArrowRight
                    | KeyCode::Home
                    | KeyCode::End
            )
        {
            let key_code = event.key_code;
            ev.propagate(false);

            // Find all radio descendants that are not disabled
            let radio_buttons = q_children
                .iter_descendants(ev.focused_entity)
                .filter_map(|child_id| match q_radio.get(child_id) {
                    Ok((checked, false)) => Some((child_id, checked)),
                    Ok((_, true)) | Err(_) => None,
                })
                .collect::<Vec<_>>();
            if radio_buttons.is_empty() {
                return; // No enabled radio buttons in the group
            }
            let current_index = radio_buttons
                .iter()
                .position(|(_, checked)| *checked)
                .unwrap_or(usize::MAX); // Default to invalid index if none are checked

            let next_index = match key_code {
                KeyCode::ArrowUp | KeyCode::ArrowLeft => {
                    // Navigate to the previous radio button in the group
                    if current_index == 0 || current_index >= radio_buttons.len() {
                        // If we're at the first one, wrap around to the last
                        radio_buttons.len() - 1
                    } else {
                        // Move to the previous one
                        current_index - 1
                    }
                }
                KeyCode::ArrowDown | KeyCode::ArrowRight => {
                    // Navigate to the next radio button in the group
                    if current_index >= radio_buttons.len() - 1 {
                        // If we're at the last one, wrap around to the first
                        0
                    } else {
                        // Move to the next one
                        current_index + 1
                    }
                }
                KeyCode::Home => {
                    // Navigate to the first radio button in the group
                    0
                }
                KeyCode::End => {
                    // Navigate to the last radio button in the group
                    radio_buttons.len() - 1
                }
                _ => {
                    return;
                }
            };

            if current_index == next_index {
                // If the next index is the same as the current, do nothing
                return;
            }

            let (next_id, _) = radio_buttons[next_index];

            // Trigger the value change event on the radio button
            commands.trigger(ValueChange::<bool> {
                source: next_id,
                value: true,
                is_final: true,
            });
            // Trigger the `ValueChange` event for the newly checked radio button on radio group
            commands.trigger(ValueChange::<Entity> {
                source: ev.focused_entity,
                value: next_id,
                is_final: true,
            });
        }
    }
}

// Provides functionality for standalone focusable [`RadioButton`] to react
// on `Space` or `Enter` key press.
fn radio_button_on_key_input(
    mut ev: On<FocusedInput<KeyboardInput>>,
    q_radio_button: Query<(Has<InteractionDisabled>, Has<Checked>), With<RadioButton>>,
    q_group: Query<(), With<RadioGroup>>,
    q_parents: Query<&ChildOf>,
    mut commands: Commands,
) {
    let Ok((disabled, checked)) = q_radio_button.get(ev.focused_entity) else {
        // Not a radio button
        return;
    };

    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);

        // Radio button is disabled or already checked
        if disabled || checked {
            return;
        }

        trigger_radio_button_and_radio_group_value_change(
            ev.focused_entity,
            &q_group,
            &q_parents,
            &mut commands,
        );
    }
}

fn radio_button_on_click(
    mut click: On<PointerClick>,
    q_group: Query<(), With<RadioGroup>>,
    q_radio: Query<
        (Has<InteractionDisabled>, Has<Checked>),
        (With<RadioButton>, Without<ActivateOnPress>),
    >,
    q_parents: Query<&ChildOf>,
    mut commands: Commands,
) {
    let Ok((disabled, checked)) = q_radio.get(click.entity) else {
        // Not a radio button
        return;
    };

    click.propagate(false);

    // Radio button is disabled or already checked
    if disabled || checked {
        return;
    }

    trigger_radio_button_and_radio_group_value_change(
        click.entity,
        &q_group,
        &q_parents,
        &mut commands,
    );
}

fn radio_button_on_pointer_down(
    mut press: On<PointerPress>,
    q_group: Query<(), With<RadioGroup>>,
    mut q_radio: Query<
        (
            Entity,
            Has<InteractionDisabled>,
            Has<Checked>,
            Has<Pressed>,
            Has<ActivateOnPress>,
        ),
        With<RadioButton>,
    >,
    q_parents: Query<&ChildOf>,
    mut commands: Commands,
) {
    if let Ok((radio, disabled, checked, pressed, activate_on_press)) =
        q_radio.get_mut(press.entity)
    {
        press.propagate(false);
        if !disabled && !pressed {
            commands.entity(radio).insert(Pressed);
            if activate_on_press && !checked {
                trigger_radio_button_and_radio_group_value_change(
                    press.entity,
                    &q_group,
                    &q_parents,
                    &mut commands,
                );
            }
        }
    }
}

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

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

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

fn trigger_radio_button_and_radio_group_value_change(
    radio_button: Entity,
    q_group: &Query<(), With<RadioGroup>>,
    q_parents: &Query<&ChildOf>,
    commands: &mut Commands,
) {
    commands.trigger(ValueChange::<bool> {
        source: radio_button,
        value: true,
        is_final: true,
    });

    // Find if radio button is inside radio group
    let radio_group = q_parents
        .iter_ancestors(radio_button)
        .find(|ancestor| q_group.contains(*ancestor));

    // If is inside radio group
    if let Some(radio_group) = radio_group {
        // Trigger event for radio group
        commands.trigger(ValueChange::<Entity> {
            source: radio_group,
            value: radio_button,
            is_final: true,
        });
    }
}

/// Plugin that adds the observers for [`RadioButton`] and [`RadioGroup`] widget.
pub struct RadioGroupPlugin;

impl Plugin for RadioGroupPlugin {
    fn build(&self, app: &mut App) {
        app.add_observer(radio_group_on_key_input)
            .add_observer(radio_button_on_click)
            .add_observer(radio_button_on_key_input)
            .add_observer(radio_button_on_pointer_down)
            .add_observer(radio_button_on_pointer_up)
            .add_observer(radio_button_on_pointer_drag_end)
            .add_observer(radio_button_on_pointer_cancel);
    }
}

/// Observer function which updates the radio buttons in a group in response to a [`ValueChange`] event.
/// This can be used to make the radio buttons automatically update their own states and within
/// the correct radio group when clicked, as opposed to managing the states externally.
pub fn radio_self_update(
    value_change: On<ValueChange<Entity>>,
    q_radio_group: Query<&Children, With<RadioGroup>>,
    q_radio: Query<Entity, With<RadioButton>>,
    mut commands: Commands,
) {
    // Get the children of the source radio group
    let Ok(children) = q_radio_group.get(value_change.source) else {
        return;
    };

    // Iterate the children of this radio group
    let mut iter = q_radio.iter_many(children).matched();
    while let Some(radio) = iter.fetch_next() {
        if radio == value_change.value {
            commands.entity(radio).insert(Checked);
        } else {
            commands.entity(radio).remove::<Checked>();
        }
    }
}

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

    /// Builds a headless app with the radio-group observers plus [`radio_self_update`], so that a
    /// group's `ValueChange<Entity>` moves the [`Checked`] component onto the selected button.
    fn radio_app() -> (App, Entity) {
        let mut app = App::new();
        app.add_plugins((
            InputPlugin,
            InputFocusPlugin,
            TabNavigationPlugin,
            RadioGroupPlugin,
        ));
        app.add_observer(radio_self_update);
        let window = app
            .world_mut()
            .spawn((Window::default(), PrimaryWindow))
            .id();
        app.update();
        (app, window)
    }

    fn window_location(window: Entity) -> Location {
        Location {
            target: bevy_camera::NormalizedRenderTarget::Window(
                WindowRef::Entity(window).normalize(Some(window)).unwrap(),
            ),
            position: Vec2::ZERO,
        }
    }

    /// Triggers the `PointerClick` event, the last event a real click ends with, on `target`.
    fn click_entity(app: &mut App, target: Entity, window: Entity) {
        app.world_mut().trigger(PointerClick {
            entity: target,
            pointer: Pointer::new(PointerId::Mouse, window_location(window)),
            button: PointerButton::Primary,
            hit: HitData::new(window, 0.0, None, None),
            duration: core::time::Duration::from_millis(10),
            count: 1,
        });
        app.update();
    }

    /// Clicking a radio option moves the selection to it. Clicking a different option moves it
    /// again, and the previously-selected option is unchecked (mutual exclusion within the group).
    #[test]
    fn click_moves_radio_selection_within_group() {
        let (mut app, window) = radio_app();
        let group = app.world_mut().spawn((RadioGroup, ChildOf(window))).id();
        let option_a = app.world_mut().spawn((RadioButton, ChildOf(group))).id();
        let option_b = app.world_mut().spawn((RadioButton, ChildOf(group))).id();
        app.update();

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

        click_entity(&mut app, option_a, window);
        assert!(app.world().entity(option_a).contains::<Checked>());
        assert!(!app.world().entity(option_b).contains::<Checked>());

        click_entity(&mut app, option_b, window);
        assert!(
            !app.world().entity(option_a).contains::<Checked>(),
            "selecting another option must uncheck the previous one"
        );
        assert!(app.world().entity(option_b).contains::<Checked>());
    }

    /// Clicking an already-checked radio option leaves it selected (no toggle-off for radios).
    #[test]
    fn clicking_checked_radio_keeps_it_selected() {
        let (mut app, window) = radio_app();
        let group = app.world_mut().spawn((RadioGroup, ChildOf(window))).id();
        let option = app.world_mut().spawn((RadioButton, ChildOf(group))).id();
        app.update();

        click_entity(&mut app, option, window);
        assert!(app.world().entity(option).contains::<Checked>());

        click_entity(&mut app, option, window);
        assert!(
            app.world().entity(option).contains::<Checked>(),
            "clicking an already-selected radio must not deselect it"
        );
    }

    /// A disabled radio option does not become selected on click.
    #[test]
    fn disabled_radio_button_does_not_select() {
        let (mut app, window) = radio_app();
        let group = app.world_mut().spawn((RadioGroup, ChildOf(window))).id();
        let option = app
            .world_mut()
            .spawn((RadioButton, InteractionDisabled, ChildOf(group)))
            .id();
        app.update();

        click_entity(&mut app, option, window);
        assert!(
            !app.world().entity(option).contains::<Checked>(),
            "a disabled radio option must not become selected"
        );
    }
}