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
use std::rc::{Rc, Weak};

/// A trait to take a [Callback] or other custom callback type and
/// produce a [Listener], a weak reference to that callback.
pub trait AsListener<State, Event> {
    /// Produce a [Listener], a weak reference to this callback.
    fn as_listener(&self) -> Listener<State, Event>;
}

/// A weak reference to a callback function (usually [Callback]) which
/// is notified of changes to [Store](crate::Store) `State`, and
/// `Event`s produced by the store.
///
/// See [Callback](Callback) for more information about how this is
/// typically used.
#[derive(Clone)]
pub struct Listener<State, Event>(Weak<dyn Fn(Rc<State>, Event)>);

impl<State, Event> Listener<State, Event> {
    /// Attempt to upgrade the weak reference in this listener to a
    /// [Callback], otherwise if unable to, returns `None`.
    pub fn as_callback(&self) -> Option<Callback<State, Event>> {
        match self.0.upgrade() {
            Some(listener_rc) => Some(Callback(listener_rc)),
            None => None,
        }
    }
}

impl<State, Event> AsListener<State, Event> for Listener<State, Event> {
    fn as_listener(&self) -> Listener<State, Event> {
        Listener(self.0.clone())
    }
}

/// A wrapper for a callback which is notified of changes to
/// [Store](crate::Store) `State`, and `Event`s produced by the store.
///
/// ## Example
///
/// The following example makes use of the [AsListener](AsListener)
/// trait implementation for `Callback` which allows it to be used in
/// [Store::subscribe()](crate::Store::subscribe). The
/// [AsListener](AsListener) trait creates a weak reference to this
/// callback in a [Listener](Listener), which is given to the
/// [Store](crate::Store). When the callback is dropped, the listener will be
/// removed from the store.
///
/// ```
/// # use reactive_state::{ReducerFn, Store, ReducerResult};
/// # let reducer: ReducerFn<(), (), (), ()> = |_state, _action| { ReducerResult::default() };
/// # let store = Store::new(reducer, ());
/// use reactive_state::Callback;
///
/// let callback = Callback::new(|_state, _event| {
///     println!("Callback invoked");
/// });
///
/// store.subscribe(&callback);
/// ```
///
/// ## Optional Features
///
/// If the `"yew"` crate feature is enabled, a number of `From`
/// implementations are available to convert `yew` callbacks into
/// this:
///
/// + `From<yew::Callback<Rc<State>>>`
/// + `From<yew::Callback<(Rc<State>, Event)>>`
/// + `From<yew::Callback<()>>`
#[derive(Clone)]
pub struct Callback<State, Event>(Rc<dyn Fn(Rc<State>, Event)>);

impl<State, Event> AsListener<State, Event> for &Callback<State, Event> {
    fn as_listener(&self) -> Listener<State, Event> {
        Listener(Rc::downgrade(&self.0))
    }
}

impl<State, Event> Callback<State, Event> {
    pub fn new<C: Fn(Rc<State>, Event) + 'static>(closure: C) -> Self {
        Callback(Rc::new(closure))
    }
    pub fn emit(&self, state: Rc<State>, event: Event) {
        (self.0)(state, event)
    }
}

impl<C, State, Event> From<C> for Callback<State, Event>
where
    C: Fn(Rc<State>, Event) + 'static,
{
    fn from(closure: C) -> Self {
        Callback(Rc::new(closure))
    }
}

#[cfg(feature = "yew")]
#[cfg_attr(docsrs, doc(cfg(feature = "yew")))]
impl<State, Event> From<yew::Callback<Rc<State>>> for Callback<State, Event>
where
    State: 'static,
    Event: 'static,
{
    fn from(yew_callback: yew::Callback<Rc<State>>) -> Self {
        Callback(Rc::new(move |state, _| {
            yew_callback.emit(state);
        }))
    }
}

#[cfg(feature = "yew")]
#[cfg_attr(docsrs, doc(cfg(feature = "yew")))]
impl<State, Event> From<yew::Callback<(Rc<State>, Event)>> for Callback<State, Event>
where
    State: 'static,
    Event: 'static,
{
    fn from(yew_callback: yew::Callback<(Rc<State>, Event)>) -> Self {
        Callback(Rc::new(move |state, event| {
            yew_callback.emit((state, event));
        }))
    }
}

#[cfg(feature = "yew")]
#[cfg_attr(docsrs, doc(cfg(feature = "yew")))]
impl<State, Event> From<yew::Callback<()>> for Callback<State, Event>
where
    State: 'static,
    Event: 'static,
{
    fn from(yew_callback: yew::Callback<()>) -> Self {
        Callback(Rc::new(move |_, _| {
            yew_callback.emit(());
        }))
    }
}