1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use self::error::{UseSharedStateError, UseSharedStateResult};
use dioxus_core::{ScopeId, ScopeState};
use std::{collections::HashSet, rc::Rc, sync::Arc};

#[cfg(debug_assertions)]
pub use dioxus_debug_cell::{
    error::{BorrowError, BorrowMutError},
    Ref, RefCell, RefMut,
};

#[cfg(not(debug_assertions))]
pub use std::cell::{BorrowError, BorrowMutError, Ref, RefCell, RefMut};

#[macro_export]
macro_rules! debug_location {
    () => {{
        #[cfg(debug_assertions)]
        {
            std::panic::Location::caller()
        }
        #[cfg(not(debug_assertions))]
        {
            ()
        }
    }};
}

pub mod error {
    fn locations_display(locations: &[&'static std::panic::Location<'static>]) -> String {
        locations
            .iter()
            .map(|location| format!(" - {location}"))
            .collect::<Vec<_>>()
            .join("\n")
    }
    #[derive(thiserror::Error, Debug)]
    pub enum UseSharedStateError {
        #[cfg_attr(
            debug_assertions,
            error(
                "[{0}] {1} is already borrowed at, so it cannot be borrowed mutably. Previous borrows:\n[{2}]\n\n",
                .source.attempted_at,
                .type_name,
                locations_display(&.source.already_borrowed_at)
            )
         )]
        #[cfg_attr(
            not(debug_assertions),
            error("{type_name} is already borrowed, so it cannot be borrowed mutably. (More detail available in debug mode)")
        )]
        AlreadyBorrowed {
            source: super::BorrowMutError,
            type_name: &'static str,
        },
        #[cfg_attr(
            debug_assertions,
            error(
                "[{0}] {1} is already borrowed mutably at [{2}], so it cannot be borrowed anymore.",
                .source.attempted_at,
                .type_name,
                locations_display(&.source.already_borrowed_at)
            )
         )]
        #[cfg_attr(
            not(debug_assertions),
            error("{type_name} is already borrowed mutably, so it cannot be borrowed anymore. (More detail available in debug mode)")
        )]
        AlreadyBorrowedMutably {
            source: super::BorrowError,
            type_name: &'static str,
        },
    }

    pub type UseSharedStateResult<T> = Result<T, UseSharedStateError>;
}

type ProvidedState<T> = Rc<RefCell<ProvidedStateInner<T>>>;

// Tracks all the subscribers to a shared State
pub(crate) struct ProvidedStateInner<T> {
    value: T,
    notify_any: Arc<dyn Fn(ScopeId)>,
    consumers: HashSet<ScopeId>,
    gen: usize,
}

impl<T> ProvidedStateInner<T> {
    pub(crate) fn notify_consumers(&mut self) {
        self.gen += 1;
        for consumer in self.consumers.iter() {
            (self.notify_any)(*consumer);
        }
    }
}

/// This hook provides some relatively light ergonomics around shared state.
///
/// It is not a substitute for a proper state management system, but it is capable enough to provide use_state - type
/// ergonomics in a pinch, with zero cost.
///
/// # Example
///
/// ```rust
/// # use dioxus::prelude::*;
/// #
/// # fn app(cx: Scope) -> Element {
/// #     render! {
/// #         Parent{}
/// #     }
/// # }
///
/// #[derive(Clone, Copy)]
/// enum Theme {
///     Light,
///     Dark,
/// }
///
/// // Provider
/// fn Parent<'a>(cx: Scope<'a>) -> Element<'a> {
///     use_shared_state_provider(cx, || Theme::Dark);
///     let theme = use_shared_state::<Theme>(cx).unwrap();
///
///     render! {
///         button{
///             onclick: move |_| {
///                 let current_theme = *theme.read();
///                 *theme.write() = match current_theme {
///                     Theme::Dark => Theme::Light,
///                     Theme::Light => Theme::Dark,
///                 };
///             },
///             "Change theme"
///         }
///         Child{}
///     }
/// }
///
/// // Consumer
/// fn Child<'a>(cx: Scope<'a>) -> Element<'a> {
///     let theme = use_shared_state::<Theme>(cx).unwrap();
///     let current_theme = *theme.read();
///
///     render! {
///         match current_theme {
///             Theme::Dark => {
///                 "Dark mode"
///             }
///             Theme::Light => {
///                 "Light mode"
///             }
///         }
///     }
/// }
/// ```
///
/// # How it works
///
/// Any time a component calls `write`, every consumer of the state will be notified - excluding the provider.
///
/// Right now, there is not a distinction between read-only and write-only, so every consumer will be notified.
#[must_use]
pub fn use_shared_state<T: 'static>(cx: &ScopeState) -> Option<&UseSharedState<T>> {
    let state_owner: &mut Option<UseSharedStateOwner<T>> = &mut *cx.use_hook(move || {
        let scope_id = cx.scope_id();
        let root = cx.consume_context::<ProvidedState<T>>()?;

        root.borrow_mut().consumers.insert(scope_id);

        let state = UseSharedState::new(root);
        let owner = UseSharedStateOwner { state, scope_id };
        Some(owner)
    });
    state_owner.as_mut().map(|s| {
        s.state.gen = s.state.inner.borrow().gen;
        &s.state
    })
}

/// This wrapper detects when the hook is dropped and will unsubscribe when the component is unmounted
struct UseSharedStateOwner<T> {
    state: UseSharedState<T>,
    scope_id: ScopeId,
}

impl<T> Drop for UseSharedStateOwner<T> {
    fn drop(&mut self) {
        // we need to unsubscribe when our component is unmounted
        let mut root = self.state.inner.borrow_mut();
        root.consumers.remove(&self.scope_id);
    }
}

/// State that is shared between components through the context system
pub struct UseSharedState<T> {
    pub(crate) inner: Rc<RefCell<ProvidedStateInner<T>>>,
    gen: usize,
}

impl<T> UseSharedState<T> {
    fn new(inner: Rc<RefCell<ProvidedStateInner<T>>>) -> Self {
        let gen = inner.borrow().gen;
        Self { inner, gen }
    }

    /// Notify all consumers of the state that it has changed. (This is called automatically when you call "write")
    pub fn notify_consumers(&self) {
        self.inner.borrow_mut().notify_consumers();
    }

    /// Try reading the shared state
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn try_read(&self) -> UseSharedStateResult<Ref<'_, T>> {
        match self.inner.try_borrow() {
            Ok(value) => Ok(Ref::map(value, |inner| &inner.value)),
            Err(source) => Err(UseSharedStateError::AlreadyBorrowedMutably {
                source,
                type_name: std::any::type_name::<Self>(),
            }),
        }
    }

    /// Read the shared value
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn read(&self) -> Ref<'_, T> {
        match self.try_read() {
            Ok(value) => value,
            Err(message) => panic!(
                "Reading the shared state failed: {}\n({:?})",
                message, message
            ),
        }
    }

    /// Try writing the shared state
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn try_write(&self) -> UseSharedStateResult<RefMut<'_, T>> {
        match self.inner.try_borrow_mut() {
            Ok(mut value) => {
                value.notify_consumers();
                Ok(RefMut::map(value, |inner| &mut inner.value))
            }
            Err(source) => Err(UseSharedStateError::AlreadyBorrowed {
                source,
                type_name: std::any::type_name::<Self>(),
            }),
        }
    }

    /// Calling "write" will force the component to re-render
    ///
    ///
    // TODO: We prevent unncessary notifications only in the hook, but we should figure out some more global lock
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn write(&self) -> RefMut<'_, T> {
        match self.try_write() {
            Ok(value) => value,
            Err(message) => panic!(
                "Writing to shared state failed: {}\n({:?})",
                message, message
            ),
        }
    }

    /// Tries writing the value without forcing a re-render
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn try_write_silent(&self) -> UseSharedStateResult<RefMut<'_, T>> {
        match self.inner.try_borrow_mut() {
            Ok(value) => Ok(RefMut::map(value, |inner| &mut inner.value)),
            Err(source) => Err(UseSharedStateError::AlreadyBorrowed {
                source,
                type_name: std::any::type_name::<Self>(),
            }),
        }
    }

    /// Writes the value without forcing a re-render
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn write_silent(&self) -> RefMut<'_, T> {
        match self.try_write_silent() {
            Ok(value) => value,
            Err(message) => panic!(
                "Writing to shared state silently failed: {}\n({:?})",
                message, message
            ),
        }
    }

    /// Take a reference to the inner value temporarily and produce a new value
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn with<O>(&self, immutable_callback: impl FnOnce(&T) -> O) -> O {
        immutable_callback(&*self.read())
    }

    /// Take a mutable reference to the inner value temporarily and produce a new value
    #[cfg_attr(debug_assertions, track_caller)]
    #[cfg_attr(debug_assertions, inline(never))]
    pub fn with_mut<O>(&self, mutable_callback: impl FnOnce(&mut T) -> O) -> O {
        mutable_callback(&mut *self.write())
    }
}

impl<T> Clone for UseSharedState<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            gen: self.gen,
        }
    }
}

impl<T> PartialEq for UseSharedState<T> {
    fn eq(&self, other: &Self) -> bool {
        self.gen == other.gen
    }
}

/// Provide some state for components down the hierarchy to consume without having to drill props. See [`use_shared_state`] to consume the state
///
///
/// # Example
///
/// ```rust
/// # use dioxus::prelude::*;
/// #
/// # fn app(cx: Scope) -> Element {
/// #     render! {
/// #         Parent{}
/// #     }
/// # }
///
/// #[derive(Clone, Copy)]
/// enum Theme {
///     Light,
///     Dark,
/// }
///
/// // Provider
/// fn Parent<'a>(cx: Scope<'a>) -> Element<'a> {
///     use_shared_state_provider(cx, || Theme::Dark);
///     let theme = use_shared_state::<Theme>(cx).unwrap();
///
///     render! {
///         button{
///             onclick: move |_| {
///                 let current_theme = *theme.read();
///                 *theme.write() = match current_theme {
///                     Theme::Dark => Theme::Light,
///                     Theme::Light => Theme::Dark,
///                 };
///             },
///             "Change theme"
///         }
///         // Children components that consume the state...
///     }
/// }
/// ```
pub fn use_shared_state_provider<T: 'static>(cx: &ScopeState, f: impl FnOnce() -> T) {
    cx.use_hook(|| {
        let state: ProvidedState<T> = Rc::new(RefCell::new(ProvidedStateInner {
            value: f(),
            notify_any: cx.schedule_update_any(),
            consumers: HashSet::new(),
            gen: 0,
        }));

        cx.provide_context(state);
    });
}