use crate::core::component::{Child, ChildOp, Children, Component};
use crate::core::theme::{DefaultRegion, RegionRef, ThemeRef};
use crate::{builder_fn, AutoDefault, UniqueId};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
trait ComponentGlobal: Send + Sync {
fn as_child(&self) -> Child;
}
impl<T: Component + Clone + 'static> ComponentGlobal for T {
#[inline]
fn as_child(&self) -> Child {
Child::with(self.clone())
}
}
type RegionComponents = HashMap<String, Vec<Arc<dyn ComponentGlobal>>>;
static THEME_REGIONS: LazyLock<RwLock<HashMap<UniqueId, RegionComponents>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
static COMMON_REGIONS: LazyLock<RwLock<RegionComponents>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
#[derive(AutoDefault)]
pub(crate) struct ChildrenInRegions(HashMap<String, Children>);
impl ChildrenInRegions {
pub fn with(region_ref: RegionRef, child: Child) -> Self {
Self::default().with_child_in(region_ref, child)
}
#[builder_fn]
pub fn with_child_in(mut self, region_ref: RegionRef, op: impl Into<ChildOp>) -> Self {
let child = op.into();
if let Some(region) = self.0.get_mut(region_ref.name()) {
region.alter_child(child);
} else {
self.0.insert(
region_ref.name().to_owned(),
Children::new().with_child(child),
);
}
self
}
pub fn children_for(&mut self, theme_ref: ThemeRef, region_ref: RegionRef) -> Children {
let name = region_ref.name();
let common = COMMON_REGIONS.read();
let themed = THEME_REGIONS.read();
let mut result = Children::new();
if let Some(protos) = common.get(name) {
for proto in protos {
result.add(proto.as_child());
}
}
if let Some(page_children) = self.0.remove(name) {
for child in page_children {
result.add(child);
}
}
if let Some(theme_map) = themed.get(&theme_ref.type_id()) {
if let Some(protos) = theme_map.get(name) {
for proto in protos {
result.add(proto.as_child());
}
}
}
result
}
}
pub enum InRegion {
Content,
Global(RegionRef),
ForTheme(ThemeRef, RegionRef),
}
impl InRegion {
pub fn add(&self, component: impl Component + Clone + 'static) -> &Self {
let proto: Arc<dyn ComponentGlobal> = Arc::new(component);
match self {
InRegion::Content => Self::add_to_common(&DefaultRegion::Content, proto),
InRegion::Global(region_ref) => Self::add_to_common(*region_ref, proto),
InRegion::ForTheme(theme_ref, region_ref) => {
THEME_REGIONS
.write()
.entry(theme_ref.type_id())
.or_default()
.entry((*region_ref).name().to_owned())
.or_default()
.push(proto);
}
}
self
}
#[inline]
fn add_to_common(region_ref: RegionRef, proto: Arc<dyn ComponentGlobal>) {
COMMON_REGIONS
.write()
.entry(region_ref.name().to_owned())
.or_default()
.push(proto);
}
}