Selector.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. // HACK: `:host()` has both a function and a non-function form, so handle that first.
  205. // It's also not in the spec.
  206. if (pseudo_class.type == PseudoClass::Host) {
  207. if (pseudo_class.argument_selector_list.is_empty()) {
  208. TRY(s.try_append(':'));
  209. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  210. } else {
  211. TRY(s.try_append(':'));
  212. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  213. TRY(s.try_append('('));
  214. TRY(s.try_append(TRY(serialize_a_group_of_selectors(pseudo_class.argument_selector_list))));
  215. TRY(s.try_append(')'));
  216. }
  217. }
  218. // If the pseudo-class does not accept arguments append ":" (U+003A), followed by the name of the pseudo-class, to s.
  219. else if (metadata.is_valid_as_identifier) {
  220. TRY(s.try_append(':'));
  221. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  222. }
  223. // Otherwise, append ":" (U+003A), followed by the name of the pseudo-class, followed by "(" (U+0028),
  224. // followed by the value of the pseudo-class argument(s) determined as per below, followed by ")" (U+0029), to s.
  225. else {
  226. TRY(s.try_append(':'));
  227. TRY(s.try_append(pseudo_class_name(pseudo_class.type)));
  228. TRY(s.try_append('('));
  229. if (pseudo_class.type == PseudoClass::NthChild
  230. || pseudo_class.type == PseudoClass::NthLastChild
  231. || pseudo_class.type == PseudoClass::NthOfType
  232. || pseudo_class.type == PseudoClass::NthLastOfType) {
  233. // The result of serializing the value using the rules to serialize an <an+b> value.
  234. TRY(s.try_append(TRY(pseudo_class.nth_child_pattern.serialize())));
  235. } else if (pseudo_class.type == PseudoClass::Not
  236. || pseudo_class.type == PseudoClass::Is
  237. || pseudo_class.type == PseudoClass::Where) {
  238. // The result of serializing the value using the rules for serializing a group of selectors.
  239. // NOTE: `:is()` and `:where()` aren't in the spec for this yet, but it should be!
  240. TRY(s.try_append(TRY(serialize_a_group_of_selectors(pseudo_class.argument_selector_list))));
  241. } else if (pseudo_class.type == PseudoClass::Lang) {
  242. // The serialization of a comma-separated list of each argument’s serialization as a string, preserving relative order.
  243. s.join(", "sv, pseudo_class.languages);
  244. }
  245. TRY(s.try_append(')'));
  246. }
  247. break;
  248. }
  249. case Selector::SimpleSelector::Type::PseudoElement:
  250. // Note: Pseudo-elements are dealt with in Selector::serialize()
  251. break;
  252. default:
  253. dbgln("FIXME: Unsupported simple selector serialization for type {}", to_underlying(type));
  254. break;
  255. }
  256. return s.to_string();
  257. }
  258. // https://www.w3.org/TR/cssom/#serialize-a-selector
  259. ErrorOr<String> Selector::serialize() const
  260. {
  261. StringBuilder s;
  262. // 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:
  263. for (size_t i = 0; i < compound_selectors().size(); ++i) {
  264. auto const& compound_selector = compound_selectors()[i];
  265. // 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.
  266. if (compound_selector.simple_selectors.size() == 1
  267. && compound_selector.simple_selectors.first().type == Selector::SimpleSelector::Type::Universal) {
  268. TRY(s.try_append(TRY(compound_selector.simple_selectors.first().serialize())));
  269. }
  270. // 2. Otherwise, for each simple selector in the compound selectors that is not a universal selector
  271. // of which the namespace prefix maps to a namespace that is not the default namespace
  272. // serialize the simple selector and append the result to s.
  273. else {
  274. for (auto& simple_selector : compound_selector.simple_selectors) {
  275. if (simple_selector.type == SimpleSelector::Type::Universal) {
  276. auto qualified_name = simple_selector.qualified_name();
  277. if (qualified_name.namespace_type == SimpleSelector::QualifiedName::NamespaceType::Default)
  278. continue;
  279. // FIXME: I *think* if we have a namespace prefix that happens to equal the same as the default namespace,
  280. // we also should skip it. But we don't have access to that here. eg:
  281. // <style>
  282. // @namespace "http://example";
  283. // @namespace foo "http://example";
  284. // foo|*.bar { } /* This would skip the `foo|*` when serializing. */
  285. // </style>
  286. }
  287. TRY(s.try_append(TRY(simple_selector.serialize())));
  288. }
  289. }
  290. // 3. If this is not the last part of the chain of the selector append a single SPACE (U+0020),
  291. // followed by the combinator ">", "+", "~", ">>", "||", as appropriate, followed by another
  292. // single SPACE (U+0020) if the combinator was not whitespace, to s.
  293. if (i != compound_selectors().size() - 1) {
  294. TRY(s.try_append(' '));
  295. // Note: The combinator that appears between parts `i` and `i+1` appears with the `i+1` selector,
  296. // so we have to check that one.
  297. switch (compound_selectors()[i + 1].combinator) {
  298. case Selector::Combinator::ImmediateChild:
  299. TRY(s.try_append("> "sv));
  300. break;
  301. case Selector::Combinator::NextSibling:
  302. TRY(s.try_append("+ "sv));
  303. break;
  304. case Selector::Combinator::SubsequentSibling:
  305. TRY(s.try_append("~ "sv));
  306. break;
  307. case Selector::Combinator::Column:
  308. TRY(s.try_append("|| "sv));
  309. break;
  310. default:
  311. break;
  312. }
  313. } else {
  314. // 4. If this is the last part of the chain of the selector and there is a pseudo-element,
  315. // append "::" followed by the name of the pseudo-element, to s.
  316. if (compound_selector.simple_selectors.last().type == Selector::SimpleSelector::Type::PseudoElement) {
  317. TRY(s.try_append("::"sv));
  318. TRY(s.try_append(pseudo_element_name(compound_selector.simple_selectors.last().pseudo_element())));
  319. }
  320. }
  321. }
  322. return s.to_string();
  323. }
  324. // https://www.w3.org/TR/cssom/#serialize-a-group-of-selectors
  325. ErrorOr<String> serialize_a_group_of_selectors(Vector<NonnullRefPtr<Selector>> const& selectors)
  326. {
  327. // To serialize a group of selectors serialize each selector in the group of selectors and then serialize a comma-separated list of these serializations.
  328. return String::join(", "sv, selectors);
  329. }
  330. Optional<Selector::PseudoElement> pseudo_element_from_string(StringView name)
  331. {
  332. if (name.equals_ignoring_ascii_case("after"sv)) {
  333. return Selector::PseudoElement::After;
  334. } else if (name.equals_ignoring_ascii_case("before"sv)) {
  335. return Selector::PseudoElement::Before;
  336. } else if (name.equals_ignoring_ascii_case("first-letter"sv)) {
  337. return Selector::PseudoElement::FirstLetter;
  338. } else if (name.equals_ignoring_ascii_case("first-line"sv)) {
  339. return Selector::PseudoElement::FirstLine;
  340. } else if (name.equals_ignoring_ascii_case("marker"sv)) {
  341. return Selector::PseudoElement::Marker;
  342. } else if (name.equals_ignoring_ascii_case("-webkit-progress-bar"sv)) {
  343. return Selector::PseudoElement::ProgressBar;
  344. } else if (name.equals_ignoring_ascii_case("-webkit-progress-value"sv)) {
  345. return Selector::PseudoElement::ProgressValue;
  346. } else if (name.equals_ignoring_ascii_case("placeholder"sv)) {
  347. return Selector::PseudoElement::Placeholder;
  348. } else if (name.equals_ignoring_ascii_case("selection"sv)) {
  349. return Selector::PseudoElement::Selection;
  350. }
  351. return {};
  352. }
  353. }