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
//! Types and [`TryFrom`] instances that can 're-animate' views or portions of views from the DOM.
use mogwai::{builder::{DecomposedViewBuilder, ViewBuilder}, prelude::{Component, HashPatch, HashPatchApply, ListPatchApply}, view::{Dom, EitherExt, View}};
use snafu::{OptionExt, Snafu, ensure};
use std::collections::HashMap;
pub use std::{convert::TryFrom, ops::Deref};
pub use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt};
use web_sys::Node;
pub use web_sys::{Element, Event, EventTarget, HtmlElement};

#[derive(Debug, Snafu)]
#[snafu(visibility = "pub(crate)")]
pub enum Error {
    #[snafu(display(
        "Missing any hydration option for node '{}' - must be the child of a node or have an id",
        tag
    ))]
    NoHydrationOption { tag: String },

    #[snafu(display("Could not find an element with id '{}'", id))]
    MissingId { id: String },

    #[snafu(display("Child at index {} could not be found in node '{}' containing '{:?}'", index, node.node_name(), node.node_value()))]
    MissingChild { node: Node, index: u32 },

    #[snafu(display("Could not convert from '{}' to '{}' for value: {:#?}", from, to, node))]
    Conversion {
        from: String,
        to: String,
        node: JsValue,
    },

    #[snafu(display("View cannot be hydrated"))]
    ViewOnly,

    #[snafu(display("Hydration only available on WASM"))]
    WASMOnly {
        backtrace: snafu::Backtrace,
    },

    #[snafu(display("Hydration failed: {}", msg))]
    Other { msg: String },
}

pub enum HydrationKey {
    Id(String),
    IndexedChildOf { node: Node, index: u32 },
}

impl HydrationKey {
    pub fn try_new(
        tag: String,
        attribs: Vec<HashPatch<String, String>>,
        may_parent: Option<(usize, &Node)>,
    ) -> Result<Self, Error> {
        let mut attributes = HashMap::new();
        for patch in attribs.into_iter() {
            let _ = attributes.hash_patch_apply(patch);
        }

        if let Some(id) = attributes.remove("id") {
            return Ok(HydrationKey::Id(id));
        }

        if let Some((index, parent)) = may_parent {
            return Ok(HydrationKey::IndexedChildOf {
                node: parent.clone(),
                index: index as u32,
            });
        }

        Err(Error::NoHydrationOption { tag })
    }

    pub fn hydrate(self) -> Result<Dom, Error> {
        snafu::ensure!(cfg!(target_arch = "wasm32"), WASMOnly);

        let el: Node = match self {
            HydrationKey::Id(id) => {
                let el = mogwai::utils::document()
                    .get_element_by_id(&id)
                    .with_context(|| MissingId { id })?;
                el.clone().dyn_into::<Node>().or_else(|_| {
                    Conversion {
                        from: "Element",
                        to: "Node",
                        node: el,
                    }
                    .fail()
                })?
            }
            HydrationKey::IndexedChildOf { node, index } => {
                let children = node.child_nodes();
                let mut non_empty_children = vec![];
                for i in 0..children.length() {
                    let child = children.get(i).with_context(|| MissingChild {
                        node: node.clone(),
                        index,
                    })?;
                    if child.node_type() == 3 {
                        // This is a text node
                        let has_text: bool = child
                            .node_value()
                            .map(|s| !s.trim().is_empty())
                            .unwrap_or_else(|| false);
                        if has_text {
                            non_empty_children.push(child);
                        }
                    } else {
                        non_empty_children.push(child);
                    }
                }
                let el = non_empty_children
                    .get(index as usize)
                    .with_context(|| MissingChild {
                        node: node.clone(),
                        index,
                    })?
                    .clone();
                el
            }
        };

        let dom = Dom::try_from(JsValue::from(el));
        ensure!(dom.is_ok(), WASMOnly);

        Ok(dom.unwrap())
    }
}

pub struct Hydrator {
    inner: Dom,
}

impl From<Hydrator> for View<Dom> {
    fn from(Hydrator { inner }: Hydrator) -> Self {
        View::from(inner)
    }
}

impl TryFrom<Component<Dom>> for Hydrator {
    type Error = Error;

    fn try_from(comp: Component<Dom>) -> Result<Self, Self::Error> {
        let builder = ViewBuilder::from(comp);
        Hydrator::try_from(builder)
    }
}

impl TryFrom<ViewBuilder<Dom>> for Hydrator {
    type Error = Error;

    fn try_from(value: ViewBuilder<Dom>) -> Result<Self, Self::Error> {
        let decomp = DecomposedViewBuilder::from(value);
        Self::try_hydrate(decomp, None)
    }
}

impl Hydrator {
    /// Attempt to hydrate [`Dom`] from [`DecomposedViewBuilder<Dom>`].
    fn try_hydrate(
        DecomposedViewBuilder {
            construct_with,
            ns: _,
            texts: _,
            text_stream,
            attribs,
            attrib_stream,
            bool_attribs: _,
            bool_attrib_stream,
            styles: _,
            style_stream,
            children,
            child_stream,
            ops,
        }: DecomposedViewBuilder<Dom>,
        may_parent: Option<(usize, &Node)>,
    ) -> Result<Hydrator, Error> {
        let key = HydrationKey::try_new(construct_with, attribs, may_parent)?;
        let mut dom = key.hydrate()?;
        for op in ops.into_iter() {
            (op)(&mut dom);
        }

        mogwai::builder::set_streaming_values(
            &dom,
            text_stream,
            attrib_stream,
            bool_attrib_stream,
            style_stream,
            child_stream,
        ).map_err(|msg| Error::Other{ msg })?;

        let guard = dom.inner_read().left().with_context(|| WASMOnly)?;
        let node = guard.dyn_ref::<Node>().with_context(|| Conversion {
            from: format!("{:?}", guard.deref()),
            to: "Node".to_string(),
            node: guard.clone(),
        })?;

        let mut child_builders = vec![];
        for patch in children.into_iter() {
            let _ = child_builders.list_patch_apply(patch.map(DecomposedViewBuilder::from));
        }
        for (decomp, i) in child_builders.into_iter().zip(0..) {
            let _ = Hydrator::try_hydrate(decomp, Some((i, node)))?;
        }
        drop(guard);

        Ok(Hydrator { inner: dom })
    }
}