SelectorEngine.cpp 30 KB

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