bevy/examples/helpers/widgets.rs
UkoeHB c2c19e5ae4
Text rework (#15591)
**Ready for review. Examples migration progress: 100%.**

# Objective

- Implement https://github.com/bevyengine/bevy/discussions/15014

## Solution

This implements [cart's
proposal](https://github.com/bevyengine/bevy/discussions/15014#discussioncomment-10574459)
faithfully except for one change. I separated `TextSpan` from
`TextSpan2d` because `TextSpan` needs to require the `GhostNode`
component, which is a `bevy_ui` component only usable by UI.

Extra changes:
- Added `EntityCommands::commands_mut` that returns a mutable reference.
This is a blocker for extension methods that return something other than
`self`. Note that `sickle_ui`'s `UiBuilder::commands` returns a mutable
reference for this reason.

## Testing

- [x] Text examples all work.

---

## Showcase

TODO: showcase-worthy

## Migration Guide

TODO: very breaking

### Accessing text spans by index

Text sections are now text sections on different entities in a
hierarchy, Use the new `TextReader` and `TextWriter` system parameters
to access spans by index.

Before:
```rust
fn refresh_text(mut query: Query<&mut Text, With<TimeText>>, time: Res<Time>) {
    let text = query.single_mut();
    text.sections[1].value = format_time(time.elapsed());
}
```

After:
```rust
fn refresh_text(
    query: Query<Entity, With<TimeText>>,
    mut writer: UiTextWriter,
    time: Res<Time>
) {
    let entity = query.single();
    *writer.text(entity, 1) = format_time(time.elapsed());
}
```

### Iterating text spans

Text spans are now entities in a hierarchy, so the new `UiTextReader`
and `UiTextWriter` system parameters provide ways to iterate that
hierarchy. The `UiTextReader::iter` method will give you a normal
iterator over spans, and `UiTextWriter::for_each` lets you visit each of
the spans.

---------

Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-10-09 18:35:36 +00:00

177 lines
5.6 KiB
Rust

//! Simple widgets for example UI.
use bevy::{ecs::system::EntityCommands, prelude::*};
/// An event that's sent whenever the user changes one of the settings by
/// clicking a radio button.
#[derive(Clone, Event, Deref, DerefMut)]
pub struct WidgetClickEvent<T>(T);
/// A marker component that we place on all widgets that send
/// [`WidgetClickEvent`]s of the given type.
#[derive(Clone, Component, Deref, DerefMut)]
pub struct WidgetClickSender<T>(T)
where
T: Clone + Send + Sync + 'static;
/// A marker component that we place on all radio `Button`s.
#[derive(Clone, Copy, Component)]
pub struct RadioButton;
/// A marker component that we place on all `Text` inside radio buttons.
#[derive(Clone, Copy, Component)]
pub struct RadioButtonText;
/// Returns a [`Style`] appropriate for the outer main UI node.
///
/// This UI is in the bottom left corner and has flex column support
pub fn main_ui_style() -> Style {
Style {
flex_direction: FlexDirection::Column,
position_type: PositionType::Absolute,
row_gap: Val::Px(6.0),
left: Val::Px(10.0),
bottom: Val::Px(10.0),
..default()
}
}
/// Spawns a single radio button that allows configuration of a setting.
///
/// The type parameter specifies the value that will be packaged up and sent in
/// a [`WidgetClickEvent`] when the radio button is clicked.
pub fn spawn_option_button<T>(
parent: &mut ChildBuilder,
option_value: T,
option_name: &str,
is_selected: bool,
is_first: bool,
is_last: bool,
) where
T: Clone + Send + Sync + 'static,
{
let (bg_color, fg_color) = if is_selected {
(Color::WHITE, Color::BLACK)
} else {
(Color::BLACK, Color::WHITE)
};
// Add the button node.
parent
.spawn(ButtonBundle {
style: Style {
border: UiRect::all(Val::Px(1.0)).with_left(if is_first {
Val::Px(1.0)
} else {
Val::Px(0.0)
}),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
padding: UiRect::axes(Val::Px(12.0), Val::Px(6.0)),
..default()
},
border_color: BorderColor(Color::WHITE),
border_radius: BorderRadius::ZERO
.with_left(if is_first { Val::Px(6.0) } else { Val::Px(0.0) })
.with_right(if is_last { Val::Px(6.0) } else { Val::Px(0.0) }),
background_color: BackgroundColor(bg_color),
..default()
})
.insert(RadioButton)
.insert(WidgetClickSender(option_value.clone()))
.with_children(|parent| {
spawn_ui_text(parent, option_name, fg_color)
.insert(RadioButtonText)
.insert(WidgetClickSender(option_value));
});
}
/// Spawns the buttons that allow configuration of a setting.
///
/// The user may change the setting to any one of the labeled `options`. The
/// value of the given type parameter will be packaged up and sent as a
/// [`WidgetClickEvent`] when one of the radio buttons is clicked.
pub fn spawn_option_buttons<T>(parent: &mut ChildBuilder, title: &str, options: &[(T, &str)])
where
T: Clone + Send + Sync + 'static,
{
// Add the parent node for the row.
parent
.spawn(NodeBundle {
style: Style {
align_items: AlignItems::Center,
..default()
},
..default()
})
.with_children(|parent| {
spawn_ui_text(parent, title, Color::BLACK).insert(Style {
width: Val::Px(125.0),
..default()
});
for (option_index, (option_value, option_name)) in options.iter().cloned().enumerate() {
spawn_option_button(
parent,
option_value,
option_name,
option_index == 0,
option_index == 0,
option_index == options.len() - 1,
);
}
});
}
/// Spawns text for the UI.
///
/// Returns the `EntityCommands`, which allow further customization of the text
/// style.
pub fn spawn_ui_text<'a>(
parent: &'a mut ChildBuilder,
label: &str,
color: Color,
) -> EntityCommands<'a> {
parent.spawn((
Text::new(label),
TextStyle {
font_size: 18.0,
color,
..default()
},
))
}
/// Checks for clicks on the radio buttons and sends `RadioButtonChangeEvent`s
/// as necessary.
pub fn handle_ui_interactions<T>(
mut interactions: Query<
(&Interaction, &WidgetClickSender<T>),
(With<Button>, With<RadioButton>),
>,
mut widget_click_events: EventWriter<WidgetClickEvent<T>>,
) where
T: Clone + Send + Sync + 'static,
{
for (interaction, click_event) in interactions.iter_mut() {
if *interaction == Interaction::Pressed {
widget_click_events.send(WidgetClickEvent((**click_event).clone()));
}
}
}
/// Updates the style of the button part of a radio button to reflect its
/// selected status.
pub fn update_ui_radio_button(background_color: &mut BackgroundColor, selected: bool) {
background_color.0 = if selected { Color::WHITE } else { Color::BLACK };
}
/// Updates the style of the label of a radio button to reflect its selected
/// status.
pub fn update_ui_radio_button_text(entity: Entity, writer: &mut UiTextWriter, selected: bool) {
let text_color = if selected { Color::BLACK } else { Color::WHITE };
writer.for_each_style(entity, |mut style| {
style.color = text_color;
});
}