mitsuami_core/store.rs
1//! Stores: app-wide state and the actions on it, Pinia-style.
2//!
3//! A store is a plain struct of signals (and resources, actions) with
4//! methods. [`use_store`] returns the app's one instance, created on first
5//! use, and views share it:
6//!
7//! ```ignore
8//! #[derive(Clone, Copy)]
9//! struct Cart { items: Signal<Vec<Item>> }
10//!
11//! impl Store for Cart {
12//! fn create() -> Cart { Cart { items: signal(Vec::new()) } }
13//! }
14//!
15//! let cart = use_store::<Cart>();
16//! ```
17//!
18//! A store `provide`d in a scope takes precedence there, which is how tests
19//! (and previews) swap in a store in a known state.
20
21use std::any::{Any, TypeId};
22use std::cell::RefCell;
23use std::collections::HashMap;
24use std::rc::Rc;
25
26use mitsuami_reactive::{Owner, inject, provide};
27
28/// App-wide state, created once per app by [`use_store`].
29pub trait Store: Clone + 'static {
30 /// Creates the store. Runs once, in a scope that lives as long as the
31 /// app, so the store's effects, resources and tasks do too.
32 fn create() -> Self;
33}
34
35#[derive(Clone)]
36struct Registry {
37 stores: Rc<RefCell<HashMap<TypeId, Rc<dyn Any>>>>,
38 /// The app scope; each store gets a child of it.
39 owner: Owner,
40}
41
42/// Makes [`use_store`] work in the current scope and below: the stores
43/// live as long as it. `App` and `TestApp` call it in their app scope.
44///
45/// # Panics
46/// When called outside of any scope.
47pub fn provide_stores() {
48 let owner = Owner::current().expect("mitsuami: provide_stores needs a scope (Owner::with)");
49 provide(Registry { stores: Rc::default(), owner });
50}
51
52/// The app's instance of store `S`, created on first use; or the one
53/// `provide`d nearest to this scope, if any.
54///
55/// # Panics
56/// Outside of an app (no [`provide_stores`] above this scope).
57pub fn use_store<S: Store>() -> S {
58 if let Some(store) = inject::<S>() {
59 return store;
60 }
61 let registry = inject::<Registry>().unwrap_or_else(|| {
62 panic!(
63 "mitsuami: use_store::<{}>() outside of an app; mount the view with App or TestApp, \
64 or call provide_stores() in an enclosing scope",
65 std::any::type_name::<S>()
66 )
67 });
68 let existing = registry.stores.borrow().get(&TypeId::of::<S>()).cloned();
69 if let Some(store) = existing {
70 return store.downcast_ref::<S>().expect("mitsuami: store registry holds the wrong type").clone();
71 }
72 // Not borrowed while creating: a store may use other stores.
73 let store = registry.owner.child().with(S::create);
74 registry.stores.borrow_mut().insert(TypeId::of::<S>(), Rc::new(store.clone()));
75 store
76}