SelectorEngine.cpp 43 KB

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