Compare commits

...

7 Commits

1
Cargo.lock generated

@ -2226,6 +2226,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"bevy", "bevy",
"bevy_rapier3d", "bevy_rapier3d",
"serde",
] ]
[[package]] [[package]]

@ -43,6 +43,7 @@ path = "bin/chars.rs"
[dependencies] [dependencies]
bevy = "0.11" bevy = "0.11"
bevy_rapier3d = "*" bevy_rapier3d = "*"
serde = "1"
# From rapier docs # From rapier docs
[profile.dev.package.bevy_rapier3d] [profile.dev.package.bevy_rapier3d]

File diff suppressed because it is too large Load Diff

@ -68,140 +68,27 @@ fn spawn_tree(parent: &mut ChildBuilder, pos: UiKitPosition, depth: u8, length:
}; };
(0..length).for_each(|_| { (0..length).for_each(|_| {
parent parent
.spawn(UiKitButton::new(Color::PINK)) .spawn((
UiKitButton { color: Color::PINK },
UiKitSelect::default(),
UiKitLabel {
name: "Button".into(),
},
))
.with_children(|parent| { .with_children(|parent| {
if depth > 1 { if depth > 1 {
parent parent
.spawn(UiKitContainer::new(pos)) .spawn((
UiKitContainer { position: pos },
UiKitSelect::default(),
UiKitLabel { name: "Tab".into() },
))
.with_children(|parent| { .with_children(|parent| {
spawn_tree(parent, pos2, depth - 1, length); spawn_tree(parent, pos2, depth - 1, length);
}); });
} }
}); });
}); });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos))
// .with_children(|parent| {
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos))
// .with_children(|parent| {
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos))
// .with_children(|parent| {
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// parent
// .spawn(UiKitButton::new(Color::PINK))
// .with_children(|parent| {
// parent
// .spawn(UiKitContainer::new(pos2))
// .with_children(|parent| {
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// parent.spawn(UiKitButton::new(Color::PINK));
// });
// });
// });
// });
} }
fn init_ui2(mut commands: Commands) { fn init_ui2(mut commands: Commands) {
@ -226,8 +113,8 @@ fn init_ui2(mut commands: Commands) {
.spawn(ButtonBundle { .spawn(ButtonBundle {
style: Style { style: Style {
border: UiRect::all(Val::Px(1.0)), border: UiRect::all(Val::Px(1.0)),
width: Val::Px(200.0), // width: Val::Px(200.0),
height: Val::Px(150.0), // height: Val::Px(150.0),
align_self: AlignSelf::Center, align_self: AlignSelf::Center,
..default() ..default()
}, },
@ -254,7 +141,7 @@ fn init_ui2(mut commands: Commands) {
..default() ..default()
}) })
.with_children(|parent| { .with_children(|parent| {
spawn_tree(parent, UiKitPosition::Left, 3, 7); spawn_tree(parent, UiKitPosition::Left, 3, 4);
}); });
parent parent
@ -289,7 +176,7 @@ fn init_ui2(mut commands: Commands) {
..default() ..default()
}) })
.with_children(|parent| { .with_children(|parent| {
spawn_tree(parent, UiKitPosition::Top, 3, 7); spawn_tree(parent, UiKitPosition::Top, 3, 3);
}); });
}); });
} }

@ -1,399 +1,605 @@
/// TODO: /// TODO:
/// * Text box w/ clear button /// * Text box w/ "reset" button
/// * Names/Labels management /// * Generic Minimize/Close Components
/// * Button color management /// * Title bar w/ min/close controls
/// * Notice/Warning/Error Popups
/// * Textbox (ReadOnly)
/// * Textbox (ReadWrite)
/// * Move code to submodules /// * Move code to submodules
/// ///
/// BUGS:
/// * When selecting one tree, possible to select another without the first closing.
///
use bevy::{ use bevy::{
input::{ asset::Asset,
keyboard::KeyboardInput, input::mouse::{MouseScrollUnit, MouseWheel},
mouse::{MouseScrollUnit, MouseWheel},
ButtonState,
},
prelude::*, prelude::*,
window::PrimaryWindow, window::PrimaryWindow,
}; };
use std::cmp::PartialEq;
#[derive(Debug, Component, PartialEq)]
pub struct TargetAsset<T: Asset> {
pub handle: Handle<T>,
}
#[derive(Debug, Component, PartialEq)]
pub struct TargetEntity {
pub entity: Entity,
}
pub struct GameUiPlugin; pub struct GameUiPlugin;
impl Plugin for GameUiPlugin { impl Plugin for GameUiPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(Update, (select_tab, select_textbox, text_editor, scroll)) app.add_event::<Alert>()
.add_systems(PostUpdate, selection); .add_systems(Startup, init_alerts)
.add_systems(
Update,
(
create_titles,
manage_titles,
manage_button_interaction,
manage_select_active,
manage_cursor,
manage_scroll,
manage_collapse_hiding,
manage_collapse_active,
show_child_number,
manage_sort,
spawn_alert,
),
)
.add_systems(PostUpdate, close_window);
} }
} }
#[derive(Debug, Bundle)] pub use title::*;
pub struct UiKitContainer { mod title {
node_bundle: NodeBundle, use super::*;
select: UiKitSelect,
}
#[derive(Copy, Clone)] #[derive(Debug, Component)]
pub enum UiKitPosition { pub struct Title {
Top, pub text: String,
Left, }
Right,
}
impl UiKitContainer { #[derive(Debug, Component)]
pub fn new(position: UiKitPosition) -> Self { pub struct Note {
let style = match position { pub text: String,
UiKitPosition::Top => Style {
border: UiRect::all(Val::Px(1.0)),
top: Val::Percent(102.0),
left: Val::Px(-2.0),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexStart,
display: Display::None,
..default()
},
UiKitPosition::Left => Style {
border: UiRect::all(Val::Px(1.0)),
left: Val::Percent(100.0),
top: Val::Px(-2.0),
flex_direction: FlexDirection::Column,
justify_items: JustifyItems::Start,
display: Display::None,
..default()
},
UiKitPosition::Right => Style {
border: UiRect::all(Val::Px(1.0)),
right: Val::Percent(104.0),
top: Val::Px(-2.0),
flex_direction: FlexDirection::Column,
justify_items: JustifyItems::Start,
display: Display::None,
..default()
},
};
UiKitContainer {
node_bundle: NodeBundle {
style,
background_color: BackgroundColor(Color::PURPLE),
border_color: BorderColor(Color::BLACK),
..default()
},
select: UiKitSelect::None,
}
} }
}
#[derive(Debug, Bundle)] #[derive(Debug, Component)]
pub struct UiKitButton { pub struct TitleText;
button_bundle: ButtonBundle,
select: UiKitSelect,
}
impl UiKitButton { #[derive(Debug, Component)]
pub fn new(color: Color) -> Self { pub struct Minimize {
UiKitButton { pub target: Entity,
button_bundle: ButtonBundle {
style: Style {
border: UiRect::all(Val::Px(1.0)),
width: Val::Px(100.0),
height: Val::Px(50.0),
flex_direction: FlexDirection::Column,
..default()
},
background_color: BackgroundColor(color),
border_color: BorderColor(Color::BLACK),
..default()
},
select: UiKitSelect::None,
}
} }
}
#[derive(Debug, Component, Copy, Clone, PartialEq)]
pub enum UiKitSelect {
Active,
None,
}
#[derive(Debug, Bundle)] #[derive(Debug, Component)]
pub struct UiKitTextInput { pub struct Close {
text_bundle: TextBundle, pub target: Entity,
interaction: Interaction, }
select: UiKitSelect,
}
impl UiKitTextInput { pub fn create_titles(
pub fn new() -> Self { events: Query<
UiKitTextInput { (
text_bundle: TextBundle { Entity,
style: Style { &Title,
width: Val::Percent(100.0), Option<&Note>,
height: Val::Percent(100.0), Option<&Minimize>,
..default() Option<&Close>,
}, ),
..default() Added<Title>,
}, >,
interaction: Interaction::None, mut commands: Commands,
select: UiKitSelect::None, ) {
} events.for_each(|(entity, title, note, minimize, close)| {
commands.entity(entity).with_children(|parent| {
parent.spawn((
TextBundle {
text: Text {
sections: vec![
TextSection {
value: title.text.clone(),
style: TextStyle {
color: Color::BLACK,
..default()
},
},
TextSection {
value: note
.unwrap_or(&Note {
text: String::new(),
})
.text
.clone(),
style: TextStyle {
color: Color::BLACK,
..default()
},
},
],
..default()
},
style: Style {
margin: UiRect::all(Val::Px(3.0)),
padding: UiRect::all(Val::Px(3.0)),
left: Val::Px(0.0),
..default()
},
..default()
},
Sorting(0),
TitleText,
));
if minimize.is_some() || close.is_some() {
parent
.spawn(NodeBundle {
style: Style {
// border: UiRect::all(Val::Px(1.0)),
// margin: UiRect::all(Val::Px(1.0)),
// padding: UiRect::all(Val::Px(1.0)),
right: Val::Px(0.0),
..default()
},
background_color: Color::WHITE.into(),
border_color: Color::BLACK.into(),
..default()
})
.with_children(|parent| {
if let Some(Minimize { target }) = minimize {
parent
.spawn((
ButtonBundle {
style: Style {
border: UiRect::all(Val::Px(1.0)),
// margin: UiRect::all(Val::Px(1.0)),
padding: UiRect::all(Val::Px(1.0)),
..default()
},
background_color: Color::WHITE.into(),
border_color: Color::BLACK.into(),
..default()
},
Collapse { target: *target },
Active,
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"-",
TextStyle {
color: Color::BLACK,
..default()
},
));
});
}
if let Some(Close { target }) = close {
parent
.spawn((
ButtonBundle {
style: Style {
border: UiRect::all(Val::Px(1.0)),
// margin: UiRect::all(Val::Px(1.0)),
padding: UiRect::all(Val::Px(1.0)),
..default()
},
background_color: Color::WHITE.into(),
border_color: Color::BLACK.into(),
..default()
},
Close { target: *target },
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"x",
TextStyle {
color: Color::BLACK,
..default()
},
));
});
}
});
}
});
});
} }
}
/// When an item is selected/de-selected change it's display accordingly pub fn manage_titles(
fn selection( events: Query<(&Title, Option<&Note>, &Children), Or<(Changed<Title>, Changed<Note>)>>,
mut events: Query< mut texts: Query<&mut Text, With<TitleText>>,
(&mut BackgroundColor, &UiKitSelect, &Children), ) {
(Changed<UiKitSelect>, With<Button>), events.iter().for_each(|(title, note, children)| {
>, children.iter().for_each(|child| {
mut styles: Query<&mut Style>, if let Ok(mut text) = texts.get_mut(*child) {
) { *text = Text {
events sections: vec![
.iter_mut() TextSection {
.for_each(|(mut bg_color, select, children)| { value: title.text.clone(),
bg_color.0 = match select { style: TextStyle {
UiKitSelect::Active => Color::RED, color: Color::BLACK,
UiKitSelect::None => Color::WHITE, ..default()
}; },
children.iter().for_each(|&child| { },
if let Ok(mut style) = styles.get_mut(child) { TextSection {
style.display = match select { value: note
UiKitSelect::Active => Display::Flex, .unwrap_or(&Note {
UiKitSelect::None => Display::None, text: String::new(),
})
.text
.clone(),
style: TextStyle {
color: Color::BLACK,
..default()
},
},
],
..default()
} }
} }
})
})
}
pub fn close_window(
events: Query<(&Interaction, &Close), (With<Button>, Changed<Interaction>)>,
mut commands: Commands,
) {
events
.iter()
.filter(|(&interaction, _)| interaction == Interaction::Pressed)
.for_each(|(_, Close { target })| {
commands.entity(*target).despawn_recursive();
}); });
}); }
} }
/// Toggle a UI Nav tree open/closed pub use collapse::*;
/// mod collapse {
/// PERF: This is hella not performant, we just usually don't have many elements to iterate over so use super::*;
/// it's tolerable.
///
// TODO: Should not be able to select multiple children in branch of tree
// TODO: Port to ui.rs
fn select_tab(
events: Query<Entity, (Changed<Interaction>, With<Button>)>,
interactions: Query<&Interaction, With<Button>>,
mut selects: Query<&mut UiKitSelect>,
parents: Query<&Parent>,
children: Query<&Children>,
) {
events.iter().for_each(|entity| {
// Otherwise, update nav tree(s)
if let Ok(interaction) = interactions.get(entity) {
match interaction {
Interaction::Pressed | Interaction::Hovered => {
{
let parent = parents.get(entity).expect("entity has parent");
children
.get(parent.get())
.expect("parent has children")
.iter()
.filter(|&e| *e != entity)
.for_each(|sibling| {
if let Ok(mut select) = selects.get_mut(*sibling) {
*select = UiKitSelect::None
}
});
}
if let Ok(mut select) = selects.get_mut(entity) { #[derive(Debug, Component)]
*select = UiKitSelect::Active pub struct Collapse {
pub target: Entity,
}
pub fn manage_collapse_active(
events: Query<
(Entity, Option<&Active>, &Interaction),
(Changed<Interaction>, With<Button>, With<Collapse>),
>,
mut commands: Commands,
) {
events
.iter()
.filter(|(_, _, &interaction)| interaction == Interaction::Pressed)
.for_each(|(entity, active, _)| {
match active {
Some(_) => {
commands.entity(entity).remove::<Active>();
} }
} None => {
Interaction::None => { // Set this butotn to active
// Find the ancestor which does not have a parent commands.entity(entity).insert(Active);
let root_parent = parents
.iter_ancestors(entity)
.find(|&e| parents.get(e).is_err())
.expect("entity has root parent");
let family: Vec<Entity> = children.iter_descendants(root_parent).collect();
let family_inactive = family
.iter()
.filter_map(|member| interactions.get(*member).ok())
.all(|&interaction| interaction == Interaction::None);
// Zero out children
let descendants: Vec<Entity> = children.iter_descendants(entity).collect();
let descendants_inactive = descendants
.iter()
.filter_map(|child| interactions.get(*child).ok())
.all(|&interaction| interaction == Interaction::None);
// The entire tree is inactive
if family_inactive {
family.iter().for_each(|member| {
if let Ok(mut select) = selects.get_mut(*member) {
*select = UiKitSelect::None
}
});
if let Ok(mut select) = selects.get_mut(entity) {
*select = UiKitSelect::None
}
// Just the sub-tree is inactive
} else if descendants_inactive {
descendants.iter().for_each(|child| {
if let Ok(mut select) = selects.get_mut(*child) {
*select = UiKitSelect::None
}
});
if let Ok(mut select) = selects.get_mut(entity) {
*select = UiKitSelect::None
}
// This node is active (usually a parent of an active child)
} else if let Ok(mut select) = selects.get_mut(entity) {
*select = UiKitSelect::Active
} }
};
});
}
pub fn manage_collapse_hiding(
added: Query<Entity, (Added<Active>, With<Collapse>)>,
mut removed: RemovedComponents<Active>,
collapses: Query<&Collapse, With<Button>>,
mut styles: Query<&mut Style>,
) {
// Added collapse, display the target entity
added.iter().for_each(|e| {
if let Ok(Collapse { target }) = collapses.get(e) {
if let Ok(mut style) = styles.get_mut(*target) {
style.display = Display::Flex;
} }
} }
} });
}); // Removed collapse, hide the target entity
} removed.iter().for_each(|e| {
if let Ok(Collapse { target }) = collapses.get(e) {
if let Ok(mut style) = styles.get_mut(*target) {
style.display = Display::None;
}
}
});
}
fn select_textbox( pub fn show_child_number(
mut events: Query<(&Interaction, &mut UiKitSelect), (With<Text>, Changed<Interaction>)>, events: Query<(Entity, &Children), (Changed<Children>, With<Node>)>,
) { mut tabs: Query<(Entity, &Collapse)>,
events.iter_mut().for_each(|(interaction, mut select)| { mut commands: Commands,
*select = match interaction { ) {
Interaction::Pressed => UiKitSelect::Active, // Any time a widget changes
Interaction::Hovered => UiKitSelect::Active, events.iter().for_each(|(entity, children)| {
Interaction::None => UiKitSelect::None, // Find any tabs which have this as a target
} tabs.iter_mut()
}); .find_map(|(button, collapse)| {
if entity == collapse.target {
Some(button)
} else {
None
}
})
.iter()
.for_each(|button| {
let num_children = children.len();
commands.entity(*button).insert(Note {
text: format!("({})", num_children),
});
});
});
}
} }
fn text_editor( pub use buttons::*;
keyboard: Res<Input<KeyCode>>, mod buttons {
mut events: EventReader<KeyboardInput>, use super::*;
mut query: Query<&mut Text, With<UiKitSelect>>,
) { #[derive(Debug, Component)]
events.iter().for_each( pub struct Active;
|KeyboardInput {
key_code, pub fn manage_button_interaction(
state, events: Query<
scan_code, (Entity, &Interaction, Option<&Active>),
.. (Changed<Interaction>, With<Button>),
}| { >,
match state { added_active: Query<Entity, Added<Active>>,
ButtonState::Pressed => { mut removed_active: RemovedComponents<Active>,
if let Some(kc) = key_code { mut bg_colors: Query<&mut BackgroundColor>,
query.iter_mut().for_each(|mut text| { ) {
use KeyCode::*; added_active.for_each(|e| {
if let Ok(mut bg_color) = bg_colors.get_mut(e) {
let style = TextStyle { *bg_color = Color::ORANGE.into();
color: Color::BLACK, }
..default() });
}; removed_active.iter().for_each(|e| {
if let Ok(mut bg_color) = bg_colors.get_mut(e) {
if *kc == Back { *bg_color = Color::WHITE.into();
text.sections.pop(); }
} else { });
let c = match kc { events.for_each(|(entity, interaction, active)| {
// Letters if let Ok(mut bg_color) = bg_colors.get_mut(entity) {
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O match active {
| P | Q | R | S | T | U | V | W | X | Y | Z => { Some(_) => match interaction {
if keyboard.any_pressed([ShiftLeft, ShiftRight]) { Interaction::None => *bg_color = Color::ORANGE.into(),
format!("{:?}", kc).to_uppercase() Interaction::Pressed => *bg_color = Color::YELLOW.into(),
} else { Interaction::Hovered => *bg_color = Color::RED.into(),
format!("{:?}", kc).to_lowercase() },
} None => match interaction {
} Interaction::None => *bg_color = Color::WHITE.into(),
// Top Row Interaction::Pressed => *bg_color = Color::WHITE.into(),
Grave => "`".to_string(), Interaction::Hovered => *bg_color = Color::GRAY.into(),
Key1 | Numpad1 => "1".to_string(), },
Key2 | Numpad2 => "2".to_string(), }
Key3 | Numpad3 => "3".to_string(), }
Key4 | Numpad4 => "4".to_string(), })
Key5 | Numpad5 => "5".to_string(), }
Key6 | Numpad6 => "6".to_string(),
Key7 | Numpad7 => "7".to_string(), /// Marks a container node as having single- or multi-active components
Key8 | Numpad8 => "8".to_string(), #[derive(Debug, Component)]
Key9 | Numpad9 => "9".to_string(), pub enum Select {
Key0 | Numpad0 => "0".to_string(), Multi,
Minus => "-".to_string(), Single,
Equals => "=".to_string(), }
// Left side pub fn manage_select_active(
Tab => "\t".to_string(), events: Query<(Entity, &Parent), Added<Active>>,
// Right side children: Query<(&Select, &Children)>,
// Row 2 mut commands: Commands,
BracketLeft => "[".to_string(), ) {
BracketRight => "]".to_string(), events.iter().for_each(|(entity, parent)| {
Backslash => "\\".to_string(), if let Ok((select, childs)) = children.get(parent.get()) {
// Row 3 match select {
Semicolon => ";".to_string(), Select::Single => {
Apostrophe => "'".to_string(), childs
Return => "\n".to_string(), .iter()
// Row 4 .filter(|&child| *child != entity)
Comma => ",".to_string(), .for_each(|&child| {
Period => ".".to_string(), commands.entity(child).remove::<Active>();
Slash => "/".to_string(), })
// Space
Space => " ".to_string(),
// None
_ => "".to_string(),
};
if c.len() > 0 {
text.sections.push(TextSection::new(c, style));
}
}
});
} }
Select::Multi => (),
} }
_ => (),
} }
}, });
) }
} }
// TODO: Reset default position when de-activated pub use scroll::*;
fn scroll( mod scroll {
mut scrolls: EventReader<MouseWheel>, use super::*;
mut query: Query<(&mut Style, &UiKitSelect, Entity, &Children, &Parent)>,
changes: Query<Entity, Changed<UiKitSelect>>, #[derive(Debug, Component)]
) { pub struct Scroll;
// Brute force: When all Actives are set to None (event) reset all style tops...
changes.iter().for_each(|_| { pub fn manage_scroll(
let all_inactive = query mut events: EventReader<MouseWheel>,
.iter_mut() mut query: Query<(&Interaction, &Parent, &Children, &mut Style), With<Scroll>>,
.all(|(_, select, _, _, _)| *select == UiKitSelect::None); interactions: Query<&Interaction>,
all_inactive.then(|| { ) {
events.iter().for_each(|MouseWheel { unit, y, .. }| {
query query
.iter_mut() .iter_mut()
.for_each(|(mut style, _, _, _, _)| style.top = Val::Px(0.0)); .filter(|(&interaction, parent, children, _)| {
let self_hover = interaction == Interaction::Hovered;
let child_hover = children.iter().any(|&child| {
if let Ok(&interaction) = interactions.get(child) {
interaction == Interaction::Hovered
} else {
false
}
});
let parent_hover = interactions
.get(parent.get())
.map_or(false, |&interaction| interaction == Interaction::Hovered);
self_hover || child_hover || parent_hover
})
.for_each(|(_, _, _, mut style)| {
let factor = 2.0;
let val = match unit {
MouseScrollUnit::Line => match style.top {
Val::Px(v) => v + (y * factor),
_ => (*y) * factor,
},
MouseScrollUnit::Pixel => match style.top {
Val::Px(v) => v + (y * factor),
_ => (*y) * factor,
},
};
style.top = Val::Px(val.min(0.0));
});
}); });
}); }
scrolls.iter().for_each(|MouseWheel { unit, y, .. }| { }
// Find the leaf selected entity
let leaf = query use cursor::*;
.iter() mod cursor {
.find(|(_, select, _, children, parent)| { use super::*;
// This node is active
let self_active = **select == UiKitSelect::Active; pub fn manage_cursor(
// All children are not selected events: Query<&Interaction, Changed<Interaction>>,
let children_inactive = children.iter().all(|&child| { mut window: Query<&mut Window, With<PrimaryWindow>>,
if let Ok((_, select, _, _, _)) = query.get(child) { ) {
*select == UiKitSelect::None events.for_each(|interaction| {
let mut win = window.single_mut();
win.cursor.icon = match interaction {
Interaction::None => CursorIcon::Default,
Interaction::Hovered => CursorIcon::Hand,
Interaction::Pressed => CursorIcon::Grabbing,
}
})
}
}
pub use sort::*;
mod sort {
use std::cmp::Ordering;
use super::*;
#[derive(Debug, Component)]
pub struct Sorting(pub u8);
pub fn manage_sort(
mut events: Query<&mut Children, Changed<Children>>,
sorting: Query<Option<&Sorting>>,
) {
events.iter_mut().for_each(|mut children| {
children.sort_by(|&a, &b| match (sorting.get(a), sorting.get(b)) {
(Ok(Some(Sorting(ord_a))), Ok(Some(Sorting(ord_b)))) => {
if ord_a > ord_b {
Ordering::Greater
} else if ord_a < ord_b {
Ordering::Less
} else { } else {
true Ordering::Equal
} }
});
// Both must be true
self_active && children_inactive
})
.map(|(_, _, _, _, parent)| parent.get());
if let Some(l) = leaf {
if let Ok((mut style, _, _, _, _)) = query.get_mut(l) {
if *y != 0.0 {
let delta = match unit {
MouseScrollUnit::Line => *y,
MouseScrollUnit::Pixel => 5.0,
};
style.top.try_sub_assign(Val::Px(delta));
info!("Top: {:?}", style.top);
} }
} (Ok(Some(_)), Err(_)) | (Ok(Some(_)), Ok(None)) => Ordering::Less,
}; (Err(_), Ok(Some(_))) | (Ok(None), Ok(Some(_))) => Ordering::Greater,
}); _ => Ordering::Equal,
});
})
}
}
pub use alert::*;
pub mod alert {
use super::*;
#[derive(Debug, Event)]
pub enum Alert {
Info(String),
Warn(String),
Danger(String),
}
#[derive(Debug, Component)]
pub struct AlertsWidget;
pub fn init_alerts(mut commands: Commands) {
commands.spawn((
NodeBundle {
style: Style {
top: Val::Px(0.0),
right: Val::Px(0.0),
position_type: PositionType::Absolute,
width: Val::Percent(33.0),
padding: UiRect::all(Val::Px(1.0)),
margin: UiRect::all(Val::Px(1.0)),
border: UiRect::all(Val::Px(1.0)),
flex_direction: FlexDirection::Column,
justify_items: JustifyItems::Center,
..default()
},
border_color: Color::WHITE.into(),
..default()
},
AlertsWidget,
));
}
pub fn spawn_alert(
mut events: EventReader<Alert>,
root: Query<Entity, With<AlertsWidget>>,
mut commands: Commands,
) {
events.iter().for_each(|alert| {
info!("Processing alert {:?}", alert);
let (color, text) = match alert {
Alert::Info(text) => (Color::BLUE, text),
Alert::Warn(text) => (Color::ORANGE, text),
Alert::Danger(text) => (Color::RED, text),
};
commands.entity(root.single()).with_children(|parent| {
parent
.spawn(NodeBundle {
style: Style {
width: Val::Percent(100.0),
padding: UiRect::all(Val::Px(1.0)),
margin: UiRect::all(Val::Px(1.0)),
border: UiRect::all(Val::Px(2.0)),
flex_direction: FlexDirection::Column,
justify_self: JustifySelf::Center,
..default()
},
border_color: color.into(),
..default()
})
.with_children(|parent| {
parent.spawn((
NodeBundle {
style: Style {
padding: UiRect::all(Val::Px(1.0)),
margin: UiRect::all(Val::Px(1.0)),
border: UiRect::all(Val::Px(1.0)),
flex_direction: FlexDirection::Row,
align_items: AlignItems::Center,
align_content: AlignContent::Center,
justify_content: JustifyContent::SpaceBetween,
..default()
},
background_color: color.into(),
..default()
},
Title {
text: "Alert".into(),
},
Close {
target: parent.parent_entity(),
},
Sorting(0),
));
parent.spawn(TextBundle::from_section(text, TextStyle { ..default() }));
});
});
});
}
} }

Loading…
Cancel
Save