SelectorEngine.cpp 52 KB

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