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
mod graphics;
mod lazy_bridge;
mod live;
mod wired_bridge;
pub mod wired_widget;

use crate::agents::graphics::{GraphicsAgent, GraphicsResponse};
use crate::agents::live::wire::WireEnvelope;
use crate::agents::live::{LiveAgent, LiveResponse};
use anyhow::Error;
use lazy_bridge::LazyBridge;
pub use lazy_bridge::OnBridgeEvent;
use rill_protocol::io::client::ClientReqId;
use std::hash::Hash;
use std::time::Duration;
pub use wired_bridge::OnWireEvent;
use wired_bridge::WiredBridge;
use yew::services::timeout::{TimeoutService, TimeoutTask};
use yew::{Callback, Component, ComponentLink, Html, Properties, ShouldRender};

pub trait Widget: Default + 'static {
    type Event;
    // TODO: Don't `Clone` since the reference required
    type Tag: Clone + Eq + Hash;
    type Properties: Properties + PartialEq;
    type Meta: Default;

    fn init(&mut self, _ctx: &mut Context<Self>) {}

    fn on_props(&mut self, _ctx: &mut Context<Self>) {}

    fn on_event(&mut self, _event: Self::Event, _ctx: &mut Context<Self>) {}

    fn view(&self, ctx: &Context<Self>) -> Html;

    // TODO: Replate to the trait `OnRendered`
    fn rendered(&mut self, _first: bool) -> Result<(), Error> {
        Ok(())
    }
}

pub type Context<T> = WidgetContext<T>;

pub struct WidgetContext<T: Widget> {
    props: T::Properties,
    link: ComponentLink<WidgetRuntime<T>>,

    live: WiredBridge<ClientReqId, LiveAgent, T>,
    graphics: LazyBridge<GraphicsAgent, T>,
    should_render: bool,
    rendered: bool,
    scheduled: Option<TimeoutTask>,

    drop_hooks: Vec<DropHook<T>>,

    // TODO: Store router state here
    // keep them together with `Meta`
    // provide access to it and store in the
    meta: T::Meta,
}

pub type DropHook<T> = Box<dyn FnOnce(&mut T, &mut Context<T>)>;

impl<T: Widget> Drop for WidgetRuntime<T> {
    fn drop(&mut self) {
        if !self.context.drop_hooks.is_empty() {
            let hooks: Vec<_> = self.context.drop_hooks.drain(..).collect();
            for hook in hooks {
                hook(&mut self.widget, &mut self.context);
            }
        }
        /*
        for (req_id, _tag) in self.wires_from_live.drain() {
            let req = LiveRequest::TerminateWire;
            let envelope = WireEnvelope::new(req_id, req);
            self.context.connection.send(envelope);
        }
        */
    }
}

impl<T: Widget> WidgetContext<T> {
    /// Schedule a timeout.
    ///
    /// Note: It's impossible to move to a separate module,
    /// because it requires a link to a `Component`.
    pub fn schedule(&mut self, ms: u64, msg: T::Event) {
        let dur = Duration::from_millis(ms);
        let generator = move |_| Msg::Event(msg);
        let callback = self.link.callback_once(generator);
        let task = TimeoutService::spawn(dur, callback);
        self.scheduled = Some(task);
    }

    pub fn is_scheduled(&self) -> bool {
        self.scheduled.is_some()
    }

    pub fn unschedule(&mut self) {
        self.scheduled.take();
    }
}

impl<T: Widget> WidgetContext<T> {
    pub fn properties(&self) -> &T::Properties {
        &self.props
    }

    pub fn meta(&self) -> &T::Meta {
        &self.meta
    }

    pub fn meta_mut(&mut self) -> &mut T::Meta {
        &mut self.meta
    }

    // TODO: Rename to `schedule_redraw`
    pub fn redraw(&mut self) {
        self.should_render = true;
    }

    pub fn is_rendered(&self) -> bool {
        self.rendered
    }

    pub fn callback<F, IN>(&self, f: F) -> Callback<IN>
    where
        F: Fn(IN) -> T::Event + 'static,
    {
        let generator = move |event| Msg::Event(f(event));
        self.link.callback(generator)
    }

    pub fn event<IN>(&self, msg: impl Into<T::Event>) -> Callback<IN>
    where
        T::Event: Clone,
    {
        let msg = msg.into();
        let generator = move |_| Msg::Event(msg.clone());
        self.link.callback(generator)
    }

    pub fn notification<IN>(&self) -> Callback<IN>
    where
        T: NotificationHandler<IN>,
        IN: 'static,
    {
        let generator = move |event| {
            let holder = NotificationImpl { event: Some(event) };
            Msg::InPlace(Box::new(holder))
        };
        self.link.callback(generator)
    }

    /* not necessary right now
    pub fn send(&mut self, event: T::Event) {
        self.link.send_message(Msg::Event(event));
    }
    */
}

pub trait NotificationHandler<IN>: Widget {
    fn handle(&mut self, event: IN, context: &mut Context<Self>) -> Result<(), Error>;
}

struct NotificationImpl<IN> {
    event: Option<IN>,
}

impl<T, IN> WidgetCallbackFn<T> for NotificationImpl<IN>
where
    T: NotificationHandler<IN> + Widget,
{
    fn handle(&mut self, widget: &mut T, context: &mut Context<T>) -> Result<(), Error> {
        if let Some(event) = self.event.take() {
            widget.handle(event, context)?;
        }
        Ok(())
    }
}

pub trait WidgetCallbackFn<T: Widget> {
    fn handle(&mut self, widget: &mut T, context: &mut Context<T>) -> Result<(), Error>;
}

pub enum Msg<T: Widget> {
    // TODO: Implement handlers as traits. Envelope-based.
    LiveIncomingWired(WireEnvelope<ClientReqId, LiveResponse>),
    GraphicsIncoming(GraphicsResponse),
    Event(T::Event),
    InPlace(Box<dyn WidgetCallbackFn<T>>),
}

pub struct WidgetRuntime<T: Widget> {
    widget: T,
    context: WidgetContext<T>,
}

impl<T: Widget> Component for WidgetRuntime<T> {
    type Message = Msg<T>;
    type Properties = T::Properties;

    fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
        let mut context = WidgetContext {
            props,
            link,

            live: WiredBridge::default(),
            graphics: LazyBridge::default(),
            //router: LazyBridge::default(),
            should_render: false,
            rendered: false,
            scheduled: None,

            drop_hooks: Vec::new(),
            meta: T::Meta::default(),
            //router_state: T::RouterState::default(),
        };
        let mut widget = T::default();
        widget.init(&mut context);
        widget.on_props(&mut context);
        Self { widget, context }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        self.context.should_render = false;
        match msg {
            Msg::LiveIncomingWired(envelope) => {
                let req_id = envelope.id;
                if let Some(tag) = self.context.live.registry().tag(&req_id) {
                    match &envelope.data {
                        LiveResponse::WireDone => {
                            self.context.live.registry().remove(&req_id);
                        }
                        LiveResponse::Forwarded(_) => {
                            // TODO: Extract response here and use it in handler
                        }
                    }
                    if let Some(handler) = self.context.live.handler() {
                        if let Err(err) =
                            handler(&mut self.widget, tag.as_ref(), envelope, &mut self.context)
                        {
                            log::error!("Live handler failed: {}", err);
                        }
                    }
                }
            }
            Msg::GraphicsIncoming(response) => {
                if let Some(handler) = self.context.graphics.handler() {
                    if let Err(err) = handler(&mut self.widget, response, &mut self.context) {
                        log::error!("Graphics handler failed: {}", err);
                    }
                }
            }
            Msg::InPlace(mut func) => {
                if let Err(err) = func.handle(&mut self.widget, &mut self.context) {
                    log::error!("Widget callback failed: {}", err);
                }
            }
            Msg::Event(event) => {
                self.widget.on_event(event, &mut self.context);
            }
        }
        self.context.should_render
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        if props != self.context.props {
            self.context.props = props;
            self.widget.on_props(&mut self.context);
            self.context.should_render
        } else {
            false
        }
    }

    fn view(&self) -> Html {
        self.widget.view(&self.context)
    }

    fn rendered(&mut self, first_render: bool) {
        if first_render {
            self.context.rendered = true;
        }
        if let Err(err) = self.widget.rendered(first_render) {
            log::error!("Rendering failed: {}", err);
        }
    }
}