SelectorEngine.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <LibHTML/CSS/SelectorEngine.h>
  2. #include <LibHTML/DOM/Element.h>
  3. namespace SelectorEngine {
  4. bool matches(const Selector::Component& component, const Element& element)
  5. {
  6. switch (component.type) {
  7. case Selector::Component::Type::Id:
  8. return component.value == element.attribute("id");
  9. case Selector::Component::Type::Class:
  10. return element.has_class(component.value);
  11. case Selector::Component::Type::TagName:
  12. return component.value == element.tag_name();
  13. default:
  14. ASSERT_NOT_REACHED();
  15. }
  16. }
  17. bool matches(const Selector& selector, int component_index, const Element& element)
  18. {
  19. auto& component = selector.components()[component_index];
  20. if (!matches(component, element))
  21. return false;
  22. switch (component.relation) {
  23. case Selector::Component::Relation::None:
  24. return true;
  25. case Selector::Component::Relation::Descendant:
  26. ASSERT(component_index != 0);
  27. for (auto* ancestor = element.parent(); ancestor; ancestor = ancestor->parent()) {
  28. if (!is<Element>(*ancestor))
  29. continue;
  30. if (matches(selector, component_index - 1, to<Element>(*ancestor)))
  31. return true;
  32. }
  33. return false;
  34. case Selector::Component::Relation::ImmediateChild:
  35. ASSERT(component_index != 0);
  36. if (!element.parent() || !is<Element>(*element.parent()))
  37. return false;
  38. return matches(selector, component_index - 1, to<Element>(*element.parent()));
  39. case Selector::Component::Relation::AdjacentSibling:
  40. ASSERT(component_index != 0);
  41. if (auto* sibling = element.previous_element_sibling())
  42. return matches(selector, component_index - 1, *sibling);
  43. return false;
  44. case Selector::Component::Relation::GeneralSibling:
  45. ASSERT(component_index != 0);
  46. for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  47. if (matches(selector, component_index - 1, *sibling))
  48. return true;
  49. }
  50. return false;
  51. }
  52. ASSERT_NOT_REACHED();
  53. }
  54. bool matches(const Selector& selector, const Element& element)
  55. {
  56. ASSERT(!selector.components().is_empty());
  57. return matches(selector, selector.components().size() - 1, element);
  58. }
  59. }