use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::future::Future;
use std::rc::Rc;
use mitsuami_reactive::{Owner, inject, provide};
use crate::task::{TaskHandle, spawn_local};
pub trait Store: Clone + 'static {
fn create() -> Self;
fn spawn(&self, future: impl Future<Output = ()> + 'static) -> TaskHandle {
store_scope::<Self>().with(|| spawn_local(future))
}
}
#[derive(Clone)]
struct Registry {
stores: Rc<RefCell<HashMap<TypeId, Rc<dyn Any>>>>,
scopes: Rc<RefCell<HashMap<TypeId, Owner>>>,
owner: Owner,
}
pub fn provide_stores() {
let owner = Owner::current().expect("mitsuami: provide_stores needs a scope (Owner::with)");
provide(Registry { stores: Rc::default(), scopes: 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 scope = registry.owner.child();
registry.scopes.borrow_mut().insert(TypeId::of::<S>(), scope);
let store = scope.with(S::create);
registry.stores.borrow_mut().insert(TypeId::of::<S>(), Rc::new(store.clone()));
store
}
fn store_scope<S: Store>() -> Owner {
if let Some(scope) = Owner::providing::<S>() {
return scope;
}
let scope = inject::<Registry>().and_then(|registry| registry.scopes.borrow().get(&TypeId::of::<S>()).copied());
scope.unwrap_or_else(|| {
panic!(
"mitsuami: {}::spawn found no store scope; spawn from an app's view or task, with a store \
from use_store or one provided above it",
std::any::type_name::<S>()
)
})
}