use_shared_state.rs 4.6 KB

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