Node.cpp 20 KB

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