Node.cpp 19 KB

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