| 1 | // Copyright 2019 the SimpleCSS Authors |
| 2 | // SPDX-License-Identifier: Apache-2.0 OR MIT |
| 3 | |
| 4 | //! Select |
| 5 | |
| 6 | struct XmlNode<'a, 'input: 'a>(roxmltree::Node<'a, 'input>); |
| 7 | |
| 8 | impl<'a, 'input: 'a> XmlNode<'a, 'input> { |
| 9 | fn select(&self, text: &str) -> Option<roxmltree::Node<'a, 'input>> { |
| 10 | let selectors = simplecss::Selector::parse(text)?; |
| 11 | self.0 |
| 12 | .descendants() |
| 13 | .filter(|n| n.is_element()) |
| 14 | .find(|&node| selectors.matches(&XmlNode(node))) |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | impl simplecss::Element for XmlNode<'_, '_> { |
| 19 | fn parent_element(&self) -> Option<Self> { |
| 20 | self.0.parent_element().map(XmlNode) |
| 21 | } |
| 22 | |
| 23 | fn prev_sibling_element(&self) -> Option<Self> { |
| 24 | self.0 |
| 25 | .prev_siblings() |
| 26 | .filter(|n| n.is_element()) |
| 27 | .nth(0) |
| 28 | .map(XmlNode) |
| 29 | } |
| 30 | |
| 31 | fn has_local_name(&self, local_name: &str) -> bool { |
| 32 | self.0.tag_name().name() == local_name |
| 33 | } |
| 34 | |
| 35 | fn attribute_matches( |
| 36 | &self, |
| 37 | local_name: &str, |
| 38 | operator: simplecss::AttributeOperator<'_>, |
| 39 | ) -> bool { |
| 40 | match self.0.attribute(local_name) { |
| 41 | Some(value) => operator.matches(value), |
| 42 | None => false, |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | fn pseudo_class_matches(&self, class: simplecss::PseudoClass<'_>) -> bool { |
| 47 | match class { |
| 48 | simplecss::PseudoClass::FirstChild => self.prev_sibling_element().is_none(), |
| 49 | _ => false, // Since we are querying a static XML we can ignore other pseudo-classes. |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | fn main() { |
| 55 | let doc = roxmltree::Document::parse( |
| 56 | "<svg> |
| 57 | <g> |
| 58 | <rect id='rect1' class='round blue'/> |
| 59 | <rect id='rect2' color='red'/> |
| 60 | </g> |
| 61 | </svg>", |
| 62 | ) |
| 63 | .unwrap(); |
| 64 | let root = XmlNode(doc.root_element()); |
| 65 | |
| 66 | assert_eq!( |
| 67 | root.select("rect:first-child") |
| 68 | .unwrap() |
| 69 | .attribute("id") |
| 70 | .unwrap(), |
| 71 | "rect1", |
| 72 | "selected wrong element" |
| 73 | ); |
| 74 | |
| 75 | assert_eq!( |
| 76 | root.select("[color=red]").unwrap().attribute("id").unwrap(), |
| 77 | "rect2", |
| 78 | "selected wrong element" |
| 79 | ); |
| 80 | |
| 81 | assert_eq!( |
| 82 | root.select("svg rect").unwrap().attribute("id").unwrap(), |
| 83 | "rect1", |
| 84 | "selected wrong element" |
| 85 | ); |
| 86 | |
| 87 | assert_eq!( |
| 88 | root.select("svg > g > rect") |
| 89 | .unwrap() |
| 90 | .attribute("id") |
| 91 | .unwrap(), |
| 92 | "rect1", |
| 93 | "selected wrong element" |
| 94 | ); |
| 95 | |
| 96 | assert_eq!( |
| 97 | root.select(".blue").unwrap().attribute("id").unwrap(), |
| 98 | "rect1", |
| 99 | "selected wrong element" |
| 100 | ); |
| 101 | } |