1
0

atom_ref.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. use crate::{use_atom_root, AtomId, AtomRef, AtomRoot, Readable};
  2. use dioxus_core::{ScopeId, ScopeState};
  3. use std::{
  4. cell::{Ref, RefCell, RefMut},
  5. rc::Rc,
  6. };
  7. ///
  8. ///
  9. ///
  10. ///
  11. ///
  12. ///
  13. ///
  14. ///
  15. pub fn use_atom_ref<T: 'static>(cx: &ScopeState, atom: AtomRef<T>) -> &UseAtomRef<T> {
  16. let root = use_atom_root(cx);
  17. &cx.use_hook(|_| {
  18. root.initialize(atom);
  19. (
  20. UseAtomRef {
  21. ptr: atom.unique_id(),
  22. root: root.clone(),
  23. scope_id: cx.scope_id(),
  24. value: root.register(atom, cx.scope_id()),
  25. },
  26. AtomRefSubscription {
  27. ptr: atom.unique_id(),
  28. root: root.clone(),
  29. scope_id: cx.scope_id(),
  30. },
  31. )
  32. })
  33. .0
  34. }
  35. pub struct AtomRefSubscription {
  36. ptr: AtomId,
  37. root: Rc<AtomRoot>,
  38. scope_id: ScopeId,
  39. }
  40. impl Drop for AtomRefSubscription {
  41. fn drop(&mut self) {
  42. self.root.unsubscribe(self.ptr, self.scope_id)
  43. }
  44. }
  45. pub struct UseAtomRef<T> {
  46. ptr: AtomId,
  47. value: Rc<RefCell<T>>,
  48. root: Rc<AtomRoot>,
  49. scope_id: ScopeId,
  50. }
  51. impl<T> Clone for UseAtomRef<T> {
  52. fn clone(&self) -> Self {
  53. Self {
  54. ptr: self.ptr,
  55. value: self.value.clone(),
  56. root: self.root.clone(),
  57. scope_id: self.scope_id,
  58. }
  59. }
  60. }
  61. impl<T: 'static> UseAtomRef<T> {
  62. pub fn read(&self) -> Ref<T> {
  63. self.value.borrow()
  64. }
  65. pub fn write(&self) -> RefMut<T> {
  66. self.root.force_update(self.ptr);
  67. self.value.borrow_mut()
  68. }
  69. pub fn write_silent(&self) -> RefMut<T> {
  70. self.value.borrow_mut()
  71. }
  72. pub fn set(&self, new: T) {
  73. self.root.force_update(self.ptr);
  74. self.root.set(self.ptr, new);
  75. }
  76. }