SelectorEngine.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/CSS/Parser/Parser.h>
  8. #include <LibWeb/CSS/SelectorEngine.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/DOM/Element.h>
  11. #include <LibWeb/DOM/Text.h>
  12. #include <LibWeb/HTML/AttributeNames.h>
  13. #include <LibWeb/HTML/HTMLHtmlElement.h>
  14. #include <LibWeb/HTML/HTMLInputElement.h>
  15. namespace Web::SelectorEngine {
  16. // https://drafts.csswg.org/selectors-4/#the-lang-pseudo
  17. static inline bool matches_lang_pseudo_class(DOM::Element const& element, Vector<FlyString> const& languages)
  18. {
  19. FlyString element_language;
  20. for (auto const* e = &element; e; e = e->parent_element()) {
  21. auto lang = e->attribute(HTML::AttributeNames::lang);
  22. if (!lang.is_null()) {
  23. element_language = lang;
  24. break;
  25. }
  26. }
  27. if (element_language.is_null())
  28. return false;
  29. // FIXME: This is ad-hoc. Implement a proper language range matching algorithm as recommended by BCP47.
  30. for (auto const& language : languages) {
  31. if (language.is_empty())
  32. return false;
  33. if (language == "*"sv)
  34. return true;
  35. if (!element_language.view().contains('-'))
  36. return element_language.equals_ignoring_case(language);
  37. auto parts = element_language.view().split_view('-');
  38. return parts[0].equals_ignoring_case(language);
  39. }
  40. return false;
  41. }
  42. static inline bool matches_hover_pseudo_class(DOM::Element const& element)
  43. {
  44. auto* hovered_node = element.document().hovered_node();
  45. if (!hovered_node)
  46. return false;
  47. if (&element == hovered_node)
  48. return true;
  49. return element.is_ancestor_of(*hovered_node);
  50. }
  51. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-checked
  52. static inline bool matches_checked_pseudo_class(DOM::Element const& element)
  53. {
  54. // The :checked pseudo-class must match any element falling into one of the following categories:
  55. // - input elements whose type attribute is in the Checkbox state and whose checkedness state is true
  56. // - input elements whose type attribute is in the Radio Button state and whose checkedness state is true
  57. if (is<HTML::HTMLInputElement>(element)) {
  58. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  59. switch (input_element.type_state()) {
  60. case HTML::HTMLInputElement::TypeAttributeState::Checkbox:
  61. case HTML::HTMLInputElement::TypeAttributeState::RadioButton:
  62. return static_cast<HTML::HTMLInputElement const&>(element).checked();
  63. default:
  64. return false;
  65. }
  66. }
  67. // FIXME: - option elements whose selectedness is true
  68. return false;
  69. }
  70. static inline bool matches_attribute(CSS::Selector::SimpleSelector::Attribute const& attribute, DOM::Element const& element)
  71. {
  72. switch (attribute.match_type) {
  73. case CSS::Selector::SimpleSelector::Attribute::MatchType::HasAttribute:
  74. return element.has_attribute(attribute.name);
  75. case CSS::Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch:
  76. return element.attribute(attribute.name) == attribute.value;
  77. case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsWord:
  78. return element.attribute(attribute.name).split_view(' ').contains_slow(attribute.value);
  79. case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsString:
  80. return element.attribute(attribute.name).contains(attribute.value);
  81. case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment: {
  82. auto segments = element.attribute(attribute.name).split_view('-');
  83. return !segments.is_empty() && segments.first() == attribute.value;
  84. }
  85. case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithString:
  86. return element.attribute(attribute.name).starts_with(attribute.value);
  87. case CSS::Selector::SimpleSelector::Attribute::MatchType::EndsWithString:
  88. return element.attribute(attribute.name).ends_with(attribute.value);
  89. }
  90. return false;
  91. }
  92. static inline DOM::Element const* previous_sibling_with_same_tag_name(DOM::Element const& element)
  93. {
  94. for (auto const* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  95. if (sibling->tag_name() == element.tag_name())
  96. return sibling;
  97. }
  98. return nullptr;
  99. }
  100. static inline DOM::Element const* next_sibling_with_same_tag_name(DOM::Element const& element)
  101. {
  102. for (auto const* sibling = element.next_element_sibling(); sibling; sibling = sibling->next_element_sibling()) {
  103. if (sibling->tag_name() == element.tag_name())
  104. return sibling;
  105. }
  106. return nullptr;
  107. }
  108. static inline bool matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClass const& pseudo_class, DOM::Element const& element)
  109. {
  110. switch (pseudo_class.type) {
  111. case CSS::Selector::SimpleSelector::PseudoClass::Type::Link:
  112. return element.is_link();
  113. case CSS::Selector::SimpleSelector::PseudoClass::Type::Visited:
  114. // FIXME: Maybe match this selector sometimes?
  115. return false;
  116. case CSS::Selector::SimpleSelector::PseudoClass::Type::Active:
  117. return element.is_active();
  118. case CSS::Selector::SimpleSelector::PseudoClass::Type::Hover:
  119. return matches_hover_pseudo_class(element);
  120. case CSS::Selector::SimpleSelector::PseudoClass::Type::Focus:
  121. return element.is_focused();
  122. case CSS::Selector::SimpleSelector::PseudoClass::Type::FocusWithin: {
  123. auto* focused_element = element.document().focused_element();
  124. return focused_element && element.is_inclusive_ancestor_of(*focused_element);
  125. }
  126. case CSS::Selector::SimpleSelector::PseudoClass::Type::FirstChild:
  127. return !element.previous_element_sibling();
  128. case CSS::Selector::SimpleSelector::PseudoClass::Type::LastChild:
  129. return !element.next_element_sibling();
  130. case CSS::Selector::SimpleSelector::PseudoClass::Type::OnlyChild:
  131. return !(element.previous_element_sibling() || element.next_element_sibling());
  132. case CSS::Selector::SimpleSelector::PseudoClass::Type::Empty: {
  133. if (!element.has_children())
  134. return true;
  135. if (element.first_child_of_type<DOM::Element>())
  136. return false;
  137. // NOTE: CSS Selectors level 4 changed ":empty" to also match whitespace-only text nodes.
  138. // However, none of the major browser supports this yet, so let's just hang back until they do.
  139. bool has_nonempty_text_child = false;
  140. element.for_each_child_of_type<DOM::Text>([&](auto const& text_child) {
  141. if (!text_child.data().is_empty()) {
  142. has_nonempty_text_child = true;
  143. return IterationDecision::Break;
  144. }
  145. return IterationDecision::Continue;
  146. });
  147. return !has_nonempty_text_child;
  148. }
  149. case CSS::Selector::SimpleSelector::PseudoClass::Type::Root:
  150. return is<HTML::HTMLHtmlElement>(element);
  151. case CSS::Selector::SimpleSelector::PseudoClass::Type::FirstOfType:
  152. return !previous_sibling_with_same_tag_name(element);
  153. case CSS::Selector::SimpleSelector::PseudoClass::Type::LastOfType:
  154. return !next_sibling_with_same_tag_name(element);
  155. case CSS::Selector::SimpleSelector::PseudoClass::Type::OnlyOfType:
  156. return !previous_sibling_with_same_tag_name(element) && !next_sibling_with_same_tag_name(element);
  157. case CSS::Selector::SimpleSelector::PseudoClass::Type::Lang:
  158. return matches_lang_pseudo_class(element, pseudo_class.languages);
  159. case CSS::Selector::SimpleSelector::PseudoClass::Type::Disabled:
  160. if (!element.tag_name().equals_ignoring_case(HTML::TagNames::input))
  161. return false;
  162. if (!element.has_attribute("disabled"))
  163. return false;
  164. return true;
  165. case CSS::Selector::SimpleSelector::PseudoClass::Type::Enabled:
  166. if (!element.tag_name().equals_ignoring_case(HTML::TagNames::input))
  167. return false;
  168. if (element.has_attribute("disabled"))
  169. return false;
  170. return true;
  171. case CSS::Selector::SimpleSelector::PseudoClass::Type::Checked:
  172. return matches_checked_pseudo_class(element);
  173. case CSS::Selector::SimpleSelector::PseudoClass::Type::Is:
  174. case CSS::Selector::SimpleSelector::PseudoClass::Type::Where:
  175. for (auto& selector : pseudo_class.argument_selector_list) {
  176. if (matches(selector, element))
  177. return true;
  178. }
  179. return false;
  180. case CSS::Selector::SimpleSelector::PseudoClass::Type::Not:
  181. for (auto& selector : pseudo_class.argument_selector_list) {
  182. if (matches(selector, element))
  183. return false;
  184. }
  185. return true;
  186. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthChild:
  187. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastChild:
  188. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthOfType:
  189. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastOfType:
  190. auto const step_size = pseudo_class.nth_child_pattern.step_size;
  191. auto const offset = pseudo_class.nth_child_pattern.offset;
  192. if (step_size == 0 && offset == 0)
  193. return false; // "If both a and b are equal to zero, the pseudo-class represents no element in the document tree."
  194. auto const* parent = element.parent_element();
  195. if (!parent)
  196. return false;
  197. auto matches_selector_list = [](CSS::SelectorList const& list, DOM::Element const& element) {
  198. if (list.is_empty())
  199. return true;
  200. for (auto const& child_selector : list) {
  201. if (matches(child_selector, element)) {
  202. return true;
  203. }
  204. }
  205. return false;
  206. };
  207. int index = 1;
  208. switch (pseudo_class.type) {
  209. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthChild: {
  210. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  211. return false;
  212. for (auto* child = parent->first_child_of_type<DOM::Element>(); child && child != &element; child = child->next_element_sibling()) {
  213. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  214. ++index;
  215. }
  216. break;
  217. }
  218. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastChild: {
  219. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  220. return false;
  221. for (auto* child = parent->last_child_of_type<DOM::Element>(); child && child != &element; child = child->previous_element_sibling()) {
  222. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  223. ++index;
  224. }
  225. break;
  226. }
  227. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthOfType: {
  228. for (auto* child = previous_sibling_with_same_tag_name(element); child; child = previous_sibling_with_same_tag_name(*child))
  229. ++index;
  230. break;
  231. }
  232. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastOfType: {
  233. for (auto* child = next_sibling_with_same_tag_name(element); child; child = next_sibling_with_same_tag_name(*child))
  234. ++index;
  235. break;
  236. }
  237. default:
  238. VERIFY_NOT_REACHED();
  239. }
  240. // When "step_size == -1", selector represents first "offset" elements in document tree.
  241. if (step_size == -1)
  242. return !(offset <= 0 || index > offset);
  243. // When "step_size == 1", selector represents last "offset" elements in document tree.
  244. if (step_size == 1)
  245. return !(offset < 0 || index < offset);
  246. // When "step_size == 0", selector picks only the "offset" element.
  247. if (step_size == 0)
  248. return index == offset;
  249. // If both are negative, nothing can match.
  250. if (step_size < 0 && offset < 0)
  251. return false;
  252. // Like "a % b", but handles negative integers correctly.
  253. auto const canonical_modulo = [](int a, int b) -> int {
  254. int c = a % b;
  255. if ((c < 0 && b > 0) || (c > 0 && b < 0)) {
  256. c += b;
  257. }
  258. return c;
  259. };
  260. // When "step_size < 0", we start at "offset" and count backwards.
  261. if (step_size < 0)
  262. return index <= offset && canonical_modulo(index - offset, -step_size) == 0;
  263. // Otherwise, we start at "offset" and count forwards.
  264. return index >= offset && canonical_modulo(index - offset, step_size) == 0;
  265. }
  266. return false;
  267. }
  268. static inline bool matches(CSS::Selector::SimpleSelector const& component, DOM::Element const& element)
  269. {
  270. switch (component.type) {
  271. case CSS::Selector::SimpleSelector::Type::Universal:
  272. return true;
  273. case CSS::Selector::SimpleSelector::Type::Id:
  274. return component.name() == element.attribute(HTML::AttributeNames::id);
  275. case CSS::Selector::SimpleSelector::Type::Class:
  276. return element.has_class(component.name());
  277. case CSS::Selector::SimpleSelector::Type::TagName:
  278. return component.name() == element.local_name();
  279. case CSS::Selector::SimpleSelector::Type::Attribute:
  280. return matches_attribute(component.attribute(), element);
  281. case CSS::Selector::SimpleSelector::Type::PseudoClass:
  282. return matches_pseudo_class(component.pseudo_class(), element);
  283. case CSS::Selector::SimpleSelector::Type::PseudoElement:
  284. // Pseudo-element matching/not-matching is handled in the top level matches().
  285. return true;
  286. default:
  287. VERIFY_NOT_REACHED();
  288. }
  289. }
  290. static inline bool matches(CSS::Selector const& selector, int component_list_index, DOM::Element const& element)
  291. {
  292. auto& relative_selector = selector.compound_selectors()[component_list_index];
  293. for (auto& simple_selector : relative_selector.simple_selectors) {
  294. if (!matches(simple_selector, element))
  295. return false;
  296. }
  297. switch (relative_selector.combinator) {
  298. case CSS::Selector::Combinator::None:
  299. return true;
  300. case CSS::Selector::Combinator::Descendant:
  301. VERIFY(component_list_index != 0);
  302. for (auto* ancestor = element.parent(); ancestor; ancestor = ancestor->parent()) {
  303. if (!is<DOM::Element>(*ancestor))
  304. continue;
  305. if (matches(selector, component_list_index - 1, static_cast<DOM::Element const&>(*ancestor)))
  306. return true;
  307. }
  308. return false;
  309. case CSS::Selector::Combinator::ImmediateChild:
  310. VERIFY(component_list_index != 0);
  311. if (!element.parent() || !is<DOM::Element>(*element.parent()))
  312. return false;
  313. return matches(selector, component_list_index - 1, static_cast<DOM::Element const&>(*element.parent()));
  314. case CSS::Selector::Combinator::NextSibling:
  315. VERIFY(component_list_index != 0);
  316. if (auto* sibling = element.previous_element_sibling())
  317. return matches(selector, component_list_index - 1, *sibling);
  318. return false;
  319. case CSS::Selector::Combinator::SubsequentSibling:
  320. VERIFY(component_list_index != 0);
  321. for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  322. if (matches(selector, component_list_index - 1, *sibling))
  323. return true;
  324. }
  325. return false;
  326. case CSS::Selector::Combinator::Column:
  327. TODO();
  328. }
  329. VERIFY_NOT_REACHED();
  330. }
  331. bool matches(CSS::Selector const& selector, DOM::Element const& element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  332. {
  333. VERIFY(!selector.compound_selectors().is_empty());
  334. if (pseudo_element.has_value() && selector.pseudo_element() != pseudo_element)
  335. return false;
  336. if (!pseudo_element.has_value() && selector.pseudo_element().has_value())
  337. return false;
  338. return matches(selector, selector.compound_selectors().size() - 1, element);
  339. }
  340. }