Rewrite Document::create_collection to work better with createNodeList.

This commit is contained in:
Ms2ger 2014-03-05 12:19:28 +01:00
parent cd1d81e402
commit 7ecc39e9ba

View file

@ -405,8 +405,13 @@ impl Document {
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-getelementsbyname // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-getelementsbyname
pub fn GetElementsByName(&self, name: DOMString) -> JS<NodeList> { pub fn GetElementsByName(&self, name: DOMString) -> JS<NodeList> {
self.createNodeList(|elem| { self.createNodeList(|node| {
elem.get().get_attribute(Null, "name").map_default(false, |attr| { if !node.is_element() {
return false;
}
let element: JS<Element> = ElementCast::to(node);
element.get().get_attribute(Null, "name").map_default(false, |attr| {
attr.get().value_ref() == name attr.get().value_ref() == name
}) })
}) })
@ -451,36 +456,46 @@ impl Document {
self.createHTMLCollection(|elem| "applet" == elem.get().tag_name) self.createHTMLCollection(|elem| "applet" == elem.get().tag_name)
} }
pub fn create_collection(&self, callback: |elem: &JS<Element>| -> bool) -> ~[JS<Element>] { pub fn create_collection<T>(&self, callback: |elem: &JS<Node>| -> Option<JS<T>>) -> ~[JS<T>] {
let mut elements = ~[]; let mut nodes = ~[];
match self.GetDocumentElement() { match self.GetDocumentElement() {
None => {}, None => {},
Some(root) => { Some(root) => {
let root: JS<Node> = NodeCast::from(&root); let root: JS<Node> = NodeCast::from(&root);
for child in root.traverse_preorder() { for child in root.traverse_preorder() {
if child.is_element() { match callback(&child) {
let elem: JS<Element> = ElementCast::to(&child); Some(node) => nodes.push(node),
if callback(&elem) { None => (),
elements.push(elem);
}
} }
} }
} }
} }
elements nodes
} }
pub fn createHTMLCollection(&self, callback: |elem: &JS<Element>| -> bool) -> JS<HTMLCollection> { pub fn createHTMLCollection(&self, callback: |elem: &JS<Element>| -> bool) -> JS<HTMLCollection> {
HTMLCollection::new(&self.window, self.create_collection(callback)) HTMLCollection::new(&self.window, self.create_collection(|node| {
if !node.is_element() {
return None;
}
let element: JS<Element> = ElementCast::to(node);
if !callback(&element) {
return None;
}
Some(element)
}))
} }
pub fn createNodeList(&self, callback: |elem: &JS<Element>| -> bool) -> JS<NodeList> { pub fn createNodeList(&self, callback: |node: &JS<Node>| -> bool) -> JS<NodeList> {
let elements = self.create_collection(callback); NodeList::new_simple_list(&self.window, self.create_collection(|node| {
let nodes = elements.map(|element| { if !callback(node) {
let node: JS<Node> = NodeCast::from(element); return None;
node }
});
NodeList::new_simple_list(&self.window, nodes) Some(node.clone())
}))
} }
pub fn content_changed(&self) { pub fn content_changed(&self) {