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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! A wasm app in the structure of [The Elm Architecture].
//!
//! The app is represented by a model which is the state of the app, a function that accepts user
//! defined messages and updates the model, and a function which renders the model into a virtual
//! dom representation.
//!
//! Because the update and render portions of the app are completely separated, it is trivial to
//! test these in isolation.
//!
//! [The Elm Architecture]: https://guide.elm-lang.org/architecture/

pub mod detach;
pub mod model;
pub mod dispatch;
pub mod side_effect;
pub mod application;

pub use crate::app::detach::Detach;
pub use crate::app::model::{Update, Render};
pub use crate::app::dispatch::Dispatcher;
pub use crate::app::side_effect::{SideEffect, Processor, Commands};
pub use crate::app::application::{Application, ScheduledRender};

use web_sys;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt;
use std::hash::Hash;
use crate::diff;
use crate::vdom::DomIter;
use crate::vdom::Storage;
use crate::vdom::WebItem;
use crate::route::Route;

/// Struct used to configure and attach an application to the DOM.
pub struct AppBuilder<Message, Command, Processor, Router>
where
    Command: SideEffect<Message>,
    Processor: side_effect::Processor<Message, Command>,
    Router: Route<Message>,
{
    router: Option<Rc<Router>>,
    processor: Processor,
    clear_parent: bool,
    message: std::marker::PhantomData<Message>,
    command: std::marker::PhantomData<Command>,
}

impl<Message, Command> Default
for AppBuilder<
    Message,
    Command,
    side_effect::DefaultProcessor<Message, Command>,
    (),
>
where
    Command: SideEffect<Message>,
{
    fn default() -> Self {
        AppBuilder {
            router: None,
            processor: side_effect::DefaultProcessor::default(),
            clear_parent: false,
            message: std::marker::PhantomData,
            command: std::marker::PhantomData,
        }
    }
}

impl<Message, Command, Processor, Router>
AppBuilder<Message, Command, Processor, Router>
where
    Command: SideEffect<Message> + 'static,
    Processor: side_effect::Processor<Message, Command> + 'static,
    Router: Route<Message> + 'static,
{
    /// Handle popstate and hashchange events for this app.
    ///
    /// The router will need to implement the [`Route`] trait.
    ///
    /// [`Route`]: ../route/trait.Route.html
    #[must_use]
    pub fn router<R: Route<Message>>(self, router: R) -> AppBuilder<Message, Command, Processor, R> {
        let AppBuilder {
            message,
            command,
            processor,
            clear_parent,
            router: _router,
        } = self;

        AppBuilder {
            message: message,
            command: command,
            processor,
            clear_parent: clear_parent,
            router: Some(Rc::new(router)),
        }
    }

    /// Process side-effecting commands.
    #[must_use]
    pub(crate) fn processor<P: side_effect::Processor<Message, Command>>(self, processor: P) -> AppBuilder<Message, Command, P, Router> {
        let AppBuilder {
            message,
            command,
            router,
            clear_parent,
            processor: _processor,
        } = self;

        AppBuilder {
            message: message,
            command: command,
            processor: processor,
            router: router,
            clear_parent: clear_parent,
        }
    }

    /// Remove all children from the parent when attaching the app.
    ///
    /// This is useful for displaying fallback text or a loading screen that will then be removed
    /// when the app is attached.
    #[must_use]
    pub fn clear(mut self) -> Self {
        self.clear_parent = true;
        self
    }

    /// Create an app, but don't attach it yet.
    ///
    /// Initialize everything, but don't actually attach the app to the dom. Instead return all of
    /// the top level nodes.
    #[must_use]
    pub(crate) fn create<Model, DomTree, Key>(self, mut model: Model)
    -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>)
    where
        Model: Update<Message, Command> + Render<DomTree> + 'static,
        DomTree: DomIter<Message, Command, Key> + 'static,
        Message: fmt::Debug + Clone + PartialEq + 'static,
        Command: SideEffect<Message> + fmt::Debug + 'static,
        Key: Eq + Hash + 'static,
    {
        let AppBuilder {
            router,
            processor,
            ..
        } = self;

        let mut commands = Commands::default();

        if let Some(ref router) = router {
            // initialize the model with the initial URL
            let url = web_sys::window()
                .expect("window")
                .document()
                .expect("document")
                .url()
                .expect("url");

            if let Some(msg) = router.route(&url) {
                model.update(msg, &mut commands);
            }
        }

        // create the app
        let (app_rc, nodes) = App::create(model, processor);
        let dispatcher = Dispatcher::from(&app_rc);

        if let Some(ref router) = router {
            let window = web_sys::window()
                .expect("couldn't get window handle");

            let document = window.document()
                .expect("couldn't get document handle");

            // register event handlers
            for event in ["popstate", "hashchange"].iter() {
                let dispatcher = dispatcher.clone();
                let document = document.clone();
                let router = router.clone();
                let closure = Closure::wrap(
                    Box::new(move |_event| {
                        let url = document.url()
                            .expect_throw("couldn't get document url");

                        if let Some(msg) = router.route(&url) {
                            dispatcher.dispatch(msg);
                        }
                    }) as Box<dyn FnMut(web_sys::Event)>
                );

                window
                    .add_event_listener_with_callback(event, closure.as_ref().unchecked_ref())
                    .expect("failed to add event listener");

                app_rc.borrow_mut().push_listener((event.to_string(), closure));
            }

            // execute side effects
            for cmd in commands.immediate {
                app_rc.borrow().process(cmd, &dispatcher);
            }
            for cmd in commands.post_render {
                app_rc.borrow().process(cmd, &dispatcher);
            }
        }

        (app_rc, nodes)
    }

    /// Attach an app to the dom.
    ///
    /// The app will be attached at the given parent node and initialized with the given model.
    /// Event handlers will be registered as necessary.
    #[must_use]
    pub fn attach<Model, DomTree, Key>(self, parent: web_sys::Element, model: Model)
    -> Rc<RefCell<Box<dyn Application<Message, Command>>>>
    where
        Model: Update<Message, Command> + Render<DomTree> + 'static,
        DomTree: DomIter<Message, Command, Key> + 'static,
        Message: fmt::Debug + Clone + PartialEq + 'static,
        Command: SideEffect<Message> + fmt::Debug + 'static,
        Key: Eq + Hash + 'static,
    {
        if self.clear_parent {
            // remove all children of our parent element
            while let Some(child) = parent.first_child() {
                parent.remove_child(&child)
                    .expect("failed to remove child of parent element");
            }
        }

        // create the app
        let (app_rc, nodes) = self.create(model);

        // attach this app to the dom
        for node in nodes.iter() {
            parent.append_child(node)
                .expect("failed to append child to parent element");
        }

        app_rc
    }
}

impl<Model, DomTree, Processor, Message, Command, Key>
Application<Message, Command>
for App<Model, DomTree, Processor, Message, Command, Key>
where
    Model: Update<Message, Command> + Render<DomTree> + 'static,
    Command: SideEffect<Message> + fmt::Debug + 'static,
    Processor: side_effect::Processor<Message, Command> + 'static,
    Message: fmt::Debug + Clone + PartialEq + 'static,
    DomTree: DomIter<Message, Command, Key> + 'static,
    Key: Eq + Hash + 'static,
{
    fn update(&mut self, msg: Message) -> Commands<Command> {
        // update the model
        let mut commands = Commands::default();
        self.model.update(msg, &mut commands);
        commands
    }

    fn get_scheduled_render(&mut self) -> &mut Option<ScheduledRender<Command>> {
        &mut self.animation_frame_handle
    }

    fn set_scheduled_render(&mut self, handle: ScheduledRender<Command>) {
        self.animation_frame_handle = Some(handle)
    }

    fn render(&mut self, app_rc: &Dispatcher<Message, Command>) -> Vec<Command> {
        let parent = self.node()
            .expect("empty app?")
            .parent_element()
            .expect("app not attached to the dom");

        let App {
            ref mut model,
            ref mut storage,
            ref dom,
            ..
        } = *self;

        // render a new dom from the updated model
        let new_dom = model.render();

        // push changes to the browser
        let old = dom.dom_iter();
        let new = new_dom.dom_iter();
        let patch_set = diff::diff(old, new, storage);
        self.storage = patch_set.apply(&parent, app_rc);

        self.dom = new_dom;

        let commands;
        if let Some((cmds, _, _)) = self.animation_frame_handle.take() {
            commands = cmds;
        }
        else {
            commands = vec![];
        }

        commands

        // TODO: evaluate speedup or lack there of from using patch_set.is_noop() to check if we
        // actually need to apply this patch before applying the patch
    }

    fn process(&self, cmd: Command, app: &Dispatcher<Message, Command>) {
        Processor::process(&self.processor, cmd, app);
    }

    fn push_listener(&mut self, listener: (String, Closure<dyn FnMut(web_sys::Event)>)) {
        self.listeners.push(listener);
    }

    fn detach(&mut self, app: &Dispatcher<Message, Command>) {
        use std::iter;

        let parent = self.node()
            .expect("empty app?")
            .parent_element()
            .expect("app not attached to the dom");

        let App {
            ref mut storage,
            ref dom,
            ref mut listeners,
            ..
        } = *self;

        // remove listeners
        let window = web_sys::window()
            .expect("couldn't get window handle");

        for (event, listener) in listeners.drain(..) {
            window
                .remove_event_listener_with_callback(&event, listener.as_ref().unchecked_ref())
                .expect("failed to remove event listener");
        }

        // remove the current app from the browser's dom by diffing it with an empty virtual dom.
        let o = dom.dom_iter();
        let patch_set = diff::diff(o, iter::empty(), storage);
        self.storage = patch_set.apply(&parent, app);
    }

    fn node(&self) -> Option<web_sys::Node> {
        self.storage.first()
            .and_then(|item| -> Option<web_sys::Node> {
                match item {
                    WebItem::Element(ref node) => Some(node.clone().into()),
                    WebItem::Text(ref node) => Some(node.clone().into()),
                    WebItem::Component(component) => component.node(),
                    i => panic!("unknown item, expected something with a node in it: {:?}", i)
                }
            })
    }

    fn nodes(&self) -> Vec<web_sys::Node> {
        let mut nodes = vec![];
        let mut depth = 0;
        for item in &self.storage {
            match item {
                // ignore nodes that are not top level
                WebItem::Element(_)
                | WebItem::Text(_)
                | WebItem::Component(_)
                if depth > 0
                => {
                    depth += 1;
                }
                WebItem::Up => depth -= 1,
                WebItem::Closure(_) => {}
                WebItem::Element(ref node) => {
                    nodes.push(node.clone().into());
                    depth += 1;
                }
                WebItem::Text(ref node) => {
                    nodes.push(node.clone().into());
                    depth += 1;
                }
                WebItem::Component(component) => {
                    nodes.extend(component.nodes());
                    depth += 1;
                }
                i => panic!("unexpected item, expected something with a node in it, got : {:?}", i)
            }
        }
        nodes
    }

    fn create(&mut self, app: &Dispatcher<Message, Command>) -> Vec<web_sys::Node> {
        // render the initial app
        use std::iter;

        let App {
            ref mut storage,
            ref dom,
            ..
        } = *self;

        let n = dom.dom_iter();
        let patch_set = diff::diff(iter::empty(), n, storage);

        let (storage, pending) = patch_set.prepare(app);
        self.storage = storage;
        pending
    }
}

/// A wasm application consisting of a model, a virtual dom representation, and the parent element
/// where this app lives in the dom.
struct App<Model, DomTree, Processor, Message, Command, Key>
where
    Command: SideEffect<Message>,
    Processor: side_effect::Processor<Message, Command>,
{
    dom: DomTree,
    model: Model,
    storage: Storage<Message>,
    listeners: Vec<(String, Closure<dyn FnMut(web_sys::Event)>)>,
    animation_frame_handle: Option<ScheduledRender<Command>>,
    processor: Processor,
    command: std::marker::PhantomData<Command>,
    key: std::marker::PhantomData<Key>,
}

impl<Model, DomTree, Processor, Message, Command, Key>
App<Model, DomTree, Processor, Message, Command, Key>
where
    Command: SideEffect<Message>,
    Processor: side_effect::Processor<Message, Command> + 'static,
{
    /// Create an application.
    ///
    /// The app will be initialized with the given model.  Dom nodes will be created and event
    /// handlers will be registered as necessary.
    fn create(model: Model, processor: Processor)
    -> (Rc<RefCell<Box<dyn Application<Message, Command>>>>, Vec<web_sys::Node>)
    where
        Model: Update<Message, Command> + Render<DomTree> + 'static,
        DomTree: DomIter<Message, Command, Key> + 'static,
        Message: fmt::Debug + Clone + PartialEq + 'static,
        Command: SideEffect<Message> + fmt::Debug + 'static,
        Key: Eq + Hash + 'static,
    {

        // render our initial model
        let dom = model.render();
        let app = App {
            dom: dom,
            model: model,
            storage: vec![],
            listeners: vec![],
            animation_frame_handle: None,
            processor: processor,
            command: std::marker::PhantomData,
            key: std::marker::PhantomData,
        };

        // we use a RefCell here because we need the dispatch callback to be able to mutate our
        // App. This should be safe because the browser should only ever dispatch events from a
        // single thread.
        let app_rc = Rc::new(RefCell::new(Box::new(app) as Box<dyn Application<Message, Command>>));

        // create the initial app
        let nodes = Application::create(&mut **app_rc.borrow_mut(), &Dispatcher::from(&app_rc));

        (app_rc, nodes)
    }
}