use std::collections::HashMap;
use bevy::prelude::*;
use crate::render::{NoesisRenderState, NoesisSet};
pub type Margin = [f32; 4];
#[derive(Component, Clone, Default, Debug)]
pub struct NoesisLayout {
pub margins: HashMap<String, Margin>,
}
impl NoesisLayout {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn margin(mut self, name: impl Into<String>, margin: Margin) -> Self {
self.margins.insert(name.into(), margin);
self
}
pub fn write(&mut self, name: impl Into<String>, margin: Margin) {
self.margins.insert(name.into(), margin);
}
}
#[allow(clippy::needless_pass_by_value)]
pub(crate) fn sync_layout_bridge(
views: Query<(Entity, Ref<NoesisLayout>)>,
state: Option<NonSendMut<NoesisRenderState>>,
) {
let Some(mut state) = state else {
return;
};
for (entity, layout) in &views {
if layout.is_changed() || state.scene_rebuilt_this_frame(entity) {
state.apply_layout_for(entity, &layout.margins);
}
}
}
pub struct NoesisLayoutPlugin;
impl Plugin for NoesisLayoutPlugin {
fn build(&self, app: &mut App) {
app.add_systems(PostUpdate, sync_layout_bridge.in_set(NoesisSet::Apply));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder_collects_margins() {
let l = NoesisLayout::new()
.margin("Menu", [10.0, 20.0, 0.0, 0.0])
.margin("Tip", [1.0, 2.0, 3.0, 4.0]);
assert_eq!(l.margins.get("Menu"), Some(&[10.0, 20.0, 0.0, 0.0]));
assert_eq!(l.margins.get("Tip"), Some(&[1.0, 2.0, 3.0, 4.0]));
}
}