Compare commits

..
4 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
8 changed files with 2082 additions and 1378 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"
[dependencies]
app_dirs2 = "2.5.5"
bevy = { version = "0.19", features = ["system_clipboard", "debug"] }
bevy-inspector-egui = "0.37"
derive_more = { version = "2.1.1", features = ["deref", "deref_mut"] }
jiff = { version = "0.2.35", features = ["serde"] }
ron = "0.12.2"
serde = { version = "1.0.229", features = ["derive"] }
xxhash-rust = { version = "0.8.18", features = ["xxh3", "std"] }
app_dirs2 = "2.5"
bevy = { version = "0.20", features = ["system_clipboard", "debug"] }
bevy-inspector-egui = "0.38"
derive_more = { version = "2.1", features = ["deref", "deref_mut"] }
jiff = { version = "0.2", features = ["serde"] }
ron = "0.12"
serde = { version = "1.0", features = ["derive"] }
xxhash-rust = { version = "0.8", features = ["xxh3", "std"] }
[profile.dev]
opt-level = 1
+34 -5
View File
@@ -1,7 +1,11 @@
use bevy::prelude::*;
use bevy_inspector_egui::{bevy_egui::EguiPlugin, quick::ResourceInspectorPlugin};
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)]
@@ -13,20 +17,45 @@ 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);
.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) {
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;
// }
// }
// }
+298 -200
View File
@@ -1,13 +1,18 @@
use bevy::{
color::palettes::tailwind::SLATE_900,
input_focus::tab_navigation::TabIndex,
input_focus::{
AutoFocus, InputFocus,
tab_navigation::{TabGroup, TabIndex},
},
picking::hover::Hovered,
prelude::*,
text::{EditableText, EditableTextFilter, TextCursorStyle},
ui::Checked,
ui_widgets::{RadioButton, RadioGroup, ValueChange},
ui::{Checked, Pressed, auto_directional_navigation::AutoDirectionalNavigation},
ui_widgets::{Activate, Button, RadioButton, RadioGroup, TextInput, ValueChange},
};
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);
@@ -23,16 +28,23 @@ const OPTION_SELECTED_PRESSED_BACKGROUND: Color = Color::srgb(0.07, 0.36, 0.44);
pub struct LobbyPlugin;
#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq, Reflect)]
#[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::Public,
privacy: LobbyPrivacy::InviteOnly,
port: 5599,
password: String::new(),
session_active: false,
}
}
}
@@ -40,14 +52,26 @@ impl Default for LobbyUiState {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Reflect)]
pub enum LobbyPrivacy {
#[default]
Public,
FriendsOnly,
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 {
fn build(&self, app: &mut App) {
app.init_resource::<LobbyUiState>();
@@ -58,7 +82,14 @@ impl Plugin for LobbyPlugin {
)
.add_systems(
Update,
(update_privacy_controls, style_privacy_options).chain(),
(
update_privacy_controls,
session_visuals,
sync_lobby_fields,
style_privacy_options,
style_lobby_focus,
)
.chain(),
);
app.add_observer(on_privacy_changed);
}
@@ -75,6 +106,7 @@ fn setup_lobby(mut commands: Commands) {
commands.spawn_scene(bsn! {
#LobbyUiRoot
LobbyUiRoot
TabGroup::default()
DespawnOnExit::<AppState>(AppState::Lobby)
Node {
width: percent(100),
@@ -88,138 +120,305 @@ fn setup_lobby(mut commands: Commands) {
fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRoot>>) {
let root_ui = *root_ui;
commands.spawn_scene(bsn! {
ChildOf(root_ui)
Node {
width: percent(50),
flex_direction: FlexDirection::Column,
align_self: AlignSelf::FlexEnd,
flex_grow: 1.,
align_self: AlignSelf::Stretch,
border_radius: BorderRadius::all(px(24)),
padding: Val::all(px(24)),
}
BackgroundColor(PANEL_BACKGROUND)
Children [
(
Text("Server Settings")
Node {
align_self: AlignSelf::Center,
}
TextFont {
font_size: px(100.0),
font_size: px(76.),
}
TextColor(TEXT_COLOR)
TextShadow
),
(
--
Text("Session Visibility")
Node {
margin: UiRect::top(px(24)),
}
TextFont {
font_size: px(38.),
}
TextColor(TEXT_COLOR)
--
RadioGroup
AutoFocus
AutoDirectionalNavigation::default()
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
width: px(900),
height: px(110),
width: percent(100),
height: px(90),
}
TabIndex(0)
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.)),
@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.),
)
]
),
(
Text("Save Name")
--
@field_label("Port")
--
Node {
margin: UiRect::axes(px(12), px(0)),
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: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
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 {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
flex_grow: 1.,
}
BorderColor::from(SLATE_900)
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
--
Button
Node {
width: px(600),
height: px(130),
border: px(6),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
margin: UiRect::all(px(4)),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
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: FontSize::Px(66.),
font_size: px(66.),
}
TextCursorStyle {
color: Color::BLACK
}
TabIndex(0)
BackgroundColor(TEXT_INPUT_BACKGROUND)
),
TextColor(TEXT_COLOR)
TextShadow
]
]
});
commands.spawn_scene(bsn! {
ChildOf(root_ui)
Node {
width: percent(50),
flex_direction: FlexDirection::Column,
align_self: AlignSelf::FlexEnd,
flex_grow: 1.,
align_self: AlignSelf::Stretch,
border_radius: BorderRadius::all(px(24)),
padding: Val::all(px(24)),
}
BackgroundColor(PANEL_BACKGROUND)
Children [
(
Text("Lobby")
Text("Connected Players")
Node {
align_self: AlignSelf::Center,
}
TextFont {
font_size: px(100.0),
font_size: px(76.),
}
TextColor(TEXT_COLOR)
TextShadow
),
(
Text("Save Name")
--
@player_row("Joe (you)")
--
@player_row("Alex")
--
@player_row("Sam")
--
@player_row("Taylor")
]
});
}
fn field_label(label: &'static str) -> impl Scene {
bsn! {
Text(label)
Node {
margin: UiRect::axes(px(12), px(0)),
margin: UiRect::top(px(18)),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
font_size: px(38.),
}
TextColor(TEXT_COLOR)
TextShadow
),
(
}
}
fn port_field() -> impl Scene {
bsn! {
PortField
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::new("5599")
EditableText {
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()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK
color: Color::BLACK,
}
TabIndex(0)
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)
}
}
fn player_row(name: &'static str) -> impl Scene {
bsn! {
Node {
width: percent(100),
height: px(130),
margin: UiRect::top(px(14)),
padding: Val::all(px(16)),
align_items: AlignItems::Center,
column_gap: px(24),
border_radius: BorderRadius::all(px(12)),
}
BackgroundColor(OPTION_BACKGROUND)
Children [
Node {
width: px(96),
height: px(96),
border_radius: BorderRadius::MAX,
}
BackgroundColor(OPTION_SELECTED_BACKGROUND)
--
Text(name)
TextFont {
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(
@@ -230,24 +429,24 @@ fn privacy_option(
bsn! {
RadioButton
LobbyPrivacyOption(privacy)
Interaction
Hovered
Node {
display: Display::Flex,
flex_grow: 1.,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
border: UiRect::all(px(3)),
border: UiRect::all(px(4)),
border_radius,
}
BorderColor::all(OPTION_BORDER_COLOR)
BackgroundColor(OPTION_BACKGROUND)
Children [(
Children [
Text(label)
TextFont {
font_size: px(38.0),
}
TextColor(OPTION_TEXT_COLOR)
)]
]
}
}
@@ -255,9 +454,13 @@ fn privacy_option(
fn update_privacy_controls(
lobby_ui: Res<LobbyUiState>,
mut commands: Commands,
options: Query<(Entity, &LobbyPrivacyOption, &Interaction, Has<Checked>), With<RadioButton>>,
options: Query<(Entity, &LobbyPrivacyOption, &Hovered, Has<Checked>), With<RadioButton>>,
) {
for (entity, option, interaction, checked) in &options {
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);
@@ -265,8 +468,8 @@ fn update_privacy_controls(
commands
.entity(entity)
.remove::<Checked>()
// Reinserting the interaction will trigger the visual redraw
.insert(*interaction);
// Reinserting hovered will trigger the visual redraw
.insert(*hovered);
}
}
}
@@ -285,146 +488,41 @@ fn on_privacy_changed(
/// Styles the UI options according to their interactions.
fn style_privacy_options(
mut options: Query<
(&Interaction, Has<Checked>, &mut BackgroundColor),
(&Hovered, Has<Pressed>, Has<Checked>, &mut BackgroundColor),
(
With<LobbyPrivacyOption>,
Or<(Changed<Interaction>, Changed<Checked>)>,
Or<(Changed<Hovered>, Changed<Checked>)>,
),
>,
) {
for (interaction, checked, mut bg) in options.iter_mut() {
bg.0 = match (checked, *interaction) {
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, Interaction::Pressed) => OPTION_SELECTED_PRESSED_BACKGROUND,
(true, _) => OPTION_SELECTED_BACKGROUND,
(false, Interaction::Hovered) => OPTION_HOVERED_BACKGROUND,
(false, _) => OPTION_BACKGROUND,
(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,
};
}
}
#[cfg(test)]
mod tests {
use super::*;
fn style_lobby_focus(
input_focus: Res<InputFocus>,
mut options: Query<(&ChildOf, &mut BorderColor), With<LobbyPrivacyOption>>,
) {
let focused_entity = input_focus.get();
fn option(privacy: LobbyPrivacy) -> impl Bundle {
(
RadioButton,
LobbyPrivacyOption(privacy),
BackgroundColor(OPTION_BACKGROUND),
)
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;
}
#[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"
);
}
}
+5 -2
View File
@@ -1,14 +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 main_menu::MainMenuPlugin;
use networking::NetworkingPlugin;
use crate::{debug::DebugInspectorPlugin, lobby::LobbyPlugin, save::SavePlugin};
mod debug;
mod focus_navigation;
mod lobby;
mod main_menu;
mod networking;
mod save;
mod ui_logic;
// TODO: pull from cargo.toml or something?
pub const CURRENT_GAME_VERSION: &str = "v0.0.1";
@@ -32,6 +34,7 @@ fn main() {
App::new()
.add_plugins((
DefaultPlugins,
FocusNavigationPlugin,
MainMenuPlugin,
NetworkingPlugin,
SavePlugin,
+155 -151
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::{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::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::ui_widgets::Button;
use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation;
use bevy::ui_widgets::{Button, TextInput};
use bevy::{prelude::*, ui_widgets::Activate};
use derive_more::{Deref, DerefMut};
@@ -13,60 +21,25 @@ impl Plugin for MainMenuPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Menu), setup_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_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.
#[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
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
struct MenuRoot;
@@ -101,25 +74,27 @@ impl MenuLayer {
fn render(&self, layer: usize, menu_root: Entity) -> Box<dyn Scene> {
match self {
MenuLayer::Root => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Play", Some(MenuLayer::Play)),
menu_button("Settings", Some(MenuLayer::Settings)),
(
menu_button("Quit", None)
@menu_button("Play", Some(MenuLayer::Play))
--
@menu_button("Settings", Some(MenuLayer::Settings))
--
@menu_button("Quit", None)
on(|_event: On<Activate>, mut exit: MessageWriter<AppExit>| { exit.write(AppExit::Success); } )
InteractionColors::DANGER
),
]
}),
MenuLayer::Play => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Load Save", Some(MenuLayer::LoadSave)),
menu_button("Browse Games", Some(MenuLayer::Browse)),
menu_button("Direct Connect", Some(MenuLayer::DirectConnect)),
@menu_button("Load Save", Some(MenuLayer::LoadSave))
--
@menu_button("Browse Games", Some(MenuLayer::Browse))
--
@menu_button("Direct Connect", Some(MenuLayer::DirectConnect))
]
}),
MenuLayer::LoadSave => {
@@ -134,40 +109,39 @@ impl MenuLayer {
// TODO: get rid of row gap when many saves are present.
Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
{entries}
(
menu_button("New Game", Some(MenuLayer::NewGame))
--
@menu_button("New Game", Some(MenuLayer::NewGame))
InteractionColors::GOOD
),
]
})
}
MenuLayer::NewGame => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
{new_game_menu()}
]
}),
MenuLayer::GameInfo(game) => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
{game_info_menu(game)}
]
}),
MenuLayer::Browse => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Game 1", None),
@menu_button("Game 1", None)
]
}),
MenuLayer::DirectConnect => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
// TODO: have IP addr text box here
@@ -175,22 +149,23 @@ impl MenuLayer {
]
}),
MenuLayer::Settings => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Controls", Some(MenuLayer::Controls)),
menu_button("Graphics", Some(MenuLayer::Graphics)),
@menu_button("Controls", Some(MenuLayer::Controls))
--
@menu_button("Graphics", Some(MenuLayer::Graphics))
]
}),
MenuLayer::Controls => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
Text("Controls..")
]
}),
MenuLayer::Graphics => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
Text("Graphics..")
@@ -207,13 +182,6 @@ struct LastMenu(Vec<MenuLayer>);
#[derive(Resource, Debug, Clone, PartialEq, Eq, Hash, Deref, DerefMut)]
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) {
commands.insert_resource(CurrentMenu(vec![MenuLayer::Root]));
commands.insert_resource(LastMenu(vec![]));
@@ -276,8 +244,7 @@ fn menu_redraw(
}
fn new_game_menu() -> impl SceneList {
bsn_list![
(
bsn_list! {
Text("New Game")
Node {
align_self: AlignSelf::Center,
@@ -288,8 +255,7 @@ fn new_game_menu() -> impl SceneList {
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
--
Text("Save Name")
Node {
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))
TextShadow
),
(
--
#NewGameTextField
GameNameTextField
Node {
@@ -310,6 +275,8 @@ fn new_game_menu() -> impl SceneList {
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
@@ -320,17 +287,18 @@ fn new_game_menu() -> impl SceneList {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK
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)
@menu_button("Create", None)
InteractionColors::GOOD
Node {
margin: UiRect::left(Val::Auto),
@@ -342,14 +310,12 @@ fn new_game_menu() -> impl SceneList {
// TODO: refresh listing
})
]
),
]
}
}
fn game_info_menu(name: impl Into<String>) -> impl SceneList {
let name = name.into();
bsn_list![
(
bsn_list! {
#GameInfoTitle
Text("Load Save")
Node {
@@ -361,8 +327,7 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
--
Text("Save Name")
Node {
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))
TextShadow
),
(
--
#SaveNameTextField
GameNameTextField
Node {
@@ -383,6 +347,8 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText::new(name)
EditableText {
cursor_width: 0.05,
@@ -394,18 +360,18 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK
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)
@menu_button("Delete", None)
InteractionColors::DANGER
Node {
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();
// TODO: refresh listing
})
),
(
--
// 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
Node {
margin: UiRect::left(Val::Auto),
@@ -434,10 +399,8 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
// TODO: refresh listing
})
)
]
),
]
}
}
fn menu_layer(layer: usize) -> impl Scene {
@@ -445,6 +408,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 +424,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 +438,18 @@ 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();
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! {
Button
AutoDirectionalNavigation::default()
TabIndex(0)
Node {
width: px(600),
height: px(130),
@@ -485,11 +459,12 @@ fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<d
align_items: AlignItems::Center,
margin: UiRect::all(px(4)),
}
{next_layer.map(|l| template_value(NextLayer(l)))}
@next_layer
BorderColor::from(Color::BLACK)
InteractionColors::DEFAULT
Interaction
Children [(
// TODO: add interaction component here if neccesary
Hovered
Children [
Text(label)
TextFont {
// 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))
TextShadow
)]
]
})
}
fn button_activate_observer(
event: On<Activate>,
mut commands: Commands,
mut menu: ResMut<CurrentMenu>,
menu: Option<ResMut<CurrentMenu>>,
q_next_layer: Query<(&NextLayer, &ChildOf)>,
q_layer: Query<(&Layer, &Children)>,
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) {
let Ok((layer, layer_entries)) = q_layer.get(parent.parent()) else {
warn!(
@@ -524,8 +502,10 @@ 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) {
// TODO: This custom "selected" logic, where there is one selected button
// 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 !selected {
commands.entity(entity).insert(Selected);
@@ -537,49 +517,73 @@ 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)>,
)>,
mut removed_selected: RemovedComponents<Selected>,
// TODO: generify the inputing of the nav inputs that are in here
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>>,
) {
for (interaction, mut bg, colors, selected) in q_interaction_set.p0().iter_mut() {
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) => colors.default,
};
bg.0 = new_color;
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;
}
// 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,
};
bg.0 = new_color;
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 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;
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;
}