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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use super::change_list::ChangeList;
use super::node::{Attribute, ElementNode, Listener, Node, TextNode};
use super::RootRender;
use crate::events::EventsRegistry;
use bumpalo::Bump;
use futures::future::Future;
use std::cell::Cell;
use std::cell::RefCell;
use std::cmp;
use std::fmt;
use std::mem;
use std::mem::ManuallyDrop;
use std::rc::{Rc, Weak};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;

/// A strong handle to a mounted virtual DOM.
///
/// When this handle is dropped, the virtual DOM is unmounted and its listeners
/// removed. To keep it mounted forever, use the `Vdom::forget` method.
#[must_use = "A `Vdom` will only keep rendering and listening to events while it has not been \
              dropped. If you want a `Vdom` to run forever, call `Vdom::forget`."]
#[derive(Debug)]
pub struct Vdom {
    inner: Rc<VdomInner>,
}

/// A weak handle to a virtual DOM.
///
/// Does not prevent the virtual DOM from being unmounted: only keeping the
/// original `Vdom` alive guarantees that.
///
/// A `VdomWeak` also gives you the capability to scheduling re-rendering (say
/// after mutating the render component state).
#[derive(Clone, Debug)]
pub struct VdomWeak {
    inner: Weak<VdomInner>,
}

#[derive(Debug)]
pub(crate) struct VdomInner {
    pub(crate) shared: VdomInnerShared,
    pub(crate) exclusive: RefCell<VdomInnerExclusive>,
}

pub(crate) struct VdomInnerShared {
    pub(crate) render_scheduled: Cell<Option<js_sys::Promise>>,
}

pub(crate) struct VdomInnerExclusive {
    // Always `Some` except just before we drop. Just an option so that
    // `unmount` can take the component out but we can still have a Drop
    // implementation.
    component: Option<Box<RootRender>>,

    dom_buffers: [Bump; 2],
    change_list: ManuallyDrop<ChangeList>,
    container: web_sys::Element,
    events_registry: Option<Rc<RefCell<EventsRegistry>>>,

    // Actually a reference into `self.dom_buffers[0]` or if `self.component` is
    // caching renders, into `self.component`'s bump.
    current_root: Option<Node<'static>>,
}

unsafe fn extend_node_lifetime<'a>(node: Node<'a>) -> Node<'static> {
    mem::transmute(node)
}

impl fmt::Debug for VdomInnerShared {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let render_scheduled = Cell::new(None);
        self.render_scheduled.swap(&render_scheduled);
        let render_scheduled = render_scheduled.into_inner();
        let r = f
            .debug_struct("VdomInnerShared")
            .field("render_scheduled", &render_scheduled)
            .finish();
        self.render_scheduled.set(render_scheduled);
        r
    }
}

impl fmt::Debug for VdomInnerExclusive {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("VdomInnerExclusive")
            .field("component", &"..")
            .field("dom_buffers", &self.dom_buffers)
            .field("change_list", &self.change_list)
            .field("container", &self.container)
            .field("events_registry", &self.events_registry)
            .field("current_root", &self.current_root)
            .finish()
    }
}

impl Drop for VdomInnerExclusive {
    fn drop(&mut self) {
        debug!("Dropping VdomInnerExclusive");

        // Make sure that we clean up our JS listeners and all that before we
        // empty the container.
        unsafe {
            ManuallyDrop::drop(&mut self.change_list);
        }

        let registry = self.events_registry.take().unwrap_throw();
        let mut registry = registry.borrow_mut();
        registry.clear_active_listeners();

        self.container.set_inner_html("");
    }
}

impl Vdom {
    /// Mount a new `Vdom` in the given container element with the given root
    /// rendering component.
    ///
    /// This will box the given component into trait object.
    pub fn new<R>(container: &web_sys::Element, component: R) -> Vdom
    where
        R: RootRender,
    {
        Self::with_boxed_root_render(container, Box::new(component) as Box<RootRender>)
    }

    /// Construct a `Vdom` with the already-boxed-as-a-trait-object root
    /// rendering component.
    pub fn with_boxed_root_render(
        container: &web_sys::Element,
        component: Box<RootRender>,
    ) -> Vdom {
        let dom_buffers = [Bump::new(), Bump::new()];
        let change_list = ManuallyDrop::new(ChangeList::new(container));

        // Ensure that the container is empty.
        container.set_inner_html("");

        // Create a dummy `<div/>` in our container.
        let current_root = Node::element(&dom_buffers[0], "div", [], [], []);
        let current_root = Some(unsafe { extend_node_lifetime(current_root) });
        let window = web_sys::window().expect("should have acess to the Window");
        let document = window
            .document()
            .expect("should have access to the Document");
        container
            .append_child(
                document
                    .create_element("div")
                    .expect("should create element OK")
                    .as_ref(),
            )
            .expect("should append child OK");

        let container = container.clone();
        let inner = Rc::new(VdomInner {
            shared: VdomInnerShared {
                render_scheduled: Cell::new(None),
            },
            exclusive: RefCell::new(VdomInnerExclusive {
                component: Some(component),
                dom_buffers,
                change_list,
                container,
                current_root,
                events_registry: None,
            }),
        });

        let (events_registry, events_trampoline) = EventsRegistry::new(Rc::downgrade(&inner));

        {
            let mut inner = inner.exclusive.borrow_mut();
            inner.events_registry = Some(events_registry);
            inner.change_list.init_events_trampoline(events_trampoline);

            // Diff and apply the `contents` against our dummy `<div/>`.
            inner.render();
        }

        Vdom { inner }
    }

    /// Run this virtual DOM and its listeners forever and never unmount it.
    #[inline]
    pub fn forget(self) {
        mem::forget(self);
    }

    /// Get a weak handle to this virtual DOM.
    #[inline]
    pub fn weak(&self) -> VdomWeak {
        VdomWeak::new(&self.inner)
    }

    /// Unmount this virtual DOM, unregister its event listeners, and return its
    /// root render component.
    #[inline]
    pub fn unmount(self) -> Box<RootRender> {
        Rc::try_unwrap(self.inner.clone())
            .map_err(|_| ())
            .unwrap_throw()
            .exclusive
            .into_inner()
            .component
            .take()
            .unwrap_throw()
    }
}

impl VdomInnerExclusive {
    /// Get an exclusive reference to the underlying render component as a raw
    /// trait object.
    #[inline]
    pub(crate) fn component_raw_mut(&mut self) -> &mut dyn RootRender {
        &mut **self.component.as_mut().unwrap_throw()
    }

    /// Re-render this virtual dom's current component.
    pub(crate) fn render(&mut self) {
        unsafe {
            let events_registry = self.events_registry.take().unwrap();

            {
                // All the old listeners are no longer active. We will build a new
                // set of active listeners when diffing.
                //
                // NB: if we end up avoiding diffing cached renders (instead of just
                // avoiding re-rendering them) then we will need to maintain cached
                // active listeners, and can't just clear all active listeners and
                // rebuild them here.
                let mut registry = events_registry.borrow_mut();
                registry.clear_active_listeners();

                // Reset the inactive bump arena's pointer.
                self.dom_buffers[1].reset();

                // Render the new current contents into the inactive bump arena.
                let new_contents = self
                    .component
                    .as_ref()
                    .unwrap_throw()
                    .render(&self.dom_buffers[1]);
                let new_contents = extend_node_lifetime(new_contents);

                // Diff the old contents with the new contents.
                let old_contents = self.current_root.take().unwrap();
                self.diff(&mut registry, old_contents, new_contents.clone());

                // Swap the buffers to make the bump arena with the new contents the
                // active arena, and the old one into the inactive arena.
                self.swap_buffers();
                self.set_current_root(new_contents);
            }

            self.events_registry = Some(events_registry);

            // Find and drop cached strings that aren't in use anymore.
            self.change_list.drop_unused_strings();

            // Tell JS to apply our diff-generated changes to the physical DOM!
            self.change_list.apply_changes();
        }
    }

    fn swap_buffers(&mut self) {
        let (first, second) = self.dom_buffers.as_mut().split_at_mut(1);
        mem::swap(&mut first[0], &mut second[0]);
    }

    unsafe fn set_current_root(&mut self, current: Node<'static>) {
        debug_assert!(self.current_root.is_none());
        self.current_root = Some(current);
    }

    fn diff<'a>(&mut self, registry: &mut EventsRegistry, old: Node<'a>, new: Node<'a>) {
        // debug!("---------------------------------------------------------");
        // debug!("dodrio::Vdom::diff");
        // debug!("  old = {:#?}", old);
        // debug!("  new = {:#?}", new);
        match (&new, old) {
            (&Node::Text(TextNode { text: new_text }), Node::Text(TextNode { text: old_text })) => {
                debug!("  both are text nodes");
                if new_text != old_text {
                    debug!("  text needs updating");
                    self.change_list.emit_set_text(new_text);
                }
            }
            (&Node::Text(TextNode { .. }), Node::Element(ElementNode { .. })) => {
                debug!("  replacing a text node with an element");
                self.create(registry, new);
                self.change_list.emit_replace_with();
            }
            (&Node::Element(ElementNode { .. }), Node::Text(TextNode { .. })) => {
                debug!("  replacing an element with a text node");
                self.create(registry, new);
                self.change_list.emit_replace_with();
            }
            (
                &Node::Element(ElementNode {
                    tag_name: new_tag_name,
                    listeners: new_listeners,
                    attributes: new_attributes,
                    children: new_children,
                }),
                Node::Element(ElementNode {
                    tag_name: old_tag_name,
                    listeners: old_listeners,
                    attributes: old_attributes,
                    children: old_children,
                }),
            ) => {
                debug!("  updating an element");
                if new_tag_name != old_tag_name {
                    debug!("  different tag names; creating new element and replacing old element");
                    self.create(registry, new);
                    self.change_list.emit_replace_with();
                    return;
                }
                self.diff_listeners(registry, old_listeners, new_listeners);
                self.diff_attributes(old_attributes, new_attributes);
                self.diff_children(registry, old_children, new_children);
            }
        }
    }

    fn diff_listeners<'a>(
        &mut self,
        registry: &mut EventsRegistry,
        old: &'a [Listener<'a>],
        new: &'a [Listener<'a>],
    ) {
        debug!("  updating event listeners");

        'outer1: for new_l in new {
            unsafe {
                // Safety relies on removing `new_l` from the registry manually
                // at the end of its lifetime. This happens when we invoke
                // `clear_active_listeners` at the start of a new rendering
                // phase.
                registry.add(new_l);
            }
            for old_l in old {
                if new_l.event == old_l.event {
                    self.change_list.emit_update_event_listener(new_l);
                    continue 'outer1;
                }
            }
            self.change_list.emit_new_event_listener(new_l);
        }

        'outer2: for old_l in old {
            for new_l in new {
                if new_l.event == old_l.event {
                    continue 'outer2;
                }
            }
            self.change_list.emit_remove_event_listener(old_l.event);
        }
    }

    fn diff_attributes(&mut self, old: &[Attribute], new: &[Attribute]) {
        debug!("  updating attributes");

        // Do O(n^2) passes to add/update and remove attributes, since
        // there are almost always very few attributes.
        'outer: for new_attr in new {
            if new_attr.is_volatile() {
                self.change_list
                    .emit_set_attribute(new_attr.name, new_attr.value);
            } else {
                for old_attr in old {
                    if old_attr.name == new_attr.name {
                        if old_attr.value != new_attr.value {
                            self.change_list
                                .emit_set_attribute(new_attr.name, new_attr.value);
                        }
                        continue 'outer;
                    }
                }
                self.change_list
                    .emit_set_attribute(new_attr.name, new_attr.value);
            }
        }

        'outer2: for old_attr in old {
            for new_attr in new {
                if old_attr.name == new_attr.name {
                    continue 'outer2;
                }
            }
            self.change_list.emit_remove_attribute(old_attr.name);
        }
    }

    fn diff_children<'a>(
        &mut self,
        registry: &mut EventsRegistry,
        old: &'a [Node<'a>],
        new: &'a [Node<'a>],
    ) {
        debug!("  updating children shared by old and new");

        let num_children_to_diff = cmp::min(new.len(), old.len());
        let mut new_children = new.iter();
        let mut old_children = old.iter();
        let mut pushed = false;

        for (i, (new_child, old_child)) in new_children
            .by_ref()
            .zip(old_children.by_ref())
            .take(num_children_to_diff)
            .enumerate()
        {
            if i == 0 {
                self.change_list.emit_push_first_child();
                pushed = true;
            } else {
                debug_assert!(pushed);
                self.change_list.emit_pop_push_next_sibling();
            }

            self.diff(registry, old_child.clone(), new_child.clone());
        }

        if old_children.next().is_some() {
            debug!("  removing extra old children");
            debug_assert!(new_children.next().is_none());
            if !pushed {
                self.change_list.emit_push_first_child();
            } else {
                self.change_list.emit_pop_push_next_sibling();
            }
            self.change_list.emit_remove_self_and_next_siblings();
            pushed = false;
        } else {
            debug!("  creating new children");
            for (i, new_child) in new_children.enumerate() {
                if i == 0 && pushed {
                    self.change_list.emit_pop();
                    pushed = false;
                }
                self.create(registry, new_child.clone());
                self.change_list.emit_append_child();
            }
        }

        debug!("  done updating children");
        if pushed {
            self.change_list.emit_pop();
        }
    }

    fn create<'a>(&mut self, registry: &mut EventsRegistry, node: Node<'a>) {
        match node {
            Node::Text(TextNode { text }) => {
                self.change_list.emit_create_text_node(text);
            }
            Node::Element(ElementNode {
                tag_name,
                listeners,
                attributes,
                children,
            }) => {
                self.change_list.emit_create_element(tag_name);
                for l in listeners {
                    unsafe {
                        registry.add(l);
                    }
                    self.change_list.emit_new_event_listener(l);
                }
                for attr in attributes {
                    self.change_list.emit_set_attribute(&attr.name, &attr.value);
                }
                for child in children {
                    self.create(registry, child.clone());
                    self.change_list.emit_append_child();
                }
            }
        }
    }
}

fn request_animation_frame(f: &Closure<FnMut()>) {
    web_sys::window()
        .expect_throw("should have a window")
        .request_animation_frame(f.as_ref().unchecked_ref())
        .expect_throw("should register `requestAnimationFrame` OK");
}

fn with_animation_frame<F>(mut f: F)
where
    F: 'static + FnMut(),
{
    let g = Rc::new(RefCell::new(None));
    let h = g.clone();

    let f = Closure::wrap(Box::new(move || {
        *g.borrow_mut() = None;
        f();
    }) as Box<FnMut()>);
    request_animation_frame(&f);

    *h.borrow_mut() = Some(f);
}

/// An operation failed because the virtual DOM was already dropped and
/// unmounted.
#[derive(Debug)]
pub struct VdomDroppedError {}

impl fmt::Display for VdomDroppedError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "The virtual DOM was dropped.")
    }
}

impl std::error::Error for VdomDroppedError {}

impl VdomWeak {
    /// Construct a new weak handle to the given virtual DOM.
    #[inline]
    pub(crate) fn new(inner: &Rc<VdomInner>) -> VdomWeak {
        VdomWeak {
            inner: Rc::downgrade(inner),
        }
    }

    /// Replace the root rendering component with the new `root`.
    ///
    /// Returns a future that resolves to the *old* root component.
    pub fn set_component(
        self,
        root: Box<dyn RootRender>,
    ) -> impl Future<Item = Box<dyn RootRender + 'static>, Error = VdomDroppedError> {
        futures::future::ok(self.inner.upgrade())
            .and_then(|inner| inner.ok_or(()))
            .map_err(|_| VdomDroppedError {})
            .and_then(|inner| {
                let promise = js_sys::Promise::resolve(&JsValue::null());
                JsFuture::from(promise)
                    .map_err(|_| VdomDroppedError {})
                    .and_then(move |_| {
                        let old = {
                            let mut exclusive = inner.exclusive.borrow_mut();
                            mem::replace(&mut *exclusive.component.as_mut().unwrap_throw(), root)
                        };
                        VdomWeak::new(&inner).render().map(|_| old)
                    })
            })
    }

    /// Execute `f` with a reference to this virtual DOM's root rendering
    /// component.
    ///
    /// To ensure exclusive access to the root rendering component, the
    /// invocation takes place on a new tick of the micro-task queue.
    pub fn with_component<F, T>(&self, f: F) -> impl Future<Item = T, Error = VdomDroppedError>
    where
        F: 'static + FnOnce(&mut dyn RootRender) -> T,
    {
        futures::future::ok(self.inner.upgrade())
            .and_then(|inner| inner.ok_or(()))
            .map_err(|_| VdomDroppedError {})
            .and_then(|inner| {
                let mut f = Some(f);
                let promise = js_sys::Promise::resolve(&JsValue::null());
                JsFuture::from(promise)
                    .map_err(|_| VdomDroppedError {})
                    .map(move |_| {
                        let f = f.take().unwrap_throw();
                        let mut exclusive = inner.exclusive.borrow_mut();
                        f(exclusive.component_raw_mut())
                    })
            })
    }

    /// Schedule a render to occur during the next animation frame.
    ///
    /// If you want a future that resolves after the render has finished, use
    /// `render` instead.
    pub fn schedule_render(&self) {
        debug!("VdomWeak::schedule_render");
        wasm_bindgen_futures::spawn_local(self.render().map_err(|_| ()));
    }

    /// Schedule a render to occur during the next animation frame and return a
    /// future that will complete once the render has finished.
    ///
    /// If you don't want to do more things after the render completes, then use
    /// `schedule_render` instead of `render`.
    pub fn render(&self) -> impl Future<Item = (), Error = VdomDroppedError> {
        debug!("VdomWeak::render: initiating render in new animation frame");
        futures::future::ok(self.inner.upgrade())
            .and_then(|inner| inner.ok_or(()))
            .map_err(|_| VdomDroppedError {})
            .and_then(|inner| {
                let promise = inner.shared.render_scheduled.take().unwrap_or_else(|| {
                    js_sys::Promise::new(&mut |resolve, reject| {
                        let vdom = VdomWeak {
                            inner: Rc::downgrade(&inner),
                        };
                        with_animation_frame(move || match vdom.inner.upgrade() {
                            None => {
                                warn!("VdomWeak::render: vdom unmounted before we could render");
                                let r = reject.call0(&JsValue::null());
                                debug_assert!(r.is_ok());
                            }
                            Some(inner) => {
                                let mut exclusive = inner.exclusive.borrow_mut();
                                exclusive.render();

                                // We did the render, so take the promise away
                                // and let future `render` calls request new
                                // animation frames.
                                let _ = inner.shared.render_scheduled.take();

                                debug!("VdomWeak::render: finished rendering");
                                let r = resolve.call0(&JsValue::null());
                                debug_assert!(r.is_ok());
                            }
                        });
                    })
                });
                inner.shared.render_scheduled.set(Some(promise.clone()));
                JsFuture::from(promise)
                    .map(|_| ())
                    .map_err(|_| VdomDroppedError {})
            })
    }
}