bounce 0.9.0

The uncomplicated state management library for Yew.
Documentation
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;

use anymap2::AnyMap;
use wasm_bindgen::prelude::*;
use yew::prelude::*;

use crate::any_state::AnyState;
use crate::root_state::BounceRootState;
use crate::utils::{notify_listeners, Listener, ListenerVec};

pub use bounce_macros::Slice;

#[doc(hidden)]
pub trait Slice: PartialEq + Default {
    type Action;

    /// Performs a reduce action.
    ///
    /// This always yields a new instance of [`Rc<Self>`] so it can be compared with the previous
    /// slice using [`PartialEq`].
    fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self>;

    /// Applies a notion.
    ///
    /// This always yields a new instance of [`Rc<Self>`] so it can be compared with the previous
    /// slice using [`PartialEq`].
    #[allow(unused_variables)]
    fn apply(self: Rc<Self>, notion: Rc<dyn Any>) -> Rc<Self> {
        self
    }

    /// Returns a list of notion ids that this Slice accepts.
    fn notion_ids(&self) -> Vec<TypeId>;

    /// Notifies a slice that it has changed.
    fn changed(self: Rc<Self>) {}

    /// Creates a new slice with its initial value.
    fn create(init_states: &mut AnyMap) -> Self
    where
        Self: 'static + Sized,
    {
        init_states.remove().unwrap_or_default()
    }
}

/// A trait to provide cloning on slices.
///
/// This trait provides a `self.clone_slice()` method that can be used as an alias of `(*self).clone()`
/// in reduce and apply functions to produce a owned clone of the slice.
pub trait CloneSlice: Slice + Clone {
    /// Clones current slice.
    #[inline]
    fn clone_slice(&self) -> Self {
        self.clone()
    }
}

impl<T> CloneSlice for T where T: Slice + Clone {}

#[derive(Debug, Default)]
pub(crate) struct SliceState<T>
where
    T: Slice,
{
    value: Rc<RefCell<Rc<T>>>,
    listeners: Rc<RefCell<ListenerVec<T>>>,
}

impl<T> Clone for SliceState<T>
where
    T: Slice,
{
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            listeners: self.listeners.clone(),
        }
    }
}

impl<T> SliceState<T>
where
    T: Slice + 'static,
{
    pub fn dispatch(&self, action: T::Action) {
        let maybe_next_val = {
            let mut value = self.value.borrow_mut();
            let prev_val: Rc<T> = value.clone();
            let next_val = prev_val.clone().reduce(action);

            let should_notify = prev_val != next_val;
            *value = next_val.clone();

            should_notify.then_some(next_val)
        };

        if let Some(next_val) = maybe_next_val {
            self.notify_listeners(next_val);
        }
    }

    pub fn notify_listeners(&self, val: Rc<T>) {
        val.clone().changed();
        notify_listeners(self.listeners.clone(), val);
    }

    pub fn listen(&self, callback: Rc<Callback<Rc<T>>>) -> Listener {
        let mut callbacks_ref = self.listeners.borrow_mut();
        callbacks_ref.push(Rc::downgrade(&callback));

        Listener::new(callback)
    }

    pub fn get(&self) -> Rc<T> {
        let value = self.value.borrow();
        value.clone()
    }
}

impl<T> AnyState for SliceState<T>
where
    T: Slice + 'static,
{
    fn apply(&self, notion: Rc<dyn Any>) {
        let maybe_next_val = {
            let mut value = self.value.borrow_mut();
            let prev_val: Rc<T> = value.clone();
            let next_val = prev_val.clone().apply(notion);

            let should_notify = prev_val != next_val;
            *value = next_val.clone();

            should_notify.then_some(next_val)
        };

        if let Some(next_val) = maybe_next_val {
            self.notify_listeners(next_val);
        }
    }

    fn notion_ids(&self) -> Vec<TypeId> {
        self.value.borrow().notion_ids()
    }

    fn create(init_states: &mut AnyMap) -> Self
    where
        Self: Sized,
    {
        Self {
            value: Rc::new(RefCell::new(T::create(init_states).into())),
            listeners: Rc::default(),
        }
    }
}

/// A handle returned by [`use_slice`].
///
/// This type dereferences to `T` and has a `dispatch` method to dispatch actions.
pub struct UseSliceHandle<T>
where
    T: Slice,
{
    inner: Rc<T>,
    root: BounceRootState,
}

impl<T> UseSliceHandle<T>
where
    T: Slice + 'static,
{
    /// Dispatches `Action`.
    pub fn dispatch(&self, action: T::Action) {
        self.root.get_state::<SliceState<T>>().dispatch(action);
    }
}

impl<T> Deref for UseSliceHandle<T>
where
    T: Slice,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T> Clone for UseSliceHandle<T>
where
    T: Slice,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            root: self.root.clone(),
        }
    }
}

impl<T> fmt::Debug for UseSliceHandle<T>
where
    T: Slice + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UseSliceHandle")
            .field("inner", &self.inner)
            .finish()
    }
}

/// A hook to connect to a [`Slice`](macro@crate::Slice).
///
/// Returns a [`UseSliceHandle<T>`].
///
/// # Example
///
/// ```
/// # use std::rc::Rc;
/// # use yew::prelude::*;
/// # use bounce::prelude::*;
/// #
/// enum CounterAction {
///     Increment,
///     Decrement,
/// }
///
/// #[derive(PartialEq, Default, Slice)]
/// struct Counter(u64);
///
/// impl Reducible for Counter {
///     type Action = CounterAction;
///
///     fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
///         match action {
///             CounterAction::Increment => Self(self.0 + 1).into(),
///             CounterAction::Decrement => Self(self.0 - 1).into(),
///         }
///     }
/// }
///
/// #[function_component(CounterComp)]
/// fn counter_comp() -> Html {
///     let ctr = use_slice::<Counter>();
///
///     let inc = {
///         let ctr = ctr.clone();
///         Callback::from(move |_| {ctr.dispatch(CounterAction::Increment);})
///     };
///     let dec = {
///         let ctr = ctr.clone();
///         Callback::from(move |_| {ctr.dispatch(CounterAction::Decrement);})
///     };
///
///     html! {
///         <div>
///             <div>{"Current Counter: "}{ctr.0}</div>
///             <button onclick={inc}>{"Increase"}</button>
///             <button onclick={dec}>{"Decrease"}</button>
///         </div>
///     }
/// }
/// ```
#[hook]
pub fn use_slice<T>() -> UseSliceHandle<T>
where
    T: Slice + 'static,
{
    let root = use_context::<BounceRootState>().expect_throw("No bounce root found.");

    let val = {
        let root = root.clone();
        use_state_eq(move || root.get_state::<SliceState<T>>().get())
    };

    {
        let val = val.clone();
        let root = root.clone();
        use_memo(root, move |root| {
            let state = root.get_state::<SliceState<T>>();

            // we need to set the value here again in case the value has changed between the
            // initial render and the listener is registered.
            val.set(state.get());

            state.listen(Rc::new(Callback::from(move |m| {
                val.set(m);
            })))
        });
    }

    let val = (*val).clone();

    UseSliceHandle { inner: val, root }
}

/// A hook to produce a dispatch function for a [`Slice`](macro@crate::Slice).
///
/// Returns a `Rc<dyn Fn(T::Action)>`.
///
/// This hook will return a dispatch function that will not change across the entire lifetime of the
/// component.
///
/// # Example
///
/// ```
/// # use std::rc::Rc;
/// # use yew::prelude::*;
/// # use bounce::prelude::*;
/// #
/// # enum CounterAction {
/// #     Increment,
/// #     Decrement,
/// # }
/// #
/// # #[derive(PartialEq, Default, Slice)]
/// # struct Counter(u64);
/// #
/// # impl Reducible for Counter {
/// #     type Action = CounterAction;
/// #
/// #     fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
/// #         match action {
/// #             CounterAction::Increment => Self(self.0 + 1).into(),
/// #             CounterAction::Decrement => Self(self.0 - 1).into(),
/// #         }
/// #     }
/// # }
/// #
/// #[function_component(CounterComp)]
/// fn counter_comp() -> Html {
///     let dispatch_ctr = use_slice_dispatch::<Counter>();
///
///     let inc = {
///         let dispatch_ctr = dispatch_ctr.clone();
///         Callback::from(move |_| {dispatch_ctr(CounterAction::Increment);})
///     };
///     let dec = {
///         let dispatch_ctr = dispatch_ctr.clone();
///         Callback::from(move |_| {dispatch_ctr(CounterAction::Decrement);})
///     };
///
///     html! {
///         <div>
///             <button onclick={inc}>{"Increase"}</button>
///             <button onclick={dec}>{"Decrease"}</button>
///         </div>
///     }
/// }
/// ```
#[hook]
pub fn use_slice_dispatch<T>() -> Rc<dyn Fn(T::Action)>
where
    T: Slice + 'static,
{
    let root = use_context::<BounceRootState>().expect_throw("No bounce root found.");

    // Recreate the dispatch function in case root has changed.
    Rc::new(move |action: T::Action| {
        root.get_state::<SliceState<T>>().dispatch(action);
    })
}

/// A read-only hook to connect to the value of a [`Slice`](macro@crate::Slice).
///
/// Returns `Rc<T>`.
///
/// # Example
///
/// ```
/// # use std::rc::Rc;
/// # use yew::prelude::*;
/// # use bounce::prelude::*;
/// #
/// # enum CounterAction {
/// #     Increment,
/// #     Decrement,
/// # }
/// #
/// # #[derive(PartialEq, Default, Slice)]
/// # struct Counter(u64);
/// #
/// # impl Reducible for Counter {
/// #     type Action = CounterAction;
/// #
/// #     fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
/// #         match action {
/// #             CounterAction::Increment => Self(self.0 + 1).into(),
/// #             CounterAction::Decrement => Self(self.0 - 1).into(),
/// #         }
/// #     }
/// # }
/// #
/// #[function_component(CounterComp)]
/// fn counter_comp() -> Html {
///     let ctr = use_slice_value::<Counter>();
///
///     html! {
///         <div>
///             <div>{"Current Counter: "}{ctr.0}</div>
///         </div>
///     }
/// }
/// ```
#[hook]
pub fn use_slice_value<T>() -> Rc<T>
where
    T: Slice + 'static,
{
    use_slice::<T>().inner
}