srctree

Robin Linden parent 8fe233eb 5fcc0010
style: Support xpath-lookup for StyledNode

inlinesplit
style/styled_node.h added: 40, removed: 2, total 38
@@ -14,6 +14,7 @@
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
 
namespace style {
@@ -74,6 +75,22 @@ private:
return a.node == b.node && a.properties == b.properties && a.children == b.children;
}
 
inline std::string_view dom_name(StyledNode const &node) {
return std::get<dom::Element>(node.node).name;
}
 
inline std::vector<StyledNode const *> dom_children(StyledNode const &node) {
std::vector<StyledNode const *> children{};
for (auto const &child : node.children) {
if (!std::holds_alternative<dom::Element>(child.node)) {
continue;
}
 
children.push_back(&child);
}
return children;
}
 
} // namespace style
 
#endif
 
style/styled_node_test.cpp added: 40, removed: 2, total 38
@@ -221,5 +221,26 @@ int main() {
std::ignore = child.get_property<css::PropertyId::FontSize>();
});
 
etest::test("xpath", [] {
dom::Node html_node = dom::Element{"html"s};
dom::Node div_node = dom::Element{"div"s};
dom::Node text_node = dom::Text{"hello!"s};
style::StyledNode styled_node{
.node = html_node,
.children{
style::StyledNode{.node = text_node},
style::StyledNode{.node = div_node},
},
};
 
using NodeVec = std::vector<style::StyledNode const *>;
expect_eq(dom::nodes_by_xpath(styled_node, "/html"), NodeVec{&styled_node});
expect_eq(dom::nodes_by_xpath(styled_node, "/html/div"), NodeVec{&styled_node.children[1]});
expect_eq(dom::nodes_by_xpath(styled_node, "/html/div/"), NodeVec{});
expect_eq(dom::nodes_by_xpath(styled_node, "/html/div/p"), NodeVec{});
expect_eq(dom::nodes_by_xpath(styled_node, "/htm/div"), NodeVec{});
expect_eq(dom::nodes_by_xpath(styled_node, "//div"), NodeVec{});
});
 
return etest::run_all_tests();
}