ParentNode.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. * Copyright (c) 2020, Luke Wilde <lukew@serenityos.org>
  3. * Copyright (c) 2022, Andreas Kling <andreas@ladybird.org>
  4. * Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibWeb/CSS/Parser/Parser.h>
  9. #include <LibWeb/CSS/SelectorEngine.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/DOM/HTMLCollection.h>
  12. #include <LibWeb/DOM/NodeOperations.h>
  13. #include <LibWeb/DOM/ParentNode.h>
  14. #include <LibWeb/DOM/ShadowRoot.h>
  15. #include <LibWeb/DOM/StaticNodeList.h>
  16. #include <LibWeb/Dump.h>
  17. #include <LibWeb/Infra/CharacterTypes.h>
  18. #include <LibWeb/Infra/Strings.h>
  19. #include <LibWeb/Namespace.h>
  20. namespace Web::DOM {
  21. GC_DEFINE_ALLOCATOR(ParentNode);
  22. static bool contains_named_namespace(const CSS::SelectorList& selectors)
  23. {
  24. for (auto const& selector : selectors) {
  25. for (auto const& compound_selector : selector->compound_selectors()) {
  26. for (auto simple_selector : compound_selector.simple_selectors) {
  27. if (simple_selector.value.has<CSS::Selector::SimpleSelector::QualifiedName>()) {
  28. if (simple_selector.qualified_name().namespace_type == CSS::Selector::SimpleSelector::QualifiedName::NamespaceType::Named)
  29. return true;
  30. }
  31. if (simple_selector.value.has<CSS::Selector::SimpleSelector::PseudoClassSelector>()) {
  32. if (contains_named_namespace(simple_selector.pseudo_class().argument_selector_list))
  33. return true;
  34. }
  35. }
  36. }
  37. }
  38. return false;
  39. }
  40. enum class ReturnMatches {
  41. First,
  42. All,
  43. };
  44. // https://dom.spec.whatwg.org/#scope-match-a-selectors-string
  45. static WebIDL::ExceptionOr<Variant<GC::Ptr<Element>, GC::Ref<NodeList>>> scope_match_a_selectors_string(ParentNode& node, StringView selector_text, ReturnMatches return_matches)
  46. {
  47. // To scope-match a selectors string selectors against a node, run these steps:
  48. // 1. Let s be the result of parse a selector selectors.
  49. auto maybe_selectors = parse_selector(CSS::Parser::ParsingContext { node }, selector_text);
  50. // 2. If s is failure, then throw a "SyntaxError" DOMException.
  51. if (!maybe_selectors.has_value())
  52. return WebIDL::SyntaxError::create(node.realm(), "Failed to parse selector"_string);
  53. auto selectors = maybe_selectors.value();
  54. // "Note: Support for namespaces within selectors is not planned and will not be added."
  55. if (contains_named_namespace(selectors))
  56. return WebIDL::SyntaxError::create(node.realm(), "Failed to parse selector"_string);
  57. // 3. Return the result of match a selector against a tree with s and node’s root using scoping root node.
  58. GC::Ptr<Element> single_result;
  59. Vector<GC::Root<Node>> results;
  60. // FIXME: This should be shadow-including. https://drafts.csswg.org/selectors-4/#match-a-selector-against-a-tree
  61. node.for_each_in_subtree_of_type<Element>([&](auto& element) {
  62. for (auto& selector : selectors) {
  63. if (SelectorEngine::matches(selector, {}, element, nullptr, {}, node)) {
  64. if (return_matches == ReturnMatches::First) {
  65. single_result = &element;
  66. return TraversalDecision::Break;
  67. }
  68. results.append(element);
  69. break;
  70. }
  71. }
  72. return TraversalDecision::Continue;
  73. });
  74. if (return_matches == ReturnMatches::First)
  75. return { single_result };
  76. return { StaticNodeList::create(node.realm(), move(results)) };
  77. }
  78. // https://dom.spec.whatwg.org/#dom-parentnode-queryselector
  79. WebIDL::ExceptionOr<GC::Ptr<Element>> ParentNode::query_selector(StringView selector_text)
  80. {
  81. // The querySelector(selectors) method steps are to return the first result of running scope-match a selectors string selectors against this,
  82. // if the result is not an empty list; otherwise null.
  83. return TRY(scope_match_a_selectors_string(*this, selector_text, ReturnMatches::First)).get<GC::Ptr<Element>>();
  84. }
  85. // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
  86. WebIDL::ExceptionOr<GC::Ref<NodeList>> ParentNode::query_selector_all(StringView selector_text)
  87. {
  88. // The querySelectorAll(selectors) method steps are to return the static result of running scope-match a selectors string selectors against this.
  89. return TRY(scope_match_a_selectors_string(*this, selector_text, ReturnMatches::All)).get<GC::Ref<NodeList>>();
  90. }
  91. GC::Ptr<Element> ParentNode::first_element_child()
  92. {
  93. return first_child_of_type<Element>();
  94. }
  95. GC::Ptr<Element> ParentNode::last_element_child()
  96. {
  97. return last_child_of_type<Element>();
  98. }
  99. // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
  100. u32 ParentNode::child_element_count() const
  101. {
  102. u32 count = 0;
  103. for (auto* child = first_child(); child; child = child->next_sibling()) {
  104. if (is<Element>(child))
  105. ++count;
  106. }
  107. return count;
  108. }
  109. void ParentNode::visit_edges(Cell::Visitor& visitor)
  110. {
  111. Base::visit_edges(visitor);
  112. visitor.visit(m_children);
  113. }
  114. // https://dom.spec.whatwg.org/#dom-parentnode-children
  115. GC::Ref<HTMLCollection> ParentNode::children()
  116. {
  117. // The children getter steps are to return an HTMLCollection collection rooted at this matching only element children.
  118. if (!m_children) {
  119. m_children = HTMLCollection::create(*this, HTMLCollection::Scope::Children, [](Element const&) {
  120. return true;
  121. });
  122. }
  123. return *m_children;
  124. }
  125. // https://dom.spec.whatwg.org/#concept-getelementsbytagname
  126. // NOTE: This method is only exposed on Document and Element, but is in ParentNode to prevent code duplication.
  127. GC::Ref<HTMLCollection> ParentNode::get_elements_by_tag_name(FlyString const& qualified_name)
  128. {
  129. // 1. If qualifiedName is "*" (U+002A), return a HTMLCollection rooted at root, whose filter matches only descendant elements.
  130. if (qualified_name == "*") {
  131. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const&) {
  132. return true;
  133. });
  134. }
  135. // 2. Otherwise, if root’s node document is an HTML document, return a HTMLCollection rooted at root, whose filter matches the following descendant elements:
  136. if (root().document().document_type() == Document::Type::HTML) {
  137. FlyString qualified_name_in_ascii_lowercase = qualified_name.to_ascii_lowercase();
  138. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [qualified_name, qualified_name_in_ascii_lowercase](Element const& element) {
  139. // - Whose namespace is the HTML namespace and whose qualified name is qualifiedName, in ASCII lowercase.
  140. if (element.namespace_uri() == Namespace::HTML)
  141. return element.qualified_name() == qualified_name_in_ascii_lowercase;
  142. // - Whose namespace is not the HTML namespace and whose qualified name is qualifiedName.
  143. return element.qualified_name() == qualified_name;
  144. });
  145. }
  146. // 3. Otherwise, return a HTMLCollection rooted at root, whose filter matches descendant elements whose qualified name is qualifiedName.
  147. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [qualified_name](Element const& element) {
  148. return element.qualified_name() == qualified_name;
  149. });
  150. }
  151. // https://dom.spec.whatwg.org/#concept-getelementsbytagnamens
  152. // NOTE: This method is only exposed on Document and Element, but is in ParentNode to prevent code duplication.
  153. GC::Ref<HTMLCollection> ParentNode::get_elements_by_tag_name_ns(Optional<FlyString> namespace_, FlyString const& local_name)
  154. {
  155. // 1. If namespace is the empty string, set it to null.
  156. if (namespace_ == FlyString {})
  157. namespace_ = OptionalNone {};
  158. // 2. If both namespace and localName are "*" (U+002A), return a HTMLCollection rooted at root, whose filter matches descendant elements.
  159. if (namespace_ == "*" && local_name == "*") {
  160. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [](Element const&) {
  161. return true;
  162. });
  163. }
  164. // 3. Otherwise, if namespace is "*" (U+002A), return a HTMLCollection rooted at root, whose filter matches descendant elements whose local name is localName.
  165. if (namespace_ == "*") {
  166. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [local_name](Element const& element) {
  167. return element.local_name() == local_name;
  168. });
  169. }
  170. // 4. Otherwise, if localName is "*" (U+002A), return a HTMLCollection rooted at root, whose filter matches descendant elements whose namespace is namespace.
  171. if (local_name == "*") {
  172. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [namespace_](Element const& element) {
  173. return element.namespace_uri() == namespace_;
  174. });
  175. }
  176. // 5. Otherwise, return a HTMLCollection rooted at root, whose filter matches descendant elements whose namespace is namespace and local name is localName.
  177. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [namespace_, local_name](Element const& element) {
  178. return element.namespace_uri() == namespace_ && element.local_name() == local_name;
  179. });
  180. }
  181. // https://dom.spec.whatwg.org/#dom-parentnode-prepend
  182. WebIDL::ExceptionOr<void> ParentNode::prepend(Vector<Variant<GC::Root<Node>, String>> const& nodes)
  183. {
  184. // 1. Let node be the result of converting nodes into a node given nodes and this’s node document.
  185. auto node = TRY(convert_nodes_to_single_node(nodes, document()));
  186. // 2. Pre-insert node into this before this’s first child.
  187. (void)TRY(pre_insert(node, first_child()));
  188. return {};
  189. }
  190. WebIDL::ExceptionOr<void> ParentNode::append(Vector<Variant<GC::Root<Node>, String>> const& nodes)
  191. {
  192. // 1. Let node be the result of converting nodes into a node given nodes and this’s node document.
  193. auto node = TRY(convert_nodes_to_single_node(nodes, document()));
  194. // 2. Append node to this.
  195. (void)TRY(append_child(node));
  196. return {};
  197. }
  198. WebIDL::ExceptionOr<void> ParentNode::replace_children(Vector<Variant<GC::Root<Node>, String>> const& nodes)
  199. {
  200. // 1. Let node be the result of converting nodes into a node given nodes and this’s node document.
  201. auto node = TRY(convert_nodes_to_single_node(nodes, document()));
  202. // 2. Ensure pre-insertion validity of node into this before null.
  203. TRY(ensure_pre_insertion_validity(node, nullptr));
  204. // 3. Replace all with node within this.
  205. replace_all(*node);
  206. return {};
  207. }
  208. // https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname
  209. GC::Ref<HTMLCollection> ParentNode::get_elements_by_class_name(StringView class_names)
  210. {
  211. Vector<FlyString> list_of_class_names;
  212. for (auto& name : class_names.split_view_if(Infra::is_ascii_whitespace)) {
  213. list_of_class_names.append(FlyString::from_utf8(name).release_value_but_fixme_should_propagate_errors());
  214. }
  215. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [list_of_class_names = move(list_of_class_names), quirks_mode = document().in_quirks_mode()](Element const& element) {
  216. for (auto& name : list_of_class_names) {
  217. if (!element.has_class(name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive))
  218. return false;
  219. }
  220. return !list_of_class_names.is_empty();
  221. });
  222. }
  223. }