rosace_core/context.rs
1use crate::types::ComponentId;
2use rosace_state::{hook_state, Atom};
3
4/// Per-component context passed to every [`Component::build`] call.
5///
6/// Carries the component's identity and provides access to persistent local
7/// state via [`Context::state`]. State is keyed by `(component_id, call_order)`
8/// — the hook model — so call order within `build()` must be stable across frames.
9pub struct Context {
10 pub(crate) component_id: ComponentId,
11 pub(crate) hook_index: usize,
12}
13
14impl Context {
15 pub fn new(id: ComponentId) -> Self {
16 Context {
17 component_id: id,
18 hook_index: 0,
19 }
20 }
21
22 pub fn component_id(&self) -> ComponentId {
23 self.component_id
24 }
25
26 /// Returns a persistent [`Atom<T>`] for local component state.
27 ///
28 /// On first call per slot the atom is seeded with `default`. On subsequent
29 /// frames the existing atom is returned, preserving the last value.
30 pub fn state<T: Clone + Send + Sync + 'static>(&mut self, default: T) -> Atom<T> {
31 let idx = self.hook_index;
32 self.hook_index += 1;
33 hook_state(self.component_id, idx, default)
34 }
35
36 /// D008's `permanent` tier, on the hook model (D114/D121): like
37 /// [`Context::state`], but the FIRST initialization reads `key` from
38 /// the installed persist backend (falling back to `default` if the
39 /// key is absent or its bytes are stale), and every later `set`
40 /// writes through — the value survives a full app restart.
41 ///
42 /// `key` is app-global: two components using the same key share the
43 /// same stored value (by design — it's a storage key, not a hook
44 /// slot). With no backend installed (headless tests, or before
45 /// `App::launch`) this behaves exactly like plain [`Context::state`].
46 ///
47 /// Uses the atom's single `on_change` slot for the write-through —
48 /// see `Atom::set_on_change`'s doc.
49 pub fn state_permanent<T>(&mut self, key: &str, default: T) -> Atom<T>
50 where
51 T: crate::persist::PersistValue + Clone + Send + Sync + 'static,
52 {
53 let wired = self.state(false);
54 let initial = if wired.get() {
55 default // atom already exists; hook_state ignores this value
56 } else {
57 match crate::persist::persist_backend().and_then(|b| b.get(key).ok().flatten()) {
58 Some(bytes) => T::from_persist_bytes(&bytes).unwrap_or(default),
59 None => default,
60 }
61 };
62 let atom = self.state(initial);
63 if !wired.get() {
64 wired.set(true);
65 if crate::persist::persist_backend().is_some() {
66 let key = key.to_string();
67 let value_atom = atom.clone();
68 atom.set_on_change(move |_, _| {
69 if let Some(backend) = crate::persist::persist_backend() {
70 let _ = backend.set(&key, &value_atom.get().to_persist_bytes());
71 }
72 });
73 }
74 }
75 atom
76 }
77
78 /// Registers a cleanup function that runs when this component unmounts.
79 ///
80 /// Stored in the persistent [`rosace_state::cleanup_store`] keyed by
81 /// component ID. The reconciler fires these callbacks when the component
82 /// disappears from the element tree.
83 pub fn on_cleanup(&mut self, f: impl FnOnce() + Send + 'static) {
84 rosace_state::cleanup_store::register(self.component_id, Box::new(f));
85 }
86}