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(Debug, Component)]
pub struct Title {
pub text: String,
} }
#[derive(Copy, Clone)] #[derive(Debug, Component)]
pub enum UiKitPosition { pub struct Note {
Top, pub text: String,
Left,
Right,
} }
impl UiKitContainer { #[derive(Debug, Component)]
pub fn new(position: UiKitPosition) -> Self { pub struct TitleText;
let style = match position {
UiKitPosition::Top => Style { #[derive(Debug, Component)]
border: UiRect::all(Val::Px(1.0)), pub struct Minimize {
top: Val::Percent(102.0), pub target: Entity,
left: Val::Px(-2.0), }
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexStart, #[derive(Debug, Component)]
display: Display::None, pub struct Close {
pub target: Entity,
}
pub fn create_titles(
events: Query<
(
Entity,
&Title,
Option<&Note>,
Option<&Minimize>,
Option<&Close>,
),
Added<Title>,
>,
mut commands: Commands,
) {
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() ..default()
}, },
UiKitPosition::Left => Style { },
border: UiRect::all(Val::Px(1.0)), TextSection {
left: Val::Percent(100.0), value: note
top: Val::Px(-2.0), .unwrap_or(&Note {
flex_direction: FlexDirection::Column, text: String::new(),
justify_items: JustifyItems::Start, })
display: Display::None, .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() ..default()
}, },
UiKitPosition::Right => Style { 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)), border: UiRect::all(Val::Px(1.0)),
right: Val::Percent(104.0), // margin: UiRect::all(Val::Px(1.0)),
top: Val::Px(-2.0), padding: UiRect::all(Val::Px(1.0)),
flex_direction: FlexDirection::Column,
justify_items: JustifyItems::Start,
display: Display::None,
..default() ..default()
}, },
}; background_color: Color::WHITE.into(),
UiKitContainer { border_color: Color::BLACK.into(),
node_bundle: NodeBundle {
style,
background_color: BackgroundColor(Color::PURPLE),
border_color: BorderColor(Color::BLACK),
..default() ..default()
}, },
select: UiKitSelect::None, Collapse { target: *target },
} Active,
} ))
} .with_children(|parent| {
parent.spawn(TextBundle::from_section(
#[derive(Debug, Bundle)] "-",
pub struct UiKitButton { TextStyle {
button_bundle: ButtonBundle, color: Color::BLACK,
select: UiKitSelect, ..default()
},
));
});
} }
if let Some(Close { target }) = close {
impl UiKitButton { parent
pub fn new(color: Color) -> Self { .spawn((
UiKitButton { ButtonBundle {
button_bundle: ButtonBundle {
style: Style { style: Style {
border: UiRect::all(Val::Px(1.0)), border: UiRect::all(Val::Px(1.0)),
width: Val::Px(100.0), // margin: UiRect::all(Val::Px(1.0)),
height: Val::Px(50.0), padding: UiRect::all(Val::Px(1.0)),
flex_direction: FlexDirection::Column,
..default() ..default()
}, },
background_color: BackgroundColor(color), background_color: Color::WHITE.into(),
border_color: BorderColor(Color::BLACK), border_color: Color::BLACK.into(),
..default() ..default()
}, },
select: UiKitSelect::None, Close { target: *target },
} ))
} .with_children(|parent| {
parent.spawn(TextBundle::from_section(
"x",
TextStyle {
color: Color::BLACK,
..default()
},
));
});
} }
});
#[derive(Debug, Component, Copy, Clone, PartialEq)]
pub enum UiKitSelect {
Active,
None,
} }
});
#[derive(Debug, Bundle)] });
pub struct UiKitTextInput {
text_bundle: TextBundle,
interaction: Interaction,
select: UiKitSelect,
} }
impl UiKitTextInput { pub fn manage_titles(
pub fn new() -> Self { events: Query<(&Title, Option<&Note>, &Children), Or<(Changed<Title>, Changed<Note>)>>,
UiKitTextInput { mut texts: Query<&mut Text, With<TitleText>>,
text_bundle: TextBundle { ) {
style: Style { events.iter().for_each(|(title, note, children)| {
width: Val::Percent(100.0), children.iter().for_each(|child| {
height: Val::Percent(100.0), if let Ok(mut text) = texts.get_mut(*child) {
*text = Text {
sections: vec![
TextSection {
value: title.text.clone(),
style: TextStyle {
color: Color::BLACK,
..default() ..default()
}, },
},
TextSection {
value: note
.unwrap_or(&Note {
text: String::new(),
})
.text
.clone(),
style: TextStyle {
color: Color::BLACK,
..default() ..default()
}, },
interaction: Interaction::None, },
select: UiKitSelect::None, ],
..default()
} }
} }
})
})
} }
/// When an item is selected/de-selected change it's display accordingly pub fn close_window(
fn selection( events: Query<(&Interaction, &Close), (With<Button>, Changed<Interaction>)>,
mut events: Query< mut commands: Commands,
(&mut BackgroundColor, &UiKitSelect, &Children),
(Changed<UiKitSelect>, With<Button>),
>,
mut styles: Query<&mut Style>,
) { ) {
events events
.iter_mut() .iter()
.for_each(|(mut bg_color, select, children)| { .filter(|(&interaction, _)| interaction == Interaction::Pressed)
bg_color.0 = match select { .for_each(|(_, Close { target })| {
UiKitSelect::Active => Color::RED, commands.entity(*target).despawn_recursive();
UiKitSelect::None => Color::WHITE, });
};
children.iter().for_each(|&child| {
if let Ok(mut style) = styles.get_mut(child) {
style.display = match select {
UiKitSelect::Active => Display::Flex,
UiKitSelect::None => Display::None,
} }
} }
});
}); pub use collapse::*;
mod collapse {
use super::*;
#[derive(Debug, Component)]
pub struct Collapse {
pub target: Entity,
} }
/// Toggle a UI Nav tree open/closed pub fn manage_collapse_active(
/// events: Query<
/// PERF: This is hella not performant, we just usually don't have many elements to iterate over so (Entity, Option<&Active>, &Interaction),
/// it's tolerable. (Changed<Interaction>, With<Button>, With<Collapse>),
/// >,
// TODO: Should not be able to select multiple children in branch of tree mut commands: Commands,
// 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| { events
// 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() .iter()
.filter(|&e| *e != entity) .filter(|(_, _, &interaction)| interaction == Interaction::Pressed)
.for_each(|sibling| { .for_each(|(entity, active, _)| {
if let Ok(mut select) = selects.get_mut(*sibling) { match active {
*select = UiKitSelect::None Some(_) => {
commands.entity(entity).remove::<Active>();
}
None => {
// Set this butotn to active
commands.entity(entity).insert(Active);
} }
};
}); });
} }
if let Ok(mut select) = selects.get_mut(entity) { pub fn manage_collapse_hiding(
*select = UiKitSelect::Active 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;
} }
} }
Interaction::None => { });
// Find the ancestor which does not have a parent // Removed collapse, hide the target entity
let root_parent = parents removed.iter().for_each(|e| {
.iter_ancestors(entity) if let Ok(Collapse { target }) = collapses.get(e) {
.find(|&e| parents.get(e).is_err()) if let Ok(mut style) = styles.get_mut(*target) {
.expect("entity has root parent"); style.display = Display::None;
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 pub fn show_child_number(
let descendants: Vec<Entity> = children.iter_descendants(entity).collect(); events: Query<(Entity, &Children), (Changed<Children>, With<Node>)>,
let descendants_inactive = descendants mut tabs: Query<(Entity, &Collapse)>,
mut commands: Commands,
) {
// Any time a widget changes
events.iter().for_each(|(entity, children)| {
// 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() .iter()
.filter_map(|child| interactions.get(*child).ok()) .for_each(|button| {
.all(|&interaction| interaction == Interaction::None); let num_children = children.len();
commands.entity(*button).insert(Note {
text: format!("({})", num_children),
});
});
});
}
}
pub use buttons::*;
mod buttons {
use super::*;
// The entire tree is inactive #[derive(Debug, Component)]
if family_inactive { pub struct Active;
family.iter().for_each(|member| {
if let Ok(mut select) = selects.get_mut(*member) { pub fn manage_button_interaction(
*select = UiKitSelect::None events: Query<
(Entity, &Interaction, Option<&Active>),
(Changed<Interaction>, With<Button>),
>,
added_active: Query<Entity, Added<Active>>,
mut removed_active: RemovedComponents<Active>,
mut bg_colors: Query<&mut BackgroundColor>,
) {
added_active.for_each(|e| {
if let Ok(mut bg_color) = bg_colors.get_mut(e) {
*bg_color = Color::ORANGE.into();
} }
}); });
if let Ok(mut select) = selects.get_mut(entity) { removed_active.iter().for_each(|e| {
*select = UiKitSelect::None if let Ok(mut bg_color) = bg_colors.get_mut(e) {
} *bg_color = Color::WHITE.into();
// 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) { events.for_each(|(entity, interaction, active)| {
*select = UiKitSelect::None if let Ok(mut bg_color) = bg_colors.get_mut(entity) {
match active {
Some(_) => match interaction {
Interaction::None => *bg_color = Color::ORANGE.into(),
Interaction::Pressed => *bg_color = Color::YELLOW.into(),
Interaction::Hovered => *bg_color = Color::RED.into(),
},
None => match interaction {
Interaction::None => *bg_color = Color::WHITE.into(),
Interaction::Pressed => *bg_color = Color::WHITE.into(),
Interaction::Hovered => *bg_color = Color::GRAY.into(),
},
} }
// This node is active (usually a parent of an active child)
} else if let Ok(mut select) = selects.get_mut(entity) {
*select = UiKitSelect::Active
} }
})
}
/// Marks a container node as having single- or multi-active components
#[derive(Debug, Component)]
pub enum Select {
Multi,
Single,
}
pub fn manage_select_active(
events: Query<(Entity, &Parent), Added<Active>>,
children: Query<(&Select, &Children)>,
mut commands: Commands,
) {
events.iter().for_each(|(entity, parent)| {
if let Ok((select, childs)) = children.get(parent.get()) {
match select {
Select::Single => {
childs
.iter()
.filter(|&child| *child != entity)
.for_each(|&child| {
commands.entity(child).remove::<Active>();
})
} }
Select::Multi => (),
} }
} }
}); });
} }
}
fn select_textbox( pub use scroll::*;
mut events: Query<(&Interaction, &mut UiKitSelect), (With<Text>, Changed<Interaction>)>, mod scroll {
use super::*;
#[derive(Debug, Component)]
pub struct Scroll;
pub fn manage_scroll(
mut events: EventReader<MouseWheel>,
mut query: Query<(&Interaction, &Parent, &Children, &mut Style), With<Scroll>>,
interactions: Query<&Interaction>,
) { ) {
events.iter_mut().for_each(|(interaction, mut select)| { events.iter().for_each(|MouseWheel { unit, y, .. }| {
*select = match interaction { query
Interaction::Pressed => UiKitSelect::Active, .iter_mut()
Interaction::Hovered => UiKitSelect::Active, .filter(|(&interaction, parent, children, _)| {
Interaction::None => UiKitSelect::None, 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));
});
});
} }
}
use cursor::*;
mod cursor {
use super::*;
fn text_editor( pub fn manage_cursor(
keyboard: Res<Input<KeyCode>>, events: Query<&Interaction, Changed<Interaction>>,
mut events: EventReader<KeyboardInput>, mut window: Query<&mut Window, With<PrimaryWindow>>,
mut query: Query<&mut Text, With<UiKitSelect>>,
) { ) {
events.iter().for_each( events.for_each(|interaction| {
|KeyboardInput { let mut win = window.single_mut();
key_code,
state,
scan_code,
..
}| {
match state {
ButtonState::Pressed => {
if let Some(kc) = key_code {
query.iter_mut().for_each(|mut text| {
use KeyCode::*;
let style = TextStyle {
color: Color::BLACK,
..default()
};
if *kc == Back { win.cursor.icon = match interaction {
text.sections.pop(); Interaction::None => CursorIcon::Default,
} else { Interaction::Hovered => CursorIcon::Hand,
let c = match kc { Interaction::Pressed => CursorIcon::Grabbing,
// Letters }
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O })
| P | Q | R | S | T | U | V | W | X | Y | Z => { }
if keyboard.any_pressed([ShiftLeft, ShiftRight]) { }
format!("{:?}", kc).to_uppercase()
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 {
format!("{:?}", kc).to_lowercase() Ordering::Equal
}
}
// Top Row
Grave => "`".to_string(),
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(),
Key8 | Numpad8 => "8".to_string(),
Key9 | Numpad9 => "9".to_string(),
Key0 | Numpad0 => "0".to_string(),
Minus => "-".to_string(),
Equals => "=".to_string(),
// Left side
Tab => "\t".to_string(),
// Right side
// Row 2
BracketLeft => "[".to_string(),
BracketRight => "]".to_string(),
Backslash => "\\".to_string(),
// Row 3
Semicolon => ";".to_string(),
Apostrophe => "'".to_string(),
Return => "\n".to_string(),
// Row 4
Comma => ",".to_string(),
Period => ".".to_string(),
Slash => "/".to_string(),
// Space
Space => " ".to_string(),
// None
_ => "".to_string(),
};
if c.len() > 0 {
text.sections.push(TextSection::new(c, style));
} }
} }
(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,
));
} }
// TODO: Reset default position when de-activated pub fn spawn_alert(
fn scroll( mut events: EventReader<Alert>,
mut scrolls: EventReader<MouseWheel>, root: Query<Entity, With<AlertsWidget>>,
mut query: Query<(&mut Style, &UiKitSelect, Entity, &Children, &Parent)>, mut commands: Commands,
changes: Query<Entity, Changed<UiKitSelect>>,
) { ) {
// Brute force: When all Actives are set to None (event) reset all style tops... events.iter().for_each(|alert| {
changes.iter().for_each(|_| { info!("Processing alert {:?}", alert);
let all_inactive = query
.iter_mut() let (color, text) = match alert {
.all(|(_, select, _, _, _)| *select == UiKitSelect::None); Alert::Info(text) => (Color::BLUE, text),
all_inactive.then(|| { Alert::Warn(text) => (Color::ORANGE, text),
query Alert::Danger(text) => (Color::RED, text),
.iter_mut() };
.for_each(|(mut style, _, _, _, _)| style.top = Val::Px(0.0)); 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() }));
}); });
}); });
scrolls.iter().for_each(|MouseWheel { unit, y, .. }| {
// Find the leaf selected entity
let leaf = query
.iter()
.find(|(_, select, _, children, parent)| {
// This node is active
let self_active = **select == UiKitSelect::Active;
// All children are not selected
let children_inactive = children.iter().all(|&child| {
if let Ok((_, select, _, _, _)) = query.get(child) {
*select == UiKitSelect::None
} else {
true
}
}); });
// 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);
}
} }
};
});
} }

Loading…
Cancel
Save