SelectorEngine.cpp 41 KB

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