Node.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. /*
  2. * Copyright (c) 2018-2022, 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/IDLEventListener.h>
  22. #include <LibWeb/DOM/LiveNodeList.h>
  23. #include <LibWeb/DOM/Node.h>
  24. #include <LibWeb/DOM/ProcessingInstruction.h>
  25. #include <LibWeb/DOM/ShadowRoot.h>
  26. #include <LibWeb/HTML/BrowsingContextContainer.h>
  27. #include <LibWeb/HTML/HTMLAnchorElement.h>
  28. #include <LibWeb/HTML/Parser/HTMLParser.h>
  29. #include <LibWeb/Layout/InitialContainingBlock.h>
  30. #include <LibWeb/Layout/Node.h>
  31. #include <LibWeb/Layout/TextNode.h>
  32. #include <LibWeb/Origin.h>
  33. namespace Web::DOM {
  34. static IDAllocator s_node_id_allocator;
  35. static HashMap<i32, Node*> s_node_directory;
  36. static i32 allocate_node_id(Node* node)
  37. {
  38. i32 id = s_node_id_allocator.allocate();
  39. s_node_directory.set(id, node);
  40. return id;
  41. }
  42. static void deallocate_node_id(i32 node_id)
  43. {
  44. if (!s_node_directory.remove(node_id))
  45. VERIFY_NOT_REACHED();
  46. s_node_id_allocator.deallocate(node_id);
  47. }
  48. Node* Node::from_id(i32 node_id)
  49. {
  50. return s_node_directory.get(node_id).value_or(nullptr);
  51. }
  52. Node::Node(Document& document, NodeType type)
  53. : EventTarget()
  54. , m_document(&document)
  55. , m_type(type)
  56. , m_id(allocate_node_id(this))
  57. {
  58. if (!is_document())
  59. m_document->ref_from_node({});
  60. }
  61. Node::~Node()
  62. {
  63. VERIFY(m_deletion_has_begun);
  64. if (layout_node() && layout_node()->parent())
  65. layout_node()->parent()->remove_child(*layout_node());
  66. if (!is_document())
  67. m_document->unref_from_node({});
  68. deallocate_node_id(m_id);
  69. }
  70. const HTML::HTMLAnchorElement* Node::enclosing_link_element() const
  71. {
  72. for (auto* node = this; node; node = node->parent()) {
  73. if (!is<HTML::HTMLAnchorElement>(*node))
  74. continue;
  75. auto const& anchor_element = static_cast<HTML::HTMLAnchorElement const&>(*node);
  76. if (anchor_element.has_attribute(HTML::AttributeNames::href))
  77. return &anchor_element;
  78. }
  79. return nullptr;
  80. }
  81. const HTML::HTMLElement* Node::enclosing_html_element() const
  82. {
  83. return first_ancestor_of_type<HTML::HTMLElement>();
  84. }
  85. const HTML::HTMLElement* Node::enclosing_html_element_with_attribute(const FlyString& attribute) const
  86. {
  87. for (auto* node = this; node; node = node->parent()) {
  88. if (is<HTML::HTMLElement>(*node) && verify_cast<HTML::HTMLElement>(*node).has_attribute(attribute))
  89. return verify_cast<HTML::HTMLElement>(node);
  90. }
  91. return nullptr;
  92. }
  93. // https://dom.spec.whatwg.org/#concept-descendant-text-content
  94. String Node::descendant_text_content() const
  95. {
  96. StringBuilder builder;
  97. for_each_in_subtree_of_type<Text>([&](auto& text_node) {
  98. builder.append(text_node.data());
  99. return IterationDecision::Continue;
  100. });
  101. return builder.to_string();
  102. }
  103. // https://dom.spec.whatwg.org/#dom-node-textcontent
  104. String Node::text_content() const
  105. {
  106. if (is<DocumentFragment>(this) || is<Element>(this))
  107. return descendant_text_content();
  108. else if (is<CharacterData>(this))
  109. return verify_cast<CharacterData>(this)->data();
  110. // FIXME: Else if this is an Attr node, return this's value.
  111. return {};
  112. }
  113. // https://dom.spec.whatwg.org/#ref-for-dom-node-textcontent%E2%91%A0
  114. void Node::set_text_content(String const& content)
  115. {
  116. if (is<DocumentFragment>(this) || is<Element>(this)) {
  117. string_replace_all(content);
  118. } else if (is<CharacterData>(this)) {
  119. // FIXME: CharacterData::set_data is not spec compliant. Make this match the spec when set_data becomes spec compliant.
  120. // Do note that this will make this function able to throw an exception.
  121. auto* character_data_node = verify_cast<CharacterData>(this);
  122. character_data_node->set_data(content);
  123. } else {
  124. // FIXME: Else if this is an Attr node, set an existing attribute value with this and the given value.
  125. return;
  126. }
  127. set_needs_style_update(true);
  128. }
  129. // https://dom.spec.whatwg.org/#dom-node-nodevalue
  130. String Node::node_value() const
  131. {
  132. if (is<Attribute>(this)) {
  133. return verify_cast<Attribute>(this)->value();
  134. }
  135. if (is<CharacterData>(this)) {
  136. return verify_cast<CharacterData>(this)->data();
  137. }
  138. return {};
  139. }
  140. // https://dom.spec.whatwg.org/#ref-for-dom-node-nodevalue%E2%91%A0
  141. void Node::set_node_value(const String& value)
  142. {
  143. if (is<Attribute>(this)) {
  144. verify_cast<Attribute>(this)->set_value(value);
  145. } else if (is<CharacterData>(this)) {
  146. verify_cast<CharacterData>(this)->set_data(value);
  147. }
  148. // Otherwise: Do nothing.
  149. }
  150. void Node::invalidate_style()
  151. {
  152. if (is_document()) {
  153. auto& document = static_cast<DOM::Document&>(*this);
  154. document.set_needs_full_style_update(true);
  155. document.schedule_style_update();
  156. return;
  157. }
  158. for_each_in_inclusive_subtree([&](Node& node) {
  159. node.m_needs_style_update = true;
  160. if (node.has_children())
  161. node.m_child_needs_style_update = true;
  162. if (auto* shadow_root = node.is_element() ? static_cast<DOM::Element&>(node).shadow_root() : nullptr) {
  163. node.m_child_needs_style_update = true;
  164. shadow_root->m_needs_style_update = true;
  165. if (shadow_root->has_children())
  166. shadow_root->m_child_needs_style_update = true;
  167. }
  168. return IterationDecision::Continue;
  169. });
  170. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host())
  171. ancestor->m_child_needs_style_update = true;
  172. document().schedule_style_update();
  173. }
  174. bool Node::is_link() const
  175. {
  176. return enclosing_link_element();
  177. }
  178. String Node::child_text_content() const
  179. {
  180. if (!is<ParentNode>(*this))
  181. return String::empty();
  182. StringBuilder builder;
  183. verify_cast<ParentNode>(*this).for_each_child([&](auto& child) {
  184. if (is<Text>(child))
  185. builder.append(verify_cast<Text>(child).text_content());
  186. });
  187. return builder.build();
  188. }
  189. // https://dom.spec.whatwg.org/#concept-tree-root
  190. Node& Node::root()
  191. {
  192. Node* root = this;
  193. while (root->parent())
  194. root = root->parent();
  195. return *root;
  196. }
  197. // https://dom.spec.whatwg.org/#concept-shadow-including-root
  198. Node& Node::shadow_including_root()
  199. {
  200. auto& node_root = root();
  201. if (is<ShadowRoot>(node_root))
  202. return verify_cast<ShadowRoot>(node_root).host()->shadow_including_root();
  203. return node_root;
  204. }
  205. // https://dom.spec.whatwg.org/#connected
  206. bool Node::is_connected() const
  207. {
  208. return shadow_including_root().is_document();
  209. }
  210. Element* Node::parent_element()
  211. {
  212. if (!parent() || !is<Element>(parent()))
  213. return nullptr;
  214. return verify_cast<Element>(parent());
  215. }
  216. const Element* Node::parent_element() const
  217. {
  218. if (!parent() || !is<Element>(parent()))
  219. return nullptr;
  220. return verify_cast<Element>(parent());
  221. }
  222. // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  223. ExceptionOr<void> Node::ensure_pre_insertion_validity(NonnullRefPtr<Node> node, RefPtr<Node> child) const
  224. {
  225. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  226. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  227. if (node->is_host_including_inclusive_ancestor_of(*this))
  228. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  229. if (child && child->parent() != this)
  230. return DOM::NotFoundError::create("This node is not the parent of the given child");
  231. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  232. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  233. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  234. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  235. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  236. if (is<Document>(this)) {
  237. if (is<DocumentFragment>(*node)) {
  238. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  239. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  240. || (node_element_child_count == 1 && (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) || (child && child->has_following_node_of_type_in_tree_order<DocumentType>())))) {
  241. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  242. }
  243. } else if (is<Element>(*node)) {
  244. if (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) || (child && child->has_following_node_of_type_in_tree_order<DocumentType>()))
  245. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  246. } else if (is<DocumentType>(*node)) {
  247. if (has_child_of_type<DocumentType>() || (child && child->has_preceding_node_of_type_in_tree_order<Element>()) || (!child && has_child_of_type<Element>()))
  248. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  249. }
  250. }
  251. return {};
  252. }
  253. // https://dom.spec.whatwg.org/#concept-node-insert
  254. void Node::insert_before(NonnullRefPtr<Node> node, RefPtr<Node> child, bool suppress_observers)
  255. {
  256. NonnullRefPtrVector<Node> nodes;
  257. if (is<DocumentFragment>(*node))
  258. nodes = verify_cast<DocumentFragment>(*node).children_as_vector();
  259. else
  260. nodes.append(node);
  261. auto count = nodes.size();
  262. if (count == 0)
  263. return;
  264. if (is<DocumentFragment>(*node)) {
  265. node->remove_all_children(true);
  266. // FIXME: Queue a tree mutation record for node with « », nodes, null, and null.
  267. }
  268. if (child) {
  269. // 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.
  270. // 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.
  271. }
  272. // FIXME: Let previousSibling be child’s previous sibling or parent’s last child if child is null. (Currently unused so not included)
  273. for (auto& node_to_insert : nodes) { // FIXME: In tree order
  274. document().adopt_node(node_to_insert);
  275. if (!child)
  276. TreeNode<Node>::append_child(node_to_insert);
  277. else
  278. TreeNode<Node>::insert_before(node_to_insert, child);
  279. // FIXME: If parent is a shadow host and node is a slottable, then assign a slot for node.
  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: Run assign slottables for a tree with node’s root.
  282. // FIXME: This should be shadow-including.
  283. node_to_insert.for_each_in_inclusive_subtree([&](Node& inclusive_descendant) {
  284. inclusive_descendant.inserted();
  285. if (inclusive_descendant.is_connected()) {
  286. // FIXME: If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant,
  287. // callback name "connectedCallback", and an empty argument list.
  288. // FIXME: Otherwise, try to upgrade inclusiveDescendant.
  289. }
  290. return IterationDecision::Continue;
  291. });
  292. }
  293. if (!suppress_observers) {
  294. // FIXME: queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  295. }
  296. children_changed();
  297. document().invalidate_style();
  298. }
  299. // https://dom.spec.whatwg.org/#concept-node-pre-insert
  300. ExceptionOr<NonnullRefPtr<Node>> Node::pre_insert(NonnullRefPtr<Node> node, RefPtr<Node> child)
  301. {
  302. auto validity_result = ensure_pre_insertion_validity(node, child);
  303. if (validity_result.is_exception())
  304. return validity_result.exception();
  305. auto reference_child = child;
  306. if (reference_child == node)
  307. reference_child = node->next_sibling();
  308. insert_before(node, reference_child);
  309. return node;
  310. }
  311. // https://dom.spec.whatwg.org/#dom-node-removechild
  312. ExceptionOr<NonnullRefPtr<Node>> Node::remove_child(NonnullRefPtr<Node> child)
  313. {
  314. return pre_remove(child);
  315. }
  316. // https://dom.spec.whatwg.org/#concept-node-pre-remove
  317. ExceptionOr<NonnullRefPtr<Node>> Node::pre_remove(NonnullRefPtr<Node> child)
  318. {
  319. if (child->parent() != this)
  320. return DOM::NotFoundError::create("Child does not belong to this node");
  321. child->remove();
  322. return child;
  323. }
  324. // https://dom.spec.whatwg.org/#concept-node-append
  325. ExceptionOr<NonnullRefPtr<Node>> Node::append_child(NonnullRefPtr<Node> node)
  326. {
  327. return pre_insert(node, nullptr);
  328. }
  329. // https://dom.spec.whatwg.org/#concept-node-remove
  330. void Node::remove(bool suppress_observers)
  331. {
  332. auto* parent = TreeNode<Node>::parent();
  333. VERIFY(parent);
  334. // FIXME: Let index be node’s index. (Currently unused so not included)
  335. // FIXME: For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
  336. // FIXME: For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
  337. // FIXME: For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
  338. // FIXME: For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
  339. // 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.
  340. document().for_each_node_iterator([&](NodeIterator& node_iterator) {
  341. node_iterator.run_pre_removing_steps(*this);
  342. });
  343. // FIXME: Let oldPreviousSibling be node’s previous sibling. (Currently unused so not included)
  344. // FIXME: Let oldNextSibling be node’s next sibling. (Currently unused so not included)
  345. parent->TreeNode::remove_child(*this);
  346. // FIXME: If node is assigned, then run assign slottables for node’s assigned slot.
  347. // 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.
  348. // FIXME: If node has an inclusive descendant that is a slot, then:
  349. // Run assign slottables for a tree with parent’s root.
  350. // Run assign slottables for a tree with node.
  351. removed_from(parent);
  352. // FIXME: Let isParentConnected be parent’s connected. (Currently unused so not included)
  353. // FIXME: If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node,
  354. // callback name "disconnectedCallback", and an empty argument list.
  355. // FIXME: This should be shadow-including.
  356. for_each_in_subtree([&](Node& descendant) {
  357. descendant.removed_from(nullptr);
  358. // FIXME: If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant,
  359. // callback name "disconnectedCallback", and an empty argument list.
  360. return IterationDecision::Continue;
  361. });
  362. if (!suppress_observers) {
  363. // FIXME: queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  364. }
  365. parent->children_changed();
  366. document().invalidate_style();
  367. }
  368. // https://dom.spec.whatwg.org/#concept-node-replace
  369. ExceptionOr<NonnullRefPtr<Node>> Node::replace_child(NonnullRefPtr<Node> node, NonnullRefPtr<Node> child)
  370. {
  371. // NOTE: This differs slightly from ensure_pre_insertion_validity.
  372. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  373. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  374. if (node->is_host_including_inclusive_ancestor_of(*this))
  375. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  376. if (child->parent() != this)
  377. return DOM::NotFoundError::create("This node is not the parent of the given child");
  378. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  379. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  380. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  381. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  382. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  383. if (is<Document>(this)) {
  384. if (is<DocumentFragment>(*node)) {
  385. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  386. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  387. || (node_element_child_count == 1 && (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>()))) {
  388. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  389. }
  390. } else if (is<Element>(*node)) {
  391. if (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>())
  392. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  393. } else if (is<DocumentType>(*node)) {
  394. if (first_child_of_type<DocumentType>() != node || child->has_preceding_node_of_type_in_tree_order<Element>())
  395. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  396. }
  397. }
  398. auto reference_child = child->next_sibling();
  399. if (reference_child == node)
  400. reference_child = node->next_sibling();
  401. // FIXME: Let previousSibling be child’s previous sibling. (Currently unused so not included)
  402. // FIXME: Let removedNodes be the empty set. (Currently unused so not included)
  403. if (child->parent()) {
  404. // FIXME: Set removedNodes to « child ».
  405. child->remove(true);
  406. }
  407. // FIXME: Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ». (Currently unused so not included)
  408. insert_before(node, reference_child, true);
  409. // FIXME: Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
  410. return child;
  411. }
  412. // https://dom.spec.whatwg.org/#concept-node-clone
  413. NonnullRefPtr<Node> Node::clone_node(Document* document, bool clone_children)
  414. {
  415. if (!document)
  416. document = m_document;
  417. RefPtr<Node> copy;
  418. if (is<Element>(this)) {
  419. auto& element = *verify_cast<Element>(this);
  420. 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 */);
  421. element.for_each_attribute([&](auto& name, auto& value) {
  422. element_copy->set_attribute(name, value);
  423. });
  424. copy = move(element_copy);
  425. } else if (is<Document>(this)) {
  426. auto document_ = verify_cast<Document>(this);
  427. auto document_copy = Document::create(document_->url());
  428. document_copy->set_encoding(document_->encoding());
  429. document_copy->set_content_type(document_->content_type());
  430. document_copy->set_origin(document_->origin());
  431. document_copy->set_quirks_mode(document_->mode());
  432. // FIXME: Set type ("xml" or "html")
  433. copy = move(document_copy);
  434. } else if (is<DocumentType>(this)) {
  435. auto document_type = verify_cast<DocumentType>(this);
  436. auto document_type_copy = adopt_ref(*new DocumentType(*document));
  437. document_type_copy->set_name(document_type->name());
  438. document_type_copy->set_public_id(document_type->public_id());
  439. document_type_copy->set_system_id(document_type->system_id());
  440. copy = move(document_type_copy);
  441. } else if (is<Text>(this)) {
  442. auto text = verify_cast<Text>(this);
  443. auto text_copy = adopt_ref(*new Text(*document, text->data()));
  444. copy = move(text_copy);
  445. } else if (is<Comment>(this)) {
  446. auto comment = verify_cast<Comment>(this);
  447. auto comment_copy = adopt_ref(*new Comment(*document, comment->data()));
  448. copy = move(comment_copy);
  449. } else if (is<ProcessingInstruction>(this)) {
  450. auto processing_instruction = verify_cast<ProcessingInstruction>(this);
  451. auto processing_instruction_copy = adopt_ref(*new ProcessingInstruction(*document, processing_instruction->data(), processing_instruction->target()));
  452. copy = move(processing_instruction_copy);
  453. } else if (is<DocumentFragment>(this)) {
  454. auto document_fragment_copy = adopt_ref(*new DocumentFragment(*document));
  455. copy = move(document_fragment_copy);
  456. } else {
  457. dbgln("clone_node() not implemented for NodeType {}", (u16)m_type);
  458. TODO();
  459. }
  460. // 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.
  461. cloned(*copy, clone_children);
  462. if (clone_children) {
  463. for_each_child([&](auto& child) {
  464. copy->append_child(child.clone_node(document, true));
  465. });
  466. }
  467. return copy.release_nonnull();
  468. }
  469. // https://dom.spec.whatwg.org/#dom-node-clonenode
  470. ExceptionOr<NonnullRefPtr<Node>> Node::clone_node_binding(bool deep)
  471. {
  472. if (is<ShadowRoot>(*this))
  473. return NotSupportedError::create("Cannot clone shadow root");
  474. return clone_node(nullptr, deep);
  475. }
  476. void Node::set_document(Badge<Document>, Document& document)
  477. {
  478. if (m_document == &document)
  479. return;
  480. document.ref_from_node({});
  481. m_document->unref_from_node({});
  482. m_document = &document;
  483. if (needs_style_update() || child_needs_style_update()) {
  484. // NOTE: We unset and reset the "needs style update" flag here.
  485. // This ensures that there's a pending style update in the new document
  486. // that will eventually assign some style to this node if needed.
  487. set_needs_style_update(false);
  488. set_needs_style_update(true);
  489. }
  490. }
  491. bool Node::is_editable() const
  492. {
  493. return parent() && parent()->is_editable();
  494. }
  495. JS::Object* Node::create_wrapper(JS::GlobalObject& global_object)
  496. {
  497. return wrap(global_object, *this);
  498. }
  499. void Node::removed_last_ref()
  500. {
  501. if (is<Document>(*this)) {
  502. verify_cast<Document>(*this).removed_last_ref();
  503. return;
  504. }
  505. m_deletion_has_begun = true;
  506. delete this;
  507. }
  508. void Node::set_layout_node(Badge<Layout::Node>, Layout::Node* layout_node) const
  509. {
  510. if (layout_node)
  511. m_layout_node = layout_node->make_weak_ptr();
  512. else
  513. m_layout_node = nullptr;
  514. }
  515. EventTarget* Node::get_parent(const Event&)
  516. {
  517. // FIXME: returns the node’s assigned slot, if node is assigned, and node’s parent otherwise.
  518. return parent();
  519. }
  520. void Node::set_needs_style_update(bool value)
  521. {
  522. if (m_needs_style_update == value)
  523. return;
  524. m_needs_style_update = value;
  525. if (m_needs_style_update) {
  526. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
  527. ancestor->m_child_needs_style_update = true;
  528. }
  529. document().schedule_style_update();
  530. }
  531. }
  532. void Node::inserted()
  533. {
  534. set_needs_style_update(true);
  535. }
  536. ParentNode* Node::parent_or_shadow_host()
  537. {
  538. if (is<ShadowRoot>(*this))
  539. return verify_cast<ShadowRoot>(*this).host();
  540. return verify_cast<ParentNode>(parent());
  541. }
  542. NonnullRefPtr<NodeList> Node::child_nodes()
  543. {
  544. // FIXME: This should return the same LiveNodeList object every time,
  545. // but that would cause a reference cycle since NodeList refs the root.
  546. return LiveNodeList::create(*this, [this](auto& node) {
  547. return is_parent_of(node);
  548. });
  549. }
  550. NonnullRefPtrVector<Node> Node::children_as_vector() const
  551. {
  552. NonnullRefPtrVector<Node> nodes;
  553. for_each_child([&](auto& child) {
  554. nodes.append(child);
  555. });
  556. return nodes;
  557. }
  558. void Node::remove_all_children(bool suppress_observers)
  559. {
  560. while (RefPtr<Node> child = first_child())
  561. child->remove(suppress_observers);
  562. }
  563. // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
  564. u16 Node::compare_document_position(RefPtr<Node> other)
  565. {
  566. enum Position : u16 {
  567. DOCUMENT_POSITION_EQUAL = 0,
  568. DOCUMENT_POSITION_DISCONNECTED = 1,
  569. DOCUMENT_POSITION_PRECEDING = 2,
  570. DOCUMENT_POSITION_FOLLOWING = 4,
  571. DOCUMENT_POSITION_CONTAINS = 8,
  572. DOCUMENT_POSITION_CONTAINED_BY = 16,
  573. DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32,
  574. };
  575. if (this == other)
  576. return DOCUMENT_POSITION_EQUAL;
  577. Node* node1 = other.ptr();
  578. Node* node2 = this;
  579. // FIXME: Once LibWeb supports attribute nodes fix to follow the specification.
  580. VERIFY(node1->type() != NodeType::ATTRIBUTE_NODE && node2->type() != NodeType::ATTRIBUTE_NODE);
  581. if ((node1 == nullptr || node2 == nullptr) || (&node1->root() != &node2->root()))
  582. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | (node1 > node2 ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING);
  583. if (node1->is_ancestor_of(*node2))
  584. return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
  585. if (node2->is_ancestor_of(*node1))
  586. return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
  587. if (node1->is_before(*node2))
  588. return DOCUMENT_POSITION_PRECEDING;
  589. else
  590. return DOCUMENT_POSITION_FOLLOWING;
  591. }
  592. // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
  593. bool Node::is_host_including_inclusive_ancestor_of(const Node& other) const
  594. {
  595. if (is_inclusive_ancestor_of(other))
  596. return true;
  597. if (is<DocumentFragment>(other.root())
  598. && static_cast<DocumentFragment const&>(other.root()).host()
  599. && is_inclusive_ancestor_of(*static_cast<DocumentFragment const&>(other.root()).host())) {
  600. return true;
  601. }
  602. return false;
  603. }
  604. // https://dom.spec.whatwg.org/#dom-node-ownerdocument
  605. RefPtr<Document> Node::owner_document() const
  606. {
  607. if (is_document())
  608. return nullptr;
  609. return m_document;
  610. }
  611. // This function tells us whether a node is interesting enough to show up
  612. // in the DOM inspector. This hides two things:
  613. // - Non-rendered whitespace
  614. // - Rendered whitespace between block-level elements
  615. bool Node::is_uninteresting_whitespace_node() const
  616. {
  617. if (!is<Text>(*this))
  618. return false;
  619. if (!static_cast<Text const&>(*this).data().is_whitespace())
  620. return false;
  621. if (!layout_node())
  622. return true;
  623. if (layout_node()->parent()->is_anonymous())
  624. return true;
  625. return false;
  626. }
  627. void Node::serialize_tree_as_json(JsonObjectSerializer<StringBuilder>& object) const
  628. {
  629. MUST(object.add("name", node_name().view()));
  630. MUST(object.add("id", id()));
  631. if (is_document()) {
  632. MUST(object.add("type", "document"));
  633. } else if (is_element()) {
  634. MUST(object.add("type", "element"));
  635. auto const* element = static_cast<DOM::Element const*>(this);
  636. if (element->has_attributes()) {
  637. auto attributes = MUST(object.add_object("attributes"));
  638. element->for_each_attribute([&attributes](auto& name, auto& value) {
  639. MUST(attributes.add(name, value));
  640. });
  641. MUST(attributes.finish());
  642. }
  643. if (element->is_browsing_context_container()) {
  644. auto const* container = static_cast<HTML::BrowsingContextContainer const*>(element);
  645. if (auto const* content_document = container->content_document()) {
  646. auto children = MUST(object.add_array("children"));
  647. JsonObjectSerializer<StringBuilder> content_document_object = MUST(children.add_object());
  648. content_document->serialize_tree_as_json(content_document_object);
  649. MUST(content_document_object.finish());
  650. MUST(children.finish());
  651. }
  652. }
  653. } else if (is_text()) {
  654. MUST(object.add("type", "text"));
  655. auto text_node = static_cast<DOM::Text const*>(this);
  656. MUST(object.add("text", text_node->data()));
  657. } else if (is_comment()) {
  658. MUST(object.add("type"sv, "comment"sv));
  659. MUST(object.add("data"sv, static_cast<DOM::Comment const&>(*this).data()));
  660. }
  661. if (has_child_nodes()) {
  662. auto children = MUST(object.add_array("children"));
  663. for_each_child([&children](DOM::Node& child) {
  664. if (child.is_uninteresting_whitespace_node())
  665. return;
  666. JsonObjectSerializer<StringBuilder> child_object = MUST(children.add_object());
  667. child.serialize_tree_as_json(child_object);
  668. MUST(child_object.finish());
  669. });
  670. // Pseudo-elements don't have DOM nodes,so we have to add them separately.
  671. if (is_element()) {
  672. auto const* element = static_cast<DOM::Element const*>(this);
  673. element->serialize_pseudo_elements_as_json(children);
  674. }
  675. MUST(children.finish());
  676. }
  677. }
  678. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-noscript
  679. bool Node::is_scripting_disabled() const
  680. {
  681. // FIXME: or when scripting is disabled for its relevant settings object.
  682. return !document().browsing_context();
  683. }
  684. // https://dom.spec.whatwg.org/#dom-node-contains
  685. bool Node::contains(RefPtr<Node> other) const
  686. {
  687. return other && other->is_inclusive_descendant_of(*this);
  688. }
  689. // https://dom.spec.whatwg.org/#concept-shadow-including-descendant
  690. bool Node::is_shadow_including_descendant_of(Node const& other) const
  691. {
  692. if (is_descendant_of(other))
  693. return true;
  694. if (!is<ShadowRoot>(root()))
  695. return false;
  696. auto& shadow_root = verify_cast<ShadowRoot>(root());
  697. // NOTE: While host is nullable because of inheriting from DocumentFragment, shadow roots always have a host.
  698. return shadow_root.host()->is_shadow_including_inclusive_descendant_of(other);
  699. }
  700. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
  701. bool Node::is_shadow_including_inclusive_descendant_of(Node const& other) const
  702. {
  703. return &other == this || is_shadow_including_descendant_of(other);
  704. }
  705. // https://dom.spec.whatwg.org/#concept-shadow-including-ancestor
  706. bool Node::is_shadow_including_ancestor_of(Node const& other) const
  707. {
  708. return other.is_shadow_including_descendant_of(*this);
  709. }
  710. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor
  711. bool Node::is_shadow_including_inclusive_ancestor_of(Node const& other) const
  712. {
  713. return other.is_shadow_including_inclusive_descendant_of(*this);
  714. }
  715. // https://dom.spec.whatwg.org/#concept-node-replace-all
  716. void Node::replace_all(RefPtr<Node> node)
  717. {
  718. // FIXME: Let removedNodes be parent’s children. (Current unused so not included)
  719. // FIXME: Let addedNodes be the empty set. (Currently unused so not included)
  720. // FIXME: If node is a DocumentFragment node, then set addedNodes to node’s children.
  721. // FIXME: Otherwise, if node is non-null, set addedNodes to « node ».
  722. remove_all_children(true);
  723. if (node)
  724. insert_before(*node, nullptr, true);
  725. // FIXME: If either addedNodes or removedNodes is not empty, then queue a tree mutation record for parent with addedNodes, removedNodes, null, and null.
  726. }
  727. // https://dom.spec.whatwg.org/#string-replace-all
  728. void Node::string_replace_all(String const& string)
  729. {
  730. RefPtr<Node> node;
  731. if (!string.is_empty())
  732. node = make_ref_counted<Text>(document(), string);
  733. replace_all(node);
  734. }
  735. // https://w3c.github.io/DOM-Parsing/#dfn-fragment-serializing-algorithm
  736. String Node::serialize_fragment(/* FIXME: Requires well-formed flag */) const
  737. {
  738. // FIXME: Let context document be the value of node's node document.
  739. // FIXME: If context document is an HTML document, return an HTML serialization of node.
  740. // (We currently always do this)
  741. return HTML::HTMLParser::serialize_html_fragment(*this);
  742. // FIXME: Otherwise, context document is an XML document; return an XML serialization of node passing the flag require well-formed.
  743. }
  744. // https://dom.spec.whatwg.org/#dom-node-issamenode
  745. bool Node::is_same_node(Node const* other_node) const
  746. {
  747. return this == other_node;
  748. }
  749. // https://dom.spec.whatwg.org/#dom-node-isequalnode
  750. bool Node::is_equal_node(Node const* other_node) const
  751. {
  752. // The isEqualNode(otherNode) method steps are to return true if otherNode is non-null and this equals otherNode; otherwise false.
  753. if (!other_node)
  754. return false;
  755. // Fast path for testing a node against itself.
  756. if (this == other_node)
  757. return true;
  758. // A node A equals a node B if all of the following conditions are true:
  759. // A and B implement the same interfaces.
  760. if (node_name() != other_node->node_name())
  761. return false;
  762. // The following are equal, switching on the interface A implements:
  763. switch (node_type()) {
  764. case (u16)NodeType::DOCUMENT_TYPE_NODE: {
  765. // Its name, public ID, and system ID.
  766. auto& this_doctype = verify_cast<DocumentType>(*this);
  767. auto& other_doctype = verify_cast<DocumentType>(*other_node);
  768. if (this_doctype.name() != other_doctype.name()
  769. || this_doctype.public_id() != other_doctype.public_id()
  770. || this_doctype.system_id() != other_doctype.system_id())
  771. return false;
  772. break;
  773. }
  774. case (u16)NodeType::ELEMENT_NODE: {
  775. // Its namespace, namespace prefix, local name, and its attribute list’s size.
  776. auto& this_element = verify_cast<Element>(*this);
  777. auto& other_element = verify_cast<Element>(*other_node);
  778. if (this_element.namespace_() != other_element.namespace_()
  779. || this_element.prefix() != other_element.prefix()
  780. || this_element.local_name() != other_element.local_name()
  781. || this_element.attribute_list_size() != other_element.attribute_list_size())
  782. return false;
  783. // If A is an element, each attribute in its attribute list has an attribute that equals an attribute in B’s attribute list.
  784. bool has_same_attributes = true;
  785. this_element.for_each_attribute([&](auto& name, auto& value) {
  786. if (other_element.get_attribute(name) != value)
  787. has_same_attributes = false;
  788. });
  789. if (!has_same_attributes)
  790. return false;
  791. break;
  792. }
  793. case (u16)NodeType::COMMENT_NODE:
  794. case (u16)NodeType::TEXT_NODE: {
  795. // Its data.
  796. auto& this_cdata = verify_cast<CharacterData>(*this);
  797. auto& other_cdata = verify_cast<CharacterData>(*other_node);
  798. if (this_cdata.data() != other_cdata.data())
  799. return false;
  800. break;
  801. }
  802. case (u16)NodeType::PROCESSING_INSTRUCTION_NODE:
  803. case (u16)NodeType::ATTRIBUTE_NODE:
  804. TODO();
  805. default:
  806. break;
  807. }
  808. // A and B have the same number of children.
  809. size_t this_child_count = child_count();
  810. size_t other_child_count = other_node->child_count();
  811. if (this_child_count != other_child_count)
  812. return false;
  813. // Each child of A equals the child of B at the identical index.
  814. // FIXME: This can be made nicer. child_at_index() is O(n).
  815. for (size_t i = 0; i < this_child_count; ++i) {
  816. auto* this_child = child_at_index(i);
  817. auto* other_child = other_node->child_at_index(i);
  818. VERIFY(this_child);
  819. VERIFY(other_child);
  820. if (!this_child->is_equal_node(other_child))
  821. return false;
  822. }
  823. return true;
  824. }
  825. // https://dom.spec.whatwg.org/#in-a-document-tree
  826. bool Node::in_a_document_tree() const
  827. {
  828. // An element is in a document tree if its root is a document.
  829. return root().is_document();
  830. }
  831. // https://dom.spec.whatwg.org/#dom-node-getrootnode
  832. NonnullRefPtr<Node> Node::get_root_node(GetRootNodeOptions const& options)
  833. {
  834. // The getRootNode(options) method steps are to return this’s shadow-including root if options["composed"] is true; otherwise this’s root.
  835. if (options.composed)
  836. return shadow_including_root();
  837. return root();
  838. }
  839. String Node::debug_description() const
  840. {
  841. StringBuilder builder;
  842. builder.append(node_name().to_lowercase());
  843. if (is_element()) {
  844. auto& element = static_cast<DOM::Element const&>(*this);
  845. if (auto id = element.get_attribute(HTML::AttributeNames::id); !id.is_null())
  846. builder.appendff("#{}", id);
  847. for (auto const& class_name : element.class_names())
  848. builder.appendff(".{}", class_name);
  849. }
  850. return builder.to_string();
  851. }
  852. // https://dom.spec.whatwg.org/#concept-node-length
  853. size_t Node::length() const
  854. {
  855. // 1. If node is a DocumentType or Attr node, then return 0.
  856. if (is_document_type() || is_attribute())
  857. return 0;
  858. // 2. If node is a CharacterData node, then return node’s data’s length.
  859. if (is_character_data()) {
  860. auto* character_data_node = verify_cast<CharacterData>(this);
  861. return character_data_node->data().length();
  862. }
  863. // 3. Return the number of node’s children.
  864. return child_count();
  865. }
  866. Painting::Paintable const* Node::paintable() const
  867. {
  868. if (!layout_node())
  869. return nullptr;
  870. return layout_node()->paintable();
  871. }
  872. Painting::PaintableBox const* Node::paint_box() const
  873. {
  874. if (!layout_node())
  875. return nullptr;
  876. if (!layout_node()->is_box())
  877. return nullptr;
  878. return static_cast<Layout::Box const&>(*layout_node()).paint_box();
  879. }
  880. }