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
use crate::Dispatch;
use apply_patches::patch;
use sauron_vdom::Callback;
use sauron_vdom::{self, diff};
use std::collections::HashMap;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::Rc;
use std::sync::Mutex;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
use web_sys::{self, Element, EventTarget, Node, Text};
use web_sys::{Event, KeyboardEvent, MouseEvent};
use web_sys::{HtmlInputElement, HtmlTextAreaElement};

mod apply_patches;

// Used to uniquely identify elements that contain closures so that the DomUpdater can
// look them up by their unique id.
// When the DomUpdater sees that the element no longer exists it will drop all of it's
// Rc'd Closures for those events.
use lazy_static::lazy_static;
lazy_static! {
    static ref ELEM_UNIQUE_ID: Mutex<u32> = Mutex::new(0);
}

/// Closures that we are holding on to to make sure that they don't get invalidated after a
/// VirtualNode is dropped.
///
/// The u32 is a unique identifier that is associated with the DOM element that this closure is
/// attached to.
///
/// TODO: Periodically check if the DOM element is still there, and if not drop the closure.
///   Maybe whenever a DOM node is replaced or truncated we figure out all of it's
///   descendants somehow and invalidate those closures..? Need to plan this out..
///   At it stands now this hashmap will grow anytime a new element with closures is
///   appended or replaced and we will never free those closures.
pub type ActiveClosure = HashMap<u32, Vec<(&'static str, Closure<Fn(Event)>)>>;

/// A node along with all of the closures that were created for that
/// node's events and all of it's child node's events.
pub struct CreatedNode<T> {
    /// A `Node` or `Element` that was created from a `Node`
    pub node: T,
    closures: ActiveClosure,
}

/// Used for keeping a real DOM node up to date based on the current Node
/// and a new incoming Node that represents our latest DOM state.
pub struct DomUpdater<DSP, MSG> {
    current_vdom: crate::Node<MSG>,
    root_node: Node,

    /// The closures that are currently attached to elements in the page.
    ///
    /// We keep these around so that they don't get dropped (and thus stop working);
    ///
    /// FIXME: Drop them when the element is no longer in the page. Need to figure out
    /// a good strategy for when to do this.
    pub active_closures: ActiveClosure,
    _phantom_dsp: PhantomData<DSP>,
}

impl<T> CreatedNode<T> {
    pub fn without_closures<N: Into<T>>(node: N) -> Self {
        CreatedNode {
            node: node.into(),
            closures: HashMap::with_capacity(0),
        }
    }

    pub fn create_text_node(text: &sauron_vdom::Text) -> Text {
        let document = web_sys::window().unwrap().document().unwrap();
        document.create_text_node(&text.text)
    }

    /// Create and return a `CreatedNode` instance (containing a DOM `Node`
    /// together with potentially related closures) for this virtual node.
    pub fn create_dom_node<DSP, MSG>(
        program: &Rc<DSP>,
        vnode: &crate::Node<MSG>,
    ) -> CreatedNode<Node>
    where
        MSG: Clone + Debug + 'static,
        DSP: Dispatch<MSG> + 'static,
    {
        match vnode {
            crate::Node::Text(text_node) => {
                CreatedNode::without_closures(Self::create_text_node(text_node))
            }
            crate::Node::Element(element_node) => {
                let created_element: CreatedNode<Node> =
                    Self::create_element_node(program, element_node).into();
                created_element
            }
        }
    }

    /// Build a DOM element by recursively creating DOM nodes for this element and it's
    /// children, it's children's children, etc.
    pub fn create_element_node<DSP, MSG>(
        program: &Rc<DSP>,
        velem: &crate::Element<MSG>,
    ) -> CreatedNode<Element>
    where
        MSG: Clone + Debug + 'static,
        DSP: Dispatch<MSG> + 'static,
    {
        let document = web_sys::window().unwrap().document().unwrap();

        let element = if let Some(ref namespace) = velem.namespace {
            document
                .create_element_ns(Some(namespace), &velem.tag)
                .unwrap()
        } else {
            document.create_element(&velem.tag).unwrap()
        };

        let mut closures = ActiveClosure::new();

        velem.attrs.iter().for_each(|(name, value)| {
            element
                .set_attribute(name, &value.to_string())
                .expect("Set element attribute in create element");
        });

        if !velem.events.is_empty() {
            let unique_id = create_unique_identifier();

            // set the data-sauron_vdom-id this will be read later on
            // when it's time to remove this element and its closures and event listeners
            element
                .set_attribute("data-sauron_vdom-id", &unique_id.to_string())
                .expect("Could not set attribute on element");

            closures.insert(unique_id, vec![]);

            for (event_str, callback) in velem.events.iter() {
                let current_elm: &EventTarget =
                    element.dyn_ref().expect("unable to cast to event targe");
                let closure_wrap: Closure<Fn(Event)> = create_closure_wrap(program, &callback);
                current_elm
                    .add_event_listener_with_callback(
                        event_str,
                        closure_wrap.as_ref().unchecked_ref(),
                    )
                    .expect("Unable to attached event listener");
                closures
                    .get_mut(&unique_id)
                    .expect("Unable to get closure")
                    .push((event_str, closure_wrap));
            }
        }

        let mut previous_node_was_text = false;
        for child in velem.children.iter() {
            match child {
                crate::Node::Text(text_node) => {
                    let current_node = element.as_ref() as &web_sys::Node;

                    // We ensure that the text siblings are patched by preventing the browser from merging
                    // neighboring text nodes. Originally inspired by some of React's work from 2016.
                    //  -> https://reactjs.org/blog/2016/04/07/react-v15.html#major-changes
                    //  -> https://github.com/facebook/react/pull/5753
                    //
                    // `ptns` = Percy text node separator
                    if previous_node_was_text {
                        let separator = document.create_comment("ptns");
                        current_node
                            .append_child(separator.as_ref() as &web_sys::Node)
                            .unwrap();
                    }

                    current_node
                        .append_child(&Self::create_text_node(&text_node))
                        .unwrap();

                    previous_node_was_text = true;
                }
                crate::Node::Element(element_node) => {
                    previous_node_was_text = false;

                    let child = Self::create_element_node(program, element_node);
                    let child_elem: Element = child.node;
                    closures.extend(child.closures);

                    element.append_child(&child_elem).unwrap();
                }
            }
        }

        CreatedNode {
            node: element,
            closures,
        }
    }
}

/// This wrap into a closure the function that is dispatched when the event is triggered.
///
fn create_closure_wrap<DSP, MSG>(
    program: &Rc<DSP>,
    callback: &Callback<sauron_vdom::Event, MSG>,
) -> Closure<Fn(Event)>
where
    MSG: Clone + Debug + 'static,
    DSP: Dispatch<MSG> + 'static + 'static,
{
    let callback_clone = callback.clone();
    let program_clone = Rc::clone(&program);

    Closure::wrap(Box::new(move |event: Event| {
        let mouse_event: Option<&MouseEvent> = event.dyn_ref();
        let key_event: Option<&KeyboardEvent> = event.dyn_ref();
        let target: Option<EventTarget> = event.target();

        let cb_event = if let Some(mouse_event) = mouse_event {
            if event.type_() == "click" {
                sauron_vdom::Event::MouseEvent(sauron_vdom::MouseEvent::Press(
                    sauron_vdom::MouseButton::Left,
                    mouse_event.x() as u16,
                    mouse_event.y() as u16,
                ))
            } else {
                sauron_vdom::Event::Generic(event.type_())
            }
        } else if let Some(key_event) = key_event {
            sauron_vdom::Event::KeyEvent(sauron_vdom::KeyEvent {
                key: key_event.key(),
                ctrl: key_event.ctrl_key(),
                alt: key_event.alt_key(),
                shift: key_event.shift_key(),
                meta: key_event.meta_key(),
            })
        } else if let Some(target) = target {
            let input: Option<&HtmlInputElement> = target.dyn_ref();
            let textarea: Option<&HtmlTextAreaElement> = target.dyn_ref();
            if let Some(input) = input {
                sauron_vdom::Event::InputEvent(sauron_vdom::InputEvent {
                    value: input.value(),
                })
            } else if let Some(textarea) = textarea {
                sauron_vdom::Event::InputEvent(sauron_vdom::InputEvent {
                    value: textarea.value(),
                })
            } else {
                sauron_vdom::Event::Generic(event.type_())
            }
        } else {
            sauron_vdom::Event::Generic(event.type_())
        };
        let msg = callback_clone.emit(cb_event);
        program_clone.dispatch(msg);
    }))
}

impl<DSP, MSG> DomUpdater<DSP, MSG>
where
    MSG: Clone + Debug + 'static,
    DSP: Dispatch<MSG> + 'static,
{
    /// Creates and instance of this DOM updater, but doesn't mount the current_vdom to the DOM just yet.
    pub fn new(current_vdom: crate::Node<MSG>, root_node: &Node) -> DomUpdater<DSP, MSG> {
        DomUpdater {
            current_vdom,
            root_node: root_node.clone(),
            active_closures: ActiveClosure::new(),
            _phantom_dsp: PhantomData,
        }
    }

    /// count the total active closures
    /// regardless of which element it attached to.
    pub fn active_closure_len(&self) -> usize {
        self.active_closures
            .iter()
            .map(|(_elm_id, closures)| closures.len())
            .sum()
    }

    /// Mount the current_vdom appending to the actual browser DOM specified in the root_node
    /// This also gets the closures that was created when mounting the vdom to their
    /// actual DOM counterparts.
    pub fn append_to_mount(&mut self, program: &Rc<DSP>) {
        let created_node: CreatedNode<Node> =
            CreatedNode::<Node>::create_dom_node(program, &self.current_vdom);
        self.root_node
            .append_child(&created_node.node)
            .expect("Could not append child to mount");
        self.root_node = created_node.node;
        self.active_closures = created_node.closures;
    }

    /// Mount the current_vdom replacing the actual browser DOM specified in the root_node
    /// This also gets the closures that was created when mounting the vdom to their
    /// actual DOM counterparts.
    pub fn replace_mount(&mut self, program: &Rc<DSP>) {
        let created_node: CreatedNode<Node> =
            CreatedNode::<Node>::create_dom_node(program, &self.current_vdom);
        let root_element: &Element = self.root_node.unchecked_ref();
        root_element
            .replace_with_with_node_1(&created_node.node)
            .expect("Could not append child to mount");
        self.root_node = created_node.node;
        self.active_closures = created_node.closures;
    }

    /// Create a new `DomUpdater`.
    ///
    /// A root `Node` will be created and appended (as a child) to your passed
    /// in mount element.
    pub fn new_append_to_mount(
        program: &Rc<DSP>,
        current_vdom: crate::Node<MSG>,
        mount: &Element,
    ) -> DomUpdater<DSP, MSG> {
        let mut dom_updater = Self::new(current_vdom, mount);
        dom_updater.append_to_mount(program);
        dom_updater
    }

    /// Create a new `DomUpdater`.
    ///
    /// A root `Node` will be created and it will replace your passed in mount
    /// element.
    pub fn new_replace_mount(
        program: &Rc<DSP>,
        current_vdom: crate::Node<MSG>,
        mount: Element,
    ) -> DomUpdater<DSP, MSG> {
        let mut dom_updater = Self::new(current_vdom, &mount);
        dom_updater.replace_mount(program);
        dom_updater
    }

    /// Diff the current virtual dom with the new virtual dom that is being passed in.
    ///
    /// Then use that diff to patch the real DOM in the user's browser so that they are
    /// seeing the latest state of the application.
    pub fn update(&mut self, program: &Rc<DSP>, new_vdom: crate::Node<MSG>) {
        let patches = diff(&self.current_vdom, &new_vdom);
        let active_closures = patch(
            program,
            self.root_node.clone(),
            &mut self.active_closures,
            &patches,
        )
        .unwrap();
        self.active_closures.extend(active_closures);
        self.current_vdom = new_vdom;
    }

    /// Return the root node of your application, the highest ancestor of all other nodes in
    /// your real DOM tree.
    pub fn root_node(&self) -> Node {
        // Note that we're cloning the `web_sys::Node`, not the DOM element.
        // So we're effectively cloning a pointer here, which is fast.
        self.root_node.clone()
    }
}

fn create_unique_identifier() -> u32 {
    let mut elem_unique_id = ELEM_UNIQUE_ID.lock().unwrap();
    *elem_unique_id += 1;
    *elem_unique_id
}

impl From<CreatedNode<Element>> for CreatedNode<Node> {
    fn from(other: CreatedNode<Element>) -> CreatedNode<Node> {
        CreatedNode {
            node: other.node.into(),
            closures: other.closures,
        }
    }
}

impl<T> Deref for CreatedNode<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.node
    }
}