SelectorEngine.cpp 38 KB

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