Selector.h 9.4 KB

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