Node.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/StringBuilder.h>
  27. #include <LibJS/AST.h>
  28. #include <LibJS/Runtime/Function.h>
  29. #include <LibWeb/Bindings/EventWrapper.h>
  30. #include <LibWeb/Bindings/NodeWrapper.h>
  31. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  32. #include <LibWeb/DOM/Comment.h>
  33. #include <LibWeb/DOM/DocumentType.h>
  34. #include <LibWeb/DOM/Element.h>
  35. #include <LibWeb/DOM/Event.h>
  36. #include <LibWeb/DOM/EventDispatcher.h>
  37. #include <LibWeb/DOM/EventListener.h>
  38. #include <LibWeb/DOM/Node.h>
  39. #include <LibWeb/DOM/ProcessingInstruction.h>
  40. #include <LibWeb/DOM/ShadowRoot.h>
  41. #include <LibWeb/HTML/HTMLAnchorElement.h>
  42. #include <LibWeb/Layout/InitialContainingBlockBox.h>
  43. #include <LibWeb/Layout/Node.h>
  44. #include <LibWeb/Layout/TextNode.h>
  45. namespace Web::DOM {
  46. Node::Node(Document& document, NodeType type)
  47. : EventTarget(static_cast<Bindings::ScriptExecutionContext&>(document))
  48. , m_document(&document)
  49. , m_type(type)
  50. {
  51. if (!is_document())
  52. m_document->ref_from_node({});
  53. }
  54. Node::~Node()
  55. {
  56. VERIFY(m_deletion_has_begun);
  57. if (layout_node() && layout_node()->parent())
  58. layout_node()->parent()->remove_child(*layout_node());
  59. if (!is_document())
  60. m_document->unref_from_node({});
  61. }
  62. const HTML::HTMLAnchorElement* Node::enclosing_link_element() const
  63. {
  64. for (auto* node = this; node; node = node->parent()) {
  65. if (is<HTML::HTMLAnchorElement>(*node) && downcast<HTML::HTMLAnchorElement>(*node).has_attribute(HTML::AttributeNames::href))
  66. return downcast<HTML::HTMLAnchorElement>(node);
  67. }
  68. return nullptr;
  69. }
  70. const HTML::HTMLElement* Node::enclosing_html_element() const
  71. {
  72. return first_ancestor_of_type<HTML::HTMLElement>();
  73. }
  74. const HTML::HTMLElement* Node::enclosing_html_element_with_attribute(const FlyString& attribute) const
  75. {
  76. for (auto* node = this; node; node = node->parent()) {
  77. if (is<HTML::HTMLElement>(*node) && downcast<HTML::HTMLElement>(*node).has_attribute(attribute))
  78. return downcast<HTML::HTMLElement>(node);
  79. }
  80. return nullptr;
  81. }
  82. String Node::text_content() const
  83. {
  84. StringBuilder builder;
  85. for (auto* child = first_child(); child; child = child->next_sibling()) {
  86. builder.append(child->text_content());
  87. }
  88. return builder.to_string();
  89. }
  90. void Node::set_text_content(const String& content)
  91. {
  92. if (is_text()) {
  93. downcast<Text>(this)->set_data(content);
  94. } else {
  95. remove_all_children();
  96. append_child(document().create_text_node(content));
  97. }
  98. set_needs_style_update(true);
  99. document().invalidate_layout();
  100. }
  101. RefPtr<Layout::Node> Node::create_layout_node()
  102. {
  103. return nullptr;
  104. }
  105. void Node::invalidate_style()
  106. {
  107. for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) {
  108. element.set_needs_style_update(true);
  109. return IterationDecision::Continue;
  110. });
  111. document().schedule_style_update();
  112. }
  113. bool Node::is_link() const
  114. {
  115. return enclosing_link_element();
  116. }
  117. bool Node::dispatch_event(NonnullRefPtr<Event> event)
  118. {
  119. return EventDispatcher::dispatch(*this, event);
  120. }
  121. String Node::child_text_content() const
  122. {
  123. if (!is<ParentNode>(*this))
  124. return String::empty();
  125. StringBuilder builder;
  126. downcast<ParentNode>(*this).for_each_child([&](auto& child) {
  127. if (is<Text>(child))
  128. builder.append(downcast<Text>(child).text_content());
  129. });
  130. return builder.build();
  131. }
  132. Node* Node::root()
  133. {
  134. Node* root = this;
  135. while (root->parent())
  136. root = root->parent();
  137. return root;
  138. }
  139. Node* Node::shadow_including_root()
  140. {
  141. auto node_root = root();
  142. if (is<ShadowRoot>(node_root))
  143. return downcast<ShadowRoot>(node_root)->host()->shadow_including_root();
  144. return node_root;
  145. }
  146. bool Node::is_connected() const
  147. {
  148. return shadow_including_root() && shadow_including_root()->is_document();
  149. }
  150. Element* Node::parent_element()
  151. {
  152. if (!parent() || !is<Element>(parent()))
  153. return nullptr;
  154. return downcast<Element>(parent());
  155. }
  156. const Element* Node::parent_element() const
  157. {
  158. if (!parent() || !is<Element>(parent()))
  159. return nullptr;
  160. return downcast<Element>(parent());
  161. }
  162. // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  163. ExceptionOr<void> Node::ensure_pre_insertion_validity(NonnullRefPtr<Node> node, RefPtr<Node> child) const
  164. {
  165. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  166. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  167. if (node->is_host_including_inclusive_ancestor_of(*this))
  168. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  169. if (child && child->parent() != this)
  170. return DOM::NotFoundError::create("This node is not the parent of the given child");
  171. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  172. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  173. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  174. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  175. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  176. if (is<Document>(this)) {
  177. if (is<DocumentFragment>(*node)) {
  178. auto node_element_child_count = downcast<DocumentFragment>(*node).child_element_count();
  179. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  180. || (node_element_child_count == 1 && (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) /* FIXME: or child is non-null and a doctype is following child. */))) {
  181. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  182. }
  183. } else if (is<Element>(*node)) {
  184. if (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) /* FIXME: or child is non-null and a doctype is following child. */)
  185. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  186. } else if (is<DocumentType>(*node)) {
  187. if (has_child_of_type<DocumentType>() /* FIXME: or child is non-null and an element is preceding child */ || (!child && has_child_of_type<Element>()))
  188. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  189. }
  190. }
  191. return {};
  192. }
  193. // https://dom.spec.whatwg.org/#concept-node-insert
  194. void Node::insert_before(NonnullRefPtr<Node> node, RefPtr<Node> child, bool suppress_observers)
  195. {
  196. NonnullRefPtrVector<Node> nodes;
  197. if (is<DocumentFragment>(*node))
  198. nodes = downcast<DocumentFragment>(*node).child_nodes();
  199. else
  200. nodes.append(node);
  201. auto count = nodes.size();
  202. if (count == 0)
  203. return;
  204. if (is<DocumentFragment>(*node)) {
  205. node->remove_all_children(true);
  206. // FIXME: Queue a tree mutation record for node with « », nodes, null, and null.
  207. }
  208. if (child) {
  209. // FIXME: For each live range whose start node is parent and start offset is greater than child’s index, increase its start offset by count.
  210. // FIXME: For each live range whose end node is parent and end offset is greater than child’s index, increase its end offset by count.
  211. }
  212. // FIXME: Let previousSibling be child’s previous sibling or parent’s last child if child is null. (Currently unused so not included)
  213. for (auto& node_to_insert : nodes) { // FIXME: In tree order
  214. document().adopt_node(node_to_insert);
  215. if (!child)
  216. TreeNode<Node>::append_child(node);
  217. else
  218. TreeNode<Node>::insert_before(node, child);
  219. // FIXME: If parent is a shadow host and node is a slottable, then assign a slot for node.
  220. // FIXME: If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run signal a slot change for parent.
  221. // FIXME: Run assign slottables for a tree with node’s root.
  222. // FIXME: This should be shadow-including.
  223. node_to_insert.for_each_in_inclusive_subtree([&](Node& inclusive_descendant) {
  224. inclusive_descendant.inserted();
  225. if (inclusive_descendant.is_connected()) {
  226. // FIXME: If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant,
  227. // callback name "connectedCallback", and an empty argument list.
  228. // FIXME: Otherwise, try to upgrade inclusiveDescendant.
  229. }
  230. return IterationDecision::Continue;
  231. });
  232. }
  233. if (!suppress_observers) {
  234. // FIXME: queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  235. }
  236. children_changed();
  237. }
  238. // https://dom.spec.whatwg.org/#concept-node-pre-insert
  239. ExceptionOr<NonnullRefPtr<Node>> Node::pre_insert(NonnullRefPtr<Node> node, RefPtr<Node> child)
  240. {
  241. auto validity_result = ensure_pre_insertion_validity(node, child);
  242. if (validity_result.is_exception())
  243. return NonnullRefPtr<DOMException>(validity_result.exception());
  244. auto reference_child = child;
  245. if (reference_child == node)
  246. reference_child = node->next_sibling();
  247. insert_before(node, reference_child);
  248. return node;
  249. }
  250. // https://dom.spec.whatwg.org/#concept-node-pre-remove
  251. ExceptionOr<NonnullRefPtr<Node>> Node::pre_remove(NonnullRefPtr<Node> child)
  252. {
  253. if (child->parent() != this)
  254. return DOM::NotFoundError::create("Child does not belong to this node");
  255. child->remove();
  256. return child;
  257. }
  258. // https://dom.spec.whatwg.org/#concept-node-append
  259. ExceptionOr<NonnullRefPtr<Node>> Node::append_child(NonnullRefPtr<Node> node)
  260. {
  261. return pre_insert(node, nullptr);
  262. }
  263. // https://dom.spec.whatwg.org/#concept-node-remove
  264. void Node::remove(bool suppress_observers)
  265. {
  266. auto* parent = TreeNode<Node>::parent();
  267. VERIFY(parent);
  268. // FIXME: Let index be node’s index. (Currently unused so not included)
  269. // FIXME: For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
  270. // FIXME: For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
  271. // FIXME: For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
  272. // FIXME: For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
  273. // FIXME: For each NodeIterator object iterator whose root’s node document is node’s node document, run the NodeIterator pre-removing steps given node and iterator.
  274. // FIXME: Let oldPreviousSibling be node’s previous sibling. (Currently unused so not included)
  275. // FIXME: Let oldNextSibling be node’s next sibling. (Currently unused so not included)
  276. parent->remove_child(*this);
  277. // FIXME: If node is assigned, then run assign slottables for node’s assigned slot.
  278. // FIXME: If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run signal a slot change for parent.
  279. // FIXME: If node has an inclusive descendant that is a slot, then:
  280. // Run assign slottables for a tree with parent’s root.
  281. // Run assign slottables for a tree with node.
  282. removed_from(parent);
  283. // FIXME: Let isParentConnected be parent’s connected. (Currently unused so not included)
  284. // FIXME: If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node,
  285. // callback name "disconnectedCallback", and an empty argument list.
  286. // FIXME: This should be shadow-including.
  287. for_each_in_subtree([&](Node& descendant) {
  288. descendant.removed_from(nullptr);
  289. // FIXME: If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant,
  290. // callback name "disconnectedCallback", and an empty argument list.
  291. return IterationDecision::Continue;
  292. });
  293. if (!suppress_observers) {
  294. // FIXME: queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  295. }
  296. parent->children_changed();
  297. }
  298. void Node::set_document(Badge<Document>, Document& document)
  299. {
  300. if (m_document == &document)
  301. return;
  302. document.ref_from_node({});
  303. m_document->unref_from_node({});
  304. m_document = &document;
  305. }
  306. bool Node::is_editable() const
  307. {
  308. return parent() && parent()->is_editable();
  309. }
  310. JS::Object* Node::create_wrapper(JS::GlobalObject& global_object)
  311. {
  312. return wrap(global_object, *this);
  313. }
  314. void Node::removed_last_ref()
  315. {
  316. if (is<Document>(*this)) {
  317. downcast<Document>(*this).removed_last_ref();
  318. return;
  319. }
  320. m_deletion_has_begun = true;
  321. delete this;
  322. }
  323. void Node::set_layout_node(Badge<Layout::Node>, Layout::Node* layout_node) const
  324. {
  325. if (layout_node)
  326. m_layout_node = layout_node->make_weak_ptr();
  327. else
  328. m_layout_node = nullptr;
  329. }
  330. EventTarget* Node::get_parent(const Event&)
  331. {
  332. // FIXME: returns the node’s assigned slot, if node is assigned, and node’s parent otherwise.
  333. return parent();
  334. }
  335. void Node::set_needs_style_update(bool value)
  336. {
  337. if (m_needs_style_update == value)
  338. return;
  339. m_needs_style_update = value;
  340. if (m_needs_style_update) {
  341. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  342. //dbgln("{}", ancestor->node_name());
  343. ancestor->m_child_needs_style_update = true;
  344. }
  345. document().schedule_style_update();
  346. }
  347. }
  348. void Node::inserted()
  349. {
  350. set_needs_style_update(true);
  351. }
  352. ParentNode* Node::parent_or_shadow_host()
  353. {
  354. if (is<ShadowRoot>(*this))
  355. return downcast<ShadowRoot>(*this).host();
  356. return downcast<ParentNode>(parent());
  357. }
  358. NonnullRefPtrVector<Node> Node::child_nodes() const
  359. {
  360. NonnullRefPtrVector<Node> nodes;
  361. for_each_child([&](auto& child) {
  362. nodes.append(child);
  363. });
  364. return nodes;
  365. }
  366. void Node::remove_all_children(bool suppress_observers)
  367. {
  368. while (RefPtr<Node> child = first_child())
  369. child->remove(suppress_observers);
  370. }
  371. // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
  372. u16 Node::compare_document_position(RefPtr<Node> other)
  373. {
  374. enum Position : u16 {
  375. DOCUMENT_POSITION_EQUAL = 0,
  376. DOCUMENT_POSITION_DISCONNECTED = 1,
  377. DOCUMENT_POSITION_PRECEDING = 2,
  378. DOCUMENT_POSITION_FOLLOWING = 4,
  379. DOCUMENT_POSITION_CONTAINS = 8,
  380. DOCUMENT_POSITION_CONTAINED_BY = 16,
  381. DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32,
  382. };
  383. if (this == other)
  384. return DOCUMENT_POSITION_EQUAL;
  385. Node* node1 = other.ptr();
  386. Node* node2 = this;
  387. // FIXME: Once LibWeb supports attribute nodes fix to follow the specification.
  388. VERIFY(node1->type() != NodeType::ATTRIBUTE_NODE && node2->type() != NodeType::ATTRIBUTE_NODE);
  389. if ((node1 == nullptr || node2 == nullptr) || (node1->root() != node2->root()))
  390. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | (node1 > node2 ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING);
  391. if (node1->is_ancestor_of(*node2))
  392. return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
  393. if (node2->is_ancestor_of(*node1))
  394. return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
  395. if (node1->is_before(*node2))
  396. return DOCUMENT_POSITION_PRECEDING;
  397. else
  398. return DOCUMENT_POSITION_FOLLOWING;
  399. }
  400. // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
  401. bool Node::is_host_including_inclusive_ancestor_of(const Node& other) const
  402. {
  403. return is_inclusive_ancestor_of(other) || (is<DocumentFragment>(other.root()) && downcast<DocumentFragment>(other.root())->host() && is_inclusive_ancestor_of(*downcast<DocumentFragment>(other.root())->host().ptr()));
  404. }
  405. }