SelectorEngine.cpp 31 KB

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