Selector.h 8.4 KB

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