SelectorEngine.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. /*
  2. * Copyright (c) 2018-2024, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2024, Sam Atkins <sam@ladybird.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/CSS/Keyword.h>
  8. #include <LibWeb/CSS/Parser/Parser.h>
  9. #include <LibWeb/CSS/SelectorEngine.h>
  10. #include <LibWeb/CSS/StyleProperties.h>
  11. #include <LibWeb/DOM/Attr.h>
  12. #include <LibWeb/DOM/Document.h>
  13. #include <LibWeb/DOM/Element.h>
  14. #include <LibWeb/DOM/NamedNodeMap.h>
  15. #include <LibWeb/DOM/Text.h>
  16. #include <LibWeb/HTML/AttributeNames.h>
  17. #include <LibWeb/HTML/HTMLAnchorElement.h>
  18. #include <LibWeb/HTML/HTMLAreaElement.h>
  19. #include <LibWeb/HTML/HTMLButtonElement.h>
  20. #include <LibWeb/HTML/HTMLDetailsElement.h>
  21. #include <LibWeb/HTML/HTMLDialogElement.h>
  22. #include <LibWeb/HTML/HTMLFieldSetElement.h>
  23. #include <LibWeb/HTML/HTMLHtmlElement.h>
  24. #include <LibWeb/HTML/HTMLInputElement.h>
  25. #include <LibWeb/HTML/HTMLMediaElement.h>
  26. #include <LibWeb/HTML/HTMLOptGroupElement.h>
  27. #include <LibWeb/HTML/HTMLOptionElement.h>
  28. #include <LibWeb/HTML/HTMLProgressElement.h>
  29. #include <LibWeb/HTML/HTMLSelectElement.h>
  30. #include <LibWeb/HTML/HTMLTextAreaElement.h>
  31. #include <LibWeb/Infra/Strings.h>
  32. #include <LibWeb/Namespace.h>
  33. #include <LibWeb/SVG/SVGAElement.h>
  34. namespace Web::SelectorEngine {
  35. static inline bool matches(CSS::Selector const& selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, int component_list_index, DOM::Element const& element, GC::Ptr<DOM::Element const> shadow_host, GC::Ptr<DOM::ParentNode const> scope, SelectorKind selector_kind, GC::Ptr<DOM::Element const> anchor = nullptr);
  36. // Upward traversal for descendant (' ') and immediate child combinator ('>')
  37. // If we're starting inside a shadow tree, traversal stops at the nearest shadow host.
  38. // This is an implementation detail of the :host selector. Otherwise we would just traverse up to the document root.
  39. static inline GC::Ptr<DOM::Node const> traverse_up(GC::Ptr<DOM::Node const> node, GC::Ptr<DOM::Element const> shadow_host)
  40. {
  41. if (!node)
  42. return nullptr;
  43. if (shadow_host) {
  44. // NOTE: We only traverse up to the shadow host, not beyond.
  45. if (node == shadow_host)
  46. return nullptr;
  47. return node->parent_or_shadow_host_element();
  48. }
  49. return node->parent();
  50. }
  51. // https://drafts.csswg.org/selectors-4/#the-lang-pseudo
  52. static inline bool matches_lang_pseudo_class(DOM::Element const& element, Vector<FlyString> const& languages)
  53. {
  54. auto maybe_element_language = element.lang();
  55. if (!maybe_element_language.has_value())
  56. return false;
  57. auto element_language = maybe_element_language.release_value();
  58. // FIXME: This is ad-hoc. Implement a proper language range matching algorithm as recommended by BCP47.
  59. for (auto const& language : languages) {
  60. if (language.is_empty())
  61. continue;
  62. if (language == "*"sv)
  63. return true;
  64. if (!element_language.contains('-') && Infra::is_ascii_case_insensitive_match(element_language, language))
  65. return true;
  66. auto parts = element_language.split_limit('-', 2).release_value_but_fixme_should_propagate_errors();
  67. if (!parts.is_empty() && Infra::is_ascii_case_insensitive_match(parts[0], language))
  68. return true;
  69. }
  70. return false;
  71. }
  72. // https://drafts.csswg.org/selectors-4/#relational
  73. static inline bool matches_relative_selector(CSS::Selector const& selector, size_t compound_index, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, GC::Ptr<DOM::Element const> shadow_host, GC::Ref<DOM::Element const> anchor)
  74. {
  75. if (compound_index >= selector.compound_selectors().size())
  76. return matches(selector, style_sheet_for_rule, element, shadow_host, {}, {}, SelectorKind::Relative, anchor);
  77. switch (selector.compound_selectors()[compound_index].combinator) {
  78. // Shouldn't be possible because we've parsed relative selectors, which always have a combinator, implicitly or explicitly.
  79. case CSS::Selector::Combinator::None:
  80. VERIFY_NOT_REACHED();
  81. case CSS::Selector::Combinator::Descendant: {
  82. bool has = false;
  83. element.for_each_in_subtree([&](auto const& descendant) {
  84. if (!descendant.is_element())
  85. return TraversalDecision::Continue;
  86. auto const& descendant_element = static_cast<DOM::Element const&>(descendant);
  87. if (matches(selector, style_sheet_for_rule, descendant_element, shadow_host, {}, {}, SelectorKind::Relative, anchor)) {
  88. has = true;
  89. return TraversalDecision::Break;
  90. }
  91. return TraversalDecision::Continue;
  92. });
  93. return has;
  94. }
  95. case CSS::Selector::Combinator::ImmediateChild: {
  96. bool has = false;
  97. element.for_each_child([&](DOM::Node const& child) {
  98. if (!child.is_element())
  99. return IterationDecision::Continue;
  100. auto const& child_element = static_cast<DOM::Element const&>(child);
  101. if (!matches(selector, style_sheet_for_rule, compound_index, child_element, shadow_host, {}, SelectorKind::Relative, anchor))
  102. return IterationDecision::Continue;
  103. if (matches_relative_selector(selector, compound_index + 1, style_sheet_for_rule, child_element, shadow_host, anchor)) {
  104. has = true;
  105. return IterationDecision::Break;
  106. }
  107. return IterationDecision::Continue;
  108. });
  109. return has;
  110. }
  111. case CSS::Selector::Combinator::NextSibling: {
  112. auto* sibling = element.next_element_sibling();
  113. if (!sibling)
  114. return false;
  115. if (!matches(selector, style_sheet_for_rule, compound_index, *sibling, shadow_host, {}, SelectorKind::Relative, anchor))
  116. return false;
  117. return matches_relative_selector(selector, compound_index + 1, style_sheet_for_rule, *sibling, shadow_host, anchor);
  118. }
  119. case CSS::Selector::Combinator::SubsequentSibling: {
  120. for (auto const* sibling = element.next_element_sibling(); sibling; sibling = sibling->next_element_sibling()) {
  121. if (!matches(selector, style_sheet_for_rule, compound_index, *sibling, shadow_host, {}, SelectorKind::Relative, anchor))
  122. continue;
  123. if (matches_relative_selector(selector, compound_index + 1, style_sheet_for_rule, *sibling, shadow_host, anchor))
  124. return true;
  125. }
  126. return false;
  127. }
  128. case CSS::Selector::Combinator::Column:
  129. TODO();
  130. }
  131. return false;
  132. }
  133. // https://drafts.csswg.org/selectors-4/#relational
  134. static inline bool matches_has_pseudo_class(CSS::Selector const& selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& anchor, GC::Ptr<DOM::Element const> shadow_host)
  135. {
  136. return matches_relative_selector(selector, 0, style_sheet_for_rule, anchor, shadow_host, anchor);
  137. }
  138. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-link
  139. static inline bool matches_link_pseudo_class(DOM::Element const& element)
  140. {
  141. // All a elements that have an href attribute, and all area elements that have an href attribute, must match one of :link and :visited.
  142. if (!is<HTML::HTMLAnchorElement>(element) && !is<HTML::HTMLAreaElement>(element) && !is<SVG::SVGAElement>(element))
  143. return false;
  144. return element.has_attribute(HTML::AttributeNames::href);
  145. }
  146. bool matches_hover_pseudo_class(DOM::Element const& element)
  147. {
  148. auto* hovered_node = element.document().hovered_node();
  149. if (!hovered_node)
  150. return false;
  151. if (&element == hovered_node)
  152. return true;
  153. return element.is_shadow_including_ancestor_of(*hovered_node);
  154. }
  155. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-checked
  156. static inline bool matches_checked_pseudo_class(DOM::Element const& element)
  157. {
  158. // The :checked pseudo-class must match any element falling into one of the following categories:
  159. // - input elements whose type attribute is in the Checkbox state and whose checkedness state is true
  160. // - input elements whose type attribute is in the Radio Button state and whose checkedness state is true
  161. if (is<HTML::HTMLInputElement>(element)) {
  162. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  163. switch (input_element.type_state()) {
  164. case HTML::HTMLInputElement::TypeAttributeState::Checkbox:
  165. case HTML::HTMLInputElement::TypeAttributeState::RadioButton:
  166. return static_cast<HTML::HTMLInputElement const&>(element).checked();
  167. default:
  168. return false;
  169. }
  170. }
  171. // - option elements whose selectedness is true
  172. if (is<HTML::HTMLOptionElement>(element)) {
  173. return static_cast<HTML::HTMLOptionElement const&>(element).selected();
  174. }
  175. return false;
  176. }
  177. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-indeterminate
  178. static inline bool matches_indeterminate_pseudo_class(DOM::Element const& element)
  179. {
  180. // The :indeterminate pseudo-class must match any element falling into one of the following categories:
  181. // - input elements whose type attribute is in the Checkbox state and whose indeterminate IDL attribute is set to true
  182. // 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.
  183. if (is<HTML::HTMLInputElement>(element)) {
  184. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  185. switch (input_element.type_state()) {
  186. case HTML::HTMLInputElement::TypeAttributeState::Checkbox:
  187. return input_element.indeterminate();
  188. default:
  189. return false;
  190. }
  191. }
  192. // - progress elements with no value content attribute
  193. if (is<HTML::HTMLProgressElement>(element)) {
  194. return !element.has_attribute(HTML::AttributeNames::value);
  195. }
  196. return false;
  197. }
  198. static inline Web::DOM::Attr const* get_optionally_namespaced_attribute(CSS::Selector::SimpleSelector::Attribute const& attribute, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element)
  199. {
  200. auto const& qualified_name = attribute.qualified_name;
  201. auto const& attribute_name = qualified_name.name.name;
  202. auto const& namespace_type = qualified_name.namespace_type;
  203. if (element.namespace_uri() == Namespace::HTML) {
  204. if (namespace_type == CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Named) {
  205. return nullptr;
  206. }
  207. return element.attributes()->get_attribute(attribute_name);
  208. }
  209. switch (namespace_type) {
  210. // "In keeping with the Namespaces in the XML recommendation, default namespaces do not apply to attributes,
  211. // therefore attribute selectors without a namespace component apply only to attributes that have no namespace (equivalent to "|attr")"
  212. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Default:
  213. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::None:
  214. return element.attributes()->get_attribute(attribute_name);
  215. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Any:
  216. return element.attributes()->get_attribute_namespace_agnostic(attribute_name);
  217. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Named:
  218. if (!style_sheet_for_rule.has_value())
  219. return nullptr;
  220. auto const& selector_namespace = style_sheet_for_rule->namespace_uri(qualified_name.namespace_);
  221. if (!selector_namespace.has_value())
  222. return nullptr;
  223. return element.attributes()->get_attribute_ns(selector_namespace, attribute_name);
  224. }
  225. VERIFY_NOT_REACHED();
  226. }
  227. 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)
  228. {
  229. auto const& attribute_name = attribute.qualified_name.name.name;
  230. auto const* attr = get_optionally_namespaced_attribute(attribute, style_sheet_for_rule, element);
  231. if (attribute.match_type == CSS::Selector::SimpleSelector::Attribute::MatchType::HasAttribute) {
  232. // Early way out in case of an attribute existence selector.
  233. return attr != nullptr;
  234. }
  235. if (!attr)
  236. return false;
  237. auto case_sensitivity = [&](CSS::Selector::SimpleSelector::Attribute::CaseType case_type) {
  238. switch (case_type) {
  239. case CSS::Selector::SimpleSelector::Attribute::CaseType::CaseInsensitiveMatch:
  240. return CaseSensitivity::CaseInsensitive;
  241. case CSS::Selector::SimpleSelector::Attribute::CaseType::CaseSensitiveMatch:
  242. return CaseSensitivity::CaseSensitive;
  243. case CSS::Selector::SimpleSelector::Attribute::CaseType::DefaultMatch:
  244. // See: https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
  245. if (element.document().is_html_document()
  246. && element.namespace_uri() == Namespace::HTML
  247. && attribute_name.is_one_of(
  248. HTML::AttributeNames::accept, HTML::AttributeNames::accept_charset, HTML::AttributeNames::align,
  249. HTML::AttributeNames::alink, HTML::AttributeNames::axis, HTML::AttributeNames::bgcolor, HTML::AttributeNames::charset,
  250. HTML::AttributeNames::checked, HTML::AttributeNames::clear, HTML::AttributeNames::codetype, HTML::AttributeNames::color,
  251. HTML::AttributeNames::compact, HTML::AttributeNames::declare, HTML::AttributeNames::defer, HTML::AttributeNames::dir,
  252. HTML::AttributeNames::direction, HTML::AttributeNames::disabled, HTML::AttributeNames::enctype, HTML::AttributeNames::face,
  253. HTML::AttributeNames::frame, HTML::AttributeNames::hreflang, HTML::AttributeNames::http_equiv, HTML::AttributeNames::lang,
  254. HTML::AttributeNames::language, HTML::AttributeNames::link, HTML::AttributeNames::media, HTML::AttributeNames::method,
  255. HTML::AttributeNames::multiple, HTML::AttributeNames::nohref, HTML::AttributeNames::noresize, HTML::AttributeNames::noshade,
  256. HTML::AttributeNames::nowrap, HTML::AttributeNames::readonly, HTML::AttributeNames::rel, HTML::AttributeNames::rev,
  257. HTML::AttributeNames::rules, HTML::AttributeNames::scope, HTML::AttributeNames::scrolling, HTML::AttributeNames::selected,
  258. HTML::AttributeNames::shape, HTML::AttributeNames::target, HTML::AttributeNames::text, HTML::AttributeNames::type,
  259. HTML::AttributeNames::valign, HTML::AttributeNames::valuetype, HTML::AttributeNames::vlink)) {
  260. return CaseSensitivity::CaseInsensitive;
  261. }
  262. return CaseSensitivity::CaseSensitive;
  263. }
  264. VERIFY_NOT_REACHED();
  265. }(attribute.case_type);
  266. auto case_insensitive_match = case_sensitivity == CaseSensitivity::CaseInsensitive;
  267. switch (attribute.match_type) {
  268. case CSS::Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch:
  269. return case_insensitive_match
  270. ? Infra::is_ascii_case_insensitive_match(attr->value(), attribute.value)
  271. : attr->value() == attribute.value;
  272. case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsWord: {
  273. if (attribute.value.is_empty()) {
  274. // This selector is always false is match value is empty.
  275. return false;
  276. }
  277. auto const& attribute_value = attr->value();
  278. auto const view = attribute_value.bytes_as_string_view().split_view(' ');
  279. auto const size = view.size();
  280. for (size_t i = 0; i < size; ++i) {
  281. auto const value = view.at(i);
  282. if (case_insensitive_match
  283. ? Infra::is_ascii_case_insensitive_match(value, attribute.value)
  284. : value == attribute.value) {
  285. return true;
  286. }
  287. }
  288. return false;
  289. }
  290. case CSS::Selector::SimpleSelector::Attribute::MatchType::ContainsString:
  291. return !attribute.value.is_empty()
  292. && attr->value().contains(attribute.value, case_sensitivity);
  293. case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment: {
  294. auto const& element_attr_value = attr->value();
  295. if (element_attr_value.is_empty()) {
  296. // If the attribute value on element is empty, the selector is true
  297. // if the match value is also empty and false otherwise.
  298. return attribute.value.is_empty();
  299. }
  300. if (attribute.value.is_empty()) {
  301. return false;
  302. }
  303. auto segments = element_attr_value.bytes_as_string_view().split_view('-');
  304. return case_insensitive_match
  305. ? Infra::is_ascii_case_insensitive_match(segments.first(), attribute.value)
  306. : segments.first() == attribute.value;
  307. }
  308. case CSS::Selector::SimpleSelector::Attribute::MatchType::StartsWithString:
  309. return !attribute.value.is_empty()
  310. && attr->value().bytes_as_string_view().starts_with(attribute.value, case_sensitivity);
  311. case CSS::Selector::SimpleSelector::Attribute::MatchType::EndsWithString:
  312. return !attribute.value.is_empty()
  313. && attr->value().bytes_as_string_view().ends_with(attribute.value, case_sensitivity);
  314. default:
  315. break;
  316. }
  317. return false;
  318. }
  319. static inline DOM::Element const* previous_sibling_with_same_tag_name(DOM::Element const& element)
  320. {
  321. for (auto const* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  322. if (sibling->tag_name() == element.tag_name())
  323. return sibling;
  324. }
  325. return nullptr;
  326. }
  327. static inline DOM::Element const* next_sibling_with_same_tag_name(DOM::Element const& element)
  328. {
  329. for (auto const* sibling = element.next_element_sibling(); sibling; sibling = sibling->next_element_sibling()) {
  330. if (sibling->tag_name() == element.tag_name())
  331. return sibling;
  332. }
  333. return nullptr;
  334. }
  335. /// Returns true if this selector should be blocked from matching against the shadow host from within a shadow tree.
  336. /// Only :host pseudo-class is allowed to match the shadow host from within shadow tree, all other selectors (including other pseudo-classes) are blocked.
  337. /// Compound selectors (:has(), :is(), :where()), nesting, and pseudo-elements are allowed as they may contain or be contained within :host.
  338. static inline bool should_block_shadow_host_matching(CSS::Selector::SimpleSelector const& component, GC::Ptr<DOM::Element const> shadow_host, DOM::Element const& element)
  339. {
  340. if (!shadow_host || &element != shadow_host.ptr())
  341. return false;
  342. // From within shadow tree, only :host pseudo-class can match the host element
  343. if (component.type == CSS::Selector::SimpleSelector::Type::PseudoClass) {
  344. auto const& pseudo_class = component.pseudo_class();
  345. return pseudo_class.type != CSS::PseudoClass::Host
  346. && pseudo_class.type != CSS::PseudoClass::Has
  347. && pseudo_class.type != CSS::PseudoClass::Is
  348. && pseudo_class.type != CSS::PseudoClass::Where;
  349. }
  350. // Allow nesting and PseudoElement as it may contain :host class
  351. if (component.type == CSS::Selector::SimpleSelector::Type::Nesting || component.type == CSS::Selector::SimpleSelector::Type::PseudoElement)
  352. return false;
  353. return true;
  354. }
  355. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-read-write
  356. static bool matches_read_write_pseudo_class(DOM::Element const& element)
  357. {
  358. // The :read-write pseudo-class must match any element falling into one of the following categories,
  359. // which for the purposes of Selectors are thus considered user-alterable: [SELECTORS]
  360. // - input elements to which the readonly attribute applies, and that are mutable
  361. // (i.e. that do not have the readonly attribute specified and that are not disabled)
  362. if (is<HTML::HTMLInputElement>(element)) {
  363. auto& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  364. if (input_element.has_attribute(HTML::AttributeNames::readonly))
  365. return false;
  366. if (!input_element.enabled())
  367. return false;
  368. return true;
  369. }
  370. // - textarea elements that do not have a readonly attribute, and that are not disabled
  371. if (is<HTML::HTMLTextAreaElement>(element)) {
  372. auto& input_element = static_cast<HTML::HTMLTextAreaElement const&>(element);
  373. if (input_element.has_attribute(HTML::AttributeNames::readonly))
  374. return false;
  375. if (!input_element.enabled())
  376. return false;
  377. return true;
  378. }
  379. // - elements that are editing hosts or editable and are neither input elements nor textarea elements
  380. return element.is_editable_or_editing_host();
  381. }
  382. // https://www.w3.org/TR/selectors-4/#open-state
  383. static bool matches_open_state_pseudo_class(DOM::Element const& element, bool open)
  384. {
  385. // The :open pseudo-class represents an element that has both “open” and “closed” states,
  386. // and which is currently in the “open” state.
  387. // The :closed pseudo-class represents an element that has both “open” and “closed” states,
  388. // and which is currently in the closed state.
  389. // NOTE: Spec specifically suggests supporting <details>, <dialog>, and <select>.
  390. // There may be others we want to treat as open or closed.
  391. if (is<HTML::HTMLDetailsElement>(element) || is<HTML::HTMLDialogElement>(element))
  392. return open == element.has_attribute(HTML::AttributeNames::open);
  393. if (is<HTML::HTMLSelectElement>(element))
  394. return open == static_cast<HTML::HTMLSelectElement const&>(element).is_open();
  395. return false;
  396. }
  397. // https://drafts.csswg.org/css-scoping/#host-selector
  398. static inline bool matches_host_pseudo_class(GC::Ref<DOM::Element const> element, GC::Ptr<DOM::Element const> shadow_host, CSS::SelectorList const& argument_selector_list, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule)
  399. {
  400. // When evaluated in the context of a shadow tree, it matches the shadow tree’s shadow host if the shadow host,
  401. // in its normal context, matches the selector argument. In any other context, it matches nothing.
  402. if (!shadow_host || element != shadow_host)
  403. return false;
  404. // NOTE: There's either 0 or 1 argument selector, since the syntax is :host or :host(<compound-selector>)
  405. if (!argument_selector_list.is_empty())
  406. return matches(argument_selector_list.first(), style_sheet_for_rule, element, nullptr);
  407. return true;
  408. }
  409. 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, GC::Ptr<DOM::Element const> shadow_host, GC::Ptr<DOM::ParentNode const> scope, SelectorKind selector_kind)
  410. {
  411. switch (pseudo_class.type) {
  412. case CSS::PseudoClass::Link:
  413. case CSS::PseudoClass::AnyLink:
  414. // NOTE: AnyLink should match whether the link is visited or not, so if we ever start matching
  415. // :visited, we'll need to handle these differently.
  416. return matches_link_pseudo_class(element);
  417. case CSS::PseudoClass::LocalLink: {
  418. // The :local-link pseudo-class allows authors to style hyperlinks based on the users current location
  419. // within a site. It represents an element that is the source anchor of a hyperlink whose target’s
  420. // absolute URL matches the element’s own document URL. If the hyperlink’s target includes a fragment
  421. // URL, then the fragment URL of the current URL must also match; if it does not, then the fragment
  422. // URL portion of the current URL is not taken into account in the comparison.
  423. if (!matches_link_pseudo_class(element))
  424. return false;
  425. auto document_url = element.document().url();
  426. URL::URL target_url = element.document().encoding_parse_url(element.attribute(HTML::AttributeNames::href).value_or({}));
  427. if (target_url.fragment().has_value())
  428. return document_url.equals(target_url, URL::ExcludeFragment::No);
  429. return document_url.equals(target_url, URL::ExcludeFragment::Yes);
  430. }
  431. case CSS::PseudoClass::Visited:
  432. // FIXME: Maybe match this selector sometimes?
  433. return false;
  434. case CSS::PseudoClass::Active:
  435. return element.is_active();
  436. case CSS::PseudoClass::Hover:
  437. return matches_hover_pseudo_class(element);
  438. case CSS::PseudoClass::Focus:
  439. return element.is_focused();
  440. case CSS::PseudoClass::FocusVisible:
  441. // FIXME: We should only apply this when a visible focus is useful. Decide when that is!
  442. return element.is_focused();
  443. case CSS::PseudoClass::FocusWithin: {
  444. auto* focused_element = element.document().focused_element();
  445. return focused_element && element.is_inclusive_ancestor_of(*focused_element);
  446. }
  447. case CSS::PseudoClass::FirstChild:
  448. return !element.previous_element_sibling();
  449. case CSS::PseudoClass::LastChild:
  450. return !element.next_element_sibling();
  451. case CSS::PseudoClass::OnlyChild:
  452. return !(element.previous_element_sibling() || element.next_element_sibling());
  453. case CSS::PseudoClass::Empty: {
  454. if (!element.has_children())
  455. return true;
  456. if (element.first_child_of_type<DOM::Element>())
  457. return false;
  458. // NOTE: CSS Selectors level 4 changed ":empty" to also match whitespace-only text nodes.
  459. // However, none of the major browser supports this yet, so let's just hang back until they do.
  460. bool has_nonempty_text_child = false;
  461. element.for_each_child_of_type<DOM::Text>([&](auto const& text_child) {
  462. if (!text_child.data().is_empty()) {
  463. has_nonempty_text_child = true;
  464. return IterationDecision::Break;
  465. }
  466. return IterationDecision::Continue;
  467. });
  468. return !has_nonempty_text_child;
  469. }
  470. case CSS::PseudoClass::Root:
  471. return is<HTML::HTMLHtmlElement>(element);
  472. case CSS::PseudoClass::Host:
  473. return matches_host_pseudo_class(element, shadow_host, pseudo_class.argument_selector_list, style_sheet_for_rule);
  474. case CSS::PseudoClass::Scope:
  475. return scope ? &element == scope : is<HTML::HTMLHtmlElement>(element);
  476. case CSS::PseudoClass::FirstOfType:
  477. return !previous_sibling_with_same_tag_name(element);
  478. case CSS::PseudoClass::LastOfType:
  479. return !next_sibling_with_same_tag_name(element);
  480. case CSS::PseudoClass::OnlyOfType:
  481. return !previous_sibling_with_same_tag_name(element) && !next_sibling_with_same_tag_name(element);
  482. case CSS::PseudoClass::Lang:
  483. return matches_lang_pseudo_class(element, pseudo_class.languages);
  484. case CSS::PseudoClass::Disabled:
  485. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-disabled
  486. // The :disabled pseudo-class must match any element that is actually disabled.
  487. return element.is_actually_disabled();
  488. case CSS::PseudoClass::Enabled:
  489. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-enabled
  490. // 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.
  491. 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))
  492. && !element.is_actually_disabled();
  493. case CSS::PseudoClass::Checked:
  494. return matches_checked_pseudo_class(element);
  495. case CSS::PseudoClass::Indeterminate:
  496. return matches_indeterminate_pseudo_class(element);
  497. case CSS::PseudoClass::Defined:
  498. return element.is_defined();
  499. case CSS::PseudoClass::Has:
  500. // :has() cannot be nested in a :has()
  501. if (selector_kind == SelectorKind::Relative)
  502. return false;
  503. // These selectors should be relative selectors (https://drafts.csswg.org/selectors-4/#relative-selector)
  504. for (auto& selector : pseudo_class.argument_selector_list) {
  505. if (matches_has_pseudo_class(selector, style_sheet_for_rule, element, shadow_host))
  506. return true;
  507. }
  508. return false;
  509. case CSS::PseudoClass::Is:
  510. case CSS::PseudoClass::Where:
  511. for (auto& selector : pseudo_class.argument_selector_list) {
  512. if (matches(selector, style_sheet_for_rule, element, shadow_host))
  513. return true;
  514. }
  515. return false;
  516. case CSS::PseudoClass::Not:
  517. for (auto& selector : pseudo_class.argument_selector_list) {
  518. if (matches(selector, style_sheet_for_rule, element, shadow_host))
  519. return false;
  520. }
  521. return true;
  522. case CSS::PseudoClass::NthChild:
  523. case CSS::PseudoClass::NthLastChild:
  524. case CSS::PseudoClass::NthOfType:
  525. case CSS::PseudoClass::NthLastOfType: {
  526. auto const step_size = pseudo_class.nth_child_pattern.step_size;
  527. auto const offset = pseudo_class.nth_child_pattern.offset;
  528. if (step_size == 0 && offset == 0)
  529. return false; // "If both a and b are equal to zero, the pseudo-class represents no element in the document tree."
  530. auto const* parent = element.parent();
  531. if (!parent)
  532. return false;
  533. auto matches_selector_list = [&style_sheet_for_rule, shadow_host](CSS::SelectorList const& list, DOM::Element const& element) {
  534. if (list.is_empty())
  535. return true;
  536. for (auto const& child_selector : list) {
  537. if (matches(child_selector, style_sheet_for_rule, element, shadow_host)) {
  538. return true;
  539. }
  540. }
  541. return false;
  542. };
  543. int index = 1;
  544. switch (pseudo_class.type) {
  545. case CSS::PseudoClass::NthChild: {
  546. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  547. return false;
  548. for (auto* child = parent->first_child_of_type<DOM::Element>(); child && child != &element; child = child->next_element_sibling()) {
  549. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  550. ++index;
  551. }
  552. break;
  553. }
  554. case CSS::PseudoClass::NthLastChild: {
  555. if (!matches_selector_list(pseudo_class.argument_selector_list, element))
  556. return false;
  557. for (auto* child = parent->last_child_of_type<DOM::Element>(); child && child != &element; child = child->previous_element_sibling()) {
  558. if (matches_selector_list(pseudo_class.argument_selector_list, *child))
  559. ++index;
  560. }
  561. break;
  562. }
  563. case CSS::PseudoClass::NthOfType: {
  564. for (auto* child = previous_sibling_with_same_tag_name(element); child; child = previous_sibling_with_same_tag_name(*child))
  565. ++index;
  566. break;
  567. }
  568. case CSS::PseudoClass::NthLastOfType: {
  569. for (auto* child = next_sibling_with_same_tag_name(element); child; child = next_sibling_with_same_tag_name(*child))
  570. ++index;
  571. break;
  572. }
  573. default:
  574. VERIFY_NOT_REACHED();
  575. }
  576. // When "step_size == -1", selector represents first "offset" elements in document tree.
  577. if (step_size == -1)
  578. return !(offset <= 0 || index > offset);
  579. // When "step_size == 1", selector represents last "offset" elements in document tree.
  580. if (step_size == 1)
  581. return !(offset < 0 || index < offset);
  582. // When "step_size == 0", selector picks only the "offset" element.
  583. if (step_size == 0)
  584. return index == offset;
  585. // If both are negative, nothing can match.
  586. if (step_size < 0 && offset < 0)
  587. return false;
  588. // Like "a % b", but handles negative integers correctly.
  589. auto const canonical_modulo = [](int a, int b) -> int {
  590. int c = a % b;
  591. if ((c < 0 && b > 0) || (c > 0 && b < 0)) {
  592. c += b;
  593. }
  594. return c;
  595. };
  596. // When "step_size < 0", we start at "offset" and count backwards.
  597. if (step_size < 0)
  598. return index <= offset && canonical_modulo(index - offset, -step_size) == 0;
  599. // Otherwise, we start at "offset" and count forwards.
  600. return index >= offset && canonical_modulo(index - offset, step_size) == 0;
  601. }
  602. case CSS::PseudoClass::Playing: {
  603. if (!is<HTML::HTMLMediaElement>(element))
  604. return false;
  605. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  606. return !media_element.paused();
  607. }
  608. case CSS::PseudoClass::Paused: {
  609. if (!is<HTML::HTMLMediaElement>(element))
  610. return false;
  611. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  612. return media_element.paused();
  613. }
  614. case CSS::PseudoClass::Seeking: {
  615. if (!is<HTML::HTMLMediaElement>(element))
  616. return false;
  617. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  618. return media_element.seeking();
  619. }
  620. case CSS::PseudoClass::Muted: {
  621. if (!is<HTML::HTMLMediaElement>(element))
  622. return false;
  623. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  624. return media_element.muted();
  625. }
  626. case CSS::PseudoClass::VolumeLocked: {
  627. // FIXME: Currently we don't allow the user to specify an override volume, so this is always false.
  628. // Once we do, implement this!
  629. return false;
  630. }
  631. case CSS::PseudoClass::Buffering: {
  632. if (!is<HTML::HTMLMediaElement>(element))
  633. return false;
  634. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  635. return media_element.blocked();
  636. }
  637. case CSS::PseudoClass::Stalled: {
  638. if (!is<HTML::HTMLMediaElement>(element))
  639. return false;
  640. auto const& media_element = static_cast<HTML::HTMLMediaElement const&>(element);
  641. return media_element.stalled();
  642. }
  643. case CSS::PseudoClass::Target:
  644. return element.is_target();
  645. case CSS::PseudoClass::TargetWithin: {
  646. auto* target_element = element.document().target_element();
  647. if (!target_element)
  648. return false;
  649. return element.is_inclusive_ancestor_of(*target_element);
  650. }
  651. case CSS::PseudoClass::Dir: {
  652. // "Values other than ltr and rtl are not invalid, but do not match anything."
  653. // - https://www.w3.org/TR/selectors-4/#the-dir-pseudo
  654. if (!first_is_one_of(pseudo_class.keyword, CSS::Keyword::Ltr, CSS::Keyword::Rtl))
  655. return false;
  656. switch (element.directionality()) {
  657. case DOM::Element::Directionality::Ltr:
  658. return pseudo_class.keyword == CSS::Keyword::Ltr;
  659. case DOM::Element::Directionality::Rtl:
  660. return pseudo_class.keyword == CSS::Keyword::Rtl;
  661. }
  662. VERIFY_NOT_REACHED();
  663. }
  664. case CSS::PseudoClass::ReadOnly:
  665. return !matches_read_write_pseudo_class(element);
  666. case CSS::PseudoClass::ReadWrite:
  667. return matches_read_write_pseudo_class(element);
  668. case CSS::PseudoClass::PlaceholderShown: {
  669. // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-placeholder-shown
  670. // The :placeholder-shown pseudo-class must match any element falling into one of the following categories:
  671. // - input elements that have a placeholder attribute whose value is currently being presented to the user.
  672. if (is<HTML::HTMLInputElement>(element) && element.has_attribute(HTML::AttributeNames::placeholder)) {
  673. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(element);
  674. return input_element.placeholder_element() && input_element.placeholder_value().has_value();
  675. }
  676. // - FIXME: textarea elements that have a placeholder attribute whose value is currently being presented to the user.
  677. return false;
  678. }
  679. case CSS::PseudoClass::Open:
  680. return matches_open_state_pseudo_class(element, pseudo_class.type == CSS::PseudoClass::Open);
  681. case CSS::PseudoClass::Modal: {
  682. // https://drafts.csswg.org/selectors/#modal-state
  683. if (is<HTML::HTMLDialogElement>(element)) {
  684. auto const& dialog_element = static_cast<HTML::HTMLDialogElement const&>(element);
  685. return dialog_element.is_modal();
  686. }
  687. // FIXME: fullscreen elements are also modal.
  688. return false;
  689. }
  690. case CSS::PseudoClass::PopoverOpen: {
  691. // https://html.spec.whatwg.org/#selector-popover-open
  692. // The :popover-open pseudo-class is defined to match any HTML element whose popover attribute is not in the no popover state and whose popover visibility state is showing.
  693. if (is<HTML::HTMLElement>(element) && element.has_attribute(HTML::AttributeNames::popover)) {
  694. auto& html_element = static_cast<HTML::HTMLElement const&>(element);
  695. return html_element.popover_visibility_state() == HTML::HTMLElement::PopoverVisibilityState::Showing;
  696. }
  697. return false;
  698. }
  699. }
  700. return false;
  701. }
  702. static ALWAYS_INLINE bool matches_namespace(
  703. CSS::Selector::SimpleSelector::QualifiedName const& qualified_name,
  704. DOM::Element const& element,
  705. Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule)
  706. {
  707. switch (qualified_name.namespace_type) {
  708. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Default:
  709. // "if no default namespace has been declared for selectors, this is equivalent to *|E."
  710. if (!style_sheet_for_rule.has_value() || !style_sheet_for_rule->default_namespace_rule())
  711. return true;
  712. // "Otherwise it is equivalent to ns|E where ns is the default namespace."
  713. return element.namespace_uri() == style_sheet_for_rule->default_namespace_rule()->namespace_uri();
  714. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::None:
  715. // "elements with name E without a namespace"
  716. return !element.namespace_uri().has_value();
  717. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Any:
  718. // "elements with name E in any namespace, including those without a namespace"
  719. return true;
  720. case CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Named:
  721. // "elements with name E in namespace ns"
  722. // Unrecognized namespace prefixes are invalid, so don't match.
  723. // (We can't detect this at parse time, since a namespace rule may be inserted later.)
  724. // So, if we don't have a context to look up namespaces from, we fail to match.
  725. if (!style_sheet_for_rule.has_value())
  726. return false;
  727. auto selector_namespace = style_sheet_for_rule->namespace_uri(qualified_name.namespace_);
  728. return selector_namespace.has_value() && selector_namespace.value() == element.namespace_uri();
  729. }
  730. VERIFY_NOT_REACHED();
  731. }
  732. static inline bool matches(CSS::Selector::SimpleSelector const& component, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, GC::Ptr<DOM::Element const> shadow_host, GC::Ptr<DOM::ParentNode const> scope, SelectorKind selector_kind, [[maybe_unused]] GC::Ptr<DOM::Element const> anchor)
  733. {
  734. if (should_block_shadow_host_matching(component, shadow_host, element))
  735. return false;
  736. switch (component.type) {
  737. case CSS::Selector::SimpleSelector::Type::Universal:
  738. case CSS::Selector::SimpleSelector::Type::TagName: {
  739. auto const& qualified_name = component.qualified_name();
  740. // Reject if the tag name doesn't match
  741. if (component.type == CSS::Selector::SimpleSelector::Type::TagName) {
  742. // See https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
  743. if (element.document().document_type() == DOM::Document::Type::HTML) {
  744. if (qualified_name.name.lowercase_name != element.local_name())
  745. return false;
  746. } else if (!Infra::is_ascii_case_insensitive_match(qualified_name.name.name, element.local_name())) {
  747. return false;
  748. }
  749. }
  750. return matches_namespace(qualified_name, element, style_sheet_for_rule);
  751. }
  752. case CSS::Selector::SimpleSelector::Type::Id:
  753. return component.name() == element.id();
  754. case CSS::Selector::SimpleSelector::Type::Class: {
  755. // Class selectors are matched case insensitively in quirks mode.
  756. // See: https://drafts.csswg.org/selectors-4/#class-html
  757. auto case_sensitivity = element.document().in_quirks_mode() ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive;
  758. return element.has_class(component.name(), case_sensitivity);
  759. }
  760. case CSS::Selector::SimpleSelector::Type::Attribute:
  761. return matches_attribute(component.attribute(), style_sheet_for_rule, element);
  762. case CSS::Selector::SimpleSelector::Type::PseudoClass:
  763. return matches_pseudo_class(component.pseudo_class(), style_sheet_for_rule, element, shadow_host, scope, selector_kind);
  764. case CSS::Selector::SimpleSelector::Type::PseudoElement:
  765. // Pseudo-element matching/not-matching is handled in the top level matches().
  766. return true;
  767. case CSS::Selector::SimpleSelector::Type::Nesting:
  768. // Nesting either behaves like :is(), or like :scope.
  769. // :is() is handled already, by us replacing it with :is() directly, so if we
  770. // got here, it's :scope.
  771. return matches_pseudo_class(CSS::Selector::SimpleSelector::PseudoClassSelector { .type = CSS::PseudoClass::Scope }, style_sheet_for_rule, element, shadow_host, scope, selector_kind);
  772. case CSS::Selector::SimpleSelector::Type::Invalid:
  773. // Invalid selectors never match
  774. return false;
  775. }
  776. VERIFY_NOT_REACHED();
  777. }
  778. bool matches(CSS::Selector const& selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, int component_list_index, DOM::Element const& element, GC::Ptr<DOM::Element const> shadow_host, GC::Ptr<DOM::ParentNode const> scope, SelectorKind selector_kind, GC::Ptr<DOM::Element const> anchor)
  779. {
  780. auto& compound_selector = selector.compound_selectors()[component_list_index];
  781. for (auto& simple_selector : compound_selector.simple_selectors) {
  782. if (!matches(simple_selector, style_sheet_for_rule, element, shadow_host, scope, selector_kind, anchor)) {
  783. return false;
  784. }
  785. }
  786. if (selector_kind == SelectorKind::Relative && component_list_index == 0) {
  787. VERIFY(anchor);
  788. return &element != anchor;
  789. }
  790. switch (compound_selector.combinator) {
  791. case CSS::Selector::Combinator::None:
  792. VERIFY(selector_kind != SelectorKind::Relative);
  793. return true;
  794. case CSS::Selector::Combinator::Descendant:
  795. VERIFY(component_list_index != 0);
  796. for (auto ancestor = traverse_up(element, shadow_host); ancestor; ancestor = traverse_up(ancestor, shadow_host)) {
  797. if (!is<DOM::Element>(*ancestor))
  798. continue;
  799. if (ancestor == anchor)
  800. return false;
  801. if (matches(selector, style_sheet_for_rule, component_list_index - 1, static_cast<DOM::Element const&>(*ancestor), shadow_host, scope, selector_kind, anchor))
  802. return true;
  803. }
  804. return false;
  805. case CSS::Selector::Combinator::ImmediateChild: {
  806. VERIFY(component_list_index != 0);
  807. auto parent = traverse_up(element, shadow_host);
  808. if (!parent || !parent->is_element())
  809. return false;
  810. return matches(selector, style_sheet_for_rule, component_list_index - 1, static_cast<DOM::Element const&>(*parent), shadow_host, scope, selector_kind, anchor);
  811. }
  812. case CSS::Selector::Combinator::NextSibling:
  813. VERIFY(component_list_index != 0);
  814. if (auto* sibling = element.previous_element_sibling())
  815. return matches(selector, style_sheet_for_rule, component_list_index - 1, *sibling, shadow_host, scope, selector_kind, anchor);
  816. return false;
  817. case CSS::Selector::Combinator::SubsequentSibling:
  818. VERIFY(component_list_index != 0);
  819. for (auto* sibling = element.previous_element_sibling(); sibling; sibling = sibling->previous_element_sibling()) {
  820. if (matches(selector, style_sheet_for_rule, component_list_index - 1, *sibling, shadow_host, scope, selector_kind, anchor))
  821. return true;
  822. }
  823. return false;
  824. case CSS::Selector::Combinator::Column:
  825. TODO();
  826. }
  827. VERIFY_NOT_REACHED();
  828. }
  829. bool matches(CSS::Selector const& selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, GC::Ptr<DOM::Element const> shadow_host, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, GC::Ptr<DOM::ParentNode const> scope, SelectorKind selector_kind, GC::Ptr<DOM::Element const> anchor)
  830. {
  831. VERIFY(!selector.compound_selectors().is_empty());
  832. if (pseudo_element.has_value() && selector.pseudo_element().has_value() && selector.pseudo_element().value().type() != pseudo_element)
  833. return false;
  834. if (!pseudo_element.has_value() && selector.pseudo_element().has_value())
  835. return false;
  836. return matches(selector, style_sheet_for_rule, selector.compound_selectors().size() - 1, element, shadow_host, scope, selector_kind, anchor);
  837. }
  838. static bool fast_matches_simple_selector(CSS::Selector::SimpleSelector const& simple_selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, GC::Ptr<DOM::Element const> shadow_host)
  839. {
  840. if (should_block_shadow_host_matching(simple_selector, shadow_host, element))
  841. return false;
  842. switch (simple_selector.type) {
  843. case CSS::Selector::SimpleSelector::Type::Universal:
  844. return matches_namespace(simple_selector.qualified_name(), element, style_sheet_for_rule);
  845. case CSS::Selector::SimpleSelector::Type::TagName:
  846. if (element.document().document_type() == DOM::Document::Type::HTML) {
  847. if (simple_selector.qualified_name().name.lowercase_name != element.local_name())
  848. return false;
  849. } else if (!Infra::is_ascii_case_insensitive_match(simple_selector.qualified_name().name.name, element.local_name())) {
  850. return false;
  851. }
  852. return matches_namespace(simple_selector.qualified_name(), element, style_sheet_for_rule);
  853. case CSS::Selector::SimpleSelector::Type::Class: {
  854. // Class selectors are matched case insensitively in quirks mode.
  855. // See: https://drafts.csswg.org/selectors-4/#class-html
  856. auto case_sensitivity = element.document().in_quirks_mode() ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive;
  857. return element.has_class(simple_selector.name(), case_sensitivity);
  858. }
  859. case CSS::Selector::SimpleSelector::Type::Id:
  860. return simple_selector.name() == element.id();
  861. case CSS::Selector::SimpleSelector::Type::Attribute:
  862. return matches_attribute(simple_selector.attribute(), style_sheet_for_rule, element);
  863. case CSS::Selector::SimpleSelector::Type::PseudoClass:
  864. return matches_pseudo_class(simple_selector.pseudo_class(), style_sheet_for_rule, element, shadow_host, nullptr, SelectorKind::Normal);
  865. default:
  866. VERIFY_NOT_REACHED();
  867. }
  868. }
  869. static bool fast_matches_compound_selector(CSS::Selector::CompoundSelector const& compound_selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element, GC::Ptr<DOM::Element const> shadow_host)
  870. {
  871. for (auto const& simple_selector : compound_selector.simple_selectors) {
  872. if (!fast_matches_simple_selector(simple_selector, style_sheet_for_rule, element, shadow_host))
  873. return false;
  874. }
  875. return true;
  876. }
  877. bool fast_matches(CSS::Selector const& selector, Optional<CSS::CSSStyleSheet const&> style_sheet_for_rule, DOM::Element const& element_to_match, GC::Ptr<DOM::Element const> shadow_host)
  878. {
  879. DOM::Element const* current = &element_to_match;
  880. ssize_t compound_selector_index = selector.compound_selectors().size() - 1;
  881. if (!fast_matches_compound_selector(selector.compound_selectors().last(), style_sheet_for_rule, *current, shadow_host))
  882. return false;
  883. // NOTE: If we fail after following a child combinator, we may need to backtrack
  884. // to the last matched descendant. We store the state here.
  885. struct {
  886. GC::Ptr<DOM::Element const> element;
  887. ssize_t compound_selector_index = 0;
  888. } backtrack_state;
  889. for (;;) {
  890. // NOTE: There should always be a leftmost compound selector without combinator that kicks us out of this loop.
  891. VERIFY(compound_selector_index >= 0);
  892. auto const* compound_selector = &selector.compound_selectors()[compound_selector_index];
  893. switch (compound_selector->combinator) {
  894. case CSS::Selector::Combinator::None:
  895. return true;
  896. case CSS::Selector::Combinator::Descendant:
  897. backtrack_state = { current->parent_element(), compound_selector_index };
  898. compound_selector = &selector.compound_selectors()[--compound_selector_index];
  899. for (current = current->parent_element(); current; current = current->parent_element()) {
  900. if (fast_matches_compound_selector(*compound_selector, style_sheet_for_rule, *current, shadow_host))
  901. break;
  902. }
  903. if (!current)
  904. return false;
  905. break;
  906. case CSS::Selector::Combinator::ImmediateChild:
  907. compound_selector = &selector.compound_selectors()[--compound_selector_index];
  908. current = current->parent_element();
  909. if (!current)
  910. return false;
  911. if (!fast_matches_compound_selector(*compound_selector, style_sheet_for_rule, *current, shadow_host)) {
  912. if (backtrack_state.element) {
  913. current = backtrack_state.element;
  914. compound_selector_index = backtrack_state.compound_selector_index;
  915. continue;
  916. }
  917. return false;
  918. }
  919. break;
  920. default:
  921. VERIFY_NOT_REACHED();
  922. }
  923. }
  924. }
  925. bool can_use_fast_matches(CSS::Selector const& selector)
  926. {
  927. for (auto const& compound_selector : selector.compound_selectors()) {
  928. if (compound_selector.combinator != CSS::Selector::Combinator::None
  929. && compound_selector.combinator != CSS::Selector::Combinator::Descendant
  930. && compound_selector.combinator != CSS::Selector::Combinator::ImmediateChild) {
  931. return false;
  932. }
  933. for (auto const& simple_selector : compound_selector.simple_selectors) {
  934. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::PseudoClass) {
  935. auto const pseudo_class = simple_selector.pseudo_class().type;
  936. if (pseudo_class != CSS::PseudoClass::FirstChild
  937. && pseudo_class != CSS::PseudoClass::LastChild
  938. && pseudo_class != CSS::PseudoClass::OnlyChild
  939. && pseudo_class != CSS::PseudoClass::Hover
  940. && pseudo_class != CSS::PseudoClass::Active
  941. && pseudo_class != CSS::PseudoClass::Focus
  942. && pseudo_class != CSS::PseudoClass::FocusVisible
  943. && pseudo_class != CSS::PseudoClass::FocusWithin
  944. && pseudo_class != CSS::PseudoClass::Link
  945. && pseudo_class != CSS::PseudoClass::AnyLink
  946. && pseudo_class != CSS::PseudoClass::Visited
  947. && pseudo_class != CSS::PseudoClass::LocalLink
  948. && pseudo_class != CSS::PseudoClass::Empty
  949. && pseudo_class != CSS::PseudoClass::Root
  950. && pseudo_class != CSS::PseudoClass::Enabled
  951. && pseudo_class != CSS::PseudoClass::Disabled
  952. && pseudo_class != CSS::PseudoClass::Checked) {
  953. return false;
  954. }
  955. } else if (simple_selector.type != CSS::Selector::SimpleSelector::Type::TagName
  956. && simple_selector.type != CSS::Selector::SimpleSelector::Type::Universal
  957. && simple_selector.type != CSS::Selector::SimpleSelector::Type::Class
  958. && simple_selector.type != CSS::Selector::SimpleSelector::Type::Id
  959. && simple_selector.type != CSS::Selector::SimpleSelector::Type::Attribute) {
  960. return false;
  961. }
  962. }
  963. }
  964. return true;
  965. }
  966. }