use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use mitsuami_reactive::{Owner, inject, provide};
pub trait Store: Clone + 'static {
fn create() -> Self;
}
#[derive(Clone)]
struct Registry {
stores: Rc<RefCell<HashMap<TypeId, Rc<dyn Any>>>>,
owner: Owner,
}
pub fn provide_stores() {
let owner = Owner::current().expect("mitsuami: provide_stores needs a scope (Owner::with)");
provide(Registry { stores: Rc::default(), owner });
}
pub fn use_store<S: Store>() -> S {
if let Some(store) = inject::<S>() {
return store;
}
let registry = inject::<Registry>().unwrap_or_else(|| {
panic!(
"mitsuami: use_store::<{}>() outside of an app; mount the view with App or TestApp, \
or call provide_stores() in an enclosing scope",
std::any::type_name::<S>()
)
});
let existing = registry.stores.borrow().get(&TypeId::of::<S>()).cloned();
if let Some(store) = existing {
return store.downcast_ref::<S>().expect("mitsuami: store registry holds the wrong type").clone();
}
let store = registry.owner.child().with(S::create);
registry.stores.borrow_mut().insert(TypeId::of::<S>(), Rc::new(store.clone()));
store
}