use crate::element::{Element, ElementId, ElementRegistry};
use bevy::asset::{Asset, AssetServer};
use bevy::prelude::{Commands, Entity, Resource, TypePath};
use bevy::ui::Node;
#[derive(Clone, Debug, Resource, Asset, TypePath)]
pub struct Page {
root: Node,
entity: Option<Entity>,
registry: ElementRegistry,
elements: Vec<Element>,
}
impl Page {
pub fn new(root: Node, elements: Vec<Element>) -> Self {
Self {
root,
entity: None,
registry: ElementRegistry::new(elements.len()),
elements,
}
}
pub(crate) fn spawn(&mut self, commands: &mut Commands, assets: &AssetServer) -> Entity {
let entity = commands
.spawn(self.root.clone())
.with_children(|parent| {
for element in &self.elements {
element.spawn(parent, assets, &mut self.registry);
}
})
.id();
self.entity = Some(entity);
entity
}
pub fn get(&self, id: impl Into<ElementId>) -> Entity {
self.try_get(id).expect("Element not found")
}
pub fn try_get(&self, id: impl Into<ElementId>) -> Option<Entity> {
self.registry.get_element(id.into())
}
pub fn entity(&self) -> Option<Entity> {
self.entity
}
}