Selector.h 9.4 KB

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