ParentNode.cpp 11 KB

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