SelectorEngine.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, 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/CSS/ValueID.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/DOM/Element.h>
  12. #include <LibWeb/DOM/Text.h>
  13. #include <LibWeb/HTML/AttributeNames.h>
  14. #include <LibWeb/HTML/HTMLAnchorElement.h>
  15. #include <LibWeb/HTML/HTMLAreaElement.h>
  16. #include <LibWeb/HTML/HTMLButtonElement.h>
  17. #include <LibWeb/HTML/HTMLFieldSetElement.h>
  18. #include <LibWeb/HTML/HTMLHtmlElement.h>
  19. #include <LibWeb/HTML/HTMLInputElement.h>
  20. #include <LibWeb/HTML/HTMLMediaElement.h>
  21. #include <LibWeb/HTML/HTMLOptGroupElement.h>
  22. #include <LibWeb/HTML/HTMLOptionElement.h>
  23. #include <LibWeb/HTML/HTMLProgressElement.h>
  24. #include <LibWeb/HTML/HTMLSelectElement.h>
  25. #include <LibWeb/HTML/HTMLTextAreaElement.h>
  26. #include <LibWeb/Infra/Strings.h>
  27. namespace Web::SelectorEngine {
  28. // https://drafts.csswg.org/selectors-4/#the-lang-pseudo
  29. static inline bool matches_lang_pseudo_class(DOM::Element const& element, Vector<FlyString> const& languages)
  30. {
  31. FlyString element_language;
  32. for (auto const* e = &element; e; e = e->parent_element()) {
  33. auto lang = e->attribute(HTML::AttributeNames::lang);
  34. if (!lang.is_null()) {
  35. element_language = FlyString::from_deprecated_fly_string(lang).release_value_but_fixme_should_propagate_errors();
  36. break;
  37. }
  38. }
  39. if (element_language.is_empty())
  40. return false;
  41. // FIXME: This is ad-hoc. Implement a proper language range matching algorithm as recommended by BCP47.
  42. for (auto const& language : languages) {
  43. if (language.is_empty())
  44. continue;
  45. if (language == "*"sv)
  46. return true;
  47. if (!element_language.to_string().contains('-') && Infra::is_ascii_case_insensitive_match(element_language, language))
  48. return true;
  49. auto parts = element_language.to_string().split_limit('-', 2).release_value_but_fixme_should_propagate_errors();
  50. if (Infra::is_ascii_case_insensitive_match(parts[0], language))
  51. return true;
  52. }
  53. return false;
  54. }
  55. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-link
  56. static inline bool matches_link_pseudo_class(DOM::Element const& element)
  57. {
  58. // All a elements that have an href attribute, and all area elements that have an href attribute, must match one of :link and :visited.
  59. if (!is<HTML::HTMLAnchorElement>(element) && !is<HTML::HTMLAreaElement>(element))
  60. return false;
  61. return element.has_attribute(HTML::AttributeNames::href);
  62. }
  63. static inline bool matches_hover_pseudo_class(DOM::Element const& element)
  64. {
  65. auto* hovered_node = element.document().hovered_node();
  66. if (!hovered_node)
  67. return false;
  68. if (&element == hovered_node)
  69. return true;
  70. return element.is_ancestor_of(*hovered_node);
  71. }
  72. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-checked
  73. static inline bool matches_checked_pseudo_class(DOM::Element const& element)
  74. {
  75. // The :checked pseudo-class must match any element falling into one of the following categories:
  76. // - input elements whose type attribute is in the Checkbox state and whose checkedness state is true
  77. // - input elements whose type attribute is in the Radio Button state and whose checkedness state is true
  78. if (is<HTML::HTMLInputElement>(element)) {
  79. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  80. switch (input_element.type_state()) {
  81. case HTML::HTMLInputElement::TypeAttributeState::Checkbox:
  82. case HTML::HTMLInputElement::TypeAttributeState::RadioButton:
  83. return static_cast<HTML::HTMLInputElement const&>(element).checked();
  84. default:
  85. return false;
  86. }
  87. }
  88. // - option elements whose selectedness is true
  89. if (is<HTML::HTMLOptionElement>(element)) {
  90. return static_cast<HTML::HTMLOptionElement const&>(element).selected();
  91. }
  92. return false;
  93. }
  94. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-indeterminate
  95. static inline bool matches_indeterminate_pseudo_class(DOM::Element const& element)
  96. {
  97. // The :indeterminate pseudo-class must match any element falling into one of the following categories:
  98. // - input elements whose type attribute is in the Checkbox state and whose indeterminate IDL attribute is set to true
  99. // FIXME: - input elements whose type attribute is in the Radio Button state and whose radio button group contains no input elements whose checkedness state is true.
  100. if (is<HTML::HTMLInputElement>(element)) {
  101. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  102. switch (input_element.type_state()) {
  103. case HTML::HTMLInputElement::TypeAttributeState::Checkbox:
  104. return input_element.indeterminate();
  105. default:
  106. return false;
  107. }
  108. }
  109. // - progress elements with no value content attribute
  110. if (is<HTML::HTMLProgressElement>(element)) {
  111. return !element.has_attribute(HTML::AttributeNames::value);
  112. }
  113. return false;
  114. }
  115. static inline bool matches_attribute(CSS::Selector::SimpleSelector::Attribute const& attribute, [[maybe_unused]] Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element)
  116. {
  117. // FIXME: Check the attribute's namespace, once we support that in DOM::Element!
  118. auto attribute_name = attribute.qualified_name.name.name.to_deprecated_fly_string();
  119. if (attribute.match_type == CSS::Selector::SimpleSelector::Attribute::MatchType::HasAttribute) {
  120. // Early way out in case of an attribute existence selector.
  121. return element.has_attribute(attribute_name);
  122. }
  123. auto const case_insensitive_match = (attribute.case_type == CSS::Selector::SimpleSelector::Attribute::CaseType::CaseInsensitiveMatch);
  124. auto const case_sensitivity = case_insensitive_match
  125. ? CaseSensitivity::CaseInsensitive
  126. : CaseSensitivity::CaseSensitive;
  127. switch (attribute.match_type) {
  128. case CSS::Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch:
  129. return case_insensitive_match
  130. ? Infra::is_ascii_case_insensitive_match(element.attribute(attribute_name), attribute.value)
  131. : element.attribute(attribute_name) == attribute.value.to_deprecated_string();
  132. case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsWord: {
  133. if (attribute.value.is_empty()) {
  134. // This selector is always false is match value is empty.
  135. return false;
  136. }
  137. auto const view = element.attribute(attribute_name).split_view(' ');
  138. auto const size = view.size();
  139. for (size_t i = 0; i < size; ++i) {
  140. auto const value = view.at(i);
  141. if (case_insensitive_match
  142. ? Infra::is_ascii_case_insensitive_match(value, attribute.value)
  143. : value == attribute.value) {
  144. return true;
  145. }
  146. }
  147. return false;
  148. }
  149. case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsString:
  150. return !attribute.value.is_empty()
  151. && element.attribute(attribute_name).contains(attribute.value, case_sensitivity);
  152. case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment: {
  153. auto const element_attr_value = element.attribute(attribute_name);
  154. if (element_attr_value.is_empty()) {
  155. // If the attribute value on element is empty, the selector is true
  156. // if the match value is also empty and false otherwise.
  157. return attribute.value.is_empty();
  158. }
  159. if (attribute.value.is_empty()) {
  160. return false;
  161. }
  162. auto segments = element_attr_value.split_view('-');
  163. return case_insensitive_match
  164. ? Infra::is_ascii_case_insensitive_match(segments.first(), attribute.value)
  165. : segments.first() == attribute.value;
  166. }
  167. case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithString:
  168. return !attribute.value.is_empty()
  169. && element.attribute(attribute_name).starts_with(attribute.value, case_sensitivity);
  170. case CSS::Selector::SimpleSelector::Attribute::MatchType::EndsWithString:
  171. return !attribute.value.is_empty()
  172. && element.attribute(attribute_name).ends_with(attribute.value, case_sensitivity);
  173. default:
  174. break;
  175. }
  176. return false;
  177. }
  178. static inline DOM::Element const* previous_sibling_with_same_tag_name(DOM::Element const& element)
  179. {
  180. for (auto const* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  181. if (sibling->tag_name() == element.tag_name())
  182. return sibling;
  183. }
  184. return nullptr;
  185. }
  186. static inline DOM::Element const* next_sibling_with_same_tag_name(DOM::Element const& element)
  187. {
  188. for (auto const* sibling = element.next_element_sibling(); sibling; sibling = sibling->next_element_sibling()) {
  189. if (sibling->tag_name() == element.tag_name())
  190. return sibling;
  191. }
  192. return nullptr;
  193. }
  194. static inline bool matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClassSelector const& pseudo_class, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, JS::GCPtr<DOM::ParentNode const> scope)
  195. {
  196. switch (pseudo_class.type) {
  197. case CSS::PseudoClass::Link:
  198. case CSS::PseudoClass::AnyLink:
  199. // NOTE: AnyLink should match whether the link is visited or not, so if we ever start matching
  200. // :visited, we'll need to handle these differently.
  201. return matches_link_pseudo_class(element);
  202. case CSS::PseudoClass::LocalLink: {
  203. // The :local-link pseudo-class allows authors to style hyperlinks based on the users current location
  204. // within a site. It represents an element that is the source anchor of a hyperlink whose target’s
  205. // absolute URL matches the element’s own document URL. If the hyperlink’s target includes a fragment
  206. // URL, then the fragment URL of the current URL must also match; if it does not, then the fragment
  207. // URL portion of the current URL is not taken into account in the comparison.
  208. if (!matches_link_pseudo_class(element))
  209. return false;
  210. auto document_url = element.document().url();
  211. AK::URL target_url = element.document().parse_url(element.attribute(HTML::AttributeNames::href));
  212. if (target_url.fragment().has_value())
  213. return document_url.equals(target_url, AK::URL::ExcludeFragment::No);
  214. return document_url.equals(target_url, AK::URL::ExcludeFragment::Yes);
  215. }
  216. case CSS::PseudoClass::Visited:
  217. // FIXME: Maybe match this selector sometimes?
  218. return false;
  219. case CSS::PseudoClass::Active:
  220. return element.is_active();
  221. case CSS::PseudoClass::Hover:
  222. return matches_hover_pseudo_class(element);
  223. case CSS::PseudoClass::Focus:
  224. return element.is_focused();
  225. case CSS::PseudoClass::FocusVisible:
  226. // FIXME: We should only apply this when a visible focus is useful. Decide when that is!
  227. return element.is_focused();
  228. case CSS::PseudoClass::FocusWithin: {
  229. auto* focused_element = element.document().focused_element();
  230. return focused_element && element.is_inclusive_ancestor_of(*focused_element);
  231. }
  232. case CSS::PseudoClass::FirstChild:
  233. return !element.previous_element_sibling();
  234. case CSS::PseudoClass::LastChild:
  235. return !element.next_element_sibling();
  236. case CSS::PseudoClass::OnlyChild:
  237. return !(element.previous_element_sibling() || element.next_element_sibling());
  238. case CSS::PseudoClass::Empty: {
  239. if (!element.has_children())
  240. return true;
  241. if (element.first_child_of_type<DOM::Element>())
  242. return false;
  243. // NOTE: CSS Selectors level 4 changed ":empty" to also match whitespace-only text nodes.
  244. // However, none of the major browser supports this yet, so let's just hang back until they do.
  245. bool has_nonempty_text_child = false;
  246. element.for_each_child_of_type<DOM::Text>([&](auto const& text_child) {
  247. if (!text_child.data().is_empty()) {
  248. has_nonempty_text_child = true;
  249. return IterationDecision::Break;
  250. }
  251. return IterationDecision::Continue;
  252. });
  253. return !has_nonempty_text_child;
  254. }
  255. case CSS::PseudoClass::Root:
  256. return is<HTML::HTMLHtmlElement>(element);
  257. case CSS::PseudoClass::Host:
  258. // FIXME: Implement :host selector.
  259. return false;
  260. case CSS::PseudoClass::Scope:
  261. return scope ? &element == scope : is<HTML::HTMLHtmlElement>(element);
  262. case CSS::PseudoClass::FirstOfType:
  263. return !previous_sibling_with_same_tag_name(element);
  264. case CSS::PseudoClass::LastOfType:
  265. return !next_sibling_with_same_tag_name(element);
  266. case CSS::PseudoClass::OnlyOfType:
  267. return !previous_sibling_with_same_tag_name(element) && !next_sibling_with_same_tag_name(element);
  268. case CSS::PseudoClass::Lang:
  269. return matches_lang_pseudo_class(element, pseudo_class.languages);
  270. case CSS::PseudoClass::Disabled:
  271. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-disabled
  272. // The :disabled pseudo-class must match any element that is actually disabled.
  273. return element.is_actually_disabled();
  274. case CSS::PseudoClass::Enabled:
  275. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-enabled
  276. // The :enabled pseudo-class must match any button, input, select, textarea, optgroup, option, fieldset element, or form-associated custom element that is not actually disabled.
  277. return (is<HTML::HTMLButtonElement>(element) || is<HTML::HTMLInputElement>(element) || is<HTML::HTMLSelectElement>(element) || is<HTML::HTMLTextAreaElement>(element) || is<HTML::HTMLOptGroupElement>(element) || is<HTML::HTMLOptionElement>(element) || is<HTML::HTMLFieldSetElement>(element))
  278. && !element.is_actually_disabled();
  279. case CSS::PseudoClass::Checked:
  280. return matches_checked_pseudo_class(element);
  281. case CSS::PseudoClass::Indeterminate:
  282. return matches_indeterminate_pseudo_class(element);
  283. case CSS::PseudoClass::Defined:
  284. return element.is_defined();
  285. case CSS::PseudoClass::Is:
  286. case CSS::PseudoClass::Where:
  287. for (auto& selector : pseudo_class.argument_selector_list) {
  288. if (matches(selector, style_sheet_for_rule, element))
  289. return true;
  290. }
  291. return false;
  292. case CSS::PseudoClass::Not:
  293. for (auto& selector : pseudo_class.argument_selector_list) {
  294. if (matches(selector, style_sheet_for_rule, element))
  295. return false;
  296. }
  297. return true;
  298. case CSS::PseudoClass::NthChild:
  299. case CSS::PseudoClass::NthLastChild:
  300. case CSS::PseudoClass::NthOfType:
  301. case CSS::PseudoClass::NthLastOfType: {
  302. auto const step_size = pseudo_class.nth_child_pattern.step_size;
  303. auto const offset = pseudo_class.nth_child_pattern.offset;
  304. if (step_size == 0 && offset == 0)
  305. return false; // "If both a and b are equal to zero, the pseudo-class represents no element in the document tree."
  306. auto const* parent = element.parent_element();
  307. if (!parent)
  308. return false;
  309. auto matches_selector_list = [&style_sheet_for_rule](CSS::SelectorList const& list, DOM::Element const& element) {
  310. if (list.is_empty())
  311. return true;
  312. for (auto const& child_selector : list) {
  313. if (matches(child_selector, style_sheet_for_rule, element)) {
  314. return true;
  315. }
  316. }
  317. return false;
  318. };
  319. int index = 1;
  320. switch (pseudo_class.type) {
  321. case CSS::PseudoClass::NthChild: {
  322. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  323. return false;
  324. for (auto* child = parent->first_child_of_type<DOM::Element>(); child && child != &element; child = child->next_element_sibling()) {
  325. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  326. ++index;
  327. }
  328. break;
  329. }
  330. case CSS::PseudoClass::NthLastChild: {
  331. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  332. return false;
  333. for (auto* child = parent->last_child_of_type<DOM::Element>(); child && child != &element; child = child->previous_element_sibling()) {
  334. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  335. ++index;
  336. }
  337. break;
  338. }
  339. case CSS::PseudoClass::NthOfType: {
  340. for (auto* child = previous_sibling_with_same_tag_name(element); child; child = previous_sibling_with_same_tag_name(*child))
  341. ++index;
  342. break;
  343. }
  344. case CSS::PseudoClass::NthLastOfType: {
  345. for (auto* child = next_sibling_with_same_tag_name(element); child; child = next_sibling_with_same_tag_name(*child))
  346. ++index;
  347. break;
  348. }
  349. default:
  350. VERIFY_NOT_REACHED();
  351. }
  352. // When "step_size == -1", selector represents first "offset" elements in document tree.
  353. if (step_size == -1)
  354. return !(offset <= 0 || index > offset);
  355. // When "step_size == 1", selector represents last "offset" elements in document tree.
  356. if (step_size == 1)
  357. return !(offset < 0 || index < offset);
  358. // When "step_size == 0", selector picks only the "offset" element.
  359. if (step_size == 0)
  360. return index == offset;
  361. // If both are negative, nothing can match.
  362. if (step_size < 0 && offset < 0)
  363. return false;
  364. // Like "a % b", but handles negative integers correctly.
  365. auto const canonical_modulo = [](int a, int b) -> int {
  366. int c = a % b;
  367. if ((c < 0 && b > 0) || (c > 0 && b < 0)) {
  368. c += b;
  369. }
  370. return c;
  371. };
  372. // When "step_size < 0", we start at "offset" and count backwards.
  373. if (step_size < 0)
  374. return index <= offset && canonical_modulo(index - offset, -step_size) == 0;
  375. // Otherwise, we start at "offset" and count forwards.
  376. return index >= offset && canonical_modulo(index - offset, step_size) == 0;
  377. }
  378. case CSS::PseudoClass::Playing: {
  379. if (!is<HTML::HTMLMediaElement>(element))
  380. return false;
  381. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  382. return !media_element.paused();
  383. }
  384. case CSS::PseudoClass::Paused: {
  385. if (!is<HTML::HTMLMediaElement>(element))
  386. return false;
  387. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  388. return media_element.paused();
  389. }
  390. case CSS::PseudoClass::Seeking: {
  391. if (!is<HTML::HTMLMediaElement>(element))
  392. return false;
  393. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  394. return media_element.seeking();
  395. }
  396. case CSS::PseudoClass::Muted: {
  397. if (!is<HTML::HTMLMediaElement>(element))
  398. return false;
  399. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  400. return media_element.muted();
  401. }
  402. case CSS::PseudoClass::VolumeLocked: {
  403. // FIXME: Currently we don't allow the user to specify an override volume, so this is always false.
  404. // Once we do, implement this!
  405. return false;
  406. }
  407. case CSS::PseudoClass::Buffering: {
  408. if (!is<HTML::HTMLMediaElement>(element))
  409. return false;
  410. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  411. return media_element.blocked();
  412. }
  413. case CSS::PseudoClass::Stalled: {
  414. if (!is<HTML::HTMLMediaElement>(element))
  415. return false;
  416. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  417. return media_element.stalled();
  418. }
  419. case CSS::PseudoClass::Target:
  420. return element.is_target();
  421. case CSS::PseudoClass::Dir: {
  422. // "Values other than ltr and rtl are not invalid, but do not match anything."
  423. // - https://www.w3.org/TR/selectors-4/#the-dir-pseudo
  424. if (!first_is_one_of(pseudo_class.identifier, CSS::ValueID::Ltr, CSS::ValueID::Rtl))
  425. return false;
  426. switch (element.directionality()) {
  427. case DOM::Element::Directionality::Ltr:
  428. return pseudo_class.identifier == CSS::ValueID::Ltr;
  429. case DOM::Element::Directionality::Rtl:
  430. return pseudo_class.identifier == CSS::ValueID::Rtl;
  431. }
  432. VERIFY_NOT_REACHED();
  433. }
  434. }
  435. return false;
  436. }
  437. static inline bool matches(CSS::Selector::SimpleSelector const& component, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, JS::GCPtr<DOM::ParentNode const> scope)
  438. {
  439. switch (component.type) {
  440. case CSS::Selector::SimpleSelector::Type::Universal:
  441. case CSS::Selector::SimpleSelector::Type::TagName: {
  442. auto qualified_name = component.qualified_name();
  443. // Reject if the tag name doesn't match
  444. if (component.type == CSS::Selector::SimpleSelector::Type::TagName) {
  445. // See https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
  446. if (element.document().document_type() == DOM::Document::Type::HTML) {
  447. if (qualified_name.name.lowercase_name != element.local_name().view())
  448. return false;
  449. } else if (!Infra::is_ascii_case_insensitive_match(qualified_name.name.name, element.local_name())) {
  450. return false;
  451. }
  452. }
  453. // Match the namespace
  454. switch (qualified_name.namespace_type) {
  455. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Default:
  456. // "if no default namespace has been declared for selectors, this is equivalent to *|E."
  457. if (!style_sheet_for_rule.has_value() || !style_sheet_for_rule->default_namespace().has_value())
  458. return true;
  459. // "Otherwise it is equivalent to ns|E where ns is the default namespace."
  460. return element.namespace_() == style_sheet_for_rule->default_namespace();
  461. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::None:
  462. // "elements with name E without a namespace"
  463. return element.namespace_().is_empty();
  464. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Any:
  465. // "elements with name E in any namespace, including those without a namespace"
  466. return true;
  467. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Named:
  468. // "elements with name E in namespace ns"
  469. // Unrecognized namespace prefixes are invalid, so don't match.
  470. // (We can't detect this at parse time, since a namespace rule may be inserted later.)
  471. // So, if we don't have a context to look up namespaces from, we fail to match.
  472. if (!style_sheet_for_rule.has_value())
  473. return false;
  474. auto selector_namespace = style_sheet_for_rule->namespace_uri(qualified_name.namespace_);
  475. return selector_namespace.has_value() && selector_namespace.value() == element.namespace_();
  476. }
  477. VERIFY_NOT_REACHED();
  478. }
  479. case CSS::Selector::SimpleSelector::Type::Id:
  480. return component.name() == element.attribute(HTML::AttributeNames::id).view();
  481. case CSS::Selector::SimpleSelector::Type::Class:
  482. return element.has_class(component.name());
  483. case CSS::Selector::SimpleSelector::Type::Attribute:
  484. return matches_attribute(component.attribute(), style_sheet_for_rule, element);
  485. case CSS::Selector::SimpleSelector::Type::PseudoClass:
  486. return matches_pseudo_class(component.pseudo_class(), style_sheet_for_rule, element, scope);
  487. case CSS::Selector::SimpleSelector::Type::PseudoElement:
  488. // Pseudo-element matching/not-matching is handled in the top level matches().
  489. return true;
  490. default:
  491. VERIFY_NOT_REACHED();
  492. }
  493. }
  494. static inline bool matches(CSS::Selector const& selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, int component_list_index, DOM::Element const& element, JS::GCPtr<DOM::ParentNode const> scope)
  495. {
  496. auto& relative_selector = selector.compound_selectors()[component_list_index];
  497. for (auto& simple_selector : relative_selector.simple_selectors) {
  498. if (!matches(simple_selector, style_sheet_for_rule, element, scope))
  499. return false;
  500. }
  501. switch (relative_selector.combinator) {
  502. case CSS::Selector::Combinator::None:
  503. return true;
  504. case CSS::Selector::Combinator::Descendant:
  505. VERIFY(component_list_index != 0);
  506. for (auto* ancestor = element.parent(); ancestor; ancestor = ancestor->parent()) {
  507. if (!is<DOM::Element>(*ancestor))
  508. continue;
  509. if (matches(selector, style_sheet_for_rule, component_list_index - 1, static_cast<DOM::Element const&>(*ancestor), scope))
  510. return true;
  511. }
  512. return false;
  513. case CSS::Selector::Combinator::ImmediateChild:
  514. VERIFY(component_list_index != 0);
  515. if (!element.parent() || !is<DOM::Element>(*element.parent()))
  516. return false;
  517. return matches(selector, style_sheet_for_rule, component_list_index - 1, static_cast<DOM::Element const&>(*element.parent()), scope);
  518. case CSS::Selector::Combinator::NextSibling:
  519. VERIFY(component_list_index != 0);
  520. if (auto* sibling = element.previous_element_sibling())
  521. return matches(selector, style_sheet_for_rule, component_list_index - 1, *sibling, scope);
  522. return false;
  523. case CSS::Selector::Combinator::SubsequentSibling:
  524. VERIFY(component_list_index != 0);
  525. for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  526. if (matches(selector, style_sheet_for_rule, component_list_index - 1, *sibling, scope))
  527. return true;
  528. }
  529. return false;
  530. case CSS::Selector::Combinator::Column:
  531. TODO();
  532. }
  533. VERIFY_NOT_REACHED();
  534. }
  535. bool matches(CSS::Selector const& selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, Optional<CSS::Selector::PseudoElement> pseudo_element, JS::GCPtr<DOM::ParentNode const> scope)
  536. {
  537. VERIFY(!selector.compound_selectors().is_empty());
  538. if (pseudo_element.has_value() && selector.pseudo_element() != pseudo_element)
  539. return false;
  540. if (!pseudo_element.has_value() && selector.pseudo_element().has_value())
  541. return false;
  542. return matches(selector, style_sheet_for_rule, selector.compound_selectors().size() - 1, element, scope);
  543. }
  544. }