SelectorEngine.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. case CSS::Selector::SimpleSelector::Attribute::MatchType::None:
  90. VERIFY_NOT_REACHED();
  91. break;
  92. }
  93. return false;
  94. }
  95. static inline DOM::Element const* previous_sibling_with_same_tag_name(DOM::Element const& element)
  96. {
  97. for (auto const* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  98. if (sibling->tag_name() == element.tag_name())
  99. return sibling;
  100. }
  101. return nullptr;
  102. }
  103. static inline DOM::Element const* next_sibling_with_same_tag_name(DOM::Element const& element)
  104. {
  105. for (auto const* sibling = element.next_element_sibling(); sibling; sibling = sibling->next_element_sibling()) {
  106. if (sibling->tag_name() == element.tag_name())
  107. return sibling;
  108. }
  109. return nullptr;
  110. }
  111. static inline bool matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClass const& pseudo_class, DOM::Element const& element)
  112. {
  113. switch (pseudo_class.type) {
  114. case CSS::Selector::SimpleSelector::PseudoClass::Type::None:
  115. break;
  116. case CSS::Selector::SimpleSelector::PseudoClass::Type::Link:
  117. return element.is_link();
  118. case CSS::Selector::SimpleSelector::PseudoClass::Type::Visited:
  119. // FIXME: Maybe match this selector sometimes?
  120. return false;
  121. case CSS::Selector::SimpleSelector::PseudoClass::Type::Active:
  122. return element.is_active();
  123. case CSS::Selector::SimpleSelector::PseudoClass::Type::Hover:
  124. return matches_hover_pseudo_class(element);
  125. case CSS::Selector::SimpleSelector::PseudoClass::Type::Focus:
  126. return element.is_focused();
  127. case CSS::Selector::SimpleSelector::PseudoClass::Type::FocusWithin: {
  128. auto* focused_element = element.document().focused_element();
  129. return focused_element && element.is_inclusive_ancestor_of(*focused_element);
  130. }
  131. case CSS::Selector::SimpleSelector::PseudoClass::Type::FirstChild:
  132. return !element.previous_element_sibling();
  133. case CSS::Selector::SimpleSelector::PseudoClass::Type::LastChild:
  134. return !element.next_element_sibling();
  135. case CSS::Selector::SimpleSelector::PseudoClass::Type::OnlyChild:
  136. return !(element.previous_element_sibling() || element.next_element_sibling());
  137. case CSS::Selector::SimpleSelector::PseudoClass::Type::Empty: {
  138. if (!element.has_children())
  139. return true;
  140. if (element.first_child_of_type<DOM::Element>())
  141. return false;
  142. // NOTE: CSS Selectors level 4 changed ":empty" to also match whitespace-only text nodes.
  143. // However, none of the major browser supports this yet, so let's just hang back until they do.
  144. bool has_nonempty_text_child = false;
  145. element.for_each_child_of_type<DOM::Text>([&](auto const& text_child) {
  146. if (!text_child.data().is_empty()) {
  147. has_nonempty_text_child = true;
  148. return IterationDecision::Break;
  149. }
  150. return IterationDecision::Continue;
  151. });
  152. return !has_nonempty_text_child;
  153. }
  154. case CSS::Selector::SimpleSelector::PseudoClass::Type::Root:
  155. return is<HTML::HTMLHtmlElement>(element);
  156. case CSS::Selector::SimpleSelector::PseudoClass::Type::FirstOfType:
  157. return !previous_sibling_with_same_tag_name(element);
  158. case CSS::Selector::SimpleSelector::PseudoClass::Type::LastOfType:
  159. return !next_sibling_with_same_tag_name(element);
  160. case CSS::Selector::SimpleSelector::PseudoClass::Type::OnlyOfType:
  161. return !previous_sibling_with_same_tag_name(element) && !next_sibling_with_same_tag_name(element);
  162. case CSS::Selector::SimpleSelector::PseudoClass::Type::Lang:
  163. return matches_lang_pseudo_class(element, pseudo_class.languages);
  164. case CSS::Selector::SimpleSelector::PseudoClass::Type::Disabled:
  165. if (!element.tag_name().equals_ignoring_case(HTML::TagNames::input))
  166. return false;
  167. if (!element.has_attribute("disabled"))
  168. return false;
  169. return true;
  170. case CSS::Selector::SimpleSelector::PseudoClass::Type::Enabled:
  171. if (!element.tag_name().equals_ignoring_case(HTML::TagNames::input))
  172. return false;
  173. if (element.has_attribute("disabled"))
  174. return false;
  175. return true;
  176. case CSS::Selector::SimpleSelector::PseudoClass::Type::Checked:
  177. return matches_checked_pseudo_class(element);
  178. case CSS::Selector::SimpleSelector::PseudoClass::Type::Is:
  179. case CSS::Selector::SimpleSelector::PseudoClass::Type::Where:
  180. for (auto& selector : pseudo_class.argument_selector_list) {
  181. if (matches(selector, element))
  182. return true;
  183. }
  184. return false;
  185. case CSS::Selector::SimpleSelector::PseudoClass::Type::Not:
  186. for (auto& selector : pseudo_class.argument_selector_list) {
  187. if (matches(selector, element))
  188. return false;
  189. }
  190. return true;
  191. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthChild:
  192. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastChild:
  193. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthOfType:
  194. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastOfType:
  195. auto const step_size = pseudo_class.nth_child_pattern.step_size;
  196. auto const offset = pseudo_class.nth_child_pattern.offset;
  197. if (step_size == 0 && offset == 0)
  198. return false; // "If both a and b are equal to zero, the pseudo-class represents no element in the document tree."
  199. auto const* parent = element.parent_element();
  200. if (!parent)
  201. return false;
  202. auto matches_selector_list = [](CSS::SelectorList const& list, DOM::Element const& element) {
  203. if (list.is_empty())
  204. return true;
  205. for (auto const& child_selector : list) {
  206. if (matches(child_selector, element)) {
  207. return true;
  208. }
  209. }
  210. return false;
  211. };
  212. int index = 1;
  213. switch (pseudo_class.type) {
  214. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthChild: {
  215. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  216. return false;
  217. for (auto* child = parent->first_child_of_type<DOM::Element>(); child && child != &element; child = child->next_element_sibling()) {
  218. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  219. ++index;
  220. }
  221. break;
  222. }
  223. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastChild: {
  224. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  225. return false;
  226. for (auto* child = parent->last_child_of_type<DOM::Element>(); child && child != &element; child = child->previous_element_sibling()) {
  227. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  228. ++index;
  229. }
  230. break;
  231. }
  232. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthOfType: {
  233. for (auto* child = previous_sibling_with_same_tag_name(element); child; child = previous_sibling_with_same_tag_name(*child))
  234. ++index;
  235. break;
  236. }
  237. case CSS::Selector::SimpleSelector::PseudoClass::Type::NthLastOfType: {
  238. for (auto* child = next_sibling_with_same_tag_name(element); child; child = next_sibling_with_same_tag_name(*child))
  239. ++index;
  240. break;
  241. }
  242. default:
  243. VERIFY_NOT_REACHED();
  244. }
  245. // When "step_size == -1", selector represents first "offset" elements in document tree.
  246. if (step_size == -1)
  247. return !(offset <= 0 || index > offset);
  248. // When "step_size == 1", selector represents last "offset" elements in document tree.
  249. if (step_size == 1)
  250. return !(offset < 0 || index < offset);
  251. // When "step_size == 0", selector picks only the "offset" element.
  252. if (step_size == 0)
  253. return index == offset;
  254. // If both are negative, nothing can match.
  255. if (step_size < 0 && offset < 0)
  256. return false;
  257. // Like "a % b", but handles negative integers correctly.
  258. auto const canonical_modulo = [](int a, int b) -> int {
  259. int c = a % b;
  260. if ((c < 0 && b > 0) || (c > 0 && b < 0)) {
  261. c += b;
  262. }
  263. return c;
  264. };
  265. // When "step_size < 0", we start at "offset" and count backwards.
  266. if (step_size < 0)
  267. return index <= offset && canonical_modulo(index - offset, -step_size) == 0;
  268. // Otherwise, we start at "offset" and count forwards.
  269. return index >= offset && canonical_modulo(index - offset, step_size) == 0;
  270. }
  271. return false;
  272. }
  273. static inline bool matches(CSS::Selector::SimpleSelector const& component, DOM::Element const& element)
  274. {
  275. switch (component.type) {
  276. case CSS::Selector::SimpleSelector::Type::Universal:
  277. return true;
  278. case CSS::Selector::SimpleSelector::Type::Id:
  279. return component.value == element.attribute(HTML::AttributeNames::id);
  280. case CSS::Selector::SimpleSelector::Type::Class:
  281. return element.has_class(component.value);
  282. case CSS::Selector::SimpleSelector::Type::TagName:
  283. return component.value == element.local_name();
  284. case CSS::Selector::SimpleSelector::Type::Attribute:
  285. return matches_attribute(component.attribute, element);
  286. case CSS::Selector::SimpleSelector::Type::PseudoClass:
  287. return matches_pseudo_class(component.pseudo_class, element);
  288. case CSS::Selector::SimpleSelector::Type::PseudoElement:
  289. // Pseudo-element matching/not-matching is handled in the top level matches().
  290. return true;
  291. default:
  292. VERIFY_NOT_REACHED();
  293. }
  294. }
  295. static inline bool matches(CSS::Selector const& selector, int component_list_index, DOM::Element const& element)
  296. {
  297. auto& relative_selector = selector.compound_selectors()[component_list_index];
  298. for (auto& simple_selector : relative_selector.simple_selectors) {
  299. if (!matches(simple_selector, element))
  300. return false;
  301. }
  302. switch (relative_selector.combinator) {
  303. case CSS::Selector::Combinator::None:
  304. return true;
  305. case CSS::Selector::Combinator::Descendant:
  306. VERIFY(component_list_index != 0);
  307. for (auto* ancestor = element.parent(); ancestor; ancestor = ancestor->parent()) {
  308. if (!is<DOM::Element>(*ancestor))
  309. continue;
  310. if (matches(selector, component_list_index - 1, static_cast<DOM::Element const&>(*ancestor)))
  311. return true;
  312. }
  313. return false;
  314. case CSS::Selector::Combinator::ImmediateChild:
  315. VERIFY(component_list_index != 0);
  316. if (!element.parent() || !is<DOM::Element>(*element.parent()))
  317. return false;
  318. return matches(selector, component_list_index - 1, static_cast<DOM::Element const&>(*element.parent()));
  319. case CSS::Selector::Combinator::NextSibling:
  320. VERIFY(component_list_index != 0);
  321. if (auto* sibling = element.previous_element_sibling())
  322. return matches(selector, component_list_index - 1, *sibling);
  323. return false;
  324. case CSS::Selector::Combinator::SubsequentSibling:
  325. VERIFY(component_list_index != 0);
  326. for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  327. if (matches(selector, component_list_index - 1, *sibling))
  328. return true;
  329. }
  330. return false;
  331. case CSS::Selector::Combinator::Column:
  332. TODO();
  333. }
  334. VERIFY_NOT_REACHED();
  335. }
  336. bool matches(CSS::Selector const& selector, DOM::Element const& element, Optional<CSS::Selector::PseudoElement> pseudo_element)
  337. {
  338. VERIFY(!selector.compound_selectors().is_empty());
  339. if (pseudo_element.has_value() && selector.pseudo_element() != pseudo_element)
  340. return false;
  341. if (!pseudo_element.has_value() && selector.pseudo_element().has_value())
  342. return false;
  343. return matches(selector, selector.compound_selectors().size() - 1, element);
  344. }
  345. }