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
//! The functional interface for Yewdux
use std::{ops::Deref, rc::Rc};

use yew::functional::*;

use crate::{dispatch::Dispatch, store::Store, Context};

#[hook]
fn use_cx() -> Context {
    #[cfg(target_arch = "wasm32")]
    {
        use_context::<crate::context::Context>().unwrap_or_else(crate::context::Context::global)
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        use_context::<crate::context::Context>().expect("YewduxRoot not found")
    }
}

#[hook]
pub fn use_dispatch<S: Store>() -> Dispatch<S> {
    Dispatch::new(&use_cx())
}

/// This hook allows accessing the state of a store. When the store is modified, a re-render is
/// automatically triggered.
///
/// # Example
/// ```
/// use yew::prelude::*;
/// use yewdux::prelude::*;
///
/// #[derive(Default, Clone, PartialEq, Store)]
/// struct State {
///     count: u32,
/// }
///
/// #[function_component]
/// fn App() -> Html {
///     let (state, dispatch) = use_store::<State>();
///     let onclick = dispatch.reduce_mut_callback(|s| s.count += 1);
///     html! {
///         <>
///         <p>{ state.count }</p>
///         <button {onclick}>{"+1"}</button>
///         </>
///     }
/// }
/// ```
#[hook]
pub fn use_store<S: Store>() -> (Rc<S>, Dispatch<S>) {
    let dispatch = use_dispatch::<S>();
    let state: UseStateHandle<Rc<S>> = use_state(|| dispatch.get());
    let dispatch = {
        let state = state.clone();
        use_state(move || dispatch.subscribe_silent(move |val| state.set(val)))
    };

    (Rc::clone(&state), dispatch.deref().clone())
}

/// Simliar to ['use_store'], but only provides the state.
#[hook]
pub fn use_store_value<S: Store>() -> Rc<S> {
    let (state, _dispatch) = use_store();

    state
}

/// Provides access to some derived portion of state. Useful when you only want to rerender
/// when that portion has changed.
///
/// # Example
/// ```
/// use yew::prelude::*;
/// use yewdux::prelude::*;
///
/// #[derive(Default, Clone, PartialEq, Store)]
/// struct State {
///     count: u32,
/// }
///
/// #[function_component]
/// fn App() -> Html {
///     let dispatch = use_dispatch::<State>();
///     let count = use_selector(|state: &State| state.count);
///     let onclick = dispatch.reduce_mut_callback(|state| state.count += 1);
///
///     html! {
///         <>
///         <p>{ *count }</p>
///         <button {onclick}>{"+1"}</button>
///         </>
///     }
/// }
/// ```
#[hook]
pub fn use_selector<S, F, R>(selector: F) -> Rc<R>
where
    S: Store,
    R: PartialEq + 'static,
    F: Fn(&S) -> R + 'static,
{
    use_selector_eq(selector, |a, b| a == b)
}

/// Similar to [`use_selector`], with the additional flexibility of a custom equality check for
/// selected value.
#[hook]
pub fn use_selector_eq<S, F, R, E>(selector: F, eq: E) -> Rc<R>
where
    S: Store,
    R: 'static,
    F: Fn(&S) -> R + 'static,
    E: Fn(&R, &R) -> bool + 'static,
{
    use_selector_eq_with_deps(move |state, _| selector(state), eq, ())
}

/// Similar to [`use_selector`], but also allows for dependencies from environment. This is
/// necessary when the derived value uses some captured value.
///
/// # Example
/// ```
/// use std::collections::HashMap;
///
/// use yew::prelude::*;
/// use yewdux::prelude::*;
///
/// #[derive(Default, Clone, PartialEq, Store)]
/// struct State {
///     user_names: HashMap<u32, String>,
/// }
///
/// #[derive(Properties, PartialEq, Clone)]
/// struct AppProps {
///     user_id: u32,
/// }
///
/// #[function_component]
/// fn ViewName(&AppProps { user_id }: &AppProps) -> Html {
///     let user_name = use_selector_with_deps(
///        |state: &State, id| state.user_names.get(id).cloned().unwrap_or_default(),
///        user_id,
///     );
///
///     html! {
///         <p>
///             { user_name }
///         </p>
///     }
/// }
/// ```
#[hook]
pub fn use_selector_with_deps<S, F, R, D>(selector: F, deps: D) -> Rc<R>
where
    S: Store,
    R: PartialEq + 'static,
    D: Clone + PartialEq + 'static,
    F: Fn(&S, &D) -> R + 'static,
{
    use_selector_eq_with_deps(selector, |a, b| a == b, deps)
}

/// Similar to [`use_selector_with_deps`], but also allows an equality function, similar to
/// [`use_selector_eq`]
#[hook]
pub fn use_selector_eq_with_deps<S, F, R, D, E>(selector: F, eq: E, deps: D) -> Rc<R>
where
    S: Store,
    R: 'static,
    D: Clone + PartialEq + 'static,
    F: Fn(&S, &D) -> R + 'static,
    E: Fn(&R, &R) -> bool + 'static,
{
    let dispatch = use_dispatch::<S>();
    // Given to user, this is what we update to force a re-render.
    let selected = {
        let state = dispatch.get();
        let value = selector(&state, &deps);

        use_state(|| Rc::new(value))
    };
    // Local tracking value, because `selected` isn't updated in our subscriber scope.
    let current = {
        let value = Rc::clone(&selected);
        use_mut_ref(|| value)
    };

    let _dispatch = {
        let selected = selected.clone();
        use_memo(deps, move |deps| {
            let deps = deps.clone();
            dispatch.subscribe(move |val: Rc<S>| {
                let value = selector(&val, &deps);

                if !eq(&current.borrow(), &value) {
                    let value = Rc::new(value);
                    // Update value for user.
                    selected.set(Rc::clone(&value));
                    // Make sure to update our tracking value too.
                    *current.borrow_mut() = Rc::clone(&value);
                }
            })
        })
    };

    Rc::clone(&selected)
}