use crate::{use_atom_root, AtomId, AtomRef, AtomRoot, Readable}; use dioxus_core::{ScopeId, ScopeState}; use std::{ cell::{Ref, RefCell, RefMut}, rc::Rc, }; /// /// /// /// /// /// /// /// pub fn use_atom_ref(cx: &ScopeState, atom: AtomRef) -> &UseAtomRef { let root = use_atom_root(cx); &cx.use_hook(|_| { root.initialize(atom); ( UseAtomRef { ptr: atom.unique_id(), root: root.clone(), scope_id: cx.scope_id(), value: root.register(atom, cx.scope_id()), }, AtomRefSubscription { ptr: atom.unique_id(), root: root.clone(), scope_id: cx.scope_id(), }, ) }) .0 } pub struct AtomRefSubscription { ptr: AtomId, root: Rc, scope_id: ScopeId, } impl Drop for AtomRefSubscription { fn drop(&mut self) { self.root.unsubscribe(self.ptr, self.scope_id) } } pub struct UseAtomRef { ptr: AtomId, value: Rc>, root: Rc, scope_id: ScopeId, } impl Clone for UseAtomRef { fn clone(&self) -> Self { Self { ptr: self.ptr, value: self.value.clone(), root: self.root.clone(), scope_id: self.scope_id, } } } impl UseAtomRef { pub fn read(&self) -> Ref { self.value.borrow() } pub fn write(&self) -> RefMut { self.root.force_update(self.ptr); self.value.borrow_mut() } pub fn write_silent(&self) -> RefMut { self.value.borrow_mut() } pub fn set(&self, new: T) { self.root.force_update(self.ptr); self.root.set(self.ptr, new); } }