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
use crate::{
    diff,
    dom::{
        apply_patches::patch,
        created_node::{
            ActiveClosure,
            CreatedNode,
        },
        Dispatch,
    },
    mt_dom::NodeIdx,
    Patch,
};
use std::collections::HashMap;
use wasm_bindgen::JsCast;
use web_sys::{
    self,
    Element,
    Node,
};

/// 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<MSG> {
    /// the current vdom representation
    pub 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);
    ///
    pub active_closures: ActiveClosure,
    /// a fast lookup for getting the Node from from NodeIdx
    pub node_idx_lookup: HashMap<NodeIdx, Node>,
    /// after mounting or update dispatch call, the element will be focused
    pub focused_node: Option<Node>,
}

impl<MSG> DomUpdater<MSG> {
    /// 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>,
        mount: &Node,
    ) -> DomUpdater<MSG> {
        DomUpdater {
            current_vdom,
            root_node: mount.clone(),
            active_closures: ActiveClosure::new(),
            node_idx_lookup: HashMap::new(),
            focused_node: None,
        }
    }

    /// 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()
    }
}

impl<MSG> DomUpdater<MSG>
where
    MSG: 'static,
{
    /// 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<DSP>(&mut self, program: &DSP)
    where
        DSP: Dispatch<MSG> + Clone + 'static,
    {
        self.mount(program, false);
    }

    /// each element and it's descendant in the vdom is created into
    /// an actual DOM node.
    fn mount<DSP>(&mut self, program: &DSP, replace: bool)
    where
        DSP: Dispatch<MSG> + Clone + 'static,
    {
        let created_node = CreatedNode::create_dom_node(
            program,
            &mut self.node_idx_lookup,
            &self.current_vdom,
            &mut self.focused_node,
            &mut None,
        );
        if replace {
            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");
        } else {
            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;
        log::trace!("focusing element after mounting");
        self.set_focus_element();
    }

    fn set_focus_element(&self) {
        if let Some(focused_node) = &self.focused_node {
            let focused_element: &Element = focused_node.unchecked_ref();
            CreatedNode::set_element_focus(focused_element);
        } else {
            log::warn!("no focused node");
        }
    }

    /// 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<DSP>(&mut self, program: &DSP)
    where
        DSP: Dispatch<MSG> + Clone + 'static,
    {
        self.mount(program, true);
    }

    /// 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<DSP>(
        program: &DSP,
        current_vdom: crate::Node<MSG>,
        mount: &Element,
    ) -> DomUpdater<MSG>
    where
        DSP: Dispatch<MSG> + Clone + 'static,
    {
        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<DSP>(
        program: &DSP,
        current_vdom: crate::Node<MSG>,
        mount: Element,
    ) -> DomUpdater<MSG>
    where
        DSP: Dispatch<MSG> + Clone + 'static,
    {
        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_dom<DSP>(&mut self, program: &DSP, new_vdom: crate::Node<MSG>)
    where
        DSP: Dispatch<MSG> + Clone + 'static,
    {
        #[cfg(feature = "with-measure")]
        let t1 = crate::now();
        let patches = diff(&self.current_vdom, &new_vdom);

        #[cfg(feature = "with-measure")]
        let _t2 = {
            let t2 = crate::now();
            log::trace!("vdom diffing took: {}ms", t2 - t1);
            t2
        };

        #[cfg(feature = "with-measure")]
        log::trace!("applying {} patches", patches.len());

        #[cfg(feature = "with-debug")]
        log::debug!("patches: {:#?}", patches);

        let active_closures = patch(
            Some(program),
            self.root_node.clone(),
            &mut self.active_closures,
            &mut self.node_idx_lookup,
            &mut self.focused_node,
            patches,
        )
        .expect("Error in patching the dom");

        self.active_closures.extend(active_closures);
        self.current_vdom = new_vdom;
        self.set_focus_element();
    }

    /// Apply patches to the dom updater
    /// Warning: only used this for debuggin purposes
    pub fn patch_dom<DSP>(&mut self, program: &DSP, patches: Vec<Patch<MSG>>)
    where
        DSP: Dispatch<MSG> + Clone + 'static,
    {
        let active_closures = patch(
            Some(program),
            self.root_node.clone(),
            &mut self.active_closures,
            &mut self.node_idx_lookup,
            &mut self.focused_node,
            patches,
        )
        .expect("Error in patching the dom");
        self.active_closures.extend(active_closures);
    }

    /// map this DomUpdater such that the Node<MSG> will become Node<MSG2>
    pub fn map_msg<F, MSG2>(self, func: F) -> DomUpdater<MSG2>
    where
        F: Fn(MSG) -> MSG2 + 'static,
        MSG2: 'static,
    {
        let DomUpdater {
            current_vdom,
            root_node,
            active_closures,
            node_idx_lookup,
            focused_node,
        } = self;
        DomUpdater {
            current_vdom: current_vdom.map_msg(func),
            root_node,
            active_closures,
            node_idx_lookup,
            focused_node,
        }
    }

    /// 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()
    }
}