SelectorEngine.cpp 18 KB

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