SelectorEngine.cpp 31 KB

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