Compare commits

...
6 Commits
Author SHA1 Message Date
mitchell 66fb0b4e23 refactor ui logic and impl 2026-10-21 00:21:01 -05:00
mitchell 25557d85ce upgrade to bevy 0.20 2026-10-20 23:59:48 -05:00
mitchell 4607f12756 ui focus 2026-10-20 20:34:05 -05:00
mitchell e46a9a2aa9 loby ui impl 2026-10-20 16:41:16 -05:00
mitchell 41a523d2e3 fix the lobby privacy radio 2026-09-18 00:11:19 -05:00
mitchell df95653b86 work on lobby ui 2026-09-17 15:59:47 -05:00
8 changed files with 2593 additions and 1183 deletions
Generated
+1539 -751
View File
File diff suppressed because it is too large Load Diff
+8 -7
View File
@@ -4,13 +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"] }
derive_more = { version = "2.1.1", features = ["deref", "deref_mut"] } bevy-inspector-egui = "0.38"
jiff = { version = "0.2.35", features = ["serde"] } derive_more = { version = "2.1", features = ["deref", "deref_mut"] }
ron = "0.12.2" jiff = { version = "0.2", features = ["serde"] }
serde = { version = "1.0.229", features = ["derive"] } ron = "0.12"
xxhash-rust = { version = "0.8.18", features = ["xxh3", "std"] } serde = { version = "1.0", features = ["derive"] }
xxhash-rust = { version = "0.8", features = ["xxh3", "std"] }
[profile.dev] [profile.dev]
opt-level = 1 opt-level = 1
+61
View File
@@ -0,0 +1,61 @@
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.
#[derive(Resource, Debug, Default)]
pub struct InspectorEnabled(bool);
pub struct DebugInspectorPlugin;
impl Plugin for DebugInspectorPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<InspectorEnabled>()
.add_plugins(EguiPlugin::default())
.add_plugins(WorldInspectorPlugin::new())
.add_plugins(
ResourceInspectorPlugin::<LobbyUiState>::new()
.run_if(|enabled: Res<InspectorEnabled>| enabled.0),
)
.add_systems(Update, (toggle_inspector, toggle_ui_layout_debug));
}
}
fn toggle_inspector(keys: Res<ButtonInput<KeyCode>>, mut enabled: ResMut<InspectorEnabled>) {
if !keys.just_pressed(KeyCode::F1) {
return;
}
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" }
);
}
+128
View File
@@ -0,0 +1,128 @@
use bevy::{
input::gamepad::GamepadButton,
input_focus::{
InputFocusSystems, InputFocusVisible, directional_navigation::DirectionalNavigationPlugin,
tab_navigation::TabNavigationPlugin,
},
math::{CompassOctant, Dir2},
prelude::*,
text::EditableText,
ui::{InteractionDisabled, auto_directional_navigation::AutoDirectionalNavigator},
ui_widgets::{Activate, Button, RadioGroup},
};
/// Orders initial focus selection before directional movement in `PreUpdate`.
#[derive(SystemSet, Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) enum NavigationSystems {
/// Selects the active menu layer's first focusable item when navigation starts without focus.
Initialize,
/// Applies arrow-key and D-pad movement after focus initialization.
Navigate,
}
/// Prevents the input that initializes focus from also moving it directionally.
#[derive(Resource, Default)]
pub(crate) struct NavigationInputState {
/// Set by the initializer and consumed by the directional-navigation system in the same frame.
///
/// This is so that the action that creates a focus can be ignored and used only to set
/// the focus to something.
pub(crate) focus_initialized: bool,
}
/// Installs Bevy focus, tab, and directional navigation for the application's UI.
pub struct FocusNavigationPlugin;
impl Plugin for FocusNavigationPlugin {
fn build(&self, app: &mut App) {
app.add_plugins((TabNavigationPlugin, DirectionalNavigationPlugin))
.insert_resource(InputFocusVisible(true))
.init_resource::<NavigationInputState>()
.configure_sets(
PreUpdate,
(NavigationSystems::Initialize, NavigationSystems::Navigate)
.chain()
.after(InputFocusSystems::Dispatch),
)
.add_systems(
PreUpdate,
navigate_directionally.in_set(NavigationSystems::Navigate),
)
// .add_systems(Update, style_focus_outlines)
.add_observer(show_focus_after_activation);
}
}
pub(crate) fn navigate_directionally(
keyboard: Res<ButtonInput<KeyCode>>,
gamepads: Query<&Gamepad>,
mut navigator: AutoDirectionalNavigator,
editable_texts: Query<(), With<EditableText>>,
radio_groups: Query<(), With<RadioGroup>>,
focusable_buttons: Query<(), (With<Button>, Without<InteractionDisabled>)>,
mut focus_visible: ResMut<InputFocusVisible>,
mut navigation_input: ResMut<NavigationInputState>,
mut commands: Commands,
) {
if std::mem::take(&mut navigation_input.focus_initialized) {
return;
}
let any_gamepad_pressed = |button| gamepads.iter().any(|gamepad| gamepad.just_pressed(button));
let focused_entity = navigator.input_focus();
let keyboard_navigation_enabled = focused_entity
.is_some_and(|entity| !editable_texts.contains(entity) && !radio_groups.contains(entity));
let mut horizontal = 0_i8;
let mut vertical = 0_i8;
if keyboard_navigation_enabled {
horizontal += i8::from(keyboard.just_pressed(KeyCode::ArrowRight));
horizontal -= i8::from(keyboard.just_pressed(KeyCode::ArrowLeft));
vertical += i8::from(keyboard.just_pressed(KeyCode::ArrowUp));
vertical -= i8::from(keyboard.just_pressed(KeyCode::ArrowDown));
}
horizontal += i8::from(any_gamepad_pressed(GamepadButton::DPadRight));
horizontal -= i8::from(any_gamepad_pressed(GamepadButton::DPadLeft));
vertical += i8::from(any_gamepad_pressed(GamepadButton::DPadUp));
vertical -= i8::from(any_gamepad_pressed(GamepadButton::DPadDown));
if let Some(direction) = Dir2::from_xy(horizontal as f32, vertical as f32)
.ok()
.map(CompassOctant::from)
&& navigator.navigate(direction).is_ok()
{
focus_visible.0 = true;
}
if any_gamepad_pressed(GamepadButton::South)
&& let Some(focused_entity) = navigator.input_focus()
&& focusable_buttons.contains(focused_entity)
{
commands.trigger(Activate {
entity: focused_entity,
});
}
}
fn show_focus_after_activation(_: On<Activate>, mut focus_visible: ResMut<InputFocusVisible>) {
focus_visible.0 = true;
}
// fn style_focus_outlines(
// input_focus: Res<InputFocus>,
// mut outlines: Query<(Entity, &InteractionColors, &mut BorderColor)>,
// ) {
// let focused_entity = input_focus.get();
// for (entity, colors, mut border_color) in &mut outlines {
// let color = if focused_entity == Some(entity) {
// colors.focused_outline
// } else {
// colors.default_outline
// };
// let new_border_color = BorderColor::all(color);
// if *border_color != new_border_color {
// *border_color = new_border_color;
// }
// }
// }
+418 -104
View File
@@ -1,21 +1,97 @@
use bevy::{ use bevy::{
color::palettes::tailwind::SLATE_900, color::palettes::tailwind::SLATE_900,
input_focus::tab_navigation::TabIndex, input_focus::{
AutoFocus, InputFocus,
tab_navigation::{TabGroup, TabIndex},
},
picking::hover::Hovered,
prelude::*, prelude::*,
text::{EditableText, EditableTextFilter, TextCursorStyle}, text::{EditableText, EditableTextFilter, TextCursorStyle},
ui_widgets::{RadioButton, RadioGroup}, ui::{Checked, Pressed, auto_directional_navigation::AutoDirectionalNavigation},
ui_widgets::{Activate, Button, RadioButton, RadioGroup, TextInput, ValueChange},
}; };
use crate::AppState; use crate::AppState;
use crate::ui_logic::InteractionColors;
const PANEL_BACKGROUND: Color = Color::srgb(0.4, 0.4, 0.4);
const TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
const TEXT_INPUT_BACKGROUND: Color = Color::srgb(0.48, 0.84, 0.87);
const OPTION_BORDER_COLOR: Color = Color::srgb(0.12, 0.16, 0.22);
const OPTION_TEXT_COLOR: Color = Color::srgb(0.92, 0.94, 0.98);
const OPTION_BACKGROUND: Color = Color::srgb(0.18, 0.22, 0.29);
const OPTION_HOVERED_BACKGROUND: Color = Color::srgb(0.26, 0.33, 0.42);
const OPTION_SELECTED_BACKGROUND: Color = Color::srgb(0.08, 0.42, 0.52);
const OPTION_SELECTED_PRESSED_BACKGROUND: Color = Color::srgb(0.07, 0.36, 0.44);
pub struct LobbyPlugin; pub struct LobbyPlugin;
#[derive(Resource, Debug, Clone, PartialEq, Eq, Reflect)]
#[reflect(Resource)]
pub struct LobbyUiState {
pub privacy: LobbyPrivacy,
pub port: u16,
pub password: String,
// TODO: replace with actual connection logic
pub session_active: bool,
}
impl Default for LobbyUiState {
fn default() -> Self {
Self {
privacy: LobbyPrivacy::InviteOnly,
port: 5599,
password: String::new(),
session_active: false,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Reflect)]
pub enum LobbyPrivacy {
#[default]
InviteOnly,
FriendsOnly,
Public,
}
#[derive(Component, Debug, Clone, Copy, Default, PartialEq, Eq)]
struct LobbyPrivacyOption(LobbyPrivacy);
#[derive(Component, Clone, Default)]
struct PortField;
#[derive(Component, Clone, Default)]
struct PasswordField;
#[derive(Component, Clone, Default)]
struct ResetPortButton;
#[derive(Component, Clone, Default)]
struct SessionStatusLabel;
impl Plugin for LobbyPlugin { impl Plugin for LobbyPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.init_resource::<LobbyUiState>();
app.register_type::<LobbyUiState>();
app.add_systems( app.add_systems(
OnEnter(AppState::Lobby), OnEnter(AppState::Lobby),
(setup_lobby, build_lobby_ui).chain(), (setup_lobby, build_lobby_ui).chain(),
)
.add_systems(
Update,
(
update_privacy_controls,
session_visuals,
sync_lobby_fields,
style_privacy_options,
style_lobby_focus,
)
.chain(),
); );
app.add_observer(on_privacy_changed);
} }
} }
@@ -24,9 +100,13 @@ impl Plugin for LobbyPlugin {
struct LobbyUiRoot; struct LobbyUiRoot;
fn setup_lobby(mut commands: Commands) { fn setup_lobby(mut commands: Commands) {
// TODO: build from whatever info we have from the loaded save
commands.insert_resource(LobbyUiState::default());
commands.spawn_scene(bsn! { commands.spawn_scene(bsn! {
#LobbyUiRoot #LobbyUiRoot
LobbyUiRoot LobbyUiRoot
TabGroup::default()
DespawnOnExit::<AppState>(AppState::Lobby) DespawnOnExit::<AppState>(AppState::Lobby)
Node { Node {
width: percent(100), width: percent(100),
@@ -40,175 +120,409 @@ fn setup_lobby(mut commands: Commands) {
fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRoot>>) { fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRoot>>) {
let root_ui = *root_ui; let root_ui = *root_ui;
commands.spawn_scene(bsn! { commands.spawn_scene(bsn! {
ChildOf(root_ui) ChildOf(root_ui)
Node { Node {
width: percent(50),
flex_direction: FlexDirection::Column, flex_direction: FlexDirection::Column,
align_self: AlignSelf::FlexEnd, align_self: AlignSelf::Stretch,
flex_grow: 1.,
border_radius: BorderRadius::all(px(24)), border_radius: BorderRadius::all(px(24)),
padding: Val::all(px(24)), padding: Val::all(px(24)),
} }
BackgroundColor(Color::srgb(0.4, 0.4, 0.4)) 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(100.0), font_size: px(76.),
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(TEXT_COLOR)
TextShadow TextShadow
), --
( Text("Session Visibility")
Node {
margin: UiRect::top(px(24)),
}
TextFont {
font_size: px(38.),
}
TextColor(TEXT_COLOR)
--
RadioGroup RadioGroup
AutoFocus
AutoDirectionalNavigation::default()
Node { Node {
display: Display::Flex, display: Display::Flex,
flex_direction: FlexDirection::Column, flex_direction: FlexDirection::Row,
align_items: AlignItems::Start, width: percent(100),
column_gap: px(4), height: px(90),
}
Children [
radio_button(),
]
),
(
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
),
(
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
} }
TabIndex(0) TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87)) Children [
), @privacy_option(
"Public",
LobbyPrivacy::Public,
BorderRadius::px(16., 0., 0., 16.),
)
--
@privacy_option("Friends Only", LobbyPrivacy::FriendsOnly, BorderRadius::ZERO)
--
@privacy_option(
"Invite Only",
LobbyPrivacy::InviteOnly,
BorderRadius::px(0., 16., 16., 0.),
)
]
--
@field_label("Port")
--
Node {
flex_direction: FlexDirection::Row,
column_gap: px(12),
align_items: AlignItems::Center,
}
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
Hovered
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
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
]
] ]
}); });
commands.spawn_scene(bsn! { commands.spawn_scene(bsn! {
ChildOf(root_ui) ChildOf(root_ui)
Node { Node {
width: percent(50),
flex_direction: FlexDirection::Column, flex_direction: FlexDirection::Column,
align_self: AlignSelf::FlexEnd, align_self: AlignSelf::Stretch,
flex_grow: 1.,
border_radius: BorderRadius::all(px(24)), border_radius: BorderRadius::all(px(24)),
padding: Val::all(px(24)), padding: Val::all(px(24)),
} }
BackgroundColor(Color::srgb(0.4, 0.4, 0.4)) BackgroundColor(PANEL_BACKGROUND)
Children [ Children [
( Text("Connected Players")
Text("Lobby")
Node { Node {
align_self: AlignSelf::Center, align_self: AlignSelf::Center,
} }
TextFont { TextFont {
font_size: px(100.0), font_size: px(76.),
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(TEXT_COLOR)
TextShadow TextShadow
), --
( @player_row("Joe (you)")
Text("Save Name") --
@player_row("Alex")
--
@player_row("Sam")
--
@player_row("Taylor")
]
});
}
fn field_label(label: &'static str) -> impl Scene {
bsn! {
Text(label)
Node { Node {
margin: UiRect::axes(px(12), px(0)), margin: UiRect::top(px(18)),
} }
TextFont { TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"), font_size: px(38.),
font_size: px(66.0),
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(TEXT_COLOR)
TextShadow }
), }
(
fn port_field() -> impl Scene {
bsn! {
PortField
Node { Node {
width: percent(100),
border: Val::all(px(6)), border: Val::all(px(6)),
padding: Val::all(px(12)), padding: Val::all(px(12)),
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 { EditableText {
cursor_width: 0.05, cursor_width: 0.05,
max_characters: Option::Some(14), max_characters: Option::Some(5),
} }
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric()) EditableTextFilter::new(|c| c.is_ascii_digit())
TextLayout::no_wrap() TextLayout::no_wrap()
TextFont { TextFont {
font_size: FontSize::Px(66.), font_size: FontSize::Px(66.),
} }
TextCursorStyle { TextCursorStyle {
color: Color::BLACK color: Color::BLACK,
}
AutoDirectionalNavigation::default()
TabIndex(1)
BackgroundColor(TEXT_INPUT_BACKGROUND)
}
}
fn password_field() -> impl Scene {
bsn! {
PasswordField
Node {
width: percent(100),
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(32),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric() || c == '_' || c == '-')
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
TabIndex(3)
BackgroundColor(TEXT_INPUT_BACKGROUND)
} }
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
]
});
} }
fn radio_button() -> impl Scene { fn player_row(name: &'static str) -> impl Scene {
bsn! { bsn! {
RadioButton
Node { Node {
display: Display::Flex, width: percent(100),
flex_direction: FlexDirection::Row, height: px(130),
justify_content: JustifyContent::FlexStart, margin: UiRect::top(px(14)),
padding: Val::all(px(16)),
align_items: AlignItems::Center, align_items: AlignItems::Center,
align_content: AlignContent::Center, column_gap: px(24),
column_gap: px(8), border_radius: BorderRadius::all(px(12)),
} }
BackgroundColor(OPTION_BACKGROUND)
Children [ Children [
#RadioOuter
Node { Node {
display: Display::Flex, width: px(96),
width: px(32), height: px(96),
height: px(32),
border: UiRect::all(px(4)),
border_radius: BorderRadius::MAX, border_radius: BorderRadius::MAX,
} }
BorderColor::all(Color::BLACK) BackgroundColor(OPTION_SELECTED_BACKGROUND)
Children [ --
#RadioInner Text(name)
Node {
display: Display::Flex,
width: px(16),
height: px(16),
position_type: PositionType::Absolute,
left: px(4),
top: px(4),
border_radius: BorderRadius::MAX,
}
BackgroundColor(Color::srgb(0.35, 0.75, 0.35))
],
Text::new("Radio Button")
TextFont { TextFont {
font_size: FontSize::Px(33.0), font_size: px(50.),
} }
TextColor(TEXT_COLOR)
TextShadow
] ]
} }
} }
fn sync_lobby_fields(
port_field: Single<&EditableText, With<PortField>>,
password_field: Single<&EditableText, With<PasswordField>>,
mut lobby: ResMut<LobbyUiState>,
) {
if let Ok(port) = port_field.value().to_string().parse::<u16>() {
lobby.port = port;
}
lobby.password = password_field.value().to_string();
}
fn session_visuals(
lobby_ui: Res<LobbyUiState>,
q_session_control_text: Option<Single<&mut Text, With<SessionStatusLabel>>>,
) {
if !lobby_ui.is_changed() {
return;
}
let Some(mut text) = q_session_control_text else {
warn!("Session Control Text not found!");
return;
};
// Set color to danger if on stop session
let new_text = match lobby_ui.session_active {
true => "Stop Session",
false => "Start Session",
};
**text = new_text.into();
}
fn privacy_option(
label: &'static str,
privacy: LobbyPrivacy,
border_radius: BorderRadius,
) -> impl Scene {
bsn! {
RadioButton
LobbyPrivacyOption(privacy)
Hovered
Node {
display: Display::Flex,
flex_grow: 1.,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
border: UiRect::all(px(4)),
border_radius,
}
BorderColor::all(OPTION_BORDER_COLOR)
BackgroundColor(OPTION_BACKGROUND)
Children [
Text(label)
TextFont {
font_size: px(38.0),
}
TextColor(OPTION_TEXT_COLOR)
]
}
}
/// Updates the privacy control items from the [`LobbyUiState`] resource.
fn update_privacy_controls(
lobby_ui: Res<LobbyUiState>,
mut commands: Commands,
options: Query<(Entity, &LobbyPrivacyOption, &Hovered, Has<Checked>), With<RadioButton>>,
) {
if !lobby_ui.is_changed() {
return;
}
for (entity, option, hovered, checked) in &options {
let should_be_checked = option.0 == lobby_ui.privacy;
if should_be_checked && !checked {
commands.entity(entity).insert(Checked);
} else if !should_be_checked && checked {
commands
.entity(entity)
.remove::<Checked>()
// Reinserting hovered will trigger the visual redraw
.insert(*hovered);
}
}
}
/// Updates the lobby privacy in response to the RadioGroup change.
fn on_privacy_changed(
value_change: On<ValueChange<Entity>>,
options: Query<&LobbyPrivacyOption>,
mut lobby_ui: ResMut<LobbyUiState>,
) {
if let Ok(option) = options.get(value_change.value) {
lobby_ui.privacy = option.0;
}
}
/// Styles the UI options according to their interactions.
fn style_privacy_options(
mut options: Query<
(&Hovered, Has<Pressed>, Has<Checked>, &mut BackgroundColor),
(
With<LobbyPrivacyOption>,
Or<(Changed<Hovered>, Changed<Checked>)>,
),
>,
) {
for (hovered, pressed, checked, mut bg) in options.iter_mut() {
bg.0 = match (checked, pressed, hovered.get()) {
// Hovering a selected radio is a no-op (pressing it changes
// nothing), so it keeps its selected color; pressing it darkens.
(true, true, _) => OPTION_SELECTED_PRESSED_BACKGROUND,
(true, _, _) => OPTION_SELECTED_BACKGROUND,
(false, true, _) => OPTION_SELECTED_PRESSED_BACKGROUND, // TODO: <<<< this is not right
(false, false, true) => OPTION_HOVERED_BACKGROUND,
(false, false, false) => OPTION_BACKGROUND,
};
}
}
fn style_lobby_focus(
input_focus: Res<InputFocus>,
mut options: Query<(&ChildOf, &mut BorderColor), With<LobbyPrivacyOption>>,
) {
let focused_entity = input_focus.get();
for (parent, mut border_color) in &mut options {
let color = if focused_entity == Some(parent.parent()) {
OPTION_TEXT_COLOR
} else {
OPTION_BORDER_COLOR
};
let new_border_color = BorderColor::all(color);
if *border_color != new_border_color {
*border_color = new_border_color;
}
}
}
+7 -2
View File
@@ -1,13 +1,16 @@
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::{lobby::LobbyPlugin, save::SavePlugin}; mod debug;
mod focus_navigation;
mod lobby; mod lobby;
mod main_menu; mod main_menu;
mod networking; mod networking;
mod save; mod save;
mod ui_logic;
// TODO: pull from cargo.toml or something? // TODO: pull from cargo.toml or something?
pub const CURRENT_GAME_VERSION: &str = "v0.0.1"; pub const CURRENT_GAME_VERSION: &str = "v0.0.1";
@@ -31,10 +34,12 @@ fn main() {
App::new() App::new()
.add_plugins(( .add_plugins((
DefaultPlugins, DefaultPlugins,
FocusNavigationPlugin,
MainMenuPlugin, MainMenuPlugin,
NetworkingPlugin, NetworkingPlugin,
SavePlugin, SavePlugin,
LobbyPlugin, LobbyPlugin,
DebugInspectorPlugin,
)) ))
.add_systems(Startup, setup) .add_systems(Startup, setup)
.add_systems(Update, debug_border) .add_systems(Update, debug_border)
+156 -152
View File
@@ -1,9 +1,17 @@
use crate::AppState;
use crate::focus_navigation::{NavigationInputState, NavigationSystems};
use crate::save::{ActiveGameSave, create_game_save, delete_game_save, get_saves}; use crate::save::{ActiveGameSave, create_game_save, delete_game_save, get_saves};
use crate::{AppState, WINDOW_TARGET_HEIGHT, WINDOW_TARGET_WIDTH}; use crate::ui_logic::{InteractionColors, Selected, scale_ui, style_ui_elements};
use bevy::color::palettes::tailwind::SLATE_900; 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::picking::hover::Hovered;
use bevy::text::{EditableText, EditableTextFilter, TextCursorStyle}; use bevy::text::{EditableText, EditableTextFilter, TextCursorStyle};
use bevy::ui_widgets::Button; use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation;
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};
@@ -13,60 +21,25 @@ 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))
.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; const N_LAYERS: usize = 5;
/// The text field for the name of the game. /// The text field for the name of the game.
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)] #[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
struct GameNameTextField; struct GameNameTextField;
/// A UI object that is selected.
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
struct Selected;
/// Defines colors that a UI object should turn when interactions occur.
#[derive(Component, Clone, PartialEq, Default, Debug)]
struct InteractionColors {
default: Color,
hovered: Color,
pressed: Color,
selected: Color,
selected_hovered: Color,
selected_pressed: Color,
}
impl InteractionColors {
pub const DEFAULT: InteractionColors = InteractionColors {
default: Color::srgb(0.25, 0.63, 0.84),
hovered: Color::srgb(0.31, 0.77, 0.93),
pressed: Color::srgb(0.16, 0.55, 0.89),
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.),
};
pub const GOOD: InteractionColors = InteractionColors {
default: Color::srgb(0.25, 0.75, 0.25),
hovered: Color::srgb(0.35, 0.85, 0.35),
pressed: Color::srgb(0.15, 0.65, 0.15),
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),
};
pub const DANGER: InteractionColors = InteractionColors {
default: Color::srgb(0.75, 0.25, 0.25),
hovered: Color::srgb(0.85, 0.35, 0.35),
pressed: Color::srgb(0.65, 0.15, 0.15),
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),
};
}
/// The root of the menu /// The root of the menu
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)] #[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
struct MenuRoot; struct MenuRoot;
@@ -101,25 +74,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 => {
@@ -134,40 +109,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
@@ -175,22 +149,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..")
@@ -207,13 +182,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![]));
@@ -276,8 +244,7 @@ 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 { Node {
align_self: AlignSelf::Center, align_self: AlignSelf::Center,
@@ -288,8 +255,7 @@ fn new_game_menu() -> impl SceneList {
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow TextShadow
), --
(
Text("Save Name") Text("Save Name")
Node { Node {
margin: UiRect::axes(px(12), px(0)), margin: UiRect::axes(px(12), px(0)),
@@ -300,8 +266,7 @@ fn new_game_menu() -> impl SceneList {
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow TextShadow
), --
(
#NewGameTextField #NewGameTextField
GameNameTextField GameNameTextField
Node { Node {
@@ -310,6 +275,8 @@ fn new_game_menu() -> impl SceneList {
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(14), max_characters: Option::Some(14),
@@ -320,17 +287,18 @@ fn new_game_menu() -> impl SceneList {
font_size: FontSize::Px(66.), font_size: FontSize::Px(66.),
} }
TextCursorStyle { TextCursorStyle {
color: Color::BLACK color: Color::BLACK,
} }
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0) TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87)) BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
), --
(
Node { Node {
margin: UiRect::top(px(48)), margin: UiRect::top(px(48)),
} }
Children [ Children [
menu_button("Create", None) @menu_button("Create", None)
InteractionColors::GOOD InteractionColors::GOOD
Node { Node {
margin: UiRect::left(Val::Auto), margin: UiRect::left(Val::Auto),
@@ -342,14 +310,12 @@ fn new_game_menu() -> impl SceneList {
// TODO: refresh listing // 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 { Node {
@@ -361,8 +327,7 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow TextShadow
), --
(
Text("Save Name") Text("Save Name")
Node { Node {
margin: UiRect::axes(px(12), px(0)), margin: UiRect::axes(px(12), px(0)),
@@ -373,8 +338,7 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
} }
TextColor(Color::srgb(0.9, 0.9, 0.9)) TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow TextShadow
), --
(
#SaveNameTextField #SaveNameTextField
GameNameTextField GameNameTextField
Node { Node {
@@ -383,6 +347,8 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
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(name) EditableText::new(name)
EditableText { EditableText {
cursor_width: 0.05, cursor_width: 0.05,
@@ -394,18 +360,18 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
font_size: FontSize::Px(66.), font_size: FontSize::Px(66.),
} }
TextCursorStyle { TextCursorStyle {
color: Color::BLACK color: Color::BLACK,
} }
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0) TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87)) BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
), --
(
Node { Node {
margin: UiRect::top(px(48)), margin: UiRect::top(px(48)),
} }
Children [ Children [
( @menu_button("Delete", None)
menu_button("Delete", None)
InteractionColors::DANGER InteractionColors::DANGER
Node { Node {
margin: UiRect::right(Val::Auto), margin: UiRect::right(Val::Auto),
@@ -416,10 +382,9 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
delete_game_save(value.to_string()).unwrap(); delete_game_save(value.to_string()).unwrap();
// TODO: refresh listing // TODO: refresh listing
}) })
), --
(
// TODO: when the user changed the name of the game, change this to a "rename" button // TODO: when the user changed the name of the game, change this to a "rename" button
menu_button("Play", None) @menu_button("Play", None)
InteractionColors::GOOD InteractionColors::GOOD
Node { Node {
margin: UiRect::left(Val::Auto), margin: UiRect::left(Val::Auto),
@@ -434,17 +399,16 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
// TODO: refresh listing // TODO: refresh listing
}) })
)
]
),
] ]
} }
}
fn menu_layer(layer: usize) -> impl Scene { fn menu_layer(layer: usize) -> impl Scene {
let name = format!("MenuLayer{}", layer); let name = format!("MenuLayer{}", layer);
bsn! { bsn! {
Name(name) Name(name)
Layer(layer) Layer(layer)
TabGroup::new(layer as i32)
Node { Node {
width: percent(100.0 / N_LAYERS as f32), width: percent(100.0 / N_LAYERS as f32),
height: percent(100), height: percent(100),
@@ -460,6 +424,7 @@ fn full_menu_layer(layer: usize) -> impl Scene {
bsn! { bsn! {
Name(name) Name(name)
Layer(layer) Layer(layer)
TabGroup::new(-(layer as i32))
Node { Node {
flex_direction: FlexDirection::Column, flex_direction: FlexDirection::Column,
align_self: AlignSelf::FlexEnd, align_self: AlignSelf::FlexEnd,
@@ -473,9 +438,18 @@ 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()
TabIndex(0)
Node { Node {
width: px(600), width: px(600),
height: px(130), height: px(130),
@@ -485,11 +459,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"),
@@ -497,18 +472,21 @@ 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
)] ]
}) })
} }
fn button_activate_observer( fn button_activate_observer(
event: On<Activate>, event: On<Activate>,
mut commands: Commands, mut commands: Commands,
mut menu: ResMut<CurrentMenu>, menu: Option<ResMut<CurrentMenu>>,
q_next_layer: Query<(&NextLayer, &ChildOf)>, q_next_layer: Query<(&NextLayer, &ChildOf)>,
q_layer: Query<(&Layer, &Children)>, q_layer: Query<(&Layer, &Children)>,
q_selected: Query<(Entity, Has<Selected>)>, q_selected: Query<(Entity, Has<Selected>)>,
) { ) {
let Some(mut menu) = menu else {
return;
};
if let Ok((next_layer, parent)) = q_next_layer.get(event.entity) { if let Ok((next_layer, parent)) = q_next_layer.get(event.entity) {
let Ok((layer, layer_entries)) = q_layer.get(parent.parent()) else { let Ok((layer, layer_entries)) = q_layer.get(parent.parent()) else {
warn!( warn!(
@@ -524,8 +502,10 @@ fn button_activate_observer(
// push next layer // push next layer
menu.push(next_layer.0.clone()); menu.push(next_layer.0.clone());
// update the buttons so the correct one is selected // TODO: This custom "selected" logic, where there is one selected button
for (entity, selected) in q_selected.iter_many(layer_entries) { // on the list of options is a lot like a radio button. Probably should replace
// this custom impl with a modified radio button impl
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);
@@ -537,49 +517,73 @@ fn button_activate_observer(
} }
} }
/// Styles the UI elements according to their [`InteractionColors`]. // TODO: generify the inputing of the nav inputs that are in here
fn style_ui_elements( fn focus_rightmost_layer_on_navigation(
mut q_interaction_set: ParamSet<( keyboard: Res<ButtonInput<KeyCode>>,
Query< gamepads: Query<&Gamepad>,
( mut input_focus: ResMut<InputFocus>,
&Interaction, mut input_focus_visible: ResMut<InputFocusVisible>,
&mut BackgroundColor, mut navigation_input: ResMut<NavigationInputState>,
&InteractionColors, layers: Query<(Entity, &Layer)>,
Has<Selected>, children: Query<&Children>,
), focusable_entities: Query<(), With<AutoDirectionalNavigation>>,
(Or<(Changed<Interaction>, Added<Selected>)>, With<Button>),
>,
Query<(&Interaction, &mut BackgroundColor, &InteractionColors)>,
)>,
mut removed_selected: RemovedComponents<Selected>,
) { ) {
for (interaction, mut bg, colors, selected) in q_interaction_set.p0().iter_mut() { let navigation_pressed = [
let new_color = match (selected, interaction) { KeyCode::Tab,
(true, Interaction::Pressed) => colors.selected_pressed, KeyCode::ArrowUp,
(true, Interaction::Hovered) => colors.selected_hovered, KeyCode::ArrowDown,
(true, Interaction::None) => colors.selected, KeyCode::ArrowLeft,
(false, Interaction::Pressed) => colors.pressed, KeyCode::ArrowRight,
(false, Interaction::Hovered) => colors.hovered, ]
(false, Interaction::None) => colors.default, .into_iter()
}; .any(|key| keyboard.just_pressed(key))
bg.0 = new_color; || 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;
} }
// also do entities that have had `Selected` removed let mut rightmost_target = None;
for entity in removed_selected.read() { for (entity, layer) in &layers {
if let Ok((interaction, mut bg, colors)) = q_interaction_set.p1().get_mut(entity) { if let Some(target) = first_focusable_in_layer(entity, &children, &focusable_entities)
let new_color = match interaction { && rightmost_target.is_none_or(|(rightmost_layer, _)| layer.0 > rightmost_layer)
Interaction::Pressed => colors.pressed, {
Interaction::Hovered => colors.hovered, rightmost_target = Some((layer.0, target));
Interaction::None => colors.default,
};
bg.0 = new_color;
}
} }
} }
fn scale_ui(mut ui_scale: ResMut<UiScale>, window: Single<&Window>) { if let Some((_, target)) = rightmost_target {
let size = window.size(); input_focus.set(target, FocusCause::Navigated);
let scale_factor = f32::min(size.x / WINDOW_TARGET_WIDTH, size.y / WINDOW_TARGET_HEIGHT); input_focus_visible.0 = true;
ui_scale.0 = scale_factor; 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))
} }
+109
View File
@@ -0,0 +1,109 @@
use crate::{WINDOW_TARGET_HEIGHT, WINDOW_TARGET_WIDTH};
use bevy::{input_focus::InputFocus, picking::hover::Hovered, prelude::*, ui::Pressed};
/// A UI object selected by activation, distinct from keyboard/pointer focus.
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
pub struct Selected;
/// Defines colors that a UI object should turn when interactions occur.
#[derive(Component, Clone, PartialEq, Default, Debug)]
pub struct InteractionColors {
pub default: Color,
pub hovered: Color,
pub pressed: Color,
pub selected: Color,
pub selected_hovered: Color,
pub selected_pressed: Color,
pub default_outline: Color,
pub focused_outline: Color,
}
impl InteractionColors {
pub const DEFAULT: InteractionColors = InteractionColors {
default: Color::srgb(0.25, 0.63, 0.84),
hovered: Color::srgb(0.31, 0.77, 0.93),
pressed: Color::srgb(0.16, 0.55, 0.89),
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),
hovered: Color::srgb(0.35, 0.85, 0.35),
pressed: Color::srgb(0.15, 0.65, 0.15),
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),
hovered: Color::srgb(0.85, 0.35, 0.35),
pressed: Color::srgb(0.65, 0.15, 0.15),
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,
};
}
/// Styles the UI elements according to their [`InteractionColors`].
pub fn style_ui_elements(
input_focus: Res<InputFocus>,
mut q_elements: Query<
(
Entity,
Option<&Hovered>,
Has<Pressed>,
Option<&mut BackgroundColor>,
Option<&mut BorderColor>,
&InteractionColors,
Has<Selected>,
),
Or<(With<BackgroundColor>, With<BorderColor>)>,
>,
) {
let focused_entity = input_focus.get();
for (entity, hovered, pressed, bg, border, colors, selected) in &mut q_elements {
let is_focused = focused_entity == Some(entity);
// if the entity is focused, its similar to it being hovered.
let hovered = hovered.is_some_and(|h| h.get()) || is_focused;
let new_color = match (selected, pressed, hovered) {
(true, true, _) => colors.selected_pressed,
(true, false, true) => colors.selected_hovered,
(true, false, false) => colors.selected,
(false, true, _) => colors.pressed,
(false, false, true) => colors.hovered,
(false, false, false) => colors.default,
};
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;
}
}
}
}
pub fn scale_ui(mut ui_scale: ResMut<UiScale>, window: Single<&Window>) {
let size = window.size();
let scale_factor = f32::min(size.x / WINDOW_TARGET_WIDTH, size.y / WINDOW_TARGET_HEIGHT);
ui_scale.0 = scale_factor;
}