ParentNode.cpp 9.7 KB

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