This commit is contained in:
2026-10-20 20:34:05 -05:00
parent e46a9a2aa9
commit 4607f12756
4 changed files with 500 additions and 34 deletions
+206 -30
View File
@@ -1,8 +1,14 @@
use crate::focus_navigation::{NavigationInputState, NavigationSystems};
use crate::save::{ActiveGameSave, create_game_save, delete_game_save, get_saves};
use crate::{AppState, WINDOW_TARGET_HEIGHT, WINDOW_TARGET_WIDTH};
use bevy::color::palettes::tailwind::SLATE_900;
use bevy::input_focus::tab_navigation::TabIndex;
use bevy::input::gamepad::GamepadButton;
use bevy::input_focus::{
AutoFocus, FocusCause, InputFocus, InputFocusVisible,
tab_navigation::{TabGroup, TabIndex},
};
use bevy::text::{EditableText, EditableTextFilter, TextCursorStyle};
use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation;
use bevy::ui_widgets::Button;
use bevy::{prelude::*, ui_widgets::Activate};
use derive_more::{Deref, DerefMut};
@@ -16,17 +22,24 @@ impl Plugin for MainMenuPlugin {
// .add_systems(Startup, enable_ui_debug)
.add_systems(Update, (menu_redraw).run_if(in_state(AppState::Menu)))
.add_observer(button_activate_observer)
.add_systems(Update, (scale_ui, style_ui_elements));
.add_systems(Update, (scale_ui, style_ui_elements))
.add_systems(
PreUpdate,
focus_rightmost_layer_on_navigation
.in_set(NavigationSystems::Initialize)
.run_if(in_state(AppState::Menu)),
);
}
}
/// The number of layers that the main menu is sized for.
const N_LAYERS: usize = 5;
/// The text field for the name of the game.
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
struct GameNameTextField;
/// A UI object that is selected.
/// A UI object selected by activation, distinct from keyboard/pointer focus.
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
struct Selected;
@@ -39,6 +52,8 @@ pub(crate) struct InteractionColors {
selected: Color,
selected_hovered: Color,
selected_pressed: Color,
pub(crate) default_outline: Color,
pub(crate) focused_outline: Color,
}
impl InteractionColors {
pub const DEFAULT: InteractionColors = InteractionColors {
@@ -48,6 +63,8 @@ impl InteractionColors {
selected: Color::srgb(0.93, 0.66, 0.06),
selected_hovered: Color::srgb(1., 0.74, 0.16),
selected_pressed: Color::srgb(0.86, 0.56, 0.),
default_outline: Color::BLACK,
focused_outline: Color::WHITE,
};
pub const GOOD: InteractionColors = InteractionColors {
default: Color::srgb(0.25, 0.75, 0.25),
@@ -56,6 +73,8 @@ impl InteractionColors {
selected: Color::srgb(0.35, 0.8, 0.35),
selected_hovered: Color::srgb(0.45, 0.9, 0.45),
selected_pressed: Color::srgb(0.25, 0.7, 0.25),
default_outline: Color::BLACK,
focused_outline: Color::WHITE,
};
pub const DANGER: InteractionColors = InteractionColors {
default: Color::srgb(0.75, 0.25, 0.25),
@@ -64,6 +83,8 @@ impl InteractionColors {
selected: Color::srgb(0.8, 0.3, 0.3),
selected_hovered: Color::srgb(0.9, 0.4, 0.4),
selected_pressed: Color::srgb(0.7, 0.2, 0.2),
default_outline: Color::BLACK,
focused_outline: Color::WHITE,
};
}
@@ -322,6 +343,8 @@ fn new_game_menu() -> impl SceneList {
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
@@ -396,6 +419,8 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
@@ -445,6 +470,7 @@ fn menu_layer(layer: usize) -> impl Scene {
bsn! {
Name(name)
Layer(layer)
TabGroup::new(layer as i32)
Node {
width: percent(100.0 / N_LAYERS as f32),
height: percent(100),
@@ -460,6 +486,7 @@ fn full_menu_layer(layer: usize) -> impl Scene {
bsn! {
Name(name)
Layer(layer)
TabGroup::new(-(layer as i32))
Node {
flex_direction: FlexDirection::Column,
align_self: AlignSelf::FlexEnd,
@@ -473,9 +500,10 @@ fn full_menu_layer(layer: usize) -> impl Scene {
fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<dyn Scene> {
let label = label.into();
Box::new(bsn! {
Button
AutoDirectionalNavigation::default()
TabIndex(0)
Node {
width: px(600),
height: px(130),
@@ -527,7 +555,6 @@ fn button_activate_observer(
// push next layer
menu.push(next_layer.0.clone());
// update the buttons so the correct one is selected
for (entity, selected) in q_selected.iter_many(layer_entries) {
if entity == event.entity {
if !selected {
@@ -542,40 +569,28 @@ fn button_activate_observer(
/// Styles the UI elements according to their [`InteractionColors`].
fn style_ui_elements(
mut q_interaction_set: ParamSet<(
Query<
(
&Interaction,
&mut BackgroundColor,
&InteractionColors,
Has<Selected>,
),
(Or<(Changed<Interaction>, Added<Selected>)>, With<Button>),
>,
Query<(&Interaction, &mut BackgroundColor, &InteractionColors)>,
input_focus: Res<InputFocus>,
mut elements: Query<(
Entity,
&Interaction,
&mut BackgroundColor,
&InteractionColors,
Has<Selected>,
)>,
mut removed_selected: RemovedComponents<Selected>,
) {
for (interaction, mut bg, colors, selected) in q_interaction_set.p0().iter_mut() {
let new_color = match (selected, interaction) {
let focused_entity = input_focus.get();
for (entity, interaction, mut bg, colors, selected) in &mut elements {
let new_color = match (selected, *interaction) {
(true, Interaction::Pressed) => colors.selected_pressed,
(true, Interaction::Hovered) => colors.selected_hovered,
(true, Interaction::None) => colors.selected,
(false, Interaction::Pressed) => colors.pressed,
(false, Interaction::Hovered) => colors.hovered,
(false, Interaction::None) if focused_entity == Some(entity) => colors.hovered,
(false, Interaction::None) => colors.default,
};
bg.0 = new_color;
}
// also do entities that have had `Selected` removed
for entity in removed_selected.read() {
if let Ok((interaction, mut bg, colors)) = q_interaction_set.p1().get_mut(entity) {
let new_color = match interaction {
Interaction::Pressed => colors.pressed,
Interaction::Hovered => colors.hovered,
Interaction::None => colors.default,
};
if bg.0 != new_color {
bg.0 = new_color;
}
}
@@ -586,3 +601,164 @@ fn scale_ui(mut ui_scale: ResMut<UiScale>, window: Single<&Window>) {
let scale_factor = f32::min(size.x / WINDOW_TARGET_WIDTH, size.y / WINDOW_TARGET_HEIGHT);
ui_scale.0 = scale_factor;
}
fn focus_rightmost_layer_on_navigation(
keyboard: Res<ButtonInput<KeyCode>>,
gamepads: Query<&Gamepad>,
mut input_focus: ResMut<InputFocus>,
mut input_focus_visible: ResMut<InputFocusVisible>,
mut navigation_input: ResMut<NavigationInputState>,
layers: Query<(Entity, &Layer)>,
children: Query<&Children>,
focusable_entities: Query<(), With<AutoDirectionalNavigation>>,
) {
let navigation_pressed = [
KeyCode::Tab,
KeyCode::ArrowUp,
KeyCode::ArrowDown,
KeyCode::ArrowLeft,
KeyCode::ArrowRight,
]
.into_iter()
.any(|key| keyboard.just_pressed(key))
|| gamepads.iter().any(|gamepad| {
[
GamepadButton::DPadUp,
GamepadButton::DPadDown,
GamepadButton::DPadLeft,
GamepadButton::DPadRight,
]
.into_iter()
.any(|button| gamepad.just_pressed(button))
});
if !navigation_pressed
|| input_focus
.get()
.is_some_and(|focused| focusable_entities.contains(focused))
{
return;
}
let mut rightmost_target = None;
for (entity, layer) in &layers {
if let Some(target) = first_focusable_in_layer(entity, &children, &focusable_entities)
&& rightmost_target.is_none_or(|(rightmost_layer, _)| layer.0 > rightmost_layer)
{
rightmost_target = Some((layer.0, target));
}
}
if let Some((_, target)) = rightmost_target {
input_focus.set(target, FocusCause::Navigated);
input_focus_visible.0 = true;
navigation_input.focus_initialized = true;
}
}
fn first_focusable_in_layer(
entity: Entity,
children: &Query<&Children>,
focusable_entities: &Query<(), With<AutoDirectionalNavigation>>,
) -> Option<Entity> {
if focusable_entities.contains(entity) {
return Some(entity);
}
children
.get(entity)
.ok()?
.iter()
.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);
}
}