Selector.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. collect_ancestor_hashes();
  24. }
  25. void Selector::collect_ancestor_hashes()
  26. {
  27. size_t next_hash_index = 0;
  28. auto append_unique_hash = [&](u32 hash) -> bool {
  29. if (next_hash_index >= m_ancestor_hashes.size())
  30. return true;
  31. for (size_t i = 0; i < next_hash_index; ++i) {
  32. if (m_ancestor_hashes[i] == hash)
  33. return false;
  34. }
  35. m_ancestor_hashes[next_hash_index++] = hash;
  36. return false;
  37. };
  38. auto last_combinator = m_compound_selectors.last().combinator;
  39. for (ssize_t compound_selector_index = static_cast<ssize_t>(m_compound_selectors.size()) - 2; compound_selector_index >= 0; --compound_selector_index) {
  40. auto const& compound_selector = m_compound_selectors[compound_selector_index];
  41. if (last_combinator == Combinator::Descendant) {
  42. for (auto const& simple_selector : compound_selector.simple_selectors) {
  43. switch (simple_selector.type) {
  44. case SimpleSelector::Type::Id:
  45. case SimpleSelector::Type::Class:
  46. if (append_unique_hash(simple_selector.name().hash()))
  47. return;
  48. break;
  49. case SimpleSelector::Type::TagName:
  50. if (append_unique_hash(simple_selector.qualified_name().name.name.hash()))
  51. return;
  52. break;
  53. case SimpleSelector::Type::Attribute:
  54. if (append_unique_hash(simple_selector.attribute().qualified_name.name.name.hash()))
  55. return;
  56. break;
  57. default:
  58. break;
  59. }
  60. }
  61. }
  62. last_combinator = compound_selector.combinator;
  63. }
  64. for (size_t i = next_hash_index; i < m_ancestor_hashes.size(); ++i)
  65. m_ancestor_hashes[i] = 0;
  66. }
  67. // https://www.w3.org/TR/selectors-4/#specificity-rules
  68. u32 Selector::specificity() const
  69. {
  70. if (m_specificity.has_value())
  71. return *m_specificity;
  72. constexpr u32 ids_shift = 16;
  73. constexpr u32 classes_shift = 8;
  74. constexpr u32 tag_names_shift = 0;
  75. constexpr u32 ids_mask = 0xff << ids_shift;
  76. constexpr u32 classes_mask = 0xff << classes_shift;
  77. constexpr u32 tag_names_mask = 0xff << tag_names_shift;
  78. u32 ids = 0;
  79. u32 classes = 0;
  80. u32 tag_names = 0;
  81. auto count_specificity_of_most_complex_selector = [&](auto& selector_list) {
  82. u32 max_selector_list_argument_specificity = 0;
  83. for (auto const& complex_selector : selector_list) {
  84. max_selector_list_argument_specificity = max(max_selector_list_argument_specificity, complex_selector->specificity());
  85. }
  86. u32 child_ids = (max_selector_list_argument_specificity & ids_mask) >> ids_shift;
  87. u32 child_classes = (max_selector_list_argument_specificity & classes_mask) >> classes_shift;
  88. u32 child_tag_names = (max_selector_list_argument_specificity & tag_names_mask) >> tag_names_shift;
  89. ids += child_ids;
  90. classes += child_classes;
  91. tag_names += child_tag_names;
  92. };
  93. for (auto& list : m_compound_selectors) {
  94. for (auto& simple_selector : list.simple_selectors) {
  95. switch (simple_selector.type) {
  96. case SimpleSelector::Type::Id:
  97. // count the number of ID selectors in the selector (= A)
  98. ++ids;
  99. break;
  100. case SimpleSelector::Type::Class:
  101. case SimpleSelector::Type::Attribute:
  102. // count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= B)
  103. ++classes;
  104. break;
  105. case SimpleSelector::Type::PseudoClass: {
  106. auto& pseudo_class = simple_selector.pseudo_class();
  107. switch (pseudo_class.type) {
  108. case PseudoClass::Is:
  109. case PseudoClass::Not: {
  110. // The specificity of an :is(), :not(), or :has() pseudo-class is replaced by the
  111. // specificity of the most specific complex selector in its selector list argument.
  112. count_specificity_of_most_complex_selector(pseudo_class.argument_selector_list);
  113. break;
  114. }
  115. case PseudoClass::NthChild:
  116. case PseudoClass::NthLastChild: {
  117. // Analogously, the specificity of an :nth-child() or :nth-last-child() selector
  118. // is the specificity of the pseudo class itself (counting as one pseudo-class selector)
  119. // plus the specificity of the most specific complex selector in its selector list argument (if any).
  120. ++classes;
  121. count_specificity_of_most_complex_selector(pseudo_class.argument_selector_list);
  122. break;
  123. }
  124. case PseudoClass::Where:
  125. // The specificity of a :where() pseudo-class is replaced by zero.
  126. break;
  127. default:
  128. ++classes;
  129. break;
  130. }
  131. break;
  132. }
  133. case SimpleSelector::Type::TagName:
  134. case SimpleSelector::Type::PseudoElement:
  135. // count the number of type selectors and pseudo-elements in the selector (= C)
  136. ++tag_names;
  137. break;
  138. case SimpleSelector::Type::Universal:
  139. // ignore the universal selector
  140. break;
  141. }
  142. }
  143. }
  144. // Due to storage limitations, implementations may have limitations on the size of A, B, or C.
  145. // If so, values higher than the limit must be clamped to that limit, and not overflow.
  146. m_specificity = (min(ids, 0xff) << ids_shift)
  147. + (min(classes, 0xff) << classes_shift)
  148. + (min(tag_names, 0xff) << tag_names_shift);
  149. return *m_specificity;
  150. }
  151. // https://www.w3.org/TR/cssom/#serialize-a-simple-selector
  152. String Selector::SimpleSelector::serialize() const
  153. {
  154. StringBuilder s;
  155. switch (type) {
  156. case Selector::SimpleSelector::Type::TagName:
  157. case Selector::SimpleSelector::Type::Universal: {
  158. auto qualified_name = this->qualified_name();
  159. // 1. If the namespace prefix maps to a namespace that is not the default namespace and is not the null
  160. // namespace (not in a namespace) append the serialization of the namespace prefix as an identifier,
  161. // followed by a "|" (U+007C) to s.
  162. if (qualified_name.namespace_type == QualifiedName::NamespaceType::Named) {
  163. serialize_an_identifier(s, qualified_name.namespace_);
  164. s.append('|');
  165. }
  166. // 2. If the namespace prefix maps to a namespace that is the null namespace (not in a namespace)
  167. // append "|" (U+007C) to s.
  168. if (qualified_name.namespace_type == QualifiedName::NamespaceType::None)
  169. s.append('|');
  170. // 3. If this is a type selector append the serialization of the element name as an identifier to s.
  171. if (type == Selector::SimpleSelector::Type::TagName)
  172. serialize_an_identifier(s, qualified_name.name.name);
  173. // 4. If this is a universal selector append "*" (U+002A) to s.
  174. if (type == Selector::SimpleSelector::Type::Universal)
  175. s.append('*');
  176. break;
  177. }
  178. case Selector::SimpleSelector::Type::Attribute: {
  179. auto& attribute = this->attribute();
  180. // 1. Append "[" (U+005B) to s.
  181. s.append('[');
  182. // 2. If the namespace prefix maps to a namespace that is not the null namespace (not in a namespace)
  183. // append the serialization of the namespace prefix as an identifier, followed by a "|" (U+007C) to s.
  184. if (attribute.qualified_name.namespace_type == QualifiedName::NamespaceType::Named) {
  185. serialize_an_identifier(s, attribute.qualified_name.namespace_);
  186. s.append('|');
  187. }
  188. // 3. Append the serialization of the attribute name as an identifier to s.
  189. serialize_an_identifier(s, attribute.qualified_name.name.name);
  190. // 4. If there is an attribute value specified, append "=", "~=", "|=", "^=", "$=", or "*=" as appropriate (depending on the type of attribute selector),
  191. // followed by the serialization of the attribute value as a string, to s.
  192. if (!attribute.value.is_empty()) {
  193. switch (attribute.match_type) {
  194. case Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch:
  195. s.append("="sv);
  196. break;
  197. case Selector::SimpleSelector::Attribute::MatchType::ContainsWord:
  198. s.append("~="sv);
  199. break;
  200. case Selector::SimpleSelector::Attribute::MatchType::ContainsString:
  201. s.append("*="sv);
  202. break;
  203. case Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment:
  204. s.append("|="sv);
  205. break;
  206. case Selector::SimpleSelector::Attribute::MatchType::StartsWithString:
  207. s.append("^="sv);
  208. break;
  209. case Selector::SimpleSelector::Attribute::MatchType::EndsWithString:
  210. s.append("$="sv);
  211. break;
  212. default:
  213. break;
  214. }
  215. serialize_a_string(s, attribute.value);
  216. }
  217. // 5. If the attribute selector has the case-insensitivity flag present, append " i" (U+0020 U+0069) to s.
  218. // If the attribute selector has the case-insensitivity flag present, append " s" (U+0020 U+0073) to s.
  219. // (the line just above is an addition to CSS OM to match Selectors Level 4 last draft)
  220. switch (attribute.case_type) {
  221. case Selector::SimpleSelector::Attribute::CaseType::CaseInsensitiveMatch:
  222. s.append(" i"sv);
  223. break;
  224. case Selector::SimpleSelector::Attribute::CaseType::CaseSensitiveMatch:
  225. s.append(" s"sv);
  226. break;
  227. default:
  228. break;
  229. }
  230. // 6. Append "]" (U+005D) to s.
  231. s.append(']');
  232. break;
  233. }
  234. case Selector::SimpleSelector::Type::Class:
  235. // Append a "." (U+002E), followed by the serialization of the class name as an identifier to s.
  236. s.append('.');
  237. serialize_an_identifier(s, name());
  238. break;
  239. case Selector::SimpleSelector::Type::Id:
  240. // Append a "#" (U+0023), followed by the serialization of the ID as an identifier to s.
  241. s.append('#');
  242. serialize_an_identifier(s, name());
  243. break;
  244. case Selector::SimpleSelector::Type::PseudoClass: {
  245. auto& pseudo_class = this->pseudo_class();
  246. auto metadata = pseudo_class_metadata(pseudo_class.type);
  247. // HACK: `:host()` has both a function and a non-function form, so handle that first.
  248. // It's also not in the spec.
  249. if (pseudo_class.type == PseudoClass::Host) {
  250. if (pseudo_class.argument_selector_list.is_empty()) {
  251. s.append(':');
  252. s.append(pseudo_class_name(pseudo_class.type));
  253. } else {
  254. s.append(':');
  255. s.append(pseudo_class_name(pseudo_class.type));
  256. s.append('(');
  257. s.append(serialize_a_group_of_selectors(pseudo_class.argument_selector_list));
  258. s.append(')');
  259. }
  260. }
  261. // If the pseudo-class does not accept arguments append ":" (U+003A), followed by the name of the pseudo-class, to s.
  262. else if (metadata.is_valid_as_identifier) {
  263. s.append(':');
  264. s.append(pseudo_class_name(pseudo_class.type));
  265. }
  266. // Otherwise, append ":" (U+003A), followed by the name of the pseudo-class, followed by "(" (U+0028),
  267. // followed by the value of the pseudo-class argument(s) determined as per below, followed by ")" (U+0029), to s.
  268. else {
  269. s.append(':');
  270. s.append(pseudo_class_name(pseudo_class.type));
  271. s.append('(');
  272. if (pseudo_class.type == PseudoClass::NthChild
  273. || pseudo_class.type == PseudoClass::NthLastChild
  274. || pseudo_class.type == PseudoClass::NthOfType
  275. || pseudo_class.type == PseudoClass::NthLastOfType) {
  276. // The result of serializing the value using the rules to serialize an <an+b> value.
  277. s.append(pseudo_class.nth_child_pattern.serialize());
  278. } else if (pseudo_class.type == PseudoClass::Not
  279. || pseudo_class.type == PseudoClass::Is
  280. || pseudo_class.type == PseudoClass::Where) {
  281. // The result of serializing the value using the rules for serializing a group of selectors.
  282. // NOTE: `:is()` and `:where()` aren't in the spec for this yet, but it should be!
  283. s.append(serialize_a_group_of_selectors(pseudo_class.argument_selector_list));
  284. } else if (pseudo_class.type == PseudoClass::Lang) {
  285. // The serialization of a comma-separated list of each argument’s serialization as a string, preserving relative order.
  286. s.join(", "sv, pseudo_class.languages);
  287. }
  288. s.append(')');
  289. }
  290. break;
  291. }
  292. case Selector::SimpleSelector::Type::PseudoElement:
  293. // Note: Pseudo-elements are dealt with in Selector::serialize()
  294. break;
  295. default:
  296. dbgln("FIXME: Unsupported simple selector serialization for type {}", to_underlying(type));
  297. break;
  298. }
  299. return MUST(s.to_string());
  300. }
  301. // https://www.w3.org/TR/cssom/#serialize-a-selector
  302. String Selector::serialize() const
  303. {
  304. StringBuilder s;
  305. // 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:
  306. for (size_t i = 0; i < compound_selectors().size(); ++i) {
  307. auto const& compound_selector = compound_selectors()[i];
  308. // 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.
  309. if (compound_selector.simple_selectors.size() == 1
  310. && compound_selector.simple_selectors.first().type == Selector::SimpleSelector::Type::Universal) {
  311. s.append(compound_selector.simple_selectors.first().serialize());
  312. }
  313. // 2. Otherwise, for each simple selector in the compound selectors that is not a universal selector
  314. // of which the namespace prefix maps to a namespace that is not the default namespace
  315. // serialize the simple selector and append the result to s.
  316. else {
  317. for (auto& simple_selector : compound_selector.simple_selectors) {
  318. if (simple_selector.type == SimpleSelector::Type::Universal) {
  319. auto qualified_name = simple_selector.qualified_name();
  320. if (qualified_name.namespace_type == SimpleSelector::QualifiedName::NamespaceType::Default)
  321. continue;
  322. // FIXME: I *think* if we have a namespace prefix that happens to equal the same as the default namespace,
  323. // we also should skip it. But we don't have access to that here. eg:
  324. // <style>
  325. // @namespace "http://example";
  326. // @namespace foo "http://example";
  327. // foo|*.bar { } /* This would skip the `foo|*` when serializing. */
  328. // </style>
  329. }
  330. s.append(simple_selector.serialize());
  331. }
  332. }
  333. // 3. If this is not the last part of the chain of the selector append a single SPACE (U+0020),
  334. // followed by the combinator ">", "+", "~", ">>", "||", as appropriate, followed by another
  335. // single SPACE (U+0020) if the combinator was not whitespace, to s.
  336. if (i != compound_selectors().size() - 1) {
  337. s.append(' ');
  338. // Note: The combinator that appears between parts `i` and `i+1` appears with the `i+1` selector,
  339. // so we have to check that one.
  340. switch (compound_selectors()[i + 1].combinator) {
  341. case Selector::Combinator::ImmediateChild:
  342. s.append("> "sv);
  343. break;
  344. case Selector::Combinator::NextSibling:
  345. s.append("+ "sv);
  346. break;
  347. case Selector::Combinator::SubsequentSibling:
  348. s.append("~ "sv);
  349. break;
  350. case Selector::Combinator::Column:
  351. s.append("|| "sv);
  352. break;
  353. default:
  354. break;
  355. }
  356. } else {
  357. // 4. If this is the last part of the chain of the selector and there is a pseudo-element,
  358. // append "::" followed by the name of the pseudo-element, to s.
  359. if (compound_selector.simple_selectors.last().type == Selector::SimpleSelector::Type::PseudoElement) {
  360. s.append("::"sv);
  361. s.append(compound_selector.simple_selectors.last().pseudo_element().name());
  362. }
  363. }
  364. }
  365. return MUST(s.to_string());
  366. }
  367. // https://www.w3.org/TR/cssom/#serialize-a-group-of-selectors
  368. String serialize_a_group_of_selectors(Vector<NonnullRefPtr<Selector>> const& selectors)
  369. {
  370. // To serialize a group of selectors serialize each selector in the group of selectors and then serialize a comma-separated list of these serializations.
  371. return MUST(String::join(", "sv, selectors));
  372. }
  373. StringView Selector::PseudoElement::name(Selector::PseudoElement::Type pseudo_element)
  374. {
  375. switch (pseudo_element) {
  376. case Selector::PseudoElement::Type::Before:
  377. return "before"sv;
  378. case Selector::PseudoElement::Type::After:
  379. return "after"sv;
  380. case Selector::PseudoElement::Type::FirstLine:
  381. return "first-line"sv;
  382. case Selector::PseudoElement::Type::FirstLetter:
  383. return "first-letter"sv;
  384. case Selector::PseudoElement::Type::Marker:
  385. return "marker"sv;
  386. case Selector::PseudoElement::Type::MeterBar:
  387. return "-webkit-meter-bar"sv;
  388. case Selector::PseudoElement::Type::MeterEvenLessGoodValue:
  389. return "-webkit-meter-even-less-good-value"sv;
  390. case Selector::PseudoElement::Type::MeterOptimumValue:
  391. return "-webkit-meter-optimum-value"sv;
  392. case Selector::PseudoElement::Type::MeterSuboptimumValue:
  393. return "-webkit-meter-suboptimum-value"sv;
  394. case Selector::PseudoElement::Type::ProgressBar:
  395. return "-webkit-progress-bar"sv;
  396. case Selector::PseudoElement::Type::ProgressValue:
  397. return "-webkit-progress-value"sv;
  398. case Selector::PseudoElement::Type::Placeholder:
  399. return "placeholder"sv;
  400. case Selector::PseudoElement::Type::Selection:
  401. return "selection"sv;
  402. case Selector::PseudoElement::Type::SliderRunnableTrack:
  403. return "-webkit-slider-runnable-track"sv;
  404. case Selector::PseudoElement::Type::SliderThumb:
  405. return "-webkit-slider-thumb"sv;
  406. case Selector::PseudoElement::Type::Backdrop:
  407. return "backdrop"sv;
  408. case Selector::PseudoElement::Type::KnownPseudoElementCount:
  409. break;
  410. case Selector::PseudoElement::Type::UnknownWebKit:
  411. VERIFY_NOT_REACHED();
  412. }
  413. VERIFY_NOT_REACHED();
  414. }
  415. Optional<Selector::PseudoElement> Selector::PseudoElement::from_string(FlyString const& name)
  416. {
  417. if (name.equals_ignoring_ascii_case("after"sv)) {
  418. return Selector::PseudoElement { Selector::PseudoElement::Type::After };
  419. } else if (name.equals_ignoring_ascii_case("before"sv)) {
  420. return Selector::PseudoElement { Selector::PseudoElement::Type::Before };
  421. } else if (name.equals_ignoring_ascii_case("first-letter"sv)) {
  422. return Selector::PseudoElement { Selector::PseudoElement::Type::FirstLetter };
  423. } else if (name.equals_ignoring_ascii_case("first-line"sv)) {
  424. return Selector::PseudoElement { Selector::PseudoElement::Type::FirstLine };
  425. } else if (name.equals_ignoring_ascii_case("marker"sv)) {
  426. return Selector::PseudoElement { Selector::PseudoElement::Type::Marker };
  427. } else if (name.equals_ignoring_ascii_case("-webkit-meter-bar"sv)) {
  428. return Selector::PseudoElement { Selector::PseudoElement::Type::MeterBar };
  429. } else if (name.equals_ignoring_ascii_case("-webkit-meter-even-less-good-value"sv)) {
  430. return Selector::PseudoElement { Selector::PseudoElement::Type::MeterEvenLessGoodValue };
  431. } else if (name.equals_ignoring_ascii_case("-webkit-meter-optimum-value"sv)) {
  432. return Selector::PseudoElement { Selector::PseudoElement::Type::MeterOptimumValue };
  433. } else if (name.equals_ignoring_ascii_case("-webkit-meter-suboptimum-value"sv)) {
  434. return Selector::PseudoElement { Selector::PseudoElement::Type::MeterSuboptimumValue };
  435. } else if (name.equals_ignoring_ascii_case("-webkit-progress-bar"sv)) {
  436. return Selector::PseudoElement { Selector::PseudoElement::Type::ProgressBar };
  437. } else if (name.equals_ignoring_ascii_case("-webkit-progress-value"sv)) {
  438. return Selector::PseudoElement { Selector::PseudoElement::Type::ProgressValue };
  439. } else if (name.equals_ignoring_ascii_case("placeholder"sv)) {
  440. return Selector::PseudoElement { Selector::PseudoElement::Type::Placeholder };
  441. } else if (name.equals_ignoring_ascii_case("selection"sv)) {
  442. return Selector::PseudoElement { Selector::PseudoElement::Type::Selection };
  443. } else if (name.equals_ignoring_ascii_case("backdrop"sv)) {
  444. return Selector::PseudoElement { Selector::PseudoElement::Type::Backdrop };
  445. } else if (name.equals_ignoring_ascii_case("-webkit-slider-runnable-track"sv)) {
  446. return Selector::PseudoElement { Selector::PseudoElement::Type::SliderRunnableTrack };
  447. } else if (name.equals_ignoring_ascii_case("-webkit-slider-thumb"sv)) {
  448. return Selector::PseudoElement { Selector::PseudoElement::Type::SliderThumb };
  449. }
  450. return {};
  451. }
  452. }