Node.cpp 39 KB

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