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
//! The main `Query` interface.

mod attributes;
mod manipulation;
mod traversing;

use crate::{selectors::Selectors, Error};
use derive_more::{AsRef, Deref, DerefMut, From, Into};
use std::{
    collections::VecDeque,
    convert::{TryFrom, TryInto},
    fmt,
};
use wasm_bindgen::JsCast;
use web_sys::{HtmlCollection, HtmlElement};

/// Document with jQuery-like methods.
#[derive(AsRef, Clone, Debug, Deref, DerefMut, From, Into)]
pub struct Document(web_sys::Document);

impl Document {
    pub fn new() -> Result<Self, Error> {
        let inner = web_sys::window()
            .ok_or(Error::DomElementNotFound("window"))?
            .document()
            .ok_or(Error::DomElementNotFound("document"))?;

        Ok(Self(inner))
    }

    pub fn descendants(&self) -> Collection {
        if let Some(root) = self.0.document_element() {
            return Element::from(root).descendants();
        }
        Collection::new()
    }
}

/// Element with jQuery-like methods.
#[derive(AsRef, Clone, Deref, DerefMut, From, Into)]
pub struct Element(web_sys::Element);

impl Element {
    pub fn descendants(&self) -> Collection {
        let mut result = vec![];
        let mut nodes = vec![self.clone()];
        while let Some(node) = nodes.pop() {
            result.push(node.clone());
            for child in Collection::from(node.0.children()).into_iter().rev() {
                nodes.push(child);
            }
        }
        result.into()
    }

    pub fn dyn_ref<T: JsCast>(&self) -> Result<&T, Error> {
        self.0.dyn_ref::<T>().ok_or(Error::DynRefFailed)
    }
}

impl fmt::Display for Element {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.local_name())?;
        let id = self.id();
        if !id.is_empty() {
            write!(f, "[id=\"{}\"]", id)?;
        }
        Ok(())
    }
}

impl fmt::Debug for Element {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)?;
        write!(f, "(children={}", self.child_element_count())?;
        let parent = self.parent_node().map(|elem| elem.node_type()).unwrap_or(0);
        write!(f, ", parent={})", parent)?;
        Ok(())
    }
}

impl<'a> TryInto<&'a web_sys::HtmlElement> for &'a Element {
    type Error = Error;

    fn try_into(self) -> Result<&'a web_sys::HtmlElement, Self::Error> {
        self.0.dyn_ref::<HtmlElement>().ok_or(Error::NotHtmlElement)
    }
}

impl TryFrom<&Document> for Element {
    type Error = Error;

    fn try_from(document: &Document) -> Result<Element, Self::Error> {
        document
            .0
            .document_element()
            .map(Into::into)
            .ok_or(Error::NoDocumentElement)
    }
}

/// HTML `Collection` that can be used as an iterator
#[derive(AsRef, Clone, Debug, Default, Deref, DerefMut)]
pub struct Collection(pub VecDeque<Element>);

impl Collection {
    pub fn new() -> Self {
        Default::default()
    }

    /// Move all elements of another collection into this collection.
    pub fn append_collection(&mut self, mut other: Self) {
        self.0.append(&mut other.0);
    }

    pub fn descendants(&self) -> Collection {
        let mut all_children = Collection::new();
        self.0
            .iter()
            .for_each(|elem| all_children.append_collection(elem.descendants()));
        all_children
    }
}

impl IntoIterator for Collection {
    type Item = Element;
    type IntoIter = std::collections::vec_deque::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl From<HtmlCollection> for Collection {
    fn from(collection: HtmlCollection) -> Self {
        let mut inner = VecDeque::new();

        for i in 0..collection.length() {
            if let Some(item) = collection.item(i) {
                inner.push_back(item.into());
            }
        }

        Self(inner)
    }
}

impl From<Vec<Element>> for Collection {
    fn from(collection: Vec<Element>) -> Self {
        Self(collection.into())
    }
}

impl From<Option<web_sys::Element>> for Collection {
    fn from(element: Option<web_sys::Element>) -> Self {
        let inner = match element {
            Some(element) => vec![element.into()],
            None => vec![],
        };

        Self(inner.into())
    }
}