Selector.cpp 23 KB

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