StyleResolver.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <LibHTML/CSS/StyleResolver.h>
  2. #include <LibHTML/CSS/StyleSheet.h>
  3. #include <LibHTML/CSS/StyledNode.h>
  4. #include <LibHTML/DOM/Document.h>
  5. #include <LibHTML/DOM/Element.h>
  6. #include <LibHTML/Dump.h>
  7. #include <stdio.h>
  8. StyleResolver::StyleResolver(Document& document)
  9. : m_document(document)
  10. {
  11. }
  12. StyleResolver::~StyleResolver()
  13. {
  14. }
  15. static bool matches(const Selector& selector, const Element& element)
  16. {
  17. // FIXME: Support compound selectors.
  18. ASSERT(selector.components().size() == 1);
  19. auto& component = selector.components().first();
  20. switch (component.type) {
  21. case Selector::Component::Type::Id:
  22. return component.value == element.attribute("id");
  23. case Selector::Component::Type::Class:
  24. return element.has_class(component.value);
  25. case Selector::Component::Type::TagName:
  26. return component.value == element.tag_name();
  27. default:
  28. ASSERT_NOT_REACHED();
  29. }
  30. }
  31. NonnullRefPtrVector<StyleRule> StyleResolver::collect_matching_rules(const Element& element) const
  32. {
  33. NonnullRefPtrVector<StyleRule> matching_rules;
  34. for (auto& sheet : document().stylesheets()) {
  35. for (auto& rule : sheet.rules()) {
  36. for (auto& selector : rule.selectors()) {
  37. if (matches(selector, element)) {
  38. matching_rules.append(rule);
  39. break;
  40. }
  41. }
  42. }
  43. }
  44. printf("Rules matching Element{%p}\n", &element);
  45. for (auto& rule : matching_rules) {
  46. dump_rule(rule);
  47. }
  48. return matching_rules;
  49. }
  50. NonnullRefPtr<StyledNode> StyleResolver::create_styled_node(const Document& document)
  51. {
  52. return StyledNode::create(document);
  53. }
  54. NonnullRefPtr<StyledNode> StyleResolver::create_styled_node(const Element& element)
  55. {
  56. auto style = StyledNode::create(element);
  57. auto matching_rules = collect_matching_rules(element);
  58. for (auto& rule : matching_rules) {
  59. for (auto& declaration : rule.declarations()) {
  60. style->set_property(declaration.property_name(), declaration.value());
  61. }
  62. }
  63. return style;
  64. }