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