Node.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/IDAllocator.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibJS/AST.h>
  11. #include <LibJS/Runtime/FunctionObject.h>
  12. #include <LibWeb/Bindings/EventWrapper.h>
  13. #include <LibWeb/Bindings/NodeWrapper.h>
  14. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  15. #include <LibWeb/DOM/Comment.h>
  16. #include <LibWeb/DOM/DocumentType.h>
  17. #include <LibWeb/DOM/Element.h>
  18. #include <LibWeb/DOM/ElementFactory.h>
  19. #include <LibWeb/DOM/Event.h>
  20. #include <LibWeb/DOM/EventDispatcher.h>
  21. #include <LibWeb/DOM/EventListener.h>
  22. #include <LibWeb/DOM/Node.h>
  23. #include <LibWeb/DOM/ProcessingInstruction.h>
  24. #include <LibWeb/DOM/ShadowRoot.h>
  25. #include <LibWeb/HTML/HTMLAnchorElement.h>
  26. #include <LibWeb/Layout/InitialContainingBlockBox.h>
  27. #include <LibWeb/Layout/Node.h>
  28. #include <LibWeb/Layout/TextNode.h>
  29. #include <LibWeb/Origin.h>
  30. namespace Web::DOM {
  31. static IDAllocator s_node_id_allocator;
  32. static HashMap<i32, Node*> s_node_directory;
  33. static i32 allocate_node_id(Node* node)
  34. {
  35. i32 id = s_node_id_allocator.allocate();
  36. s_node_directory.set(id, node);
  37. return id;
  38. }
  39. static void deallocate_node_id(i32 node_id)
  40. {
  41. if (!s_node_directory.remove(node_id))
  42. VERIFY_NOT_REACHED();
  43. s_node_id_allocator.deallocate(node_id);
  44. }
  45. Node* Node::from_id(i32 node_id)
  46. {
  47. return s_node_directory.get(node_id).value_or(nullptr);
  48. }
  49. Node::Node(Document& document, NodeType type)
  50. : EventTarget(static_cast<Bindings::ScriptExecutionContext&>(document))
  51. , m_document(&document)
  52. , m_type(type)
  53. , m_id(allocate_node_id(this))
  54. {
  55. if (!is_document())
  56. m_document->ref_from_node({});
  57. }
  58. Node::~Node()
  59. {
  60. VERIFY(m_deletion_has_begun);
  61. if (layout_node() && layout_node()->parent())
  62. layout_node()->parent()->remove_child(*layout_node());
  63. if (!is_document())
  64. m_document->unref_from_node({});
  65. deallocate_node_id(m_id);
  66. }
  67. const HTML::HTMLAnchorElement* Node::enclosing_link_element() const
  68. {
  69. for (auto* node = this; node; node = node->parent()) {
  70. if (is<HTML::HTMLAnchorElement>(*node) && verify_cast<HTML::HTMLAnchorElement>(*node).has_attribute(HTML::AttributeNames::href))
  71. return verify_cast<HTML::HTMLAnchorElement>(node);
  72. }
  73. return nullptr;
  74. }
  75. const HTML::HTMLElement* Node::enclosing_html_element() const
  76. {
  77. return first_ancestor_of_type<HTML::HTMLElement>();
  78. }
  79. const HTML::HTMLElement* Node::enclosing_html_element_with_attribute(const FlyString& attribute) const
  80. {
  81. for (auto* node = this; node; node = node->parent()) {
  82. if (is<HTML::HTMLElement>(*node) && verify_cast<HTML::HTMLElement>(*node).has_attribute(attribute))
  83. return verify_cast<HTML::HTMLElement>(node);
  84. }
  85. return nullptr;
  86. }
  87. String Node::text_content() const
  88. {
  89. StringBuilder builder;
  90. for (auto* child = first_child(); child; child = child->next_sibling()) {
  91. builder.append(child->text_content());
  92. }
  93. return builder.to_string();
  94. }
  95. void Node::set_text_content(const String& content)
  96. {
  97. if (is_text()) {
  98. verify_cast<Text>(this)->set_data(content);
  99. } else {
  100. remove_all_children();
  101. append_child(document().create_text_node(content));
  102. }
  103. set_needs_style_update(true);
  104. document().invalidate_layout();
  105. }
  106. RefPtr<Layout::Node> Node::create_layout_node()
  107. {
  108. return nullptr;
  109. }
  110. void Node::invalidate_style()
  111. {
  112. for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) {
  113. element.set_needs_style_update(true);
  114. return IterationDecision::Continue;
  115. });
  116. document().schedule_style_update();
  117. }
  118. bool Node::is_link() const
  119. {
  120. return enclosing_link_element();
  121. }
  122. bool Node::dispatch_event(NonnullRefPtr<Event> event)
  123. {
  124. return EventDispatcher::dispatch(*this, event);
  125. }
  126. String Node::child_text_content() const
  127. {
  128. if (!is<ParentNode>(*this))
  129. return String::empty();
  130. StringBuilder builder;
  131. verify_cast<ParentNode>(*this).for_each_child([&](auto& child) {
  132. if (is<Text>(child))
  133. builder.append(verify_cast<Text>(child).text_content());
  134. });
  135. return builder.build();
  136. }
  137. // https://dom.spec.whatwg.org/#concept-tree-root
  138. Node& Node::root()
  139. {
  140. Node* root = this;
  141. while (root->parent())
  142. root = root->parent();
  143. return *root;
  144. }
  145. // https://dom.spec.whatwg.org/#concept-shadow-including-root
  146. Node& Node::shadow_including_root()
  147. {
  148. auto& node_root = root();
  149. if (is<ShadowRoot>(node_root))
  150. return verify_cast<ShadowRoot>(node_root).host()->shadow_including_root();
  151. return node_root;
  152. }
  153. // https://dom.spec.whatwg.org/#connected
  154. bool Node::is_connected() const
  155. {
  156. return shadow_including_root().is_document();
  157. }
  158. Element* Node::parent_element()
  159. {
  160. if (!parent() || !is<Element>(parent()))
  161. return nullptr;
  162. return verify_cast<Element>(parent());
  163. }
  164. const Element* Node::parent_element() const
  165. {
  166. if (!parent() || !is<Element>(parent()))
  167. return nullptr;
  168. return verify_cast<Element>(parent());
  169. }
  170. // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  171. ExceptionOr<void> Node::ensure_pre_insertion_validity(NonnullRefPtr<Node> node, RefPtr<Node> child) const
  172. {
  173. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  174. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  175. if (node->is_host_including_inclusive_ancestor_of(*this))
  176. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  177. if (child && child->parent() != this)
  178. return DOM::NotFoundError::create("This node is not the parent of the given child");
  179. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  180. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  181. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  182. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  183. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  184. if (is<Document>(this)) {
  185. if (is<DocumentFragment>(*node)) {
  186. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  187. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  188. || (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. */))) {
  189. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  190. }
  191. } else if (is<Element>(*node)) {
  192. if (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) /* FIXME: or child is non-null and a doctype is following child. */)
  193. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  194. } else if (is<DocumentType>(*node)) {
  195. if (has_child_of_type<DocumentType>() /* FIXME: or child is non-null and an element is preceding child */ || (!child && has_child_of_type<Element>()))
  196. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  197. }
  198. }
  199. return {};
  200. }
  201. // https://dom.spec.whatwg.org/#concept-node-insert
  202. void Node::insert_before(NonnullRefPtr<Node> node, RefPtr<Node> child, bool suppress_observers)
  203. {
  204. NonnullRefPtrVector<Node> nodes;
  205. if (is<DocumentFragment>(*node))
  206. nodes = verify_cast<DocumentFragment>(*node).child_nodes();
  207. else
  208. nodes.append(node);
  209. auto count = nodes.size();
  210. if (count == 0)
  211. return;
  212. if (is<DocumentFragment>(*node)) {
  213. node->remove_all_children(true);
  214. // FIXME: Queue a tree mutation record for node with « », nodes, null, and null.
  215. }
  216. if (child) {
  217. // 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.
  218. // 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.
  219. }
  220. // FIXME: Let previousSibling be child’s previous sibling or parent’s last child if child is null. (Currently unused so not included)
  221. for (auto& node_to_insert : nodes) { // FIXME: In tree order
  222. document().adopt_node(node_to_insert);
  223. if (!child)
  224. TreeNode<Node>::append_child(node_to_insert);
  225. else
  226. TreeNode<Node>::insert_before(node_to_insert, child);
  227. // FIXME: If parent is a shadow host and node is a slottable, then assign a slot for node.
  228. // 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.
  229. // FIXME: Run assign slottables for a tree with node’s root.
  230. // FIXME: This should be shadow-including.
  231. node_to_insert.for_each_in_inclusive_subtree([&](Node& inclusive_descendant) {
  232. inclusive_descendant.inserted();
  233. if (inclusive_descendant.is_connected()) {
  234. // FIXME: If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant,
  235. // callback name "connectedCallback", and an empty argument list.
  236. // FIXME: Otherwise, try to upgrade inclusiveDescendant.
  237. }
  238. return IterationDecision::Continue;
  239. });
  240. }
  241. if (!suppress_observers) {
  242. // FIXME: queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  243. }
  244. children_changed();
  245. }
  246. // https://dom.spec.whatwg.org/#concept-node-pre-insert
  247. ExceptionOr<NonnullRefPtr<Node>> Node::pre_insert(NonnullRefPtr<Node> node, RefPtr<Node> child)
  248. {
  249. auto validity_result = ensure_pre_insertion_validity(node, child);
  250. if (validity_result.is_exception())
  251. return validity_result.exception();
  252. auto reference_child = child;
  253. if (reference_child == node)
  254. reference_child = node->next_sibling();
  255. insert_before(node, reference_child);
  256. return node;
  257. }
  258. // https://dom.spec.whatwg.org/#concept-node-pre-remove
  259. ExceptionOr<NonnullRefPtr<Node>> Node::pre_remove(NonnullRefPtr<Node> child)
  260. {
  261. if (child->parent() != this)
  262. return DOM::NotFoundError::create("Child does not belong to this node");
  263. child->remove();
  264. return child;
  265. }
  266. // https://dom.spec.whatwg.org/#concept-node-append
  267. ExceptionOr<NonnullRefPtr<Node>> Node::append_child(NonnullRefPtr<Node> node)
  268. {
  269. return pre_insert(node, nullptr);
  270. }
  271. // https://dom.spec.whatwg.org/#concept-node-remove
  272. void Node::remove(bool suppress_observers)
  273. {
  274. auto* parent = TreeNode<Node>::parent();
  275. VERIFY(parent);
  276. // FIXME: Let index be node’s index. (Currently unused so not included)
  277. // FIXME: For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
  278. // FIXME: For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
  279. // FIXME: For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
  280. // FIXME: For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
  281. // 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.
  282. // FIXME: Let oldPreviousSibling be node’s previous sibling. (Currently unused so not included)
  283. // FIXME: Let oldNextSibling be node’s next sibling. (Currently unused so not included)
  284. parent->remove_child(*this);
  285. // FIXME: If node is assigned, then run assign slottables for node’s assigned slot.
  286. // 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.
  287. // FIXME: If node has an inclusive descendant that is a slot, then:
  288. // Run assign slottables for a tree with parent’s root.
  289. // Run assign slottables for a tree with node.
  290. removed_from(parent);
  291. // FIXME: Let isParentConnected be parent’s connected. (Currently unused so not included)
  292. // FIXME: If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node,
  293. // callback name "disconnectedCallback", and an empty argument list.
  294. // FIXME: This should be shadow-including.
  295. for_each_in_subtree([&](Node& descendant) {
  296. descendant.removed_from(nullptr);
  297. // FIXME: If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant,
  298. // callback name "disconnectedCallback", and an empty argument list.
  299. return IterationDecision::Continue;
  300. });
  301. if (!suppress_observers) {
  302. // FIXME: queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  303. }
  304. parent->children_changed();
  305. }
  306. // https://dom.spec.whatwg.org/#concept-node-replace
  307. ExceptionOr<NonnullRefPtr<Node>> Node::replace_child(NonnullRefPtr<Node> node, NonnullRefPtr<Node> child)
  308. {
  309. // NOTE: This differs slightly from ensure_pre_insertion_validity.
  310. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  311. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  312. if (node->is_host_including_inclusive_ancestor_of(*this))
  313. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  314. if (child->parent() != this)
  315. return DOM::NotFoundError::create("This node is not the parent of the given child");
  316. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  317. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  318. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  319. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  320. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  321. if (is<Document>(this)) {
  322. if (is<DocumentFragment>(*node)) {
  323. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  324. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  325. || (node_element_child_count == 1 && (first_child_of_type<Element>() != child /* FIXME: or a doctype is following child. */))) {
  326. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  327. }
  328. } else if (is<Element>(*node)) {
  329. if (first_child_of_type<Element>() != child /* FIXME: or a doctype is following child. */)
  330. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  331. } else if (is<DocumentType>(*node)) {
  332. if (first_child_of_type<DocumentType>() != node /* FIXME: or an element is preceding child */)
  333. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  334. }
  335. }
  336. auto reference_child = child->next_sibling();
  337. if (reference_child == node)
  338. reference_child = node->next_sibling();
  339. // FIXME: Let previousSibling be child’s previous sibling. (Currently unused so not included)
  340. // FIXME: Let removedNodes be the empty set. (Currently unused so not included)
  341. if (child->parent()) {
  342. // FIXME: Set removedNodes to « child ».
  343. child->remove(true);
  344. }
  345. // FIXME: Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ». (Currently unused so not included)
  346. insert_before(node, reference_child, true);
  347. // FIXME: Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
  348. return child;
  349. }
  350. // https://dom.spec.whatwg.org/#concept-node-clone
  351. NonnullRefPtr<Node> Node::clone_node(Document* document, bool clone_children)
  352. {
  353. if (!document)
  354. document = m_document;
  355. RefPtr<Node> copy;
  356. if (is<Element>(this)) {
  357. auto& element = *verify_cast<Element>(this);
  358. auto element_copy = DOM::create_element(*document, element.local_name(), element.namespace_() /* FIXME: node’s namespace prefix, and node’s is value, with the synchronous custom elements flag unset */);
  359. element.for_each_attribute([&](auto& name, auto& value) {
  360. element_copy->set_attribute(name, value);
  361. });
  362. copy = move(element_copy);
  363. } else if (is<Document>(this)) {
  364. auto document_ = verify_cast<Document>(this);
  365. auto document_copy = Document::create(document_->url());
  366. document_copy->set_encoding(document_->encoding());
  367. document_copy->set_content_type(document_->content_type());
  368. document_copy->set_origin(document_->origin());
  369. document_copy->set_quirks_mode(document_->mode());
  370. // FIXME: Set type ("xml" or "html")
  371. copy = move(document_copy);
  372. } else if (is<DocumentType>(this)) {
  373. auto document_type = verify_cast<DocumentType>(this);
  374. auto document_type_copy = adopt_ref(*new DocumentType(*document));
  375. document_type_copy->set_name(document_type->name());
  376. document_type_copy->set_public_id(document_type->public_id());
  377. document_type_copy->set_system_id(document_type->system_id());
  378. copy = move(document_type_copy);
  379. } else if (is<Text>(this)) {
  380. auto text = verify_cast<Text>(this);
  381. auto text_copy = adopt_ref(*new Text(*document, text->data()));
  382. copy = move(text_copy);
  383. } else if (is<Comment>(this)) {
  384. auto comment = verify_cast<Comment>(this);
  385. auto comment_copy = adopt_ref(*new Comment(*document, comment->data()));
  386. copy = move(comment_copy);
  387. } else if (is<ProcessingInstruction>(this)) {
  388. auto processing_instruction = verify_cast<ProcessingInstruction>(this);
  389. auto processing_instruction_copy = adopt_ref(*new ProcessingInstruction(*document, processing_instruction->data(), processing_instruction->target()));
  390. copy = move(processing_instruction_copy);
  391. } else if (is<DocumentFragment>(this)) {
  392. auto document_fragment_copy = adopt_ref(*new DocumentFragment(*document));
  393. copy = move(document_fragment_copy);
  394. } else {
  395. dbgln("clone_node() not implemented for NodeType {}", (u16)m_type);
  396. TODO();
  397. }
  398. // 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.
  399. cloned(*copy, clone_children);
  400. if (clone_children) {
  401. for_each_child([&](auto& child) {
  402. copy->append_child(child.clone_node(document, true));
  403. });
  404. }
  405. return copy.release_nonnull();
  406. }
  407. // https://dom.spec.whatwg.org/#dom-node-clonenode
  408. ExceptionOr<NonnullRefPtr<Node>> Node::clone_node_binding(bool deep)
  409. {
  410. if (is<ShadowRoot>(*this))
  411. return NotSupportedError::create("Cannot clone shadow root");
  412. return clone_node(nullptr, deep);
  413. }
  414. void Node::set_document(Badge<Document>, Document& document)
  415. {
  416. if (m_document == &document)
  417. return;
  418. document.ref_from_node({});
  419. m_document->unref_from_node({});
  420. m_document = &document;
  421. }
  422. bool Node::is_editable() const
  423. {
  424. return parent() && parent()->is_editable();
  425. }
  426. JS::Object* Node::create_wrapper(JS::GlobalObject& global_object)
  427. {
  428. return wrap(global_object, *this);
  429. }
  430. void Node::removed_last_ref()
  431. {
  432. if (is<Document>(*this)) {
  433. verify_cast<Document>(*this).removed_last_ref();
  434. return;
  435. }
  436. m_deletion_has_begun = true;
  437. delete this;
  438. }
  439. void Node::set_layout_node(Badge<Layout::Node>, Layout::Node* layout_node) const
  440. {
  441. if (layout_node)
  442. m_layout_node = layout_node->make_weak_ptr();
  443. else
  444. m_layout_node = nullptr;
  445. }
  446. EventTarget* Node::get_parent(const Event&)
  447. {
  448. // FIXME: returns the node’s assigned slot, if node is assigned, and node’s parent otherwise.
  449. return parent();
  450. }
  451. void Node::set_needs_style_update(bool value)
  452. {
  453. if (m_needs_style_update == value)
  454. return;
  455. m_needs_style_update = value;
  456. if (m_needs_style_update) {
  457. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  458. ancestor->m_child_needs_style_update = true;
  459. }
  460. document().schedule_style_update();
  461. }
  462. }
  463. void Node::inserted()
  464. {
  465. set_needs_style_update(true);
  466. }
  467. ParentNode* Node::parent_or_shadow_host()
  468. {
  469. if (is<ShadowRoot>(*this))
  470. return verify_cast<ShadowRoot>(*this).host();
  471. return verify_cast<ParentNode>(parent());
  472. }
  473. NonnullRefPtrVector<Node> Node::child_nodes() const
  474. {
  475. NonnullRefPtrVector<Node> nodes;
  476. for_each_child([&](auto& child) {
  477. nodes.append(child);
  478. });
  479. return nodes;
  480. }
  481. void Node::remove_all_children(bool suppress_observers)
  482. {
  483. while (RefPtr<Node> child = first_child())
  484. child->remove(suppress_observers);
  485. }
  486. // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
  487. u16 Node::compare_document_position(RefPtr<Node> other)
  488. {
  489. enum Position : u16 {
  490. DOCUMENT_POSITION_EQUAL = 0,
  491. DOCUMENT_POSITION_DISCONNECTED = 1,
  492. DOCUMENT_POSITION_PRECEDING = 2,
  493. DOCUMENT_POSITION_FOLLOWING = 4,
  494. DOCUMENT_POSITION_CONTAINS = 8,
  495. DOCUMENT_POSITION_CONTAINED_BY = 16,
  496. DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32,
  497. };
  498. if (this == other)
  499. return DOCUMENT_POSITION_EQUAL;
  500. Node* node1 = other.ptr();
  501. Node* node2 = this;
  502. // FIXME: Once LibWeb supports attribute nodes fix to follow the specification.
  503. VERIFY(node1->type() != NodeType::ATTRIBUTE_NODE && node2->type() != NodeType::ATTRIBUTE_NODE);
  504. if ((node1 == nullptr || node2 == nullptr) || (&node1->root() != &node2->root()))
  505. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | (node1 > node2 ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING);
  506. if (node1->is_ancestor_of(*node2))
  507. return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
  508. if (node2->is_ancestor_of(*node1))
  509. return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
  510. if (node1->is_before(*node2))
  511. return DOCUMENT_POSITION_PRECEDING;
  512. else
  513. return DOCUMENT_POSITION_FOLLOWING;
  514. }
  515. // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
  516. bool Node::is_host_including_inclusive_ancestor_of(const Node& other) const
  517. {
  518. return is_inclusive_ancestor_of(other) || (is<DocumentFragment>(other.root()) && verify_cast<DocumentFragment>(other.root()).host() && is_inclusive_ancestor_of(*verify_cast<DocumentFragment>(other.root()).host().ptr()));
  519. }
  520. // https://dom.spec.whatwg.org/#dom-node-ownerdocument
  521. RefPtr<Document> Node::owner_document() const
  522. {
  523. if (is_document())
  524. return nullptr;
  525. return m_document;
  526. }
  527. void Node::serialize_tree_as_json(JsonObjectSerializer<StringBuilder>& object) const
  528. {
  529. object.add("name", node_name().view());
  530. object.add("id", id());
  531. if (is_document()) {
  532. object.add("type", "document");
  533. } else if (is_element()) {
  534. object.add("type", "element");
  535. auto element = static_cast<DOM::Element const*>(this);
  536. if (element->has_attributes()) {
  537. auto attributes = object.add_object("attributes");
  538. element->for_each_attribute([&attributes](auto& name, auto& value) {
  539. attributes.add(name, value);
  540. });
  541. }
  542. } else if (is_text()) {
  543. object.add("type", "text");
  544. auto text_node = static_cast<DOM::Text const*>(this);
  545. object.add("text", text_node->data());
  546. }
  547. if (has_child_nodes()) {
  548. auto children = object.add_array("children");
  549. for_each_child([&children](DOM::Node& child) {
  550. JsonObjectSerializer<StringBuilder> child_object = children.add_object();
  551. child.serialize_tree_as_json(child_object);
  552. });
  553. }
  554. }
  555. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-noscript
  556. bool Node::is_scripting_disabled() const
  557. {
  558. // FIXME: or when scripting is disabled for its relevant settings object.
  559. return !document().browsing_context();
  560. }
  561. // https://dom.spec.whatwg.org/#dom-node-contains
  562. bool Node::contains(RefPtr<Node> other) const
  563. {
  564. return other && other->is_inclusive_descendant_of(*this);
  565. }
  566. // https://dom.spec.whatwg.org/#concept-shadow-including-descendant
  567. bool Node::is_shadow_including_descendant_of(Node const& other) const
  568. {
  569. if (is_descendant_of(other))
  570. return true;
  571. if (!is<ShadowRoot>(root()))
  572. return false;
  573. auto& shadow_root = verify_cast<ShadowRoot>(root());
  574. // NOTE: While host is nullable because of inheriting from DocumentFragment, shadow roots always have a host.
  575. return shadow_root.host()->is_shadow_including_inclusive_descendant_of(other);
  576. }
  577. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
  578. bool Node::is_shadow_including_inclusive_descendant_of(Node const& other) const
  579. {
  580. return &other == this || is_shadow_including_descendant_of(other);
  581. }
  582. // https://dom.spec.whatwg.org/#concept-shadow-including-ancestor
  583. bool Node::is_shadow_including_ancestor_of(Node const& other) const
  584. {
  585. return other.is_shadow_including_descendant_of(*this);
  586. }
  587. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor
  588. bool Node::is_shadow_including_inclusive_ancestor_of(Node const& other) const
  589. {
  590. return other.is_shadow_including_inclusive_descendant_of(*this);
  591. }
  592. }