upgrade to bevy 0.20

This commit is contained in:
2026-10-20 23:59:48 -05:00
parent 4607f12756
commit 25557d85ce
7 changed files with 1626 additions and 1591 deletions
Generated
+1156 -823
View File
File diff suppressed because it is too large Load Diff
+8 -8
View File
@@ -4,14 +4,14 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
app_dirs2 = "2.5.5" app_dirs2 = "2.5"
bevy = { version = "0.19", features = ["system_clipboard", "debug"] } bevy = { version = "0.20", features = ["system_clipboard", "debug"] }
bevy-inspector-egui = "0.37" bevy-inspector-egui = "0.38"
derive_more = { version = "2.1.1", features = ["deref", "deref_mut"] } derive_more = { version = "2.1", features = ["deref", "deref_mut"] }
jiff = { version = "0.2.35", features = ["serde"] } jiff = { version = "0.2", features = ["serde"] }
ron = "0.12.2" ron = "0.12"
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
xxhash-rust = { version = "0.8.18", features = ["xxh3", "std"] } xxhash-rust = { version = "0.8", features = ["xxh3", "std"] }
[profile.dev] [profile.dev]
opt-level = 1 opt-level = 1
+39 -10
View File
@@ -1,7 +1,11 @@
use bevy::prelude::*;
use bevy_inspector_egui::{bevy_egui::EguiPlugin, quick::ResourceInspectorPlugin};
use crate::lobby::LobbyUiState; use crate::lobby::LobbyUiState;
use bevy::prelude::*;
use bevy_inspector_egui::{
bevy_egui::EguiPlugin,
quick::{ResourceInspectorPlugin, WorldInspectorPlugin},
};
// TODO: compile these in only if debug build
/// Whether the debug inspector is currently shown. /// Whether the debug inspector is currently shown.
#[derive(Resource, Debug, Default)] #[derive(Resource, Debug, Default)]
@@ -13,20 +17,45 @@ impl Plugin for DebugInspectorPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.init_resource::<InspectorEnabled>() app.init_resource::<InspectorEnabled>()
.add_plugins(EguiPlugin::default()) .add_plugins(EguiPlugin::default())
.add_plugins(WorldInspectorPlugin::new())
.add_plugins( .add_plugins(
ResourceInspectorPlugin::<LobbyUiState>::new() ResourceInspectorPlugin::<LobbyUiState>::new()
.run_if(|enabled: Res<InspectorEnabled>| enabled.0), .run_if(|enabled: Res<InspectorEnabled>| enabled.0),
) )
.add_systems(Update, toggle_inspector); .add_systems(Update, (toggle_inspector, toggle_ui_layout_debug));
} }
} }
fn toggle_inspector(keys: Res<ButtonInput<KeyCode>>, mut enabled: ResMut<InspectorEnabled>) { fn toggle_inspector(keys: Res<ButtonInput<KeyCode>>, mut enabled: ResMut<InspectorEnabled>) {
if keys.just_pressed(KeyCode::F1) { if !keys.just_pressed(KeyCode::F1) {
enabled.0 = !enabled.0; return;
info!(
"lobby ui inspector toggled {}",
if enabled.0 { "on" } else { "off" }
);
} }
enabled.0 = !enabled.0;
info!(
"lobby ui inspector toggled {}",
if enabled.0 { "on" } else { "off" }
);
}
fn toggle_ui_layout_debug(
keys: Res<ButtonInput<KeyCode>>,
mut debug_options: ResMut<GlobalUiDebugOptions>,
) {
if !keys.just_pressed(KeyCode::F2) {
return;
}
if debug_options.enabled {
debug_options.enabled = false;
} else {
debug_options.enabled = true;
debug_options.outline_border_box = true;
debug_options.outline_padding_box = true;
debug_options.outline_content_box = true;
}
info!(
"ui layout debug toggled {}",
if debug_options.enabled { "on" } else { "off" }
);
} }
+20 -137
View File
@@ -1,9 +1,8 @@
use crate::main_menu::InteractionColors;
use bevy::{ use bevy::{
input::gamepad::GamepadButton, input::gamepad::GamepadButton,
input_focus::{ input_focus::{
InputFocus, InputFocusSystems, InputFocusVisible, InputFocusSystems, InputFocusVisible, directional_navigation::DirectionalNavigationPlugin,
directional_navigation::DirectionalNavigationPlugin, tab_navigation::TabNavigationPlugin, tab_navigation::TabNavigationPlugin,
}, },
math::{CompassOctant, Dir2}, math::{CompassOctant, Dir2},
prelude::*, prelude::*,
@@ -46,7 +45,7 @@ impl Plugin for FocusNavigationPlugin {
PreUpdate, PreUpdate,
navigate_directionally.in_set(NavigationSystems::Navigate), navigate_directionally.in_set(NavigationSystems::Navigate),
) )
.add_systems(Update, style_focus_outlines) // .add_systems(Update, style_focus_outlines)
.add_observer(show_focus_after_activation); .add_observer(show_focus_after_activation);
} }
} }
@@ -106,137 +105,21 @@ fn show_focus_after_activation(_: On<Activate>, mut focus_visible: ResMut<InputF
focus_visible.0 = true; focus_visible.0 = true;
} }
fn style_focus_outlines( // fn style_focus_outlines(
input_focus: Res<InputFocus>, // input_focus: Res<InputFocus>,
mut outlines: Query<(Entity, &InteractionColors, &mut BorderColor)>, // mut outlines: Query<(Entity, &InteractionColors, &mut BorderColor)>,
) { // ) {
let focused_entity = input_focus.get(); // let focused_entity = input_focus.get();
for (entity, colors, mut border_color) in &mut outlines { // for (entity, colors, mut border_color) in &mut outlines {
let color = if focused_entity == Some(entity) { // let color = if focused_entity == Some(entity) {
colors.focused_outline // colors.focused_outline
} else { // } else {
colors.default_outline // colors.default_outline
}; // };
let new_border_color = BorderColor::all(color); // let new_border_color = BorderColor::all(color);
if *border_color != new_border_color { // if *border_color != new_border_color {
*border_color = new_border_color; // *border_color = new_border_color;
} // }
} // }
} // }
#[cfg(test)]
mod tests {
use super::*;
use bevy::{
camera::NormalizedRenderTarget,
input_focus::{
InputFocus, InputFocusPlugin,
directional_navigation::{DirectionalNavigationMap, DirectionalNavigationPlugin},
tab_navigation::TabIndex,
},
picking::{
backend::HitData,
events::{Pointer, Press},
pointer::{Location, PointerButton, PointerId},
},
window::PrimaryWindow,
};
#[test]
fn clicking_the_window_clears_focus_via_tab_navigation_plugin() {
let mut app = App::new();
app.add_plugins((InputFocusPlugin, TabNavigationPlugin));
let field = app.world_mut().spawn(TabIndex(0)).id();
let window = app
.world_mut()
.spawn((Window::default(), PrimaryWindow))
.id();
app.world_mut()
.insert_resource(InputFocus::from_entity(field));
app.update();
app.world_mut().trigger(Pointer::new(
PointerId::Mouse,
Location {
target: NormalizedRenderTarget::None {
width: 0,
height: 0,
},
position: Vec2::ZERO,
},
Press {
button: PointerButton::Primary,
hit: HitData {
camera: Entity::PLACEHOLDER,
depth: 0.0,
position: None,
normal: None,
extra: None,
},
count: 1,
},
window,
));
app.update();
assert_eq!(app.world().resource::<InputFocus>().get(), None);
}
#[test]
fn arrow_key_moves_focus_with_directional_navigation() {
let mut app = App::new();
app.add_plugins(DirectionalNavigationPlugin);
let current = app.world_mut().spawn_empty().id();
let next = app.world_mut().spawn_empty().id();
app.world_mut()
.insert_resource(InputFocus::from_entity(current));
app.world_mut().insert_resource(InputFocusVisible(false));
app.world_mut().init_resource::<NavigationInputState>();
app.world_mut().init_resource::<ButtonInput<KeyCode>>();
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::ArrowRight);
app.world_mut()
.resource_mut::<DirectionalNavigationMap>()
.add_edge(current, next, CompassOctant::East);
app.add_systems(PreUpdate, navigate_directionally);
app.update();
assert_eq!(app.world().resource::<InputFocus>().get(), Some(next));
assert!(app.world().resource::<InputFocusVisible>().0);
}
#[test]
fn white_outline_tracks_focus_not_hover() {
let mut app = App::new();
let colors = InteractionColors::DEFAULT;
let focused = app
.world_mut()
.spawn((colors.clone(), BorderColor::all(colors.default_outline)))
.id();
let hovered = app
.world_mut()
.spawn((
colors.clone(),
BorderColor::all(colors.default_outline),
Interaction::Hovered,
))
.id();
app.world_mut()
.insert_resource(InputFocus::from_entity(focused));
app.add_systems(Update, style_focus_outlines);
app.update();
assert_eq!(
app.world().get::<BorderColor>(focused).unwrap(),
&BorderColor::all(Color::WHITE)
);
assert_eq!(
app.world().get::<BorderColor>(hovered).unwrap(),
&BorderColor::all(Color::BLACK)
);
}
}
+160 -297
View File
@@ -4,10 +4,11 @@ use bevy::{
AutoFocus, InputFocus, AutoFocus, InputFocus,
tab_navigation::{TabGroup, TabIndex}, tab_navigation::{TabGroup, TabIndex},
}, },
picking::hover::Hovered,
prelude::*, prelude::*,
text::{EditableText, EditableTextFilter, TextCursorStyle}, text::{EditableText, EditableTextFilter, TextCursorStyle},
ui::{Checked, auto_directional_navigation::AutoDirectionalNavigation}, ui::{Checked, Pressed, auto_directional_navigation::AutoDirectionalNavigation},
ui_widgets::{Activate, Button, RadioButton, RadioGroup, ValueChange}, ui_widgets::{Activate, Button, RadioButton, RadioGroup, TextInput, ValueChange},
}; };
use crate::AppState; use crate::AppState;
@@ -130,104 +131,65 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
} }
BackgroundColor(PANEL_BACKGROUND) BackgroundColor(PANEL_BACKGROUND)
Children [ Children [
( Text("Server Settings")
Text("Server Settings") Node {
Node { align_self: AlignSelf::Center,
align_self: AlignSelf::Center, }
} TextFont {
TextFont { font_size: px(76.),
font_size: px(76.), }
} TextColor(TEXT_COLOR)
TextColor(TEXT_COLOR) TextShadow
TextShadow --
), Text("Session Visibility")
( Node {
Text("Session Visibility") margin: UiRect::top(px(24)),
Node { }
margin: UiRect::top(px(24)), TextFont {
} font_size: px(38.),
TextFont { }
font_size: px(38.), TextColor(TEXT_COLOR)
} --
TextColor(TEXT_COLOR) RadioGroup
), AutoFocus
( AutoDirectionalNavigation::default()
RadioGroup Node {
AutoFocus display: Display::Flex,
AutoDirectionalNavigation::default() flex_direction: FlexDirection::Row,
Node { width: percent(100),
display: Display::Flex, height: px(90),
flex_direction: FlexDirection::Row, }
width: percent(100), TabIndex(0)
height: px(90), Children [
} @privacy_option(
TabIndex(0) "Public",
Children [ LobbyPrivacy::Public,
privacy_option( BorderRadius::px(16., 0., 0., 16.),
"Public", )
LobbyPrivacy::Public, --
BorderRadius::px(16., 0., 0., 16.), @privacy_option("Friends Only", LobbyPrivacy::FriendsOnly, BorderRadius::ZERO)
), --
privacy_option("Friends Only", LobbyPrivacy::FriendsOnly, BorderRadius::ZERO), @privacy_option(
privacy_option( "Invite Only",
"Invite Only", LobbyPrivacy::InviteOnly,
LobbyPrivacy::InviteOnly, BorderRadius::px(0., 16., 16., 0.),
BorderRadius::px(0., 16., 16., 0.), )
), ]
] --
), @field_label("Port")
( --
field_label("Port") Node {
), flex_direction: FlexDirection::Row,
( column_gap: px(12),
Node { align_items: AlignItems::Center,
flex_direction: FlexDirection::Row, }
column_gap: px(12), Children [
align_items: AlignItems::Center, @port_field()
} --
Children [
port_field(),
(
Button
ResetPortButton
AutoDirectionalNavigation::default()
TabIndex(2)
Node {
width: px(600),
height: px(130),
border: px(6),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
margin: UiRect::all(px(4)),
}
BorderColor::from(Color::BLACK)
InteractionColors::DEFAULT
Interaction
Children [(
Text("Reset")
TextFont {
font_size: px(66.),
}
TextColor(TEXT_COLOR)
TextShadow
)]
on(|_event: On<Activate>, mut fields: Query<&mut EditableText, With<PortField>>| {
if let Ok(mut field) = fields.single_mut() {
field.editor_mut().set_text("5599");
}
})
),
]
),
(field_label("Password")),
(password_field()),
(
Node {
flex_grow: 1.,
}
),
(
Button Button
ResetPortButton
AutoDirectionalNavigation::default()
TabIndex(2)
Node { Node {
width: px(600), width: px(600),
height: px(130), height: px(130),
@@ -237,24 +199,58 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
margin: UiRect::all(px(4)), margin: UiRect::all(px(4)),
} }
BorderColor::from(Color::BLACK) BorderColor::from(Color::BLACK)
InteractionColors::GOOD InteractionColors::DEFAULT
Interaction Hovered
AutoDirectionalNavigation::default() Children [
TabIndex(4) Text("Reset")
on(|_event: On<Activate>, mut lobby: ResMut<LobbyUiState>| {
info!("Session clicked!");
lobby.session_active = !lobby.session_active;
})
Children [(
Text("Start Session")
SessionStatusLabel
TextFont { TextFont {
font_size: px(66.), font_size: px(66.),
} }
TextColor(TEXT_COLOR) TextColor(TEXT_COLOR)
TextShadow TextShadow
)] ]
), on(|_event: On<Activate>, mut fields: Query<&mut EditableText, With<PortField>>| {
if let Ok(mut field) = fields.single_mut() {
field.editor_mut().set_text("5599");
}
})
]
--
@field_label("Password")
--
@password_field()
--
Node {
flex_grow: 1.,
}
--
Button
Node {
width: px(600),
height: px(130),
border: px(6),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
margin: UiRect::all(px(4)),
}
BorderColor::from(Color::BLACK)
InteractionColors::GOOD
Hovered
AutoDirectionalNavigation::default()
TabIndex(4)
on(|_event: On<Activate>, mut lobby: ResMut<LobbyUiState>| {
info!("Session clicked!");
lobby.session_active = !lobby.session_active;
})
Children [
Text("Start Session")
SessionStatusLabel
TextFont {
font_size: px(66.),
}
TextColor(TEXT_COLOR)
TextShadow
]
] ]
}); });
@@ -269,21 +265,23 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
} }
BackgroundColor(PANEL_BACKGROUND) BackgroundColor(PANEL_BACKGROUND)
Children [ Children [
( Text("Connected Players")
Text("Connected Players") Node {
Node { align_self: AlignSelf::Center,
align_self: AlignSelf::Center, }
} TextFont {
TextFont { font_size: px(76.),
font_size: px(76.), }
} TextColor(TEXT_COLOR)
TextColor(TEXT_COLOR) TextShadow
TextShadow --
), @player_row("Joe (you)")
player_row("Joe (you)"), --
player_row("Alex"), @player_row("Alex")
player_row("Sam"), --
player_row("Taylor"), @player_row("Sam")
--
@player_row("Taylor")
] ]
}); });
} }
@@ -311,6 +309,8 @@ fn port_field() -> impl Scene {
border_radius: BorderRadius::all(px(12)), border_radius: BorderRadius::all(px(12)),
} }
BorderColor::from(SLATE_900) BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText::new("5599") EditableText::new("5599")
EditableText { EditableText {
cursor_width: 0.05, cursor_width: 0.05,
@@ -339,6 +339,8 @@ fn password_field() -> impl Scene {
border_radius: BorderRadius::all(px(12)), border_radius: BorderRadius::all(px(12)),
} }
BorderColor::from(SLATE_900) BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText { EditableText {
cursor_width: 0.05, cursor_width: 0.05,
max_characters: Option::Some(32), max_characters: Option::Some(32),
@@ -370,22 +372,19 @@ fn player_row(name: &'static str) -> impl Scene {
} }
BackgroundColor(OPTION_BACKGROUND) BackgroundColor(OPTION_BACKGROUND)
Children [ Children [
( Node {
Node { width: px(96),
width: px(96), height: px(96),
height: px(96), border_radius: BorderRadius::MAX,
border_radius: BorderRadius::MAX, }
} BackgroundColor(OPTION_SELECTED_BACKGROUND)
BackgroundColor(OPTION_SELECTED_BACKGROUND) --
), Text(name)
( TextFont {
Text(name) font_size: px(50.),
TextFont { }
font_size: px(50.), TextColor(TEXT_COLOR)
} TextShadow
TextColor(TEXT_COLOR)
TextShadow
),
] ]
} }
} }
@@ -414,6 +413,7 @@ fn session_visuals(
return; return;
}; };
// Set color to danger if on stop session
let new_text = match lobby_ui.session_active { let new_text = match lobby_ui.session_active {
true => "Stop Session", true => "Stop Session",
false => "Start Session", false => "Start Session",
@@ -429,7 +429,7 @@ fn privacy_option(
bsn! { bsn! {
RadioButton RadioButton
LobbyPrivacyOption(privacy) LobbyPrivacyOption(privacy)
Interaction Hovered
Node { Node {
display: Display::Flex, display: Display::Flex,
flex_grow: 1., flex_grow: 1.,
@@ -440,13 +440,13 @@ fn privacy_option(
} }
BorderColor::all(OPTION_BORDER_COLOR) BorderColor::all(OPTION_BORDER_COLOR)
BackgroundColor(OPTION_BACKGROUND) BackgroundColor(OPTION_BACKGROUND)
Children [( Children [
Text(label) Text(label)
TextFont { TextFont {
font_size: px(38.0), font_size: px(38.0),
} }
TextColor(OPTION_TEXT_COLOR) TextColor(OPTION_TEXT_COLOR)
)] ]
} }
} }
@@ -454,13 +454,13 @@ fn privacy_option(
fn update_privacy_controls( fn update_privacy_controls(
lobby_ui: Res<LobbyUiState>, lobby_ui: Res<LobbyUiState>,
mut commands: Commands, mut commands: Commands,
options: Query<(Entity, &LobbyPrivacyOption, &Interaction, Has<Checked>), With<RadioButton>>, options: Query<(Entity, &LobbyPrivacyOption, &Hovered, Has<Checked>), With<RadioButton>>,
) { ) {
if !lobby_ui.is_changed() { if !lobby_ui.is_changed() {
return; return;
} }
for (entity, option, interaction, checked) in &options { for (entity, option, hovered, checked) in &options {
let should_be_checked = option.0 == lobby_ui.privacy; let should_be_checked = option.0 == lobby_ui.privacy;
if should_be_checked && !checked { if should_be_checked && !checked {
commands.entity(entity).insert(Checked); commands.entity(entity).insert(Checked);
@@ -468,8 +468,8 @@ fn update_privacy_controls(
commands commands
.entity(entity) .entity(entity)
.remove::<Checked>() .remove::<Checked>()
// Reinserting the interaction will trigger the visual redraw // Reinserting hovered will trigger the visual redraw
.insert(*interaction); .insert(*hovered);
} }
} }
} }
@@ -488,31 +488,29 @@ fn on_privacy_changed(
/// Styles the UI options according to their interactions. /// Styles the UI options according to their interactions.
fn style_privacy_options( fn style_privacy_options(
mut options: Query< mut options: Query<
(&Interaction, Has<Checked>, &mut BackgroundColor), (&Hovered, Has<Pressed>, Has<Checked>, &mut BackgroundColor),
( (
With<LobbyPrivacyOption>, With<LobbyPrivacyOption>,
Or<(Changed<Interaction>, Changed<Checked>)>, Or<(Changed<Hovered>, Changed<Checked>)>,
), ),
>, >,
) { ) {
for (interaction, checked, mut bg) in options.iter_mut() { for (hovered, pressed, checked, mut bg) in options.iter_mut() {
bg.0 = match (checked, *interaction) { bg.0 = match (checked, pressed, hovered.get()) {
// Hovering a selected radio is a no-op (pressing it changes // Hovering a selected radio is a no-op (pressing it changes
// nothing), so it keeps its selected color; pressing it darkens. // nothing), so it keeps its selected color; pressing it darkens.
(true, Interaction::Pressed) => OPTION_SELECTED_PRESSED_BACKGROUND, (true, true, _) => OPTION_SELECTED_PRESSED_BACKGROUND,
(true, _) => OPTION_SELECTED_BACKGROUND, (true, _, _) => OPTION_SELECTED_BACKGROUND,
(false, Interaction::Hovered) => OPTION_HOVERED_BACKGROUND, (false, true, _) => OPTION_SELECTED_PRESSED_BACKGROUND, // TODO: <<<< this is not right
(false, _) => OPTION_BACKGROUND, (false, false, true) => OPTION_HOVERED_BACKGROUND,
(false, false, false) => OPTION_BACKGROUND,
}; };
} }
} }
fn style_lobby_focus( fn style_lobby_focus(
input_focus: Res<InputFocus>, input_focus: Res<InputFocus>,
mut options: Query< mut options: Query<(&ChildOf, &mut BorderColor), With<LobbyPrivacyOption>>,
(&ChildOf, &mut BorderColor),
(With<LobbyPrivacyOption>, Without<InteractionColors>),
>,
) { ) {
let focused_entity = input_focus.get(); let focused_entity = input_focus.get();
@@ -528,138 +526,3 @@ fn style_lobby_focus(
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
fn option(privacy: LobbyPrivacy) -> impl Bundle {
(
RadioButton,
LobbyPrivacyOption(privacy),
BackgroundColor(OPTION_BACKGROUND),
)
}
#[test]
fn autofocus_claims_initial_lobby_focus() {
let mut world = World::new();
world.insert_resource(InputFocus::default());
let radio_group = world.spawn((RadioGroup, AutoFocus)).id();
assert_eq!(world.resource::<InputFocus>().get(), Some(radio_group));
}
#[test]
fn checked_option_is_styled() {
let mut world = World::new();
world.insert_resource(LobbyUiState::default());
let checked = world
.spawn((
option(LobbyPrivacy::Public),
Interaction::default(),
Checked,
))
.id();
let unchecked = world
.spawn((option(LobbyPrivacy::FriendsOnly), Interaction::default()))
.id();
// Regression: without `Interaction` the style system can never match the
// option, so the background stays at the spawn-time color.
let missing_interaction = world.spawn(option(LobbyPrivacy::Public)).id();
let mut schedule = Schedule::default();
schedule.add_systems((update_privacy_controls, style_privacy_options).chain());
schedule.run(&mut world);
let checked_bg = *world.get::<BackgroundColor>(checked).unwrap();
assert_eq!(
checked_bg.0, OPTION_SELECTED_BACKGROUND,
"checked option must be restyled"
);
let unchecked_bg = *world.get::<BackgroundColor>(unchecked).unwrap();
assert_eq!(
unchecked_bg.0, OPTION_BACKGROUND,
"unchecked option must keep its base color"
);
let untouched_bg = *world.get::<BackgroundColor>(missing_interaction).unwrap();
assert_eq!(
untouched_bg.0, OPTION_BACKGROUND,
"option without Interaction is never styled"
);
}
#[test]
fn selected_option_interactions() {
let mut world = World::new();
world.insert_resource(LobbyUiState::default());
let hovered = world
.spawn((option(LobbyPrivacy::Public), Interaction::Hovered, Checked))
.id();
let pressed = world
.spawn((option(LobbyPrivacy::Public), Interaction::Pressed, Checked))
.id();
let mut schedule = Schedule::default();
schedule.add_systems(style_privacy_options);
schedule.run(&mut world);
assert_eq!(
world.get::<BackgroundColor>(hovered).unwrap().0,
OPTION_SELECTED_BACKGROUND,
"selected option must not change on hover"
);
assert_eq!(
world.get::<BackgroundColor>(pressed).unwrap().0,
OPTION_SELECTED_PRESSED_BACKGROUND,
"selected option must darken when pressed"
);
}
#[test]
fn deselected_option_is_restyled() {
let mut world = World::new();
world.insert_resource(LobbyUiState::default());
let first = world
.spawn((
option(LobbyPrivacy::Public),
Interaction::default(),
Checked,
))
.id();
let second = world
.spawn((option(LobbyPrivacy::FriendsOnly), Interaction::default()))
.id();
let mut schedule = Schedule::default();
schedule.add_systems((update_privacy_controls, style_privacy_options).chain());
schedule.run(&mut world);
assert_eq!(
world.get::<BackgroundColor>(first).unwrap().0,
OPTION_SELECTED_BACKGROUND,
"first option must be styled as checked"
);
// Selecting the other option moves the resource; `sync_privacy_options`
// must then move `Checked` and the style system must react to the move.
world.resource_mut::<LobbyUiState>().privacy = LobbyPrivacy::FriendsOnly;
schedule.run(&mut world);
assert_eq!(
world.get::<BackgroundColor>(first).unwrap().0,
OPTION_BACKGROUND,
"deselected option must be restyled to base color"
);
assert_eq!(
world.get::<BackgroundColor>(second).unwrap().0,
OPTION_SELECTED_BACKGROUND,
"newly checked option must be styled as checked"
);
}
}
+2 -3
View File
@@ -1,10 +1,9 @@
use crate::focus_navigation::FocusNavigationPlugin;
use crate::{debug::DebugInspectorPlugin, lobby::LobbyPlugin, save::SavePlugin};
use bevy::{camera::ScalingMode, color::palettes::css::GREEN, prelude::*}; use bevy::{camera::ScalingMode, color::palettes::css::GREEN, prelude::*};
use main_menu::MainMenuPlugin; use main_menu::MainMenuPlugin;
use networking::NetworkingPlugin; use networking::NetworkingPlugin;
use crate::focus_navigation::FocusNavigationPlugin;
use crate::{debug::DebugInspectorPlugin, lobby::LobbyPlugin, save::SavePlugin};
mod debug; mod debug;
mod focus_navigation; mod focus_navigation;
mod lobby; mod lobby;
+241 -313
View File
@@ -7,9 +7,11 @@ use bevy::input_focus::{
AutoFocus, FocusCause, InputFocus, InputFocusVisible, AutoFocus, FocusCause, InputFocus, InputFocusVisible,
tab_navigation::{TabGroup, TabIndex}, tab_navigation::{TabGroup, TabIndex},
}; };
use bevy::picking::hover::Hovered;
use bevy::text::{EditableText, EditableTextFilter, TextCursorStyle}; use bevy::text::{EditableText, EditableTextFilter, TextCursorStyle};
use bevy::ui::Pressed;
use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation; use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation;
use bevy::ui_widgets::Button; use bevy::ui_widgets::{Button, TextInput};
use bevy::{prelude::*, ui_widgets::Activate}; use bevy::{prelude::*, ui_widgets::Activate};
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
@@ -19,7 +21,6 @@ impl Plugin for MainMenuPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Menu), setup_menu) app.add_systems(OnEnter(AppState::Menu), setup_menu)
.add_systems(OnExit(AppState::Menu), cleanup_menu) .add_systems(OnExit(AppState::Menu), cleanup_menu)
// .add_systems(Startup, enable_ui_debug)
.add_systems(Update, (menu_redraw).run_if(in_state(AppState::Menu))) .add_systems(Update, (menu_redraw).run_if(in_state(AppState::Menu)))
.add_observer(button_activate_observer) .add_observer(button_activate_observer)
.add_systems(Update, (scale_ui, style_ui_elements)) .add_systems(Update, (scale_ui, style_ui_elements))
@@ -45,15 +46,15 @@ struct Selected;
/// Defines colors that a UI object should turn when interactions occur. /// Defines colors that a UI object should turn when interactions occur.
#[derive(Component, Clone, PartialEq, Default, Debug)] #[derive(Component, Clone, PartialEq, Default, Debug)]
pub(crate) struct InteractionColors { pub struct InteractionColors {
default: Color, pub default: Color,
hovered: Color, pub hovered: Color,
pressed: Color, pub pressed: Color,
selected: Color, pub selected: Color,
selected_hovered: Color, pub selected_hovered: Color,
selected_pressed: Color, pub selected_pressed: Color,
pub(crate) default_outline: Color, pub default_outline: Color,
pub(crate) focused_outline: Color, pub focused_outline: Color,
} }
impl InteractionColors { impl InteractionColors {
pub const DEFAULT: InteractionColors = InteractionColors { pub const DEFAULT: InteractionColors = InteractionColors {
@@ -122,25 +123,27 @@ impl MenuLayer {
fn render(&self, layer: usize, menu_root: Entity) -> Box<dyn Scene> { fn render(&self, layer: usize, menu_root: Entity) -> Box<dyn Scene> {
match self { match self {
MenuLayer::Root => Box::new(bsn! { MenuLayer::Root => Box::new(bsn! {
menu_layer(layer) @menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
menu_button("Play", Some(MenuLayer::Play)), @menu_button("Play", Some(MenuLayer::Play))
menu_button("Settings", Some(MenuLayer::Settings)), --
( @menu_button("Settings", Some(MenuLayer::Settings))
menu_button("Quit", None) --
@menu_button("Quit", None)
on(|_event: On<Activate>, mut exit: MessageWriter<AppExit>| { exit.write(AppExit::Success); } ) on(|_event: On<Activate>, mut exit: MessageWriter<AppExit>| { exit.write(AppExit::Success); } )
InteractionColors::DANGER InteractionColors::DANGER
),
] ]
}), }),
MenuLayer::Play => Box::new(bsn! { MenuLayer::Play => Box::new(bsn! {
menu_layer(layer) @menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
menu_button("Load Save", Some(MenuLayer::LoadSave)), @menu_button("Load Save", Some(MenuLayer::LoadSave))
menu_button("Browse Games", Some(MenuLayer::Browse)), --
menu_button("Direct Connect", Some(MenuLayer::DirectConnect)), @menu_button("Browse Games", Some(MenuLayer::Browse))
--
@menu_button("Direct Connect", Some(MenuLayer::DirectConnect))
] ]
}), }),
MenuLayer::LoadSave => { MenuLayer::LoadSave => {
@@ -155,40 +158,39 @@ impl MenuLayer {
// TODO: get rid of row gap when many saves are present. // TODO: get rid of row gap when many saves are present.
Box::new(bsn! { Box::new(bsn! {
menu_layer(layer) @menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
{entries}, {entries}
( --
menu_button("New Game", Some(MenuLayer::NewGame)) @menu_button("New Game", Some(MenuLayer::NewGame))
InteractionColors::GOOD InteractionColors::GOOD
),
] ]
}) })
} }
MenuLayer::NewGame => Box::new(bsn! { MenuLayer::NewGame => Box::new(bsn! {
full_menu_layer(layer) @full_menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
{new_game_menu()} {new_game_menu()}
] ]
}), }),
MenuLayer::GameInfo(game) => Box::new(bsn! { MenuLayer::GameInfo(game) => Box::new(bsn! {
full_menu_layer(layer) @full_menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
{game_info_menu(game)} {game_info_menu(game)}
] ]
}), }),
MenuLayer::Browse => Box::new(bsn! { MenuLayer::Browse => Box::new(bsn! {
full_menu_layer(layer) @full_menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
menu_button("Game 1", None) @menu_button("Game 1", None)
] ]
}), }),
MenuLayer::DirectConnect => Box::new(bsn! { MenuLayer::DirectConnect => Box::new(bsn! {
full_menu_layer(layer) @full_menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
// TODO: have IP addr text box here // TODO: have IP addr text box here
@@ -196,22 +198,23 @@ impl MenuLayer {
] ]
}), }),
MenuLayer::Settings => Box::new(bsn! { MenuLayer::Settings => Box::new(bsn! {
menu_layer(layer) @menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
menu_button("Controls", Some(MenuLayer::Controls)), @menu_button("Controls", Some(MenuLayer::Controls))
menu_button("Graphics", Some(MenuLayer::Graphics)), --
@menu_button("Graphics", Some(MenuLayer::Graphics))
] ]
}), }),
MenuLayer::Controls => Box::new(bsn! { MenuLayer::Controls => Box::new(bsn! {
full_menu_layer(layer) @full_menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
Text("Controls..") Text("Controls..")
] ]
}), }),
MenuLayer::Graphics => Box::new(bsn! { MenuLayer::Graphics => Box::new(bsn! {
full_menu_layer(layer) @full_menu_layer(layer)
ChildOf(menu_root) ChildOf(menu_root)
Children [ Children [
Text("Graphics..") Text("Graphics..")
@@ -228,13 +231,6 @@ struct LastMenu(Vec<MenuLayer>);
#[derive(Resource, Debug, Clone, PartialEq, Eq, Hash, Deref, DerefMut)] #[derive(Resource, Debug, Clone, PartialEq, Eq, Hash, Deref, DerefMut)]
struct CurrentMenu(Vec<MenuLayer>); struct CurrentMenu(Vec<MenuLayer>);
// fn enable_ui_debug(mut debug_options: ResMut<GlobalUiDebugOptions>) {
// debug_options.enabled = true;
// debug_options.outline_border_box = true;
// debug_options.outline_padding_box = true;
// debug_options.outline_content_box = true;
// }
fn setup_menu(mut commands: Commands) { fn setup_menu(mut commands: Commands) {
commands.insert_resource(CurrentMenu(vec![MenuLayer::Root])); commands.insert_resource(CurrentMenu(vec![MenuLayer::Root]));
commands.insert_resource(LastMenu(vec![])); commands.insert_resource(LastMenu(vec![]));
@@ -297,172 +293,163 @@ fn menu_redraw(
} }
fn new_game_menu() -> impl SceneList { fn new_game_menu() -> impl SceneList {
bsn_list![ bsn_list! {
( Text("New Game")
Text("New Game") Node {
align_self: AlignSelf::Center,
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(100.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
#NewGameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
--
Node {
margin: UiRect::top(px(48)),
}
Children [
@menu_button("Create", None)
InteractionColors::GOOD
Node { Node {
align_self: AlignSelf::Center, margin: UiRect::left(Val::Auto),
} }
TextFont { on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"), let value = text_field.value();
font_size: px(100.0), info!("Create triggered for: {}", value);
} create_game_save(value.to_string()).unwrap();
TextColor(Color::srgb(0.9, 0.9, 0.9)) // TODO: refresh listing
TextShadow })
), ]
( }
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
#NewGameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
(
Node {
margin: UiRect::top(px(48)),
}
Children [
menu_button("Create", None)
InteractionColors::GOOD
Node {
margin: UiRect::left(Val::Auto),
}
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
let value = text_field.value();
info!("Create triggered for: {}", value);
create_game_save(value.to_string()).unwrap();
// TODO: refresh listing
})
]
),
]
} }
fn game_info_menu(name: impl Into<String>) -> impl SceneList { fn game_info_menu(name: impl Into<String>) -> impl SceneList {
let name = name.into(); let name = name.into();
bsn_list![ bsn_list! {
( #GameInfoTitle
#GameInfoTitle Text("Load Save")
Text("Load Save") Node {
align_self: AlignSelf::Center,
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(100.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
#SaveNameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText::new(name)
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
--
Node {
margin: UiRect::top(px(48)),
}
Children [
@menu_button("Delete", None)
InteractionColors::DANGER
Node { Node {
align_self: AlignSelf::Center, margin: UiRect::right(Val::Auto),
} }
TextFont { on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"), let value = text_field.value();
font_size: px(100.0), info!("Delete triggered for: {}", value);
} delete_game_save(value.to_string()).unwrap();
TextColor(Color::srgb(0.9, 0.9, 0.9)) // TODO: refresh listing
TextShadow })
), --
( // TODO: when the user changed the name of the game, change this to a "rename" button
Text("Save Name") @menu_button("Play", None)
InteractionColors::GOOD
Node { Node {
margin: UiRect::axes(px(12), px(0)), margin: UiRect::left(Val::Auto),
} }
TextFont { on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>, mut commands: Commands, mut app_state: ResMut<NextState<AppState>>| {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"), // TODO: we should definately get this value from an added
font_size: px(66.0), // resource. Call it something like `SelectedGameSave`
} let value = text_field.value().to_string();
TextColor(Color::srgb(0.9, 0.9, 0.9)) info!("Play triggered for: {}", value);
TextShadow commands.insert_resource(ActiveGameSave::new(value));
), app_state.set(AppState::Lobby);
(
#SaveNameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
EditableText::new(name)
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
(
Node {
margin: UiRect::top(px(48)),
}
Children [
(
menu_button("Delete", None)
InteractionColors::DANGER
Node {
margin: UiRect::right(Val::Auto),
}
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
let value = text_field.value();
info!("Delete triggered for: {}", value);
delete_game_save(value.to_string()).unwrap();
// TODO: refresh listing
})
),
(
// TODO: when the user changed the name of the game, change this to a "rename" button
menu_button("Play", None)
InteractionColors::GOOD
Node {
margin: UiRect::left(Val::Auto),
}
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>, mut commands: Commands, mut app_state: ResMut<NextState<AppState>>| {
// TODO: we should definately get this value from an added
// resource. Call it something like `SelectedGameSave`
let value = text_field.value().to_string();
info!("Play triggered for: {}", value);
commands.insert_resource(ActiveGameSave::new(value));
app_state.set(AppState::Lobby);
// TODO: refresh listing // TODO: refresh listing
}) })
), ]
] }
),
]
} }
fn menu_layer(layer: usize) -> impl Scene { fn menu_layer(layer: usize) -> impl Scene {
@@ -500,6 +487,14 @@ fn full_menu_layer(layer: usize) -> impl Scene {
fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<dyn Scene> { fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<dyn Scene> {
let label = label.into(); let label = label.into();
let next_layer: Box<dyn Scene> = if let Some(next_layer) = next_layer {
Box::new(bsn! {
NextLayer(next_layer)
})
} else {
Box::new(bsn! {})
};
Box::new(bsn! { Box::new(bsn! {
Button Button
AutoDirectionalNavigation::default() AutoDirectionalNavigation::default()
@@ -513,11 +508,12 @@ fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<d
align_items: AlignItems::Center, align_items: AlignItems::Center,
margin: UiRect::all(px(4)), margin: UiRect::all(px(4)),
} }
{next_layer.map(|l| template_value(NextLayer(l)))} @next_layer
BorderColor::from(Color::BLACK) BorderColor::from(Color::BLACK)
InteractionColors::DEFAULT InteractionColors::DEFAULT
Interaction // TODO: add interaction component here if neccesary
Children [( Hovered
Children [
Text(label) Text(label)
TextFont { TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"), // font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
@@ -525,7 +521,7 @@ fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<d
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow TextShadow
)] ]
}) })
} }
@@ -555,7 +551,7 @@ fn button_activate_observer(
// push next layer // push next layer
menu.push(next_layer.0.clone()); menu.push(next_layer.0.clone());
for (entity, selected) in q_selected.iter_many(layer_entries) { for (entity, selected) in q_selected.iter_many(layer_entries).matched() {
if entity == event.entity { if entity == event.entity {
if !selected { if !selected {
commands.entity(entity).insert(Selected); commands.entity(entity).insert(Selected);
@@ -570,28 +566,50 @@ fn button_activate_observer(
/// Styles the UI elements according to their [`InteractionColors`]. /// Styles the UI elements according to their [`InteractionColors`].
fn style_ui_elements( fn style_ui_elements(
input_focus: Res<InputFocus>, input_focus: Res<InputFocus>,
mut elements: Query<( mut q_elements: Query<
Entity, (
&Interaction, Entity,
&mut BackgroundColor, Option<&Hovered>,
&InteractionColors, Has<Pressed>,
Has<Selected>, Option<&mut BackgroundColor>,
)>, Option<&mut BorderColor>,
&InteractionColors,
Has<Selected>,
),
Or<(With<BackgroundColor>, With<BorderColor>)>,
>,
) { ) {
let focused_entity = input_focus.get(); let focused_entity = input_focus.get();
for (entity, interaction, mut bg, colors, selected) in &mut elements { for (entity, hovered, pressed, bg, border, colors, selected) in &mut q_elements {
let new_color = match (selected, *interaction) { let is_focused = focused_entity == Some(entity);
(true, Interaction::Pressed) => colors.selected_pressed, // if the entity is focused, its similar to it being hovered.
(true, Interaction::Hovered) => colors.selected_hovered, let hovered = hovered.is_some_and(|h| h.get()) || is_focused;
(true, Interaction::None) => colors.selected,
(false, Interaction::Pressed) => colors.pressed, let new_color = match (selected, pressed, hovered) {
(false, Interaction::Hovered) => colors.hovered, (true, true, _) => colors.selected_pressed,
(false, Interaction::None) if focused_entity == Some(entity) => colors.hovered, (true, false, true) => colors.selected_hovered,
(false, Interaction::None) => colors.default, (true, false, false) => colors.selected,
(false, true, _) => colors.pressed,
(false, false, true) => colors.hovered,
(false, false, false) => colors.default,
}; };
if bg.0 != new_color {
bg.0 = new_color; if let Some(mut border) = border {
if is_focused {
if border.top != colors.focused_outline {
border.set_all(colors.focused_outline);
}
} else {
if border.top != colors.default_outline {
border.set_all(colors.default_outline);
}
}
}
if let Some(mut bg) = bg {
if bg.0 != new_color {
bg.0 = new_color;
}
} }
} }
} }
@@ -602,6 +620,7 @@ fn scale_ui(mut ui_scale: ResMut<UiScale>, window: Single<&Window>) {
ui_scale.0 = scale_factor; ui_scale.0 = scale_factor;
} }
// TODO: generify the inputing of the nav inputs that are in here
fn focus_rightmost_layer_on_navigation( fn focus_rightmost_layer_on_navigation(
keyboard: Res<ButtonInput<KeyCode>>, keyboard: Res<ButtonInput<KeyCode>>,
gamepads: Query<&Gamepad>, gamepads: Query<&Gamepad>,
@@ -671,94 +690,3 @@ fn first_focusable_in_layer(
.iter() .iter()
.find_map(|child| first_focusable_in_layer(child, children, focusable_entities)) .find_map(|child| first_focusable_in_layer(child, children, focusable_entities))
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::focus_navigation::navigate_directionally;
use bevy::{
input_focus::directional_navigation::{
DirectionalNavigationMap, DirectionalNavigationPlugin,
},
math::CompassOctant,
};
#[test]
fn focus_uses_hover_color_while_selected_keeps_selected_color() {
let mut app = App::new();
let colors = InteractionColors::DEFAULT;
let focused = app
.world_mut()
.spawn((
Interaction::None,
BackgroundColor(colors.default),
colors.clone(),
))
.id();
let selected = app
.world_mut()
.spawn((
Interaction::None,
BackgroundColor(colors.default),
colors.clone(),
Selected,
))
.id();
app.world_mut()
.insert_resource(InputFocus::from_entity(focused));
app.add_systems(Update, style_ui_elements);
app.update();
assert_eq!(
app.world().get::<BackgroundColor>(focused).unwrap().0,
colors.hovered
);
assert_eq!(
app.world().get::<BackgroundColor>(selected).unwrap().0,
colors.selected
);
}
#[test]
fn first_directional_input_only_focuses_first_item_in_rightmost_layer() {
let mut app = App::new();
app.add_plugins(DirectionalNavigationPlugin);
let left_layer = app.world_mut().spawn(Layer(0)).id();
app.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(left_layer)));
let right_layer = app.world_mut().spawn(Layer(1)).id();
let first_right_item = app
.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(right_layer)))
.id();
let next_right_item = app
.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(right_layer)))
.id();
app.world_mut().insert_resource(InputFocus::default());
app.world_mut().insert_resource(InputFocusVisible(false));
app.world_mut().init_resource::<NavigationInputState>();
app.world_mut().init_resource::<ButtonInput<KeyCode>>();
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::ArrowRight);
app.world_mut()
.resource_mut::<DirectionalNavigationMap>()
.add_edge(first_right_item, next_right_item, CompassOctant::East);
app.add_systems(
PreUpdate,
(focus_rightmost_layer_on_navigation, navigate_directionally).chain(),
);
app.update();
assert_eq!(
app.world().resource::<InputFocus>().get(),
Some(first_right_item)
);
assert!(app.world().resource::<InputFocusVisible>().0);
}
}