ParentNode.cpp 10 KB

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