bevy/examples/ui/display_and_visibility.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

477 lines
20 KiB
Rust

//! Demonstrates how Display and Visibility work in the UI.
use bevy::{
color::palettes::css::{DARK_GRAY, YELLOW},
prelude::*,
winit::WinitSettings,
};
const PALETTE: [&str; 4] = ["27496D", "466B7A", "669DB3", "ADCBE3"];
const HIDDEN_COLOR: Color = Color::srgb(1.0, 0.7, 0.7);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// 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_systems(
Update,
(
buttons_handler::<Display>,
buttons_handler::<Visibility>,
text_hover,
),
)
.run();
}
#[derive(Component)]
struct Target<T> {
id: Entity,
phantom: std::marker::PhantomData<T>,
}
impl<T> Target<T> {
fn new(id: Entity) -> Self {
Self {
id,
phantom: std::marker::PhantomData,
}
}
}
trait TargetUpdate {
type TargetComponent: Component;
const NAME: &'static str;
fn update_target(&self, target: &mut Self::TargetComponent) -> String;
}
impl TargetUpdate for Target<Display> {
type TargetComponent = Style;
const NAME: &'static str = "Display";
fn update_target(&self, style: &mut Self::TargetComponent) -> String {
style.display = match style.display {
Display::Flex => Display::None,
Display::None => Display::Flex,
Display::Block | Display::Grid => unreachable!(),
};
format!("{}::{:?} ", Self::NAME, style.display)
}
}
impl TargetUpdate for Target<Visibility> {
type TargetComponent = Visibility;
const NAME: &'static str = "Visibility";
fn update_target(&self, visibility: &mut Self::TargetComponent) -> String {
*visibility = match *visibility {
Visibility::Inherited => Visibility::Visible,
Visibility::Visible => Visibility::Hidden,
Visibility::Hidden => Visibility::Inherited,
};
format!("{}::{visibility:?}", Self::NAME)
}
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let palette: [Color; 4] = PALETTE.map(|hex| Srgba::hex(hex).unwrap().into());
let text_style = TextStyle {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default()
};
commands.spawn(Camera2d);
commands.spawn(NodeBundle {
style: Style {
width: Val::Percent(100.),
height: Val::Percent(100.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
justify_content: JustifyContent::SpaceEvenly,
..Default::default()
},
background_color: BackgroundColor(Color::BLACK),
..Default::default()
}).with_children(|parent| {
parent.spawn((Text::new("Use the panel on the right to change the Display and Visibility properties for the respective nodes of the panel on the left"),
text_style.clone(),
TextBlock::new_with_justify(JustifyText::Center),
Style {
margin: UiRect::bottom(Val::Px(10.)),
..Default::default()
},
));
parent
.spawn(NodeBundle {
style: Style {
width: Val::Percent(100.),
..Default::default()
},
..Default::default()
})
.with_children(|parent| {
let mut target_ids = vec![];
parent.spawn(NodeBundle {
style: Style {
width: Val::Percent(50.),
height: Val::Px(520.),
justify_content: JustifyContent::Center,
..Default::default()
},
..Default::default()
}).with_children(|parent| {
target_ids = spawn_left_panel(parent, &palette);
});
parent.spawn(NodeBundle {
style: Style {
width: Val::Percent(50.),
justify_content: JustifyContent::Center,
..Default::default()
},
..Default::default()
}).with_children(|parent| {
spawn_right_panel(parent, text_style, &palette, target_ids);
});
});
parent.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Row,
align_items: AlignItems::Start,
justify_content: JustifyContent::Start,
column_gap: Val::Px(10.),
..Default::default()
},
..default() })
.with_children(|builder| {
let text_style = TextStyle {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default()
};
builder.spawn((Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"),
TextStyle { color: HIDDEN_COLOR, ..text_style.clone() },
TextBlock::new_with_justify(JustifyText::Center),
));
builder.spawn((Text::new("-\n-\n-"),
TextStyle { color: DARK_GRAY.into(), ..text_style.clone() },
TextBlock::new_with_justify(JustifyText::Center),
));
builder.spawn((Text::new("The UI Node and its descendants will not be visible and will not be allotted any space in the UI layout.\nThe UI Node will not be visible but will still occupy space in the UI layout.\nThe UI node will inherit the visibility property of its parent. If it has no parent it will be visible."),
text_style
));
});
});
}
fn spawn_left_panel(builder: &mut ChildBuilder, palette: &[Color; 4]) -> Vec<Entity> {
let mut target_ids = vec![];
builder
.spawn(NodeBundle {
style: Style {
padding: UiRect::all(Val::Px(10.)),
..Default::default()
},
background_color: BackgroundColor(Color::WHITE),
..Default::default()
})
.with_children(|parent| {
parent
.spawn(NodeBundle {
background_color: BackgroundColor(Color::BLACK),
..Default::default()
})
.with_children(|parent| {
let id = parent
.spawn(NodeBundle {
style: Style {
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..Default::default()
},
background_color: BackgroundColor(palette[0]),
..Default::default()
})
.with_children(|parent| {
parent.spawn(NodeBundle {
style: Style {
width: Val::Px(100.),
height: Val::Px(500.),
..Default::default()
},
..Default::default()
});
let id = parent
.spawn(NodeBundle {
style: Style {
height: Val::Px(400.),
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..Default::default()
},
background_color: BackgroundColor(palette[1]),
..Default::default()
})
.with_children(|parent| {
parent.spawn(NodeBundle {
style: Style {
width: Val::Px(100.),
height: Val::Px(400.),
..Default::default()
},
..Default::default()
});
let id = parent
.spawn(NodeBundle {
style: Style {
height: Val::Px(300.),
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..Default::default()
},
background_color: BackgroundColor(palette[2]),
..Default::default()
})
.with_children(|parent| {
parent.spawn(NodeBundle {
style: Style {
width: Val::Px(100.),
height: Val::Px(300.),
..Default::default()
},
..Default::default()
});
let id = parent
.spawn(NodeBundle {
style: Style {
width: Val::Px(200.),
height: Val::Px(200.),
..Default::default()
},
background_color: BackgroundColor(palette[3]),
..Default::default()
})
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
});
});
target_ids
}
fn spawn_right_panel(
parent: &mut ChildBuilder,
text_style: TextStyle,
palette: &[Color; 4],
mut target_ids: Vec<Entity>,
) {
let spawn_buttons = |parent: &mut ChildBuilder, target_id| {
spawn_button::<Display>(parent, text_style.clone(), target_id);
spawn_button::<Visibility>(parent, text_style.clone(), target_id);
};
parent
.spawn(NodeBundle {
style: Style {
padding: UiRect::all(Val::Px(10.)),
..Default::default()
},
background_color: BackgroundColor(Color::WHITE),
..Default::default()
})
.with_children(|parent| {
parent
.spawn(NodeBundle {
style: Style {
width: Val::Px(500.),
height: Val::Px(500.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..Default::default()
},
..Default::default()
},
background_color: BackgroundColor(palette[0]),
..Default::default()
})
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn(NodeBundle {
style: Style {
width: Val::Px(400.),
height: Val::Px(400.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..Default::default()
},
..Default::default()
},
background_color: BackgroundColor(palette[1]),
..Default::default()
})
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn(NodeBundle {
style: Style {
width: Val::Px(300.),
height: Val::Px(300.),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..Default::default()
},
..Default::default()
},
background_color: BackgroundColor(palette[2]),
..Default::default()
})
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn(NodeBundle {
style: Style {
width: Val::Px(200.),
height: Val::Px(200.),
align_items: AlignItems::FlexStart,
justify_content: JustifyContent::SpaceBetween,
flex_direction: FlexDirection::Column,
padding: UiRect {
left: Val::Px(5.),
top: Val::Px(5.),
..Default::default()
},
..Default::default()
},
background_color: BackgroundColor(palette[3]),
..Default::default()
})
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent.spawn(NodeBundle {
style: Style {
width: Val::Px(100.),
height: Val::Px(100.),
..Default::default()
},
..Default::default()
});
});
});
});
});
});
}
fn spawn_button<T>(parent: &mut ChildBuilder, text_style: TextStyle, target: Entity)
where
T: Default + std::fmt::Debug + Send + Sync + 'static,
Target<T>: TargetUpdate,
{
parent
.spawn((
ButtonBundle {
style: Style {
align_self: AlignSelf::FlexStart,
padding: UiRect::axes(Val::Px(5.), Val::Px(1.)),
..Default::default()
},
background_color: Color::BLACK.with_alpha(0.5).into(),
..Default::default()
},
Target::<T>::new(target),
))
.with_children(|builder| {
builder.spawn((
Text(format!("{}::{:?}", Target::<T>::NAME, T::default())),
text_style,
TextBlock::new_with_justify(JustifyText::Center),
));
});
}
fn buttons_handler<T>(
mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
mut text_query: Query<(&mut Text, &mut TextStyle)>,
) where
T: Send + Sync,
Target<T>: TargetUpdate + Component,
{
for (target, interaction, children) in visibility_button_query.iter_mut() {
if matches!(interaction, Interaction::Pressed) {
let mut target_value = left_panel_query.get_mut(target.id).unwrap();
for &child in children {
if let Ok((mut text, mut style)) = text_query.get_mut(child) {
**text = target.update_target(target_value.as_mut());
style.color = if text.contains("None") || text.contains("Hidden") {
Color::srgb(1.0, 0.7, 0.7)
} else {
Color::WHITE
};
}
}
}
}
}
fn text_hover(
mut button_query: Query<(&Interaction, &mut BackgroundColor, &Children), Changed<Interaction>>,
mut text_query: Query<(&Text, &mut TextStyle)>,
) {
for (interaction, mut color, children) in button_query.iter_mut() {
match interaction {
Interaction::Hovered => {
*color = Color::BLACK.with_alpha(0.6).into();
for &child in children {
if let Ok((_, mut style)) = text_query.get_mut(child) {
// Bypass change detection to avoid recomputation of the text when only changing the color
style.bypass_change_detection().color = YELLOW.into();
}
}
}
_ => {
*color = Color::BLACK.with_alpha(0.5).into();
for &child in children {
if let Ok((text, mut style)) = text_query.get_mut(child) {
style.bypass_change_detection().color =
if text.contains("None") || text.contains("Hidden") {
HIDDEN_COLOR
} else {
Color::WHITE
};
}
}
}
}
}
}