Selector.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. #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/PseudoClass.h>
  13. #include <LibWeb/CSS/ValueID.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 {
  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 {
  70. Universal,
  71. TagName,
  72. Id,
  73. Class,
  74. Attribute,
  75. PseudoClass,
  76. PseudoElement,
  77. };
  78. struct ANPlusBPattern {
  79. int step_size { 0 }; // "A"
  80. int offset = { 0 }; // "B"
  81. // https://www.w3.org/TR/css-syntax-3/#serializing-anb
  82. String serialize() const
  83. {
  84. // 1. If A is zero, return the serialization of B.
  85. if (step_size == 0) {
  86. return MUST(String::number(offset));
  87. }
  88. // 2. Otherwise, let result initially be an empty string.
  89. StringBuilder result;
  90. // 3.
  91. // - A is 1: Append "n" to result.
  92. if (step_size == 1)
  93. result.append('n');
  94. // - A is -1: Append "-n" to result.
  95. else if (step_size == -1)
  96. result.append("-n"sv);
  97. // - A is non-zero: Serialize A and append it to result, then append "n" to result.
  98. else if (step_size != 0)
  99. result.appendff("{}n", step_size);
  100. // 4.
  101. // - B is greater than zero: Append "+" to result, then append the serialization of B to result.
  102. if (offset > 0)
  103. result.appendff("+{}", offset);
  104. // - B is less than zero: Append the serialization of B to result.
  105. if (offset < 0)
  106. result.appendff("{}", offset);
  107. // 5. Return result.
  108. return MUST(result.to_string());
  109. }
  110. };
  111. struct PseudoClassSelector {
  112. PseudoClass type;
  113. // FIXME: We don't need this field on every single SimpleSelector, but it's also annoying to malloc it somewhere.
  114. // Only used when "pseudo_class" is "NthChild" or "NthLastChild".
  115. ANPlusBPattern nth_child_pattern {};
  116. SelectorList argument_selector_list {};
  117. // Used for :lang(en-gb,dk)
  118. Vector<FlyString> languages {};
  119. // Used by :dir()
  120. Optional<ValueID> identifier {};
  121. };
  122. struct Name {
  123. Name(FlyString n)
  124. : name(move(n))
  125. , lowercase_name(name.to_string().to_lowercase().release_value_but_fixme_should_propagate_errors())
  126. {
  127. }
  128. FlyString name;
  129. FlyString lowercase_name;
  130. };
  131. // Equivalent to `<wq-name>`
  132. // https://www.w3.org/TR/selectors-4/#typedef-wq-name
  133. struct QualifiedName {
  134. enum class NamespaceType {
  135. Default, // `E`
  136. None, // `|E`
  137. Any, // `*|E`
  138. Named, // `ns|E`
  139. };
  140. NamespaceType namespace_type { NamespaceType::Default };
  141. FlyString namespace_ {};
  142. Name name;
  143. };
  144. struct Attribute {
  145. enum class MatchType {
  146. HasAttribute,
  147. ExactValueMatch,
  148. ContainsWord, // [att~=val]
  149. ContainsString, // [att*=val]
  150. StartsWithSegment, // [att|=val]
  151. StartsWithString, // [att^=val]
  152. EndsWithString, // [att$=val]
  153. };
  154. enum class CaseType {
  155. DefaultMatch,
  156. CaseSensitiveMatch,
  157. CaseInsensitiveMatch,
  158. };
  159. MatchType match_type;
  160. QualifiedName qualified_name;
  161. String value {};
  162. CaseType case_type;
  163. };
  164. Type type;
  165. Variant<Empty, Attribute, PseudoClassSelector, PseudoElement, Name, QualifiedName> value {};
  166. Attribute const& attribute() const { return value.get<Attribute>(); }
  167. Attribute& attribute() { return value.get<Attribute>(); }
  168. PseudoClassSelector const& pseudo_class() const { return value.get<PseudoClassSelector>(); }
  169. PseudoClassSelector& pseudo_class() { return value.get<PseudoClassSelector>(); }
  170. PseudoElement const& pseudo_element() const { return value.get<PseudoElement>(); }
  171. PseudoElement& pseudo_element() { return value.get<PseudoElement>(); }
  172. FlyString const& name() const { return value.get<Name>().name; }
  173. FlyString& name() { return value.get<Name>().name; }
  174. FlyString const& lowercase_name() const { return value.get<Name>().lowercase_name; }
  175. FlyString& lowercase_name() { return value.get<Name>().lowercase_name; }
  176. QualifiedName const& qualified_name() const { return value.get<QualifiedName>(); }
  177. QualifiedName& qualified_name() { return value.get<QualifiedName>(); }
  178. String serialize() const;
  179. };
  180. enum class Combinator {
  181. None,
  182. ImmediateChild, // >
  183. Descendant, // <whitespace>
  184. NextSibling, // +
  185. SubsequentSibling, // ~
  186. Column, // ||
  187. };
  188. struct CompoundSelector {
  189. // Spec-wise, the <combinator> is not part of a <compound-selector>,
  190. // but it is more understandable to put them together.
  191. Combinator combinator { Combinator::None };
  192. Vector<SimpleSelector> simple_selectors;
  193. };
  194. static NonnullRefPtr<Selector> create(Vector<CompoundSelector>&& compound_selectors)
  195. {
  196. return adopt_ref(*new Selector(move(compound_selectors)));
  197. }
  198. ~Selector() = default;
  199. Vector<CompoundSelector> const& compound_selectors() const { return m_compound_selectors; }
  200. Optional<PseudoElement> pseudo_element() const { return m_pseudo_element; }
  201. u32 specificity() const;
  202. String serialize() const;
  203. auto const& ancestor_hashes() const { return m_ancestor_hashes; }
  204. private:
  205. explicit Selector(Vector<CompoundSelector>&&);
  206. Vector<CompoundSelector> m_compound_selectors;
  207. mutable Optional<u32> m_specificity;
  208. Optional<Selector::PseudoElement> m_pseudo_element;
  209. void collect_ancestor_hashes();
  210. Array<u32, 8> m_ancestor_hashes;
  211. };
  212. String serialize_a_group_of_selectors(Vector<NonnullRefPtr<Selector>> const& selectors);
  213. }
  214. namespace AK {
  215. template<>
  216. struct Formatter<Web::CSS::Selector> : Formatter<StringView> {
  217. ErrorOr<void> format(FormatBuilder& builder, Web::CSS::Selector const& selector)
  218. {
  219. return Formatter<StringView>::format(builder, selector.serialize());
  220. }
  221. };
  222. }