use_shared_state.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. use dioxus_core::{prelude::Context, ScopeId};
  2. use std::{
  3. cell::{Cell, Ref, RefCell, RefMut},
  4. collections::HashSet,
  5. rc::Rc,
  6. };
  7. type ProvidedState<T> = RefCell<ProvidedStateInner<T>>;
  8. // Tracks all the subscribers to a shared State
  9. pub(crate) struct ProvidedStateInner<T> {
  10. value: Rc<RefCell<T>>,
  11. notify_any: Rc<dyn Fn(ScopeId)>,
  12. consumers: HashSet<ScopeId>,
  13. }
  14. impl<T> ProvidedStateInner<T> {
  15. pub(crate) fn notify_consumers(&mut self) {
  16. for consumer in self.consumers.iter() {
  17. println!("notifiying {:?}", consumer);
  18. // log::debug("notifiying {:?}", consumer);
  19. (self.notify_any)(*consumer);
  20. }
  21. }
  22. }
  23. /// This hook provides some relatively light ergonomics around shared state.
  24. ///
  25. /// It is not a substitute for a proper state management system, but it is capable enough to provide use_state - type
  26. /// ergonimics in a pinch, with zero cost.
  27. ///
  28. /// # Example
  29. ///
  30. /// ## Provider
  31. ///
  32. /// ```rust
  33. ///
  34. ///
  35. /// ```
  36. ///
  37. /// ## Consumer
  38. ///
  39. /// ```rust
  40. ///
  41. ///
  42. /// ```
  43. ///
  44. /// # How it works
  45. ///
  46. /// Any time a component calls `write`, every consumer of the state will be notified - excluding the provider.
  47. ///
  48. /// Right now, there is not a distinction between read-only and write-only, so every consumer will be notified.
  49. ///
  50. ///
  51. ///
  52. pub fn use_shared_state<'a, T: 'static>(cx: Context<'a>) -> Option<UseSharedState<'a, T>> {
  53. cx.use_hook(
  54. |_| {
  55. let scope_id = cx.scope_id();
  56. let root = cx.consume_state::<ProvidedState<T>>();
  57. if let Some(root) = root.as_ref() {
  58. root.borrow_mut().consumers.insert(scope_id);
  59. }
  60. let value = root.as_ref().map(|f| f.borrow().value.clone());
  61. SharedStateInner {
  62. root,
  63. value,
  64. scope_id,
  65. needs_notification: Cell::new(false),
  66. }
  67. },
  68. |f| {
  69. //
  70. f.needs_notification.set(false);
  71. match (&f.value, &f.root) {
  72. (Some(value), Some(root)) => Some(UseSharedState {
  73. cx,
  74. value,
  75. root,
  76. needs_notification: &f.needs_notification,
  77. }),
  78. _ => None,
  79. }
  80. },
  81. )
  82. }
  83. struct SharedStateInner<T: 'static> {
  84. root: Option<Rc<ProvidedState<T>>>,
  85. value: Option<Rc<RefCell<T>>>,
  86. scope_id: ScopeId,
  87. needs_notification: Cell<bool>,
  88. }
  89. impl<T> Drop for SharedStateInner<T> {
  90. fn drop(&mut self) {
  91. // we need to unsubscribe when our component is unounted
  92. if let Some(root) = &self.root {
  93. let mut root = root.borrow_mut();
  94. root.consumers.remove(&self.scope_id);
  95. }
  96. }
  97. }
  98. pub struct UseSharedState<'a, T: 'static> {
  99. pub(crate) cx: Context<'a>,
  100. pub(crate) value: &'a Rc<RefCell<T>>,
  101. pub(crate) root: &'a Rc<RefCell<ProvidedStateInner<T>>>,
  102. pub(crate) needs_notification: &'a Cell<bool>,
  103. }
  104. impl<'a, T: 'static> UseSharedState<'a, T> {
  105. pub fn read(&self) -> Ref<'_, T> {
  106. self.value.borrow()
  107. }
  108. pub fn notify_consumers(self) {
  109. // if !self.needs_notification.get() {
  110. self.root.borrow_mut().notify_consumers();
  111. // self.needs_notification.set(true);
  112. // }
  113. }
  114. pub fn read_write(&self) -> (Ref<'_, T>, &Self) {
  115. (self.read(), self)
  116. }
  117. /// Calling "write" will force the component to re-render
  118. ///
  119. ///
  120. /// TODO: We prevent unncessary notifications only in the hook, but we should figure out some more global lock
  121. pub fn write(&self) -> RefMut<'_, T> {
  122. self.cx.needs_update();
  123. self.notify_consumers();
  124. self.value.borrow_mut()
  125. }
  126. /// Allows the ability to write the value without forcing a re-render
  127. pub fn write_silent(&self) -> RefMut<'_, T> {
  128. self.value.borrow_mut()
  129. }
  130. }
  131. impl<T> Copy for UseSharedState<'_, T> {}
  132. impl<'a, T> Clone for UseSharedState<'a, T>
  133. where
  134. T: 'static,
  135. {
  136. fn clone(&self) -> Self {
  137. UseSharedState {
  138. cx: self.cx,
  139. value: self.value,
  140. root: self.root,
  141. needs_notification: self.needs_notification,
  142. }
  143. }
  144. }
  145. /// Provide some state for components down the hierarchy to consume without having to drill props.
  146. ///
  147. ///
  148. ///
  149. ///
  150. ///
  151. ///
  152. ///
  153. pub fn use_provide_state<'a, T: 'static>(cx: Context<'a>, f: impl FnOnce() -> T) {
  154. cx.use_hook(
  155. |_| {
  156. let state: ProvidedState<T> = RefCell::new(ProvidedStateInner {
  157. value: Rc::new(RefCell::new(f())),
  158. notify_any: cx.schedule_update_any(),
  159. consumers: HashSet::new(),
  160. });
  161. cx.provide_state(state)
  162. },
  163. |inner| {},
  164. )
  165. }