SelectorEngine.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-read-write
  195. static bool matches_read_write_pseudo_class(DOM::Element const& element)
  196. {
  197. // The :read-write pseudo-class must match any element falling into one of the following categories,
  198. // which for the purposes of Selectors are thus considered user-alterable: [SELECTORS]
  199. // - input elements to which the readonly attribute applies, and that are mutable
  200. // (i.e. that do not have the readonly attribute specified and that are not disabled)
  201. if (is<HTML::HTMLInputElement>(element)) {
  202. auto& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  203. if (input_element.has_attribute(HTML::AttributeNames::readonly))
  204. return false;
  205. if (!input_element.enabled())
  206. return false;
  207. return true;
  208. }
  209. // - textarea elements that do not have a readonly attribute, and that are not disabled
  210. if (is<HTML::HTMLTextAreaElement>(element)) {
  211. auto& input_element = static_cast<HTML::HTMLTextAreaElement const&>(element);
  212. if (input_element.has_attribute(HTML::AttributeNames::readonly))
  213. return false;
  214. if (!input_element.enabled())
  215. return false;
  216. return true;
  217. }
  218. // - elements that are editing hosts or editable and are neither input elements nor textarea elements
  219. return element.is_editable();
  220. }
  221. 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)
  222. {
  223. switch (pseudo_class.type) {
  224. case CSS::PseudoClass::Link:
  225. case CSS::PseudoClass::AnyLink:
  226. // NOTE: AnyLink should match whether the link is visited or not, so if we ever start matching
  227. // :visited, we'll need to handle these differently.
  228. return matches_link_pseudo_class(element);
  229. case CSS::PseudoClass::LocalLink: {
  230. // The :local-link pseudo-class allows authors to style hyperlinks based on the users current location
  231. // within a site. It represents an element that is the source anchor of a hyperlink whose target’s
  232. // absolute URL matches the element’s own document URL. If the hyperlink’s target includes a fragment
  233. // URL, then the fragment URL of the current URL must also match; if it does not, then the fragment
  234. // URL portion of the current URL is not taken into account in the comparison.
  235. if (!matches_link_pseudo_class(element))
  236. return false;
  237. auto document_url = element.document().url();
  238. AK::URL target_url = element.document().parse_url(element.attribute(HTML::AttributeNames::href));
  239. if (target_url.fragment().has_value())
  240. return document_url.equals(target_url, AK::URL::ExcludeFragment::No);
  241. return document_url.equals(target_url, AK::URL::ExcludeFragment::Yes);
  242. }
  243. case CSS::PseudoClass::Visited:
  244. // FIXME: Maybe match this selector sometimes?
  245. return false;
  246. case CSS::PseudoClass::Active:
  247. return element.is_active();
  248. case CSS::PseudoClass::Hover:
  249. return matches_hover_pseudo_class(element);
  250. case CSS::PseudoClass::Focus:
  251. return element.is_focused();
  252. case CSS::PseudoClass::FocusVisible:
  253. // FIXME: We should only apply this when a visible focus is useful. Decide when that is!
  254. return element.is_focused();
  255. case CSS::PseudoClass::FocusWithin: {
  256. auto* focused_element = element.document().focused_element();
  257. return focused_element && element.is_inclusive_ancestor_of(*focused_element);
  258. }
  259. case CSS::PseudoClass::FirstChild:
  260. return !element.previous_element_sibling();
  261. case CSS::PseudoClass::LastChild:
  262. return !element.next_element_sibling();
  263. case CSS::PseudoClass::OnlyChild:
  264. return !(element.previous_element_sibling() || element.next_element_sibling());
  265. case CSS::PseudoClass::Empty: {
  266. if (!element.has_children())
  267. return true;
  268. if (element.first_child_of_type<DOM::Element>())
  269. return false;
  270. // NOTE: CSS Selectors level 4 changed ":empty" to also match whitespace-only text nodes.
  271. // However, none of the major browser supports this yet, so let's just hang back until they do.
  272. bool has_nonempty_text_child = false;
  273. element.for_each_child_of_type<DOM::Text>([&](auto const& text_child) {
  274. if (!text_child.data().is_empty()) {
  275. has_nonempty_text_child = true;
  276. return IterationDecision::Break;
  277. }
  278. return IterationDecision::Continue;
  279. });
  280. return !has_nonempty_text_child;
  281. }
  282. case CSS::PseudoClass::Root:
  283. return is<HTML::HTMLHtmlElement>(element);
  284. case CSS::PseudoClass::Host:
  285. // FIXME: Implement :host selector.
  286. return false;
  287. case CSS::PseudoClass::Scope:
  288. return scope ? &element == scope : is<HTML::HTMLHtmlElement>(element);
  289. case CSS::PseudoClass::FirstOfType:
  290. return !previous_sibling_with_same_tag_name(element);
  291. case CSS::PseudoClass::LastOfType:
  292. return !next_sibling_with_same_tag_name(element);
  293. case CSS::PseudoClass::OnlyOfType:
  294. return !previous_sibling_with_same_tag_name(element) && !next_sibling_with_same_tag_name(element);
  295. case CSS::PseudoClass::Lang:
  296. return matches_lang_pseudo_class(element, pseudo_class.languages);
  297. case CSS::PseudoClass::Disabled:
  298. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-disabled
  299. // The :disabled pseudo-class must match any element that is actually disabled.
  300. return element.is_actually_disabled();
  301. case CSS::PseudoClass::Enabled:
  302. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-enabled
  303. // 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.
  304. 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))
  305. && !element.is_actually_disabled();
  306. case CSS::PseudoClass::Checked:
  307. return matches_checked_pseudo_class(element);
  308. case CSS::PseudoClass::Indeterminate:
  309. return matches_indeterminate_pseudo_class(element);
  310. case CSS::PseudoClass::Defined:
  311. return element.is_defined();
  312. case CSS::PseudoClass::Is:
  313. case CSS::PseudoClass::Where:
  314. for (auto& selector : pseudo_class.argument_selector_list) {
  315. if (matches(selector, style_sheet_for_rule, element))
  316. return true;
  317. }
  318. return false;
  319. case CSS::PseudoClass::Not:
  320. for (auto& selector : pseudo_class.argument_selector_list) {
  321. if (matches(selector, style_sheet_for_rule, element))
  322. return false;
  323. }
  324. return true;
  325. case CSS::PseudoClass::NthChild:
  326. case CSS::PseudoClass::NthLastChild:
  327. case CSS::PseudoClass::NthOfType:
  328. case CSS::PseudoClass::NthLastOfType: {
  329. auto const step_size = pseudo_class.nth_child_pattern.step_size;
  330. auto const offset = pseudo_class.nth_child_pattern.offset;
  331. if (step_size == 0 && offset == 0)
  332. return false; // "If both a and b are equal to zero, the pseudo-class represents no element in the document tree."
  333. auto const* parent = element.parent_element();
  334. if (!parent)
  335. return false;
  336. auto matches_selector_list = [&style_sheet_for_rule](CSS::SelectorList const& list, DOM::Element const& element) {
  337. if (list.is_empty())
  338. return true;
  339. for (auto const& child_selector : list) {
  340. if (matches(child_selector, style_sheet_for_rule, element)) {
  341. return true;
  342. }
  343. }
  344. return false;
  345. };
  346. int index = 1;
  347. switch (pseudo_class.type) {
  348. case CSS::PseudoClass::NthChild: {
  349. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  350. return false;
  351. for (auto* child = parent->first_child_of_type<DOM::Element>(); child && child != &element; child = child->next_element_sibling()) {
  352. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  353. ++index;
  354. }
  355. break;
  356. }
  357. case CSS::PseudoClass::NthLastChild: {
  358. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  359. return false;
  360. for (auto* child = parent->last_child_of_type<DOM::Element>(); child && child != &element; child = child->previous_element_sibling()) {
  361. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  362. ++index;
  363. }
  364. break;
  365. }
  366. case CSS::PseudoClass::NthOfType: {
  367. for (auto* child = previous_sibling_with_same_tag_name(element); child; child = previous_sibling_with_same_tag_name(*child))
  368. ++index;
  369. break;
  370. }
  371. case CSS::PseudoClass::NthLastOfType: {
  372. for (auto* child = next_sibling_with_same_tag_name(element); child; child = next_sibling_with_same_tag_name(*child))
  373. ++index;
  374. break;
  375. }
  376. default:
  377. VERIFY_NOT_REACHED();
  378. }
  379. // When "step_size == -1", selector represents first "offset" elements in document tree.
  380. if (step_size == -1)
  381. return !(offset <= 0 || index > offset);
  382. // When "step_size == 1", selector represents last "offset" elements in document tree.
  383. if (step_size == 1)
  384. return !(offset < 0 || index < offset);
  385. // When "step_size == 0", selector picks only the "offset" element.
  386. if (step_size == 0)
  387. return index == offset;
  388. // If both are negative, nothing can match.
  389. if (step_size < 0 && offset < 0)
  390. return false;
  391. // Like "a % b", but handles negative integers correctly.
  392. auto const canonical_modulo = [](int a, int b) -> int {
  393. int c = a % b;
  394. if ((c < 0 && b > 0) || (c > 0 && b < 0)) {
  395. c += b;
  396. }
  397. return c;
  398. };
  399. // When "step_size < 0", we start at "offset" and count backwards.
  400. if (step_size < 0)
  401. return index <= offset && canonical_modulo(index - offset, -step_size) == 0;
  402. // Otherwise, we start at "offset" and count forwards.
  403. return index >= offset && canonical_modulo(index - offset, step_size) == 0;
  404. }
  405. case CSS::PseudoClass::Playing: {
  406. if (!is<HTML::HTMLMediaElement>(element))
  407. return false;
  408. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  409. return !media_element.paused();
  410. }
  411. case CSS::PseudoClass::Paused: {
  412. if (!is<HTML::HTMLMediaElement>(element))
  413. return false;
  414. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  415. return media_element.paused();
  416. }
  417. case CSS::PseudoClass::Seeking: {
  418. if (!is<HTML::HTMLMediaElement>(element))
  419. return false;
  420. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  421. return media_element.seeking();
  422. }
  423. case CSS::PseudoClass::Muted: {
  424. if (!is<HTML::HTMLMediaElement>(element))
  425. return false;
  426. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  427. return media_element.muted();
  428. }
  429. case CSS::PseudoClass::VolumeLocked: {
  430. // FIXME: Currently we don't allow the user to specify an override volume, so this is always false.
  431. // Once we do, implement this!
  432. return false;
  433. }
  434. case CSS::PseudoClass::Buffering: {
  435. if (!is<HTML::HTMLMediaElement>(element))
  436. return false;
  437. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  438. return media_element.blocked();
  439. }
  440. case CSS::PseudoClass::Stalled: {
  441. if (!is<HTML::HTMLMediaElement>(element))
  442. return false;
  443. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  444. return media_element.stalled();
  445. }
  446. case CSS::PseudoClass::Target:
  447. return element.is_target();
  448. case CSS::PseudoClass::TargetWithin: {
  449. auto* target_element = element.document().target_element();
  450. if (!target_element)
  451. return false;
  452. return element.is_inclusive_ancestor_of(*target_element);
  453. }
  454. case CSS::PseudoClass::Dir: {
  455. // "Values other than ltr and rtl are not invalid, but do not match anything."
  456. // - https://www.w3.org/TR/selectors-4/#the-dir-pseudo
  457. if (!first_is_one_of(pseudo_class.identifier, CSS::ValueID::Ltr, CSS::ValueID::Rtl))
  458. return false;
  459. switch (element.directionality()) {
  460. case DOM::Element::Directionality::Ltr:
  461. return pseudo_class.identifier == CSS::ValueID::Ltr;
  462. case DOM::Element::Directionality::Rtl:
  463. return pseudo_class.identifier == CSS::ValueID::Rtl;
  464. }
  465. VERIFY_NOT_REACHED();
  466. }
  467. case CSS::PseudoClass::ReadOnly:
  468. return !matches_read_write_pseudo_class(element);
  469. case CSS::PseudoClass::ReadWrite:
  470. return matches_read_write_pseudo_class(element);
  471. }
  472. return false;
  473. }
  474. 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)
  475. {
  476. switch (component.type) {
  477. case CSS::Selector::SimpleSelector::Type::Universal:
  478. case CSS::Selector::SimpleSelector::Type::TagName: {
  479. auto qualified_name = component.qualified_name();
  480. // Reject if the tag name doesn't match
  481. if (component.type == CSS::Selector::SimpleSelector::Type::TagName) {
  482. // See https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
  483. if (element.document().document_type() == DOM::Document::Type::HTML) {
  484. if (qualified_name.name.lowercase_name != element.local_name().view())
  485. return false;
  486. } else if (!Infra::is_ascii_case_insensitive_match(qualified_name.name.name, element.local_name())) {
  487. return false;
  488. }
  489. }
  490. // Match the namespace
  491. switch (qualified_name.namespace_type) {
  492. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Default:
  493. // "if no default namespace has been declared for selectors, this is equivalent to *|E."
  494. if (!style_sheet_for_rule.has_value() || !style_sheet_for_rule->default_namespace().has_value())
  495. return true;
  496. // "Otherwise it is equivalent to ns|E where ns is the default namespace."
  497. return element.namespace_() == style_sheet_for_rule->default_namespace();
  498. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::None:
  499. // "elements with name E without a namespace"
  500. return element.namespace_().is_empty();
  501. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Any:
  502. // "elements with name E in any namespace, including those without a namespace"
  503. return true;
  504. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Named:
  505. // "elements with name E in namespace ns"
  506. // Unrecognized namespace prefixes are invalid, so don't match.
  507. // (We can't detect this at parse time, since a namespace rule may be inserted later.)
  508. // So, if we don't have a context to look up namespaces from, we fail to match.
  509. if (!style_sheet_for_rule.has_value())
  510. return false;
  511. auto selector_namespace = style_sheet_for_rule->namespace_uri(qualified_name.namespace_);
  512. return selector_namespace.has_value() && selector_namespace.value() == element.namespace_();
  513. }
  514. VERIFY_NOT_REACHED();
  515. }
  516. case CSS::Selector::SimpleSelector::Type::Id:
  517. return component.name() == element.attribute(HTML::AttributeNames::id).view();
  518. case CSS::Selector::SimpleSelector::Type::Class:
  519. return element.has_class(component.name());
  520. case CSS::Selector::SimpleSelector::Type::Attribute:
  521. return matches_attribute(component.attribute(), style_sheet_for_rule, element);
  522. case CSS::Selector::SimpleSelector::Type::PseudoClass:
  523. return matches_pseudo_class(component.pseudo_class(), style_sheet_for_rule, element, scope);
  524. case CSS::Selector::SimpleSelector::Type::PseudoElement:
  525. // Pseudo-element matching/not-matching is handled in the top level matches().
  526. return true;
  527. default:
  528. VERIFY_NOT_REACHED();
  529. }
  530. }
  531. 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)
  532. {
  533. auto& relative_selector = selector.compound_selectors()[component_list_index];
  534. for (auto& simple_selector : relative_selector.simple_selectors) {
  535. if (!matches(simple_selector, style_sheet_for_rule, element, scope))
  536. return false;
  537. }
  538. switch (relative_selector.combinator) {
  539. case CSS::Selector::Combinator::None:
  540. return true;
  541. case CSS::Selector::Combinator::Descendant:
  542. VERIFY(component_list_index != 0);
  543. for (auto* ancestor = element.parent(); ancestor; ancestor = ancestor->parent()) {
  544. if (!is<DOM::Element>(*ancestor))
  545. continue;
  546. if (matches(selector, style_sheet_for_rule, component_list_index - 1, static_cast<DOM::Element const&>(*ancestor), scope))
  547. return true;
  548. }
  549. return false;
  550. case CSS::Selector::Combinator::ImmediateChild:
  551. VERIFY(component_list_index != 0);
  552. if (!element.parent() || !is<DOM::Element>(*element.parent()))
  553. return false;
  554. return matches(selector, style_sheet_for_rule, component_list_index - 1, static_cast<DOM::Element const&>(*element.parent()), scope);
  555. case CSS::Selector::Combinator::NextSibling:
  556. VERIFY(component_list_index != 0);
  557. if (auto* sibling = element.previous_element_sibling())
  558. return matches(selector, style_sheet_for_rule, component_list_index - 1, *sibling, scope);
  559. return false;
  560. case CSS::Selector::Combinator::SubsequentSibling:
  561. VERIFY(component_list_index != 0);
  562. for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  563. if (matches(selector, style_sheet_for_rule, component_list_index - 1, *sibling, scope))
  564. return true;
  565. }
  566. return false;
  567. case CSS::Selector::Combinator::Column:
  568. TODO();
  569. }
  570. VERIFY_NOT_REACHED();
  571. }
  572. 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)
  573. {
  574. VERIFY(!selector.compound_selectors().is_empty());
  575. if (pseudo_element.has_value() && selector.pseudo_element() != pseudo_element)
  576. return false;
  577. if (!pseudo_element.has_value() && selector.pseudo_element().has_value())
  578. return false;
  579. return matches(selector, style_sheet_for_rule, selector.compound_selectors().size() - 1, element, scope);
  580. }
  581. }