use std::any::Any;
use std::collections::HashMap;
use crate::types::state::WidgetId;
#[derive(Default)]
pub struct StateRegistry {
states: HashMap<WidgetId, Box<dyn Any + Send + Sync>>,
}
impl StateRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn get<T: 'static>(&self, id: &WidgetId) -> Option<&T> {
self.states.get(id).and_then(|any| any.downcast_ref::<T>())
}
pub fn get_or_insert_with<T: 'static + Send + Sync, F: FnOnce() -> T>(&mut self, id: WidgetId, default: F) -> &mut T {
let entry = self.states.entry(id).or_insert_with(|| Box::new(default()));
entry.downcast_mut::<T>().expect("State type mismatch for WidgetId")
}
pub fn insert<T: 'static + Send + Sync>(&mut self, id: WidgetId, state: T) {
self.states.insert(id, Box::new(state));
}
pub fn remove(&mut self, id: &WidgetId) {
self.states.remove(id);
}
pub fn clear(&mut self) {
self.states.clear();
}
}