Selector.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. * Copyright (c) 2018-2020, 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 "Selector.h"
  8. #include <LibWeb/CSS/Serialize.h>
  9. namespace Web::CSS {
  10. Selector::Selector(Vector<CompoundSelector>&& compound_selectors)
  11. : m_compound_selectors(move(compound_selectors))
  12. {
  13. // FIXME: This assumes that only one pseudo-element is allowed in a selector, and that it appears at the end.
  14. // This is not true in Selectors-4!
  15. if (!m_compound_selectors.is_empty()) {
  16. for (auto const& simple_selector : m_compound_selectors.last().simple_selectors) {
  17. if (simple_selector.type == SimpleSelector::Type::PseudoElement) {
  18. m_pseudo_element = simple_selector.pseudo_element();
  19. break;
  20. }
  21. }
  22. }
  23. }
  24. // https://www.w3.org/TR/selectors-4/#specificity-rules
  25. u32 Selector::specificity() const
  26. {
  27. if (m_specificity.has_value())
  28. return *m_specificity;
  29. constexpr u32 ids_shift = 16;
  30. constexpr u32 classes_shift = 8;
  31. constexpr u32 tag_names_shift = 0;
  32. constexpr u32 ids_mask = 0xff << ids_shift;
  33. constexpr u32 classes_mask = 0xff << classes_shift;
  34. constexpr u32 tag_names_mask = 0xff << tag_names_shift;
  35. u32 ids = 0;
  36. u32 classes = 0;
  37. u32 tag_names = 0;
  38. auto count_specificity_of_most_complex_selector = [&](auto& selector_list) {
  39. u32 max_selector_list_argument_specificity = 0;
  40. for (auto const& complex_selector : selector_list) {
  41. max_selector_list_argument_specificity = max(max_selector_list_argument_specificity, complex_selector->specificity());
  42. }
  43. u32 child_ids = (max_selector_list_argument_specificity & ids_mask) >> ids_shift;
  44. u32 child_classes = (max_selector_list_argument_specificity & classes_mask) >> classes_shift;
  45. u32 child_tag_names = (max_selector_list_argument_specificity & tag_names_mask) >> tag_names_shift;
  46. ids += child_ids;
  47. classes += child_classes;
  48. tag_names += child_tag_names;
  49. };
  50. for (auto& list : m_compound_selectors) {
  51. for (auto& simple_selector : list.simple_selectors) {
  52. switch (simple_selector.type) {
  53. case SimpleSelector::Type::Id:
  54. // count the number of ID selectors in the selector (= A)
  55. ++ids;
  56. break;
  57. case SimpleSelector::Type::Class:
  58. case SimpleSelector::Type::Attribute:
  59. // count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= B)
  60. ++classes;
  61. break;
  62. case SimpleSelector::Type::PseudoClass: {
  63. auto& pseudo_class = simple_selector.pseudo_class();
  64. switch (pseudo_class.type) {
  65. case SimpleSelector::PseudoClass::Type::Is:
  66. case SimpleSelector::PseudoClass::Type::Not: {
  67. // The specificity of an :is(), :not(), or :has() pseudo-class is replaced by the
  68. // specificity of the most specific complex selector in its selector list argument.
  69. count_specificity_of_most_complex_selector(pseudo_class.argument_selector_list);
  70. break;
  71. }
  72. case SimpleSelector::PseudoClass::Type::NthChild:
  73. case SimpleSelector::PseudoClass::Type::NthLastChild: {
  74. // Analogously, the specificity of an :nth-child() or :nth-last-child() selector
  75. // is the specificity of the pseudo class itself (counting as one pseudo-class selector)
  76. // plus the specificity of the most specific complex selector in its selector list argument (if any).
  77. ++classes;
  78. count_specificity_of_most_complex_selector(pseudo_class.argument_selector_list);
  79. break;
  80. }
  81. case SimpleSelector::PseudoClass::Type::Where:
  82. // The specificity of a :where() pseudo-class is replaced by zero.
  83. break;
  84. default:
  85. ++classes;
  86. break;
  87. }
  88. break;
  89. }
  90. case SimpleSelector::Type::TagName:
  91. case SimpleSelector::Type::PseudoElement:
  92. // count the number of type selectors and pseudo-elements in the selector (= C)
  93. ++tag_names;
  94. break;
  95. case SimpleSelector::Type::Universal:
  96. // ignore the universal selector
  97. break;
  98. }
  99. }
  100. }
  101. // Due to storage limitations, implementations may have limitations on the size of A, B, or C.
  102. // If so, values higher than the limit must be clamped to that limit, and not overflow.
  103. m_specificity = (min(ids, 0xff) << ids_shift)
  104. + (min(classes, 0xff) << classes_shift)
  105. + (min(tag_names, 0xff) << tag_names_shift);
  106. return *m_specificity;
  107. }
  108. // https://www.w3.org/TR/cssom/#serialize-a-simple-selector
  109. ErrorOr<String> Selector::SimpleSelector::serialize() const
  110. {
  111. StringBuilder s;
  112. switch (type) {
  113. case Selector::SimpleSelector::Type::TagName:
  114. case Selector::SimpleSelector::Type::Universal:
  115. // FIXME: 1. If the namespace prefix maps to a namespace that is not the default namespace and is not the null namespace (not in a namespace) append the serialization of the namespace prefix as an identifier, followed by a "|" (U+007C) to s.
  116. // FIXME: 2. If the namespace prefix maps to a namespace that is the null namespace (not in a namespace) append "|" (U+007C) to s.
  117. // 3. If this is a type selector append the serialization of the element name as an identifier to s.
  118. if (type == Selector::SimpleSelector::Type::TagName) {
  119. TRY(serialize_an_identifier(s, name()));
  120. }
  121. // 4. If this is a universal selector append "*" (U+002A) to s.
  122. if (type == Selector::SimpleSelector::Type::Universal)
  123. TRY(s.try_append('*'));
  124. break;
  125. case Selector::SimpleSelector::Type::Attribute: {
  126. auto& attribute = this->attribute();
  127. // 1. Append "[" (U+005B) to s.
  128. TRY(s.try_append('['));
  129. // FIXME: 2. If the namespace prefix maps to a namespace that is not the null namespace (not in a namespace) append the serialization of the namespace prefix as an identifier, followed by a "|" (U+007C) to s.
  130. // 3. Append the serialization of the attribute name as an identifier to s.
  131. TRY(serialize_an_identifier(s, attribute.name));
  132. // 4. If there is an attribute value specified, append "=", "~=", "|=", "^=", "$=", or "*=" as appropriate (depending on the type of attribute selector),
  133. // followed by the serialization of the attribute value as a string, to s.
  134. if (!attribute.value.is_empty()) {
  135. switch (attribute.match_type) {
  136. case Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch:
  137. TRY(s.try_append("="sv));
  138. break;
  139. case Selector::SimpleSelector::Attribute::MatchType::ContainsWord:
  140. TRY(s.try_append("~="sv));
  141. break;
  142. case Selector::SimpleSelector::Attribute::MatchType::ContainsString:
  143. TRY(s.try_append("*="sv));
  144. break;
  145. case Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment:
  146. TRY(s.try_append("|="sv));
  147. break;
  148. case Selector::SimpleSelector::Attribute::MatchType::StartsWithString:
  149. TRY(s.try_append("^="sv));
  150. break;
  151. case Selector::SimpleSelector::Attribute::MatchType::EndsWithString:
  152. TRY(s.try_append("$="sv));
  153. break;
  154. default:
  155. break;
  156. }
  157. TRY(serialize_a_string(s, attribute.value));
  158. }
  159. // 5. If the attribute selector has the case-insensitivity flag present, append " i" (U+0020 U+0069) to s.
  160. // If the attribute selector has the case-insensitivity flag present, append " s" (U+0020 U+0073) to s.
  161. // (the line just above is an addition to CSS OM to match Selectors Level 4 last draft)
  162. switch (attribute.case_type) {
  163. case Selector::SimpleSelector::Attribute::CaseType::CaseInsensitiveMatch:
  164. TRY(s.try_append(" i"sv));
  165. break;
  166. case Selector::SimpleSelector::Attribute::CaseType::CaseSensitiveMatch:
  167. TRY(s.try_append(" s"sv));
  168. break;
  169. default:
  170. break;
  171. }
  172. // 6. Append "]" (U+005D) to s.
  173. TRY(s.try_append(']'));
  174. break;
  175. }
  176. case Selector::SimpleSelector::Type::Class:
  177. // Append a "." (U+002E), followed by the serialization of the class name as an identifier to s.
  178. TRY(s.try_append('.'));
  179. TRY(serialize_an_identifier(s, name()));
  180. break;
  181. case Selector::SimpleSelector::Type::Id:
  182. // Append a "#" (U+0023), followed by the serialization of the ID as an identifier to s.
  183. TRY(s.try_append('#'));
  184. TRY(serialize_an_identifier(s, name()));
  185. break;
  186. case Selector::SimpleSelector::Type::PseudoClass: {
  187. auto& pseudo_class = this->pseudo_class();
  188. switch (pseudo_class.type) {
  189. case Selector::SimpleSelector::PseudoClass::Type::Link:
  190. case Selector::SimpleSelector::PseudoClass::Type::Visited:
  191. case Selector::SimpleSelector::PseudoClass::Type::Hover:
  192. case Selector::SimpleSelector::PseudoClass::Type::Focus:
  193. case Selector::SimpleSelector::PseudoClass::Type::FocusWithin:
  194. case Selector::SimpleSelector::PseudoClass::Type::FirstChild:
  195. case Selector::SimpleSelector::PseudoClass::Type::LastChild:
  196. case Selector::SimpleSelector::PseudoClass::Type::OnlyChild:
  197. case Selector::SimpleSelector::PseudoClass::Type::Empty:
  198. case Selector::SimpleSelector::PseudoClass::Type::Root:
  199. case Selector::SimpleSelector::PseudoClass::Type::FirstOfType:
  200. case Selector::SimpleSelector::PseudoClass::Type::LastOfType:
  201. case Selector::SimpleSelector::PseudoClass::Type::OnlyOfType:
  202. case Selector::SimpleSelector::PseudoClass::Type::Disabled:
  203. case Selector::SimpleSelector::PseudoClass::Type::Enabled:
  204. case Selector::SimpleSelector::PseudoClass::Type::Checked:
  205. case Selector::SimpleSelector::PseudoClass::Type::Active:
  206. case Selector::SimpleSelector::PseudoClass::Type::Scope:
  207. // If the pseudo-class does not accept arguments append ":" (U+003A), followed by the name of the pseudo-class, to s.
  208. TRY(s.try_append(':'));
  209. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  210. break;
  211. case Selector::SimpleSelector::PseudoClass::Type::NthChild:
  212. case Selector::SimpleSelector::PseudoClass::Type::NthLastChild:
  213. case Selector::SimpleSelector::PseudoClass::Type::NthOfType:
  214. case Selector::SimpleSelector::PseudoClass::Type::NthLastOfType:
  215. case Selector::SimpleSelector::PseudoClass::Type::Not:
  216. case Selector::SimpleSelector::PseudoClass::Type::Is:
  217. case Selector::SimpleSelector::PseudoClass::Type::Where:
  218. case Selector::SimpleSelector::PseudoClass::Type::Lang:
  219. // Otherwise, append ":" (U+003A), followed by the name of the pseudo-class, followed by "(" (U+0028),
  220. // followed by the value of the pseudo-class argument(s) determined as per below, followed by ")" (U+0029), to s.
  221. TRY(s.try_append(':'));
  222. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  223. TRY(s.try_append('('));
  224. if (pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::NthChild
  225. || pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::NthLastChild
  226. || pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::NthOfType
  227. || pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::NthLastOfType) {
  228. // The result of serializing the value using the rules to serialize an <an+b> value.
  229. TRY(s.try_append(TRY(pseudo_class.nth_child_pattern.serialize())));
  230. } else if (pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::Not
  231. || pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::Is
  232. || pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::Where) {
  233. // The result of serializing the value using the rules for serializing a group of selectors.
  234. // NOTE: `:is()` and `:where()` aren't in the spec for this yet, but it should be!
  235. TRY(s.try_append(TRY(serialize_a_group_of_selectors(pseudo_class.argument_selector_list))));
  236. } else if (pseudo_class.type == Selector::SimpleSelector::PseudoClass::Type::Lang) {
  237. // The serialization of a comma-separated list of each argument’s serialization as a string, preserving relative order.
  238. s.join(", "sv, pseudo_class.languages);
  239. }
  240. TRY(s.try_append(')'));
  241. break;
  242. default:
  243. dbgln("FIXME: Unknown pseudo class type for serialization: {}", to_underlying(pseudo_class.type));
  244. VERIFY_NOT_REACHED();
  245. }
  246. break;
  247. }
  248. case Selector::SimpleSelector::Type::PseudoElement:
  249. // Note: Pseudo-elements are dealt with in Selector::serialize()
  250. break;
  251. default:
  252. dbgln("FIXME: Unsupported simple selector serialization for type {}", to_underlying(type));
  253. break;
  254. }
  255. return s.to_string();
  256. }
  257. // https://www.w3.org/TR/cssom/#serialize-a-selector
  258. ErrorOr<String> Selector::serialize() const
  259. {
  260. StringBuilder s;
  261. // To serialize a selector let s be the empty string, run the steps below for each part of the chain of the selector, and finally return s:
  262. for (size_t i = 0; i < compound_selectors().size(); ++i) {
  263. auto const& compound_selector = compound_selectors()[i];
  264. // 1. If there is only one simple selector in the compound selectors which is a universal selector, append the result of serializing the universal selector to s.
  265. if (compound_selector.simple_selectors.size() == 1
  266. && compound_selector.simple_selectors.first().type == Selector::SimpleSelector::Type::Universal) {
  267. TRY(s.try_append(TRY(compound_selector.simple_selectors.first().serialize())));
  268. }
  269. // 2. Otherwise, for each simple selector in the compound selectors...
  270. // FIXME: ...that is not a universal selector of which the namespace prefix maps to a namespace that is not the default namespace...
  271. // ...serialize the simple selector and append the result to s.
  272. else {
  273. for (auto& simple_selector : compound_selector.simple_selectors) {
  274. TRY(s.try_append(TRY(simple_selector.serialize())));
  275. }
  276. }
  277. // 3. If this is not the last part of the chain of the selector append a single SPACE (U+0020),
  278. // followed by the combinator ">", "+", "~", ">>", "||", as appropriate, followed by another
  279. // single SPACE (U+0020) if the combinator was not whitespace, to s.
  280. if (i != compound_selectors().size() - 1) {
  281. TRY(s.try_append(' '));
  282. // Note: The combinator that appears between parts `i` and `i+1` appears with the `i+1` selector,
  283. // so we have to check that one.
  284. switch (compound_selectors()[i + 1].combinator) {
  285. case Selector::Combinator::ImmediateChild:
  286. TRY(s.try_append("> "sv));
  287. break;
  288. case Selector::Combinator::NextSibling:
  289. TRY(s.try_append("+ "sv));
  290. break;
  291. case Selector::Combinator::SubsequentSibling:
  292. TRY(s.try_append("~ "sv));
  293. break;
  294. case Selector::Combinator::Column:
  295. TRY(s.try_append("|| "sv));
  296. break;
  297. default:
  298. break;
  299. }
  300. } else {
  301. // 4. If this is the last part of the chain of the selector and there is a pseudo-element,
  302. // append "::" followed by the name of the pseudo-element, to s.
  303. if (compound_selector.simple_selectors.last().type == Selector::SimpleSelector::Type::PseudoElement) {
  304. TRY(s.try_append("::"sv));
  305. TRY(s.try_append(pseudo_element_name(compound_selector.simple_selectors.last().pseudo_element())));
  306. }
  307. }
  308. }
  309. return s.to_string();
  310. }
  311. // https://www.w3.org/TR/cssom/#serialize-a-group-of-selectors
  312. ErrorOr<String> serialize_a_group_of_selectors(Vector<NonnullRefPtr<Selector>> const& selectors)
  313. {
  314. // To serialize a group of selectors serialize each selector in the group of selectors and then serialize a comma-separated list of these serializations.
  315. return String::join(", "sv, selectors);
  316. }
  317. Optional<Selector::PseudoElement> pseudo_element_from_string(StringView name)
  318. {
  319. if (name.equals_ignoring_ascii_case("after"sv)) {
  320. return Selector::PseudoElement::After;
  321. } else if (name.equals_ignoring_ascii_case("before"sv)) {
  322. return Selector::PseudoElement::Before;
  323. } else if (name.equals_ignoring_ascii_case("first-letter"sv)) {
  324. return Selector::PseudoElement::FirstLetter;
  325. } else if (name.equals_ignoring_ascii_case("first-line"sv)) {
  326. return Selector::PseudoElement::FirstLine;
  327. } else if (name.equals_ignoring_ascii_case("marker"sv)) {
  328. return Selector::PseudoElement::Marker;
  329. } else if (name.equals_ignoring_ascii_case("-webkit-progress-bar"sv)) {
  330. return Selector::PseudoElement::ProgressBar;
  331. } else if (name.equals_ignoring_ascii_case("-webkit-progress-value"sv)) {
  332. return Selector::PseudoElement::ProgressValue;
  333. } else if (name.equals_ignoring_ascii_case("placeholder"sv)) {
  334. return Selector::PseudoElement::Placeholder;
  335. }
  336. return {};
  337. }
  338. }