Node.cpp 38 KB

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