Node.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, 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. // 5. If child is non-null, then:
  269. if (child) {
  270. // 1. For each live range whose start node is parent and start offset is greater than child’s index, increase its start offset by count.
  271. for (auto& range : Range::live_ranges()) {
  272. if (range->start_container() == this && range->start_offset() > child->index())
  273. range->set_start(*range->start_container(), range->start_offset() + count);
  274. }
  275. // 2. For each live range whose end node is parent and end offset is greater than child’s index, increase its end offset by count.
  276. for (auto& range : Range::live_ranges()) {
  277. if (range->end_container() == this && range->end_offset() > child->index())
  278. range->set_end(*range->end_container(), range->end_offset() + count);
  279. }
  280. }
  281. // FIXME: Let previousSibling be child’s previous sibling or parent’s last child if child is null. (Currently unused so not included)
  282. for (auto& node_to_insert : nodes) { // FIXME: In tree order
  283. document().adopt_node(node_to_insert);
  284. if (!child)
  285. TreeNode<Node>::append_child(node_to_insert);
  286. else
  287. TreeNode<Node>::insert_before(node_to_insert, child);
  288. // FIXME: If parent is a shadow host and node is a slottable, then assign a slot for node.
  289. // 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.
  290. // FIXME: Run assign slottables for a tree with node’s root.
  291. // FIXME: This should be shadow-including.
  292. node_to_insert.for_each_in_inclusive_subtree([&](Node& inclusive_descendant) {
  293. inclusive_descendant.inserted();
  294. if (inclusive_descendant.is_connected()) {
  295. // FIXME: If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant,
  296. // callback name "connectedCallback", and an empty argument list.
  297. // FIXME: Otherwise, try to upgrade inclusiveDescendant.
  298. }
  299. return IterationDecision::Continue;
  300. });
  301. }
  302. if (!suppress_observers) {
  303. // FIXME: queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  304. }
  305. children_changed();
  306. document().invalidate_style();
  307. }
  308. // https://dom.spec.whatwg.org/#concept-node-pre-insert
  309. ExceptionOr<NonnullRefPtr<Node>> Node::pre_insert(NonnullRefPtr<Node> node, RefPtr<Node> child)
  310. {
  311. TRY(ensure_pre_insertion_validity(node, child));
  312. auto reference_child = child;
  313. if (reference_child == node)
  314. reference_child = node->next_sibling();
  315. insert_before(node, reference_child);
  316. return node;
  317. }
  318. // https://dom.spec.whatwg.org/#dom-node-removechild
  319. ExceptionOr<NonnullRefPtr<Node>> Node::remove_child(NonnullRefPtr<Node> child)
  320. {
  321. return pre_remove(child);
  322. }
  323. // https://dom.spec.whatwg.org/#concept-node-pre-remove
  324. ExceptionOr<NonnullRefPtr<Node>> Node::pre_remove(NonnullRefPtr<Node> child)
  325. {
  326. if (child->parent() != this)
  327. return DOM::NotFoundError::create("Child does not belong to this node");
  328. child->remove();
  329. return child;
  330. }
  331. // https://dom.spec.whatwg.org/#concept-node-append
  332. ExceptionOr<NonnullRefPtr<Node>> Node::append_child(NonnullRefPtr<Node> node)
  333. {
  334. return pre_insert(node, nullptr);
  335. }
  336. // https://dom.spec.whatwg.org/#concept-node-remove
  337. void Node::remove(bool suppress_observers)
  338. {
  339. auto* parent = TreeNode<Node>::parent();
  340. VERIFY(parent);
  341. // 3. Let index be node’s index.
  342. auto index = this->index();
  343. // 4. For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
  344. for (auto& range : Range::live_ranges()) {
  345. if (range->start_container()->is_inclusive_descendant_of(*this))
  346. range->set_start(*parent, index);
  347. }
  348. // 5. For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
  349. for (auto& range : Range::live_ranges()) {
  350. if (range->end_container()->is_inclusive_descendant_of(*this))
  351. range->set_end(*parent, index);
  352. }
  353. // 6. For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
  354. for (auto& range : Range::live_ranges()) {
  355. if (range->start_container() == parent && range->start_offset() > index)
  356. range->set_start(*range->start_container(), range->start_offset() - 1);
  357. }
  358. // 7. For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
  359. for (auto& range : Range::live_ranges()) {
  360. if (range->end_container() == parent && range->end_offset() > index)
  361. range->set_end(*range->end_container(), range->end_offset() - 1);
  362. }
  363. // 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.
  364. document().for_each_node_iterator([&](NodeIterator& node_iterator) {
  365. node_iterator.run_pre_removing_steps(*this);
  366. });
  367. // FIXME: Let oldPreviousSibling be node’s previous sibling. (Currently unused so not included)
  368. // FIXME: Let oldNextSibling be node’s next sibling. (Currently unused so not included)
  369. parent->TreeNode::remove_child(*this);
  370. // FIXME: If node is assigned, then run assign slottables for node’s assigned slot.
  371. // 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.
  372. // FIXME: If node has an inclusive descendant that is a slot, then:
  373. // Run assign slottables for a tree with parent’s root.
  374. // Run assign slottables for a tree with node.
  375. removed_from(parent);
  376. // FIXME: Let isParentConnected be parent’s connected. (Currently unused so not included)
  377. // FIXME: If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node,
  378. // callback name "disconnectedCallback", and an empty argument list.
  379. // FIXME: This should be shadow-including.
  380. for_each_in_subtree([&](Node& descendant) {
  381. descendant.removed_from(nullptr);
  382. // FIXME: If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant,
  383. // callback name "disconnectedCallback", and an empty argument list.
  384. return IterationDecision::Continue;
  385. });
  386. if (!suppress_observers) {
  387. // FIXME: queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  388. }
  389. parent->children_changed();
  390. document().invalidate_style();
  391. }
  392. // https://dom.spec.whatwg.org/#concept-node-replace
  393. ExceptionOr<NonnullRefPtr<Node>> Node::replace_child(NonnullRefPtr<Node> node, NonnullRefPtr<Node> child)
  394. {
  395. // NOTE: This differs slightly from ensure_pre_insertion_validity.
  396. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  397. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  398. if (node->is_host_including_inclusive_ancestor_of(*this))
  399. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  400. if (child->parent() != this)
  401. return DOM::NotFoundError::create("This node is not the parent of the given child");
  402. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  403. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  404. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  405. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  406. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  407. if (is<Document>(this)) {
  408. if (is<DocumentFragment>(*node)) {
  409. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  410. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  411. || (node_element_child_count == 1 && (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>()))) {
  412. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  413. }
  414. } else if (is<Element>(*node)) {
  415. if (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>())
  416. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  417. } else if (is<DocumentType>(*node)) {
  418. if (first_child_of_type<DocumentType>() != node || child->has_preceding_node_of_type_in_tree_order<Element>())
  419. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  420. }
  421. }
  422. auto reference_child = child->next_sibling();
  423. if (reference_child == node)
  424. reference_child = node->next_sibling();
  425. // FIXME: Let previousSibling be child’s previous sibling. (Currently unused so not included)
  426. // FIXME: Let removedNodes be the empty set. (Currently unused so not included)
  427. if (child->parent()) {
  428. // FIXME: Set removedNodes to « child ».
  429. child->remove(true);
  430. }
  431. // FIXME: Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ». (Currently unused so not included)
  432. insert_before(node, reference_child, true);
  433. // FIXME: Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
  434. return child;
  435. }
  436. // https://dom.spec.whatwg.org/#concept-node-clone
  437. NonnullRefPtr<Node> Node::clone_node(Document* document, bool clone_children)
  438. {
  439. if (!document)
  440. document = m_document;
  441. RefPtr<Node> copy;
  442. if (is<Element>(this)) {
  443. auto& element = *verify_cast<Element>(this);
  444. 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 */);
  445. element.for_each_attribute([&](auto& name, auto& value) {
  446. element_copy->set_attribute(name, value);
  447. });
  448. copy = move(element_copy);
  449. } else if (is<Document>(this)) {
  450. auto document_ = verify_cast<Document>(this);
  451. auto document_copy = Document::create(document_->url());
  452. document_copy->set_encoding(document_->encoding());
  453. document_copy->set_content_type(document_->content_type());
  454. document_copy->set_origin(document_->origin());
  455. document_copy->set_quirks_mode(document_->mode());
  456. // FIXME: Set type ("xml" or "html")
  457. copy = move(document_copy);
  458. } else if (is<DocumentType>(this)) {
  459. auto document_type = verify_cast<DocumentType>(this);
  460. auto document_type_copy = adopt_ref(*new DocumentType(*document));
  461. document_type_copy->set_name(document_type->name());
  462. document_type_copy->set_public_id(document_type->public_id());
  463. document_type_copy->set_system_id(document_type->system_id());
  464. copy = move(document_type_copy);
  465. } else if (is<Text>(this)) {
  466. auto text = verify_cast<Text>(this);
  467. auto text_copy = adopt_ref(*new Text(*document, text->data()));
  468. copy = move(text_copy);
  469. } else if (is<Comment>(this)) {
  470. auto comment = verify_cast<Comment>(this);
  471. auto comment_copy = adopt_ref(*new Comment(*document, comment->data()));
  472. copy = move(comment_copy);
  473. } else if (is<ProcessingInstruction>(this)) {
  474. auto processing_instruction = verify_cast<ProcessingInstruction>(this);
  475. auto processing_instruction_copy = adopt_ref(*new ProcessingInstruction(*document, processing_instruction->data(), processing_instruction->target()));
  476. copy = move(processing_instruction_copy);
  477. } else if (is<DocumentFragment>(this)) {
  478. auto document_fragment_copy = adopt_ref(*new DocumentFragment(*document));
  479. copy = move(document_fragment_copy);
  480. } else {
  481. dbgln("clone_node() not implemented for NodeType {}", (u16)m_type);
  482. TODO();
  483. }
  484. // 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.
  485. cloned(*copy, clone_children);
  486. if (clone_children) {
  487. for_each_child([&](auto& child) {
  488. copy->append_child(child.clone_node(document, true));
  489. });
  490. }
  491. return copy.release_nonnull();
  492. }
  493. // https://dom.spec.whatwg.org/#dom-node-clonenode
  494. ExceptionOr<NonnullRefPtr<Node>> Node::clone_node_binding(bool deep)
  495. {
  496. if (is<ShadowRoot>(*this))
  497. return NotSupportedError::create("Cannot clone shadow root");
  498. return clone_node(nullptr, deep);
  499. }
  500. void Node::set_document(Badge<Document>, Document& document)
  501. {
  502. if (m_document == &document)
  503. return;
  504. document.ref_from_node({});
  505. m_document->unref_from_node({});
  506. m_document = &document;
  507. if (needs_style_update() || child_needs_style_update()) {
  508. // NOTE: We unset and reset the "needs style update" flag here.
  509. // This ensures that there's a pending style update in the new document
  510. // that will eventually assign some style to this node if needed.
  511. set_needs_style_update(false);
  512. set_needs_style_update(true);
  513. }
  514. }
  515. bool Node::is_editable() const
  516. {
  517. return parent() && parent()->is_editable();
  518. }
  519. JS::Object* Node::create_wrapper(JS::GlobalObject& global_object)
  520. {
  521. return wrap(global_object, *this);
  522. }
  523. void Node::removed_last_ref()
  524. {
  525. if (is<Document>(*this)) {
  526. verify_cast<Document>(*this).removed_last_ref();
  527. return;
  528. }
  529. m_deletion_has_begun = true;
  530. delete this;
  531. }
  532. void Node::set_layout_node(Badge<Layout::Node>, Layout::Node* layout_node) const
  533. {
  534. if (layout_node)
  535. m_layout_node = layout_node->make_weak_ptr();
  536. else
  537. m_layout_node = nullptr;
  538. }
  539. EventTarget* Node::get_parent(const Event&)
  540. {
  541. // FIXME: returns the node’s assigned slot, if node is assigned, and node’s parent otherwise.
  542. return parent();
  543. }
  544. void Node::set_needs_style_update(bool value)
  545. {
  546. if (m_needs_style_update == value)
  547. return;
  548. m_needs_style_update = value;
  549. if (m_needs_style_update) {
  550. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
  551. ancestor->m_child_needs_style_update = true;
  552. }
  553. document().schedule_style_update();
  554. }
  555. }
  556. void Node::inserted()
  557. {
  558. set_needs_style_update(true);
  559. }
  560. ParentNode* Node::parent_or_shadow_host()
  561. {
  562. if (is<ShadowRoot>(*this))
  563. return verify_cast<ShadowRoot>(*this).host();
  564. return verify_cast<ParentNode>(parent());
  565. }
  566. NonnullRefPtr<NodeList> Node::child_nodes()
  567. {
  568. // FIXME: This should return the same LiveNodeList object every time,
  569. // but that would cause a reference cycle since NodeList refs the root.
  570. return LiveNodeList::create(*this, [this](auto& node) {
  571. return is_parent_of(node);
  572. });
  573. }
  574. NonnullRefPtrVector<Node> Node::children_as_vector() const
  575. {
  576. NonnullRefPtrVector<Node> nodes;
  577. for_each_child([&](auto& child) {
  578. nodes.append(child);
  579. });
  580. return nodes;
  581. }
  582. void Node::remove_all_children(bool suppress_observers)
  583. {
  584. while (RefPtr<Node> child = first_child())
  585. child->remove(suppress_observers);
  586. }
  587. // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
  588. u16 Node::compare_document_position(RefPtr<Node> other)
  589. {
  590. enum Position : u16 {
  591. DOCUMENT_POSITION_EQUAL = 0,
  592. DOCUMENT_POSITION_DISCONNECTED = 1,
  593. DOCUMENT_POSITION_PRECEDING = 2,
  594. DOCUMENT_POSITION_FOLLOWING = 4,
  595. DOCUMENT_POSITION_CONTAINS = 8,
  596. DOCUMENT_POSITION_CONTAINED_BY = 16,
  597. DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32,
  598. };
  599. if (this == other)
  600. return DOCUMENT_POSITION_EQUAL;
  601. Node* node1 = other.ptr();
  602. Node* node2 = this;
  603. // FIXME: Once LibWeb supports attribute nodes fix to follow the specification.
  604. VERIFY(node1->type() != NodeType::ATTRIBUTE_NODE && node2->type() != NodeType::ATTRIBUTE_NODE);
  605. if ((node1 == nullptr || node2 == nullptr) || (&node1->root() != &node2->root()))
  606. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | (node1 > node2 ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING);
  607. if (node1->is_ancestor_of(*node2))
  608. return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
  609. if (node2->is_ancestor_of(*node1))
  610. return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
  611. if (node1->is_before(*node2))
  612. return DOCUMENT_POSITION_PRECEDING;
  613. else
  614. return DOCUMENT_POSITION_FOLLOWING;
  615. }
  616. // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
  617. bool Node::is_host_including_inclusive_ancestor_of(const Node& other) const
  618. {
  619. if (is_inclusive_ancestor_of(other))
  620. return true;
  621. if (is<DocumentFragment>(other.root())
  622. && static_cast<DocumentFragment const&>(other.root()).host()
  623. && is_inclusive_ancestor_of(*static_cast<DocumentFragment const&>(other.root()).host())) {
  624. return true;
  625. }
  626. return false;
  627. }
  628. // https://dom.spec.whatwg.org/#dom-node-ownerdocument
  629. RefPtr<Document> Node::owner_document() const
  630. {
  631. if (is_document())
  632. return nullptr;
  633. return m_document;
  634. }
  635. // This function tells us whether a node is interesting enough to show up
  636. // in the DOM inspector. This hides two things:
  637. // - Non-rendered whitespace
  638. // - Rendered whitespace between block-level elements
  639. bool Node::is_uninteresting_whitespace_node() const
  640. {
  641. if (!is<Text>(*this))
  642. return false;
  643. if (!static_cast<Text const&>(*this).data().is_whitespace())
  644. return false;
  645. if (!layout_node())
  646. return true;
  647. if (layout_node()->parent()->is_anonymous())
  648. return true;
  649. return false;
  650. }
  651. void Node::serialize_tree_as_json(JsonObjectSerializer<StringBuilder>& object) const
  652. {
  653. MUST(object.add("name", node_name().view()));
  654. MUST(object.add("id", id()));
  655. if (is_document()) {
  656. MUST(object.add("type", "document"));
  657. } else if (is_element()) {
  658. MUST(object.add("type", "element"));
  659. auto const* element = static_cast<DOM::Element const*>(this);
  660. if (element->has_attributes()) {
  661. auto attributes = MUST(object.add_object("attributes"));
  662. element->for_each_attribute([&attributes](auto& name, auto& value) {
  663. MUST(attributes.add(name, value));
  664. });
  665. MUST(attributes.finish());
  666. }
  667. if (element->is_browsing_context_container()) {
  668. auto const* container = static_cast<HTML::BrowsingContextContainer const*>(element);
  669. if (auto const* content_document = container->content_document()) {
  670. auto children = MUST(object.add_array("children"));
  671. JsonObjectSerializer<StringBuilder> content_document_object = MUST(children.add_object());
  672. content_document->serialize_tree_as_json(content_document_object);
  673. MUST(content_document_object.finish());
  674. MUST(children.finish());
  675. }
  676. }
  677. } else if (is_text()) {
  678. MUST(object.add("type", "text"));
  679. auto text_node = static_cast<DOM::Text const*>(this);
  680. MUST(object.add("text", text_node->data()));
  681. } else if (is_comment()) {
  682. MUST(object.add("type"sv, "comment"sv));
  683. MUST(object.add("data"sv, static_cast<DOM::Comment const&>(*this).data()));
  684. }
  685. MUST((object.add("visible"sv, !!layout_node())));
  686. if (has_child_nodes()) {
  687. auto children = MUST(object.add_array("children"));
  688. for_each_child([&children](DOM::Node& child) {
  689. if (child.is_uninteresting_whitespace_node())
  690. return;
  691. JsonObjectSerializer<StringBuilder> child_object = MUST(children.add_object());
  692. child.serialize_tree_as_json(child_object);
  693. MUST(child_object.finish());
  694. });
  695. // Pseudo-elements don't have DOM nodes,so we have to add them separately.
  696. if (is_element()) {
  697. auto const* element = static_cast<DOM::Element const*>(this);
  698. element->serialize_pseudo_elements_as_json(children);
  699. }
  700. MUST(children.finish());
  701. }
  702. }
  703. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-noscript
  704. bool Node::is_scripting_disabled() const
  705. {
  706. // FIXME: or when scripting is disabled for its relevant settings object.
  707. return !document().browsing_context();
  708. }
  709. // https://dom.spec.whatwg.org/#dom-node-contains
  710. bool Node::contains(RefPtr<Node> other) const
  711. {
  712. return other && other->is_inclusive_descendant_of(*this);
  713. }
  714. // https://dom.spec.whatwg.org/#concept-shadow-including-descendant
  715. bool Node::is_shadow_including_descendant_of(Node const& other) const
  716. {
  717. if (is_descendant_of(other))
  718. return true;
  719. if (!is<ShadowRoot>(root()))
  720. return false;
  721. auto& shadow_root = verify_cast<ShadowRoot>(root());
  722. // NOTE: While host is nullable because of inheriting from DocumentFragment, shadow roots always have a host.
  723. return shadow_root.host()->is_shadow_including_inclusive_descendant_of(other);
  724. }
  725. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
  726. bool Node::is_shadow_including_inclusive_descendant_of(Node const& other) const
  727. {
  728. return &other == this || is_shadow_including_descendant_of(other);
  729. }
  730. // https://dom.spec.whatwg.org/#concept-shadow-including-ancestor
  731. bool Node::is_shadow_including_ancestor_of(Node const& other) const
  732. {
  733. return other.is_shadow_including_descendant_of(*this);
  734. }
  735. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor
  736. bool Node::is_shadow_including_inclusive_ancestor_of(Node const& other) const
  737. {
  738. return other.is_shadow_including_inclusive_descendant_of(*this);
  739. }
  740. // https://dom.spec.whatwg.org/#concept-node-replace-all
  741. void Node::replace_all(RefPtr<Node> node)
  742. {
  743. // FIXME: Let removedNodes be parent’s children. (Current unused so not included)
  744. // FIXME: Let addedNodes be the empty set. (Currently unused so not included)
  745. // FIXME: If node is a DocumentFragment node, then set addedNodes to node’s children.
  746. // FIXME: Otherwise, if node is non-null, set addedNodes to « node ».
  747. remove_all_children(true);
  748. if (node)
  749. insert_before(*node, nullptr, true);
  750. // FIXME: If either addedNodes or removedNodes is not empty, then queue a tree mutation record for parent with addedNodes, removedNodes, null, and null.
  751. }
  752. // https://dom.spec.whatwg.org/#string-replace-all
  753. void Node::string_replace_all(String const& string)
  754. {
  755. RefPtr<Node> node;
  756. if (!string.is_empty())
  757. node = make_ref_counted<Text>(document(), string);
  758. replace_all(node);
  759. }
  760. // https://w3c.github.io/DOM-Parsing/#dfn-fragment-serializing-algorithm
  761. String Node::serialize_fragment(/* FIXME: Requires well-formed flag */) const
  762. {
  763. // FIXME: Let context document be the value of node's node document.
  764. // FIXME: If context document is an HTML document, return an HTML serialization of node.
  765. // (We currently always do this)
  766. return HTML::HTMLParser::serialize_html_fragment(*this);
  767. // FIXME: Otherwise, context document is an XML document; return an XML serialization of node passing the flag require well-formed.
  768. }
  769. // https://dom.spec.whatwg.org/#dom-node-issamenode
  770. bool Node::is_same_node(Node const* other_node) const
  771. {
  772. return this == other_node;
  773. }
  774. // https://dom.spec.whatwg.org/#dom-node-isequalnode
  775. bool Node::is_equal_node(Node const* other_node) const
  776. {
  777. // The isEqualNode(otherNode) method steps are to return true if otherNode is non-null and this equals otherNode; otherwise false.
  778. if (!other_node)
  779. return false;
  780. // Fast path for testing a node against itself.
  781. if (this == other_node)
  782. return true;
  783. // A node A equals a node B if all of the following conditions are true:
  784. // A and B implement the same interfaces.
  785. if (node_name() != other_node->node_name())
  786. return false;
  787. // The following are equal, switching on the interface A implements:
  788. switch (node_type()) {
  789. case (u16)NodeType::DOCUMENT_TYPE_NODE: {
  790. // Its name, public ID, and system ID.
  791. auto& this_doctype = verify_cast<DocumentType>(*this);
  792. auto& other_doctype = verify_cast<DocumentType>(*other_node);
  793. if (this_doctype.name() != other_doctype.name()
  794. || this_doctype.public_id() != other_doctype.public_id()
  795. || this_doctype.system_id() != other_doctype.system_id())
  796. return false;
  797. break;
  798. }
  799. case (u16)NodeType::ELEMENT_NODE: {
  800. // Its namespace, namespace prefix, local name, and its attribute list’s size.
  801. auto& this_element = verify_cast<Element>(*this);
  802. auto& other_element = verify_cast<Element>(*other_node);
  803. if (this_element.namespace_() != other_element.namespace_()
  804. || this_element.prefix() != other_element.prefix()
  805. || this_element.local_name() != other_element.local_name()
  806. || this_element.attribute_list_size() != other_element.attribute_list_size())
  807. return false;
  808. // If A is an element, each attribute in its attribute list has an attribute that equals an attribute in B’s attribute list.
  809. bool has_same_attributes = true;
  810. this_element.for_each_attribute([&](auto& name, auto& value) {
  811. if (other_element.get_attribute(name) != value)
  812. has_same_attributes = false;
  813. });
  814. if (!has_same_attributes)
  815. return false;
  816. break;
  817. }
  818. case (u16)NodeType::COMMENT_NODE:
  819. case (u16)NodeType::TEXT_NODE: {
  820. // Its data.
  821. auto& this_cdata = verify_cast<CharacterData>(*this);
  822. auto& other_cdata = verify_cast<CharacterData>(*other_node);
  823. if (this_cdata.data() != other_cdata.data())
  824. return false;
  825. break;
  826. }
  827. case (u16)NodeType::PROCESSING_INSTRUCTION_NODE:
  828. case (u16)NodeType::ATTRIBUTE_NODE:
  829. TODO();
  830. default:
  831. break;
  832. }
  833. // A and B have the same number of children.
  834. size_t this_child_count = child_count();
  835. size_t other_child_count = other_node->child_count();
  836. if (this_child_count != other_child_count)
  837. return false;
  838. // Each child of A equals the child of B at the identical index.
  839. // FIXME: This can be made nicer. child_at_index() is O(n).
  840. for (size_t i = 0; i < this_child_count; ++i) {
  841. auto* this_child = child_at_index(i);
  842. auto* other_child = other_node->child_at_index(i);
  843. VERIFY(this_child);
  844. VERIFY(other_child);
  845. if (!this_child->is_equal_node(other_child))
  846. return false;
  847. }
  848. return true;
  849. }
  850. // https://dom.spec.whatwg.org/#in-a-document-tree
  851. bool Node::in_a_document_tree() const
  852. {
  853. // An element is in a document tree if its root is a document.
  854. return root().is_document();
  855. }
  856. // https://dom.spec.whatwg.org/#dom-node-getrootnode
  857. NonnullRefPtr<Node> Node::get_root_node(GetRootNodeOptions const& options)
  858. {
  859. // The getRootNode(options) method steps are to return this’s shadow-including root if options["composed"] is true; otherwise this’s root.
  860. if (options.composed)
  861. return shadow_including_root();
  862. return root();
  863. }
  864. String Node::debug_description() const
  865. {
  866. StringBuilder builder;
  867. builder.append(node_name().to_lowercase());
  868. if (is_element()) {
  869. auto& element = static_cast<DOM::Element const&>(*this);
  870. if (auto id = element.get_attribute(HTML::AttributeNames::id); !id.is_null())
  871. builder.appendff("#{}", id);
  872. for (auto const& class_name : element.class_names())
  873. builder.appendff(".{}", class_name);
  874. }
  875. return builder.to_string();
  876. }
  877. // https://dom.spec.whatwg.org/#concept-node-length
  878. size_t Node::length() const
  879. {
  880. // 1. If node is a DocumentType or Attr node, then return 0.
  881. if (is_document_type() || is_attribute())
  882. return 0;
  883. // 2. If node is a CharacterData node, then return node’s data’s length.
  884. if (is_character_data()) {
  885. auto* character_data_node = verify_cast<CharacterData>(this);
  886. return character_data_node->data().length();
  887. }
  888. // 3. Return the number of node’s children.
  889. return child_count();
  890. }
  891. Painting::Paintable const* Node::paintable() const
  892. {
  893. if (!layout_node())
  894. return nullptr;
  895. return layout_node()->paintable();
  896. }
  897. Painting::PaintableBox const* Node::paint_box() const
  898. {
  899. if (!layout_node())
  900. return nullptr;
  901. if (!layout_node()->is_box())
  902. return nullptr;
  903. return static_cast<Layout::Box const&>(*layout_node()).paint_box();
  904. }
  905. }