Selector.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 PseudoClass::Is:
  66. case PseudoClass::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 PseudoClass::NthChild:
  73. case PseudoClass::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 PseudoClass::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. auto qualified_name = this->qualified_name();
  116. // 1. If the namespace prefix maps to a namespace that is not the default namespace and is not the null
  117. // namespace (not in a namespace) append the serialization of the namespace prefix as an identifier,
  118. // followed by a "|" (U+007C) to s.
  119. if (qualified_name.namespace_type == QualifiedName::NamespaceType::Named) {
  120. TRY(serialize_an_identifier(s, qualified_name.namespace_));
  121. TRY(s.try_append('|'));
  122. }
  123. // 2. If the namespace prefix maps to a namespace that is the null namespace (not in a namespace)
  124. // append "|" (U+007C) to s.
  125. if (qualified_name.namespace_type == QualifiedName::NamespaceType::None)
  126. TRY(s.try_append('|'));
  127. // 3. If this is a type selector append the serialization of the element name as an identifier to s.
  128. if (type == Selector::SimpleSelector::Type::TagName)
  129. TRY(serialize_an_identifier(s, qualified_name.name.name));
  130. // 4. If this is a universal selector append "*" (U+002A) to s.
  131. if (type == Selector::SimpleSelector::Type::Universal)
  132. TRY(s.try_append('*'));
  133. break;
  134. }
  135. case Selector::SimpleSelector::Type::Attribute: {
  136. auto& attribute = this->attribute();
  137. // 1. Append "[" (U+005B) to s.
  138. TRY(s.try_append('['));
  139. // 2. If the namespace prefix maps to a namespace that is not the null namespace (not in a namespace)
  140. // append the serialization of the namespace prefix as an identifier, followed by a "|" (U+007C) to s.
  141. if (attribute.qualified_name.namespace_type == QualifiedName::NamespaceType::Named) {
  142. TRY(serialize_an_identifier(s, attribute.qualified_name.namespace_));
  143. TRY(s.try_append('|'));
  144. }
  145. // 3. Append the serialization of the attribute name as an identifier to s.
  146. TRY(serialize_an_identifier(s, attribute.qualified_name.name.name));
  147. // 4. If there is an attribute value specified, append "=", "~=", "|=", "^=", "$=", or "*=" as appropriate (depending on the type of attribute selector),
  148. // followed by the serialization of the attribute value as a string, to s.
  149. if (!attribute.value.is_empty()) {
  150. switch (attribute.match_type) {
  151. case Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch:
  152. TRY(s.try_append("="sv));
  153. break;
  154. case Selector::SimpleSelector::Attribute::MatchType::ContainsWord:
  155. TRY(s.try_append("~="sv));
  156. break;
  157. case Selector::SimpleSelector::Attribute::MatchType::ContainsString:
  158. TRY(s.try_append("*="sv));
  159. break;
  160. case Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment:
  161. TRY(s.try_append("|="sv));
  162. break;
  163. case Selector::SimpleSelector::Attribute::MatchType::StartsWithString:
  164. TRY(s.try_append("^="sv));
  165. break;
  166. case Selector::SimpleSelector::Attribute::MatchType::EndsWithString:
  167. TRY(s.try_append("$="sv));
  168. break;
  169. default:
  170. break;
  171. }
  172. TRY(serialize_a_string(s, attribute.value));
  173. }
  174. // 5. If the attribute selector has the case-insensitivity flag present, append " i" (U+0020 U+0069) to s.
  175. // If the attribute selector has the case-insensitivity flag present, append " s" (U+0020 U+0073) to s.
  176. // (the line just above is an addition to CSS OM to match Selectors Level 4 last draft)
  177. switch (attribute.case_type) {
  178. case Selector::SimpleSelector::Attribute::CaseType::CaseInsensitiveMatch:
  179. TRY(s.try_append(" i"sv));
  180. break;
  181. case Selector::SimpleSelector::Attribute::CaseType::CaseSensitiveMatch:
  182. TRY(s.try_append(" s"sv));
  183. break;
  184. default:
  185. break;
  186. }
  187. // 6. Append "]" (U+005D) to s.
  188. TRY(s.try_append(']'));
  189. break;
  190. }
  191. case Selector::SimpleSelector::Type::Class:
  192. // Append a "." (U+002E), followed by the serialization of the class name as an identifier to s.
  193. TRY(s.try_append('.'));
  194. TRY(serialize_an_identifier(s, name()));
  195. break;
  196. case Selector::SimpleSelector::Type::Id:
  197. // Append a "#" (U+0023), followed by the serialization of the ID as an identifier to s.
  198. TRY(s.try_append('#'));
  199. TRY(serialize_an_identifier(s, name()));
  200. break;
  201. case Selector::SimpleSelector::Type::PseudoClass: {
  202. auto& pseudo_class = this->pseudo_class();
  203. auto metadata = pseudo_class_metadata(pseudo_class.type);
  204. // If the pseudo-class does not accept arguments append ":" (U+003A), followed by the name of the pseudo-class, to s.
  205. if (metadata.is_valid_as_identifier) {
  206. TRY(s.try_append(':'));
  207. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  208. }
  209. // Otherwise, append ":" (U+003A), followed by the name of the pseudo-class, followed by "(" (U+0028),
  210. // followed by the value of the pseudo-class argument(s) determined as per below, followed by ")" (U+0029), to s.
  211. else {
  212. TRY(s.try_append(':'));
  213. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  214. TRY(s.try_append('('));
  215. if (pseudo_class.type == PseudoClass::NthChild
  216. || pseudo_class.type == PseudoClass::NthLastChild
  217. || pseudo_class.type == PseudoClass::NthOfType
  218. || pseudo_class.type == PseudoClass::NthLastOfType) {
  219. // The result of serializing the value using the rules to serialize an <an+b> value.
  220. TRY(s.try_append(TRY(pseudo_class.nth_child_pattern.serialize())));
  221. } else if (pseudo_class.type == PseudoClass::Not
  222. || pseudo_class.type == PseudoClass::Is
  223. || pseudo_class.type == PseudoClass::Where) {
  224. // The result of serializing the value using the rules for serializing a group of selectors.
  225. // NOTE: `:is()` and `:where()` aren't in the spec for this yet, but it should be!
  226. TRY(s.try_append(TRY(serialize_a_group_of_selectors(pseudo_class.argument_selector_list))));
  227. } else if (pseudo_class.type == PseudoClass::Lang) {
  228. // The serialization of a comma-separated list of each argument’s serialization as a string, preserving relative order.
  229. s.join(", "sv, pseudo_class.languages);
  230. }
  231. TRY(s.try_append(')'));
  232. }
  233. break;
  234. }
  235. case Selector::SimpleSelector::Type::PseudoElement:
  236. // Note: Pseudo-elements are dealt with in Selector::serialize()
  237. break;
  238. default:
  239. dbgln("FIXME: Unsupported simple selector serialization for type {}", to_underlying(type));
  240. break;
  241. }
  242. return s.to_string();
  243. }
  244. // https://www.w3.org/TR/cssom/#serialize-a-selector
  245. ErrorOr<String> Selector::serialize() const
  246. {
  247. StringBuilder s;
  248. // 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:
  249. for (size_t i = 0; i < compound_selectors().size(); ++i) {
  250. auto const& compound_selector = compound_selectors()[i];
  251. // 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.
  252. if (compound_selector.simple_selectors.size() == 1
  253. && compound_selector.simple_selectors.first().type == Selector::SimpleSelector::Type::Universal) {
  254. TRY(s.try_append(TRY(compound_selector.simple_selectors.first().serialize())));
  255. }
  256. // 2. Otherwise, for each simple selector in the compound selectors that is not a universal selector
  257. // of which the namespace prefix maps to a namespace that is not the default namespace
  258. // serialize the simple selector and append the result to s.
  259. else {
  260. for (auto& simple_selector : compound_selector.simple_selectors) {
  261. if (simple_selector.type == SimpleSelector::Type::Universal) {
  262. auto qualified_name = simple_selector.qualified_name();
  263. if (qualified_name.namespace_type == SimpleSelector::QualifiedName::NamespaceType::Default)
  264. continue;
  265. // FIXME: I *think* if we have a namespace prefix that happens to equal the same as the default namespace,
  266. // we also should skip it. But we don't have access to that here. eg:
  267. // <style>
  268. // @namespace "http://example";
  269. // @namespace foo "http://example";
  270. // foo|*.bar { } /* This would skip the `foo|*` when serializing. */
  271. // </style>
  272. }
  273. TRY(s.try_append(TRY(simple_selector.serialize())));
  274. }
  275. }
  276. // 3. If this is not the last part of the chain of the selector append a single SPACE (U+0020),
  277. // followed by the combinator ">", "+", "~", ">>", "||", as appropriate, followed by another
  278. // single SPACE (U+0020) if the combinator was not whitespace, to s.
  279. if (i != compound_selectors().size() - 1) {
  280. TRY(s.try_append(' '));
  281. // Note: The combinator that appears between parts `i` and `i+1` appears with the `i+1` selector,
  282. // so we have to check that one.
  283. switch (compound_selectors()[i + 1].combinator) {
  284. case Selector::Combinator::ImmediateChild:
  285. TRY(s.try_append("> "sv));
  286. break;
  287. case Selector::Combinator::NextSibling:
  288. TRY(s.try_append("+ "sv));
  289. break;
  290. case Selector::Combinator::SubsequentSibling:
  291. TRY(s.try_append("~ "sv));
  292. break;
  293. case Selector::Combinator::Column:
  294. TRY(s.try_append("|| "sv));
  295. break;
  296. default:
  297. break;
  298. }
  299. } else {
  300. // 4. If this is the last part of the chain of the selector and there is a pseudo-element,
  301. // append "::" followed by the name of the pseudo-element, to s.
  302. if (compound_selector.simple_selectors.last().type == Selector::SimpleSelector::Type::PseudoElement) {
  303. TRY(s.try_append("::"sv));
  304. TRY(s.try_append(pseudo_element_name(compound_selector.simple_selectors.last().pseudo_element())));
  305. }
  306. }
  307. }
  308. return s.to_string();
  309. }
  310. // https://www.w3.org/TR/cssom/#serialize-a-group-of-selectors
  311. ErrorOr<String> serialize_a_group_of_selectors(Vector<NonnullRefPtr<Selector>> const& selectors)
  312. {
  313. // To serialize a group of selectors serialize each selector in the group of selectors and then serialize a comma-separated list of these serializations.
  314. return String::join(", "sv, selectors);
  315. }
  316. Optional<Selector::PseudoElement> pseudo_element_from_string(StringView name)
  317. {
  318. if (name.equals_ignoring_ascii_case("after"sv)) {
  319. return Selector::PseudoElement::After;
  320. } else if (name.equals_ignoring_ascii_case("before"sv)) {
  321. return Selector::PseudoElement::Before;
  322. } else if (name.equals_ignoring_ascii_case("first-letter"sv)) {
  323. return Selector::PseudoElement::FirstLetter;
  324. } else if (name.equals_ignoring_ascii_case("first-line"sv)) {
  325. return Selector::PseudoElement::FirstLine;
  326. } else if (name.equals_ignoring_ascii_case("marker"sv)) {
  327. return Selector::PseudoElement::Marker;
  328. } else if (name.equals_ignoring_ascii_case("-webkit-progress-bar"sv)) {
  329. return Selector::PseudoElement::ProgressBar;
  330. } else if (name.equals_ignoring_ascii_case("-webkit-progress-value"sv)) {
  331. return Selector::PseudoElement::ProgressValue;
  332. } else if (name.equals_ignoring_ascii_case("placeholder"sv)) {
  333. return Selector::PseudoElement::Placeholder;
  334. } else if (name.equals_ignoring_ascii_case("selection"sv)) {
  335. return Selector::PseudoElement::Selection;
  336. }
  337. return {};
  338. }
  339. }