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//!
21//! An action that runs async work starts it with [`Store::spawn`], so it
22//! runs in the store's scope. [`spawn_local`] would tie it to the view that
23//! called the action, and closing that view (a dialog, say) would cancel it.
24
25use std::any::{Any, TypeId};
26use std::cell::RefCell;
27use std::collections::HashMap;
28use std::future::Future;
29use std::rc::Rc;
30
31use mitsuami_reactive::{Owner, inject, provide};
32
33use crate::task::{TaskHandle, spawn_local};
34
35/// App-wide state, created once per app by [`use_store`].
36pub trait Store: Clone + 'static {
37 /// Creates the store. Runs once, in a scope that lives as long as the
38 /// app, so the store's effects, resources and tasks do too.
39 fn create() -> Self;
40
41 /// Runs `future` on the UI thread in the store's scope, for its
42 /// actions' async work: it goes on when the view that called the
43 /// action goes away, and stops with the store. The store is the one
44 /// [`use_store`] finds from the caller's scope, `provide`d or the app's.
45 ///
46 /// ```ignore
47 /// fn rename(&self, path: PathBuf, name: String) {
48 /// let store = *self;
49 /// self.spawn(async move {
50 /// let result = spawn_blocking(move || fs::rename(&path, &name)).await;
51 /// store.renamed(result);
52 /// });
53 /// }
54 /// ```
55 ///
56 /// # Panics
57 /// Outside of an app, or for a store neither `provide`d above this
58 /// scope nor made by [`use_store`].
59 fn spawn(&self, future: impl Future<Output = ()> + 'static) -> TaskHandle {
60 store_scope::<Self>().with(|| spawn_local(future))
61 }
62}
63
64#[derive(Clone)]
65struct Registry {
66 stores: Rc<RefCell<HashMap<TypeId, Rc<dyn Any>>>>,
67 /// Each store's scope, a child of the app scope. Known before the store
68 /// is made, so `create` can spawn.
69 scopes: Rc<RefCell<HashMap<TypeId, Owner>>>,
70 /// The app scope.
71 owner: Owner,
72}
73
74/// Makes [`use_store`] work in the current scope and below: the stores
75/// live as long as it. `App` and `TestApp` call it in their app scope.
76///
77/// # Panics
78/// When called outside of any scope.
79pub fn provide_stores() {
80 let owner = Owner::current().expect("mitsuami: provide_stores needs a scope (Owner::with)");
81 provide(Registry { stores: Rc::default(), scopes: Rc::default(), owner });
82}
83
84/// The app's instance of store `S`, created on first use; or the one
85/// `provide`d nearest to this scope, if any.
86///
87/// # Panics
88/// Outside of an app (no [`provide_stores`] above this scope).
89pub fn use_store<S: Store>() -> S {
90 if let Some(store) = inject::<S>() {
91 return store;
92 }
93 let registry = inject::<Registry>().unwrap_or_else(|| {
94 panic!(
95 "mitsuami: use_store::<{}>() outside of an app; mount the view with App or TestApp, \
96 or call provide_stores() in an enclosing scope",
97 std::any::type_name::<S>()
98 )
99 });
100 let existing = registry.stores.borrow().get(&TypeId::of::<S>()).cloned();
101 if let Some(store) = existing {
102 return store.downcast_ref::<S>().expect("mitsuami: store registry holds the wrong type").clone();
103 }
104 // Not borrowed while creating: a store may use other stores.
105 let scope = registry.owner.child();
106 registry.scopes.borrow_mut().insert(TypeId::of::<S>(), scope);
107 let store = scope.with(S::create);
108 registry.stores.borrow_mut().insert(TypeId::of::<S>(), Rc::new(store.clone()));
109 store
110}
111
112/// The scope of the store `use_store::<S>()` would return here: the one it
113/// was `provide`d in, or the one the app made it in.
114fn store_scope<S: Store>() -> Owner {
115 if let Some(scope) = Owner::providing::<S>() {
116 return scope;
117 }
118 let scope = inject::<Registry>().and_then(|registry| registry.scopes.borrow().get(&TypeId::of::<S>()).copied());
119 scope.unwrap_or_else(|| {
120 panic!(
121 "mitsuami: {}::spawn found no store scope; spawn from an app's view or task, with a store \
122 from use_store or one provided above it",
123 std::any::type_name::<S>()
124 )
125 })
126}