Selector.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2024, Sam Atkins <sam@ladybird.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/FlyString.h>
  9. #include <AK/RefCounted.h>
  10. #include <AK/String.h>
  11. #include <AK/Vector.h>
  12. #include <LibWeb/CSS/Keyword.h>
  13. #include <LibWeb/CSS/Parser/ComponentValue.h>
  14. #include <LibWeb/CSS/PseudoClass.h>
  15. namespace Web::CSS {
  16. using SelectorList = Vector<NonnullRefPtr<class Selector>>;
  17. // This is a <complex-selector> in the spec. https://www.w3.org/TR/selectors-4/#complex
  18. class Selector : public RefCounted<Selector> {
  19. public:
  20. class PseudoElement {
  21. public:
  22. enum class Type : u8 {
  23. Before,
  24. After,
  25. FirstLine,
  26. FirstLetter,
  27. Marker,
  28. MeterBar,
  29. MeterEvenLessGoodValue,
  30. MeterOptimumValue,
  31. MeterSuboptimumValue,
  32. ProgressValue,
  33. ProgressBar,
  34. Placeholder,
  35. Selection,
  36. SliderRunnableTrack,
  37. SliderThumb,
  38. Backdrop,
  39. FileSelectorButton,
  40. // Keep this last.
  41. KnownPseudoElementCount,
  42. // https://www.w3.org/TR/selectors-4/#compat
  43. // NOTE: This is not last as the 'unknown -webkit- pseudo-elements' are not stored as part of any Element.
  44. UnknownWebKit,
  45. };
  46. explicit PseudoElement(Type type)
  47. : m_type(type)
  48. {
  49. VERIFY(type != Type::UnknownWebKit);
  50. }
  51. PseudoElement(Type type, String name)
  52. : m_type(type)
  53. , m_name(move(name))
  54. {
  55. }
  56. bool operator==(PseudoElement const&) const = default;
  57. static Optional<PseudoElement> from_string(FlyString const&);
  58. static StringView name(Selector::PseudoElement::Type pseudo_element);
  59. StringView name() const
  60. {
  61. if (!m_name.is_empty())
  62. return m_name;
  63. return name(m_type);
  64. }
  65. Type type() const { return m_type; }
  66. private:
  67. Type m_type;
  68. String m_name;
  69. };
  70. struct SimpleSelector {
  71. enum class Type : u8 {
  72. Universal,
  73. TagName,
  74. Id,
  75. Class,
  76. Attribute,
  77. PseudoClass,
  78. PseudoElement,
  79. Nesting,
  80. Invalid,
  81. };
  82. struct ANPlusBPattern {
  83. int step_size { 0 }; // "A"
  84. int offset = { 0 }; // "B"
  85. // https://www.w3.org/TR/css-syntax-3/#serializing-anb
  86. String serialize() const
  87. {
  88. // 1. If A is zero, return the serialization of B.
  89. if (step_size == 0) {
  90. return String::number(offset);
  91. }
  92. // 2. Otherwise, let result initially be an empty string.
  93. StringBuilder result;
  94. // 3.
  95. // - A is 1: Append "n" to result.
  96. if (step_size == 1)
  97. result.append('n');
  98. // - A is -1: Append "-n" to result.
  99. else if (step_size == -1)
  100. result.append("-n"sv);
  101. // - A is non-zero: Serialize A and append it to result, then append "n" to result.
  102. else if (step_size != 0)
  103. result.appendff("{}n", step_size);
  104. // 4.
  105. // - B is greater than zero: Append "+" to result, then append the serialization of B to result.
  106. if (offset > 0)
  107. result.appendff("+{}", offset);
  108. // - B is less than zero: Append the serialization of B to result.
  109. if (offset < 0)
  110. result.appendff("{}", offset);
  111. // 5. Return result.
  112. return MUST(result.to_string());
  113. }
  114. };
  115. struct PseudoClassSelector {
  116. PseudoClass type;
  117. // FIXME: We don't need this field on every single SimpleSelector, but it's also annoying to malloc it somewhere.
  118. // Only used when "pseudo_class" is "NthChild" or "NthLastChild".
  119. ANPlusBPattern nth_child_pattern {};
  120. // FIXME: This would make more sense as part of SelectorList but that's currently a `using`
  121. bool is_forgiving { false };
  122. SelectorList argument_selector_list {};
  123. // Used for :lang(en-gb,dk)
  124. Vector<FlyString> languages {};
  125. // Used by :dir()
  126. Optional<Keyword> keyword {};
  127. };
  128. struct Name {
  129. Name(FlyString n)
  130. : name(move(n))
  131. , lowercase_name(name.to_string().to_lowercase().release_value_but_fixme_should_propagate_errors())
  132. {
  133. }
  134. FlyString name;
  135. FlyString lowercase_name;
  136. };
  137. // Equivalent to `<wq-name>`
  138. // https://www.w3.org/TR/selectors-4/#typedef-wq-name
  139. struct QualifiedName {
  140. enum class NamespaceType {
  141. Default, // `E`
  142. None, // `|E`
  143. Any, // `*|E`
  144. Named, // `ns|E`
  145. };
  146. NamespaceType namespace_type { NamespaceType::Default };
  147. FlyString namespace_ {};
  148. Name name;
  149. };
  150. struct Attribute {
  151. enum class MatchType {
  152. HasAttribute,
  153. ExactValueMatch,
  154. ContainsWord, // [att~=val]
  155. ContainsString, // [att*=val]
  156. StartsWithSegment, // [att|=val]
  157. StartsWithString, // [att^=val]
  158. EndsWithString, // [att$=val]
  159. };
  160. enum class CaseType {
  161. DefaultMatch,
  162. CaseSensitiveMatch,
  163. CaseInsensitiveMatch,
  164. };
  165. MatchType match_type;
  166. QualifiedName qualified_name;
  167. String value {};
  168. CaseType case_type;
  169. };
  170. struct Invalid {
  171. Vector<Parser::ComponentValue> component_values;
  172. };
  173. Type type;
  174. Variant<Empty, Attribute, PseudoClassSelector, PseudoElement, Name, QualifiedName, Invalid> value {};
  175. Attribute const& attribute() const { return value.get<Attribute>(); }
  176. Attribute& attribute() { return value.get<Attribute>(); }
  177. PseudoClassSelector const& pseudo_class() const { return value.get<PseudoClassSelector>(); }
  178. PseudoClassSelector& pseudo_class() { return value.get<PseudoClassSelector>(); }
  179. PseudoElement const& pseudo_element() const { return value.get<PseudoElement>(); }
  180. PseudoElement& pseudo_element() { return value.get<PseudoElement>(); }
  181. FlyString const& name() const { return value.get<Name>().name; }
  182. FlyString& name() { return value.get<Name>().name; }
  183. FlyString const& lowercase_name() const { return value.get<Name>().lowercase_name; }
  184. FlyString& lowercase_name() { return value.get<Name>().lowercase_name; }
  185. QualifiedName const& qualified_name() const { return value.get<QualifiedName>(); }
  186. QualifiedName& qualified_name() { return value.get<QualifiedName>(); }
  187. String serialize() const;
  188. Optional<SimpleSelector> absolutized(SimpleSelector const& selector_for_nesting) const;
  189. };
  190. enum class Combinator {
  191. None,
  192. ImmediateChild, // >
  193. Descendant, // <whitespace>
  194. NextSibling, // +
  195. SubsequentSibling, // ~
  196. Column, // ||
  197. };
  198. struct CompoundSelector {
  199. // Spec-wise, the <combinator> is not part of a <compound-selector>,
  200. // but it is more understandable to put them together.
  201. Combinator combinator { Combinator::None };
  202. Vector<SimpleSelector> simple_selectors;
  203. Optional<CompoundSelector> absolutized(SimpleSelector const& selector_for_nesting) const;
  204. };
  205. static NonnullRefPtr<Selector> create(Vector<CompoundSelector>&& compound_selectors)
  206. {
  207. return adopt_ref(*new Selector(move(compound_selectors)));
  208. }
  209. ~Selector() = default;
  210. Vector<CompoundSelector> const& compound_selectors() const { return m_compound_selectors; }
  211. Optional<PseudoElement> const& pseudo_element() const { return m_pseudo_element; }
  212. NonnullRefPtr<Selector> relative_to(SimpleSelector const&) const;
  213. bool contains_the_nesting_selector() const { return m_contains_the_nesting_selector; }
  214. RefPtr<Selector> absolutized(SimpleSelector const& selector_for_nesting) const;
  215. u32 specificity() const;
  216. String serialize() const;
  217. auto const& ancestor_hashes() const { return m_ancestor_hashes; }
  218. private:
  219. explicit Selector(Vector<CompoundSelector>&&);
  220. Vector<CompoundSelector> m_compound_selectors;
  221. mutable Optional<u32> m_specificity;
  222. Optional<Selector::PseudoElement> m_pseudo_element;
  223. bool m_contains_the_nesting_selector { false };
  224. void collect_ancestor_hashes();
  225. Array<u32, 8> m_ancestor_hashes;
  226. };
  227. String serialize_a_group_of_selectors(SelectorList const& selectors);
  228. SelectorList adapt_nested_relative_selector_list(SelectorList const&);
  229. bool is_has_allowed_pseudo_element(Selector::PseudoElement::Type);
  230. }
  231. namespace AK {
  232. template<>
  233. struct Formatter<Web::CSS::Selector> : Formatter<StringView> {
  234. ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Selector const& selector)
  235. {
  236. return Formatter<StringView>::format(builder, selector.serialize());
  237. }
  238. };
  239. }