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
//! Wrapper for components with shared state.
use std::collections::HashSet;
use std::rc::Rc;

use yew::{
    html,
    worker::{Agent, AgentLink, Bridge, Bridged, Context, HandlerId},
    Component, ComponentLink, Html, ShouldRender,
};

use super::handle::{Handle, SharedState};
use super::handler::{Handler, Reduction, ReductionOnce};

enum Request<T> {
    /// Apply a state change.
    Apply(Reduction<T>),
    /// Apply a state change once.
    ApplyOnce(ReductionOnce<T>),
    /// Subscribe to be notified when state changes.
    Subscribe,
    /// Remove subscription.
    UnSubscribe,
}

enum Response<T> {
    /// Update subscribers with current state.
    State(Rc<T>),
}

/// Context agent for managing shared state. In charge of applying changes to state then notifying
/// subscribers of new state.
struct SharedStateService<T>
where
    T: Handler + Clone + 'static,
{
    handler: T,
    subscriptions: HashSet<HandlerId>,
    link: AgentLink<SharedStateService<T>>,
}

impl<T> Agent for SharedStateService<T>
where
    T: Handler + Clone + 'static,
{
    type Message = ();
    type Reach = Context<Self>;
    type Input = Request<<T as Handler>::Model>;
    type Output = Response<<T as Handler>::Model>;

    fn create(link: AgentLink<Self>) -> Self {
        Self {
            handler: <T as Handler>::new(),
            subscriptions: Default::default(),
            link,
        }
    }

    fn update(&mut self, _msg: Self::Message) {}

    fn handle_input(&mut self, msg: Self::Input, who: HandlerId) {
        match msg {
            Request::Apply(reduce) => {
                self.handler.apply(reduce);
                self.notify_subscibers();
            }
            Request::ApplyOnce(reduce) => {
                self.handler.apply_once(reduce);
                self.notify_subscibers();
            }
            Request::Subscribe => {
                self.subscriptions.insert(who);
                self.link
                    .respond(who, Response::State(self.handler.state()));
            }
            Request::UnSubscribe => {
                self.subscriptions.remove(&who);
            }
        }
    }
}

impl<T> SharedStateService<T>
where
    T: Handler + Clone + 'static,
{
    fn notify_subscibers(&self) {
        for who in self.subscriptions.iter().cloned() {
            self.link
                .respond(who, Response::State(self.handler.state()));
        }
    }
}

type StateHandler<T> = <<T as SharedState>::Handle as Handle>::Handler;
type Model<T> = <StateHandler<T> as Handler>::Model;

/// Wrapper for a component with shared state.
pub struct SharedStateComponent<C>
where
    C: Component,
    C::Properties: SharedState + Clone,
    StateHandler<C::Properties>: Clone,
{
    props: C::Properties,
    bridge: Box<dyn Bridge<SharedStateService<StateHandler<C::Properties>>>>,
}

/// Internal use only.
#[doc(hidden)]
pub enum SharedStateComponentMsg<T> {
    /// Recieve new local state.
    /// IMPORTANT: Changes will **not** be reflected in shared state.
    SetLocal(Rc<T>),
    /// Update shared state.
    Apply(Reduction<T>),
    ApplyOnce(ReductionOnce<T>),
}

impl<C> Component for SharedStateComponent<C>
where
    C: Component,
    C::Properties: SharedState + Clone,
    Model<C::Properties>: Default,
    StateHandler<C::Properties>: Clone,
{
    type Message = SharedStateComponentMsg<Model<C::Properties>>;
    type Properties = C::Properties;

    fn create(mut props: Self::Properties, link: ComponentLink<Self>) -> Self {
        use SharedStateComponentMsg::*;
        // Bridge to receive new state.
        let mut bridge = SharedStateService::bridge(link.callback(|msg| match msg {
            Response::State(state) => SetLocal(state),
        }));
        // Make sure we receive updates to state.
        bridge.send(Request::Subscribe);

        props
            .handle()
            .set_local_callback(link.callback(Apply), link.callback(ApplyOnce));

        SharedStateComponent { props, bridge }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        use SharedStateComponentMsg::*;
        match msg {
            Apply(reduce) => {
                self.bridge.send(Request::Apply(reduce));
                false
            }
            ApplyOnce(reduce) => {
                self.bridge.send(Request::ApplyOnce(reduce));
                false
            }
            SetLocal(state) => {
                self.props.handle().set_local_state(state);
                true
            }
        }
    }

    fn change(&mut self, mut props: Self::Properties) -> ShouldRender {
        props.handle().set_local(self.props.handle());
        self.props = props;
        true
    }

    fn view(&self) -> Html {
        let props = self.props.clone();
        html! {
            <C with props />
        }
    }
}

impl<C> std::ops::Drop for SharedStateComponent<C>
where
    C: Component,
    C::Properties: SharedState + Clone,
    StateHandler<C::Properties>: Clone,
{
    fn drop(&mut self) {
        self.bridge.send(Request::UnSubscribe);
    }
}