Node.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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. // https://dom.spec.whatwg.org/#dom-node-baseuri
  71. String Node::base_uri() const
  72. {
  73. // FIXME: Return this’s node document’s document base URL, serialized.
  74. return document().url_string();
  75. }
  76. const HTML::HTMLAnchorElement* Node::enclosing_link_element() const
  77. {
  78. for (auto* node = this; node; node = node->parent()) {
  79. if (!is<HTML::HTMLAnchorElement>(*node))
  80. continue;
  81. auto const& anchor_element = static_cast<HTML::HTMLAnchorElement const&>(*node);
  82. if (anchor_element.has_attribute(HTML::AttributeNames::href))
  83. return &anchor_element;
  84. }
  85. return nullptr;
  86. }
  87. const HTML::HTMLElement* Node::enclosing_html_element() const
  88. {
  89. return first_ancestor_of_type<HTML::HTMLElement>();
  90. }
  91. const HTML::HTMLElement* Node::enclosing_html_element_with_attribute(FlyString const& attribute) const
  92. {
  93. for (auto* node = this; node; node = node->parent()) {
  94. if (is<HTML::HTMLElement>(*node) && verify_cast<HTML::HTMLElement>(*node).has_attribute(attribute))
  95. return verify_cast<HTML::HTMLElement>(node);
  96. }
  97. return nullptr;
  98. }
  99. // https://dom.spec.whatwg.org/#concept-descendant-text-content
  100. String Node::descendant_text_content() const
  101. {
  102. StringBuilder builder;
  103. for_each_in_subtree_of_type<Text>([&](auto& text_node) {
  104. builder.append(text_node.data());
  105. return IterationDecision::Continue;
  106. });
  107. return builder.to_string();
  108. }
  109. // https://dom.spec.whatwg.org/#dom-node-textcontent
  110. String Node::text_content() const
  111. {
  112. // The textContent getter steps are to return the following, switching on the interface this implements:
  113. // If DocumentFragment or Element, return the descendant text content of this.
  114. if (is<DocumentFragment>(this) || is<Element>(this))
  115. return descendant_text_content();
  116. else if (is<CharacterData>(this))
  117. // If CharacterData, return this’s data.
  118. return verify_cast<CharacterData>(this)->data();
  119. // FIXME: If this is an Attr node, return this's value.
  120. // Otherwise, return null
  121. return {};
  122. }
  123. // https://dom.spec.whatwg.org/#ref-for-dom-node-textcontent%E2%91%A0
  124. void Node::set_text_content(String const& content)
  125. {
  126. // The textContent setter steps are to, if the given value is null, act as if it was the empty string instead,
  127. // and then do as described below, switching on the interface this implements:
  128. // If DocumentFragment or Element, string replace all with the given value within this.
  129. if (is<DocumentFragment>(this) || is<Element>(this)) {
  130. string_replace_all(content);
  131. } else if (is<CharacterData>(this)) {
  132. // If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
  133. auto* character_data_node = verify_cast<CharacterData>(this);
  134. character_data_node->set_data(content);
  135. // FIXME: CharacterData::set_data is not spec compliant. Make this match the spec when set_data becomes spec compliant.
  136. // Do note that this will make this function able to throw an exception.
  137. } else {
  138. // FIXME: If this is an Attr node, set an existing attribute value with this and the given value.
  139. return;
  140. }
  141. // Otherwise, do nothing.
  142. set_needs_style_update(true);
  143. }
  144. // https://dom.spec.whatwg.org/#dom-node-nodevalue
  145. String Node::node_value() const
  146. {
  147. // The nodeValue getter steps are to return the following, switching on the interface this implements:
  148. // If Attr, return this’s value.
  149. if (is<Attribute>(this)) {
  150. return verify_cast<Attribute>(this)->value();
  151. }
  152. // If CharacterData, return this’s data.
  153. if (is<CharacterData>(this)) {
  154. return verify_cast<CharacterData>(this)->data();
  155. }
  156. // Otherwise, return null.
  157. return {};
  158. }
  159. // https://dom.spec.whatwg.org/#ref-for-dom-node-nodevalue%E2%91%A0
  160. void Node::set_node_value(String const& value)
  161. {
  162. // The nodeValue setter steps are to, if the given value is null, act as if it was the empty string instead,
  163. // and then do as described below, switching on the interface this implements:
  164. // If Attr, set an existing attribute value with this and the given value.
  165. if (is<Attribute>(this)) {
  166. verify_cast<Attribute>(this)->set_value(value);
  167. } else if (is<CharacterData>(this)) {
  168. // If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
  169. verify_cast<CharacterData>(this)->set_data(value);
  170. }
  171. // Otherwise, do nothing.
  172. }
  173. void Node::invalidate_style()
  174. {
  175. if (is_document()) {
  176. auto& document = static_cast<DOM::Document&>(*this);
  177. document.set_needs_full_style_update(true);
  178. document.schedule_style_update();
  179. return;
  180. }
  181. for_each_in_inclusive_subtree([&](Node& node) {
  182. node.m_needs_style_update = true;
  183. if (node.has_children())
  184. node.m_child_needs_style_update = true;
  185. if (auto* shadow_root = node.is_element() ? static_cast<DOM::Element&>(node).shadow_root() : nullptr) {
  186. node.m_child_needs_style_update = true;
  187. shadow_root->m_needs_style_update = true;
  188. if (shadow_root->has_children())
  189. shadow_root->m_child_needs_style_update = true;
  190. }
  191. return IterationDecision::Continue;
  192. });
  193. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host())
  194. ancestor->m_child_needs_style_update = true;
  195. document().schedule_style_update();
  196. }
  197. bool Node::is_link() const
  198. {
  199. return enclosing_link_element();
  200. }
  201. String Node::child_text_content() const
  202. {
  203. if (!is<ParentNode>(*this))
  204. return String::empty();
  205. StringBuilder builder;
  206. verify_cast<ParentNode>(*this).for_each_child([&](auto& child) {
  207. if (is<Text>(child))
  208. builder.append(verify_cast<Text>(child).text_content());
  209. });
  210. return builder.build();
  211. }
  212. // https://dom.spec.whatwg.org/#concept-tree-root
  213. Node& Node::root()
  214. {
  215. // The root of an object is itself, if its parent is null, or else it is the root of its parent.
  216. // The root of a tree is any object participating in that tree whose parent is null.
  217. Node* root = this;
  218. while (root->parent())
  219. root = root->parent();
  220. return *root;
  221. }
  222. // https://dom.spec.whatwg.org/#concept-shadow-including-root
  223. Node& Node::shadow_including_root()
  224. {
  225. // The shadow-including root of an object is its root’s host’s shadow-including root,
  226. // if the object’s root is a shadow root; otherwise its root.
  227. auto& node_root = root();
  228. if (is<ShadowRoot>(node_root))
  229. return verify_cast<ShadowRoot>(node_root).host()->shadow_including_root();
  230. return node_root;
  231. }
  232. // https://dom.spec.whatwg.org/#connected
  233. bool Node::is_connected() const
  234. {
  235. // An element is connected if its shadow-including root is a document.
  236. return shadow_including_root().is_document();
  237. }
  238. Element* Node::parent_element()
  239. {
  240. if (!parent() || !is<Element>(parent()))
  241. return nullptr;
  242. return verify_cast<Element>(parent());
  243. }
  244. Element const* Node::parent_element() const
  245. {
  246. if (!parent() || !is<Element>(parent()))
  247. return nullptr;
  248. return verify_cast<Element>(parent());
  249. }
  250. // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  251. ExceptionOr<void> Node::ensure_pre_insertion_validity(NonnullRefPtr<Node> node, RefPtr<Node> child) const
  252. {
  253. // 1. If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  254. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  255. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  256. // 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
  257. if (node->is_host_including_inclusive_ancestor_of(*this))
  258. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  259. // 3. If child is non-null and its parent is not parent, then throw a "NotFoundError" DOMException.
  260. if (child && child->parent() != this)
  261. return DOM::NotFoundError::create("This node is not the parent of the given child");
  262. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  263. // 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  264. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  265. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  266. // 5. If either node is a Text node and parent is a document, or node is a doctype and parent is not a document, then throw a "HierarchyRequestError" DOMException.
  267. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  268. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  269. // 6. If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "HierarchyRequestError" DOMException.
  270. if (is<Document>(this)) {
  271. // DocumentFragment
  272. if (is<DocumentFragment>(*node)) {
  273. // If node has more than one element child or has a Text node child.
  274. // Otherwise, if node has one element child and either parent has an element child, child is a doctype, or child is non-null and a doctype is following child.
  275. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  276. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  277. || (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>())))) {
  278. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  279. }
  280. } else if (is<Element>(*node)) {
  281. // Element
  282. // If parent has an element child, child is a doctype, or child is non-null and a doctype is following child.
  283. if (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) || (child && child->has_following_node_of_type_in_tree_order<DocumentType>()))
  284. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  285. } else if (is<DocumentType>(*node)) {
  286. // DocumentType
  287. // parent has a doctype child, child is non-null and an element is preceding child, or child is null and parent has an element child.
  288. if (has_child_of_type<DocumentType>() || (child && child->has_preceding_node_of_type_in_tree_order<Element>()) || (!child && has_child_of_type<Element>()))
  289. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  290. }
  291. }
  292. return {};
  293. }
  294. // https://dom.spec.whatwg.org/#concept-node-insert
  295. void Node::insert_before(NonnullRefPtr<Node> node, RefPtr<Node> child, bool suppress_observers)
  296. {
  297. // 1. Let nodes be node’s children, if node is a DocumentFragment node; otherwise « node ».
  298. NonnullRefPtrVector<Node> nodes;
  299. if (is<DocumentFragment>(*node))
  300. nodes = verify_cast<DocumentFragment>(*node).children_as_vector();
  301. else
  302. nodes.append(node);
  303. // 2. Let count be nodes’s size.
  304. auto count = nodes.size();
  305. // 3. If count is 0, then return.
  306. if (count == 0)
  307. return;
  308. // 4. If node is a DocumentFragment node, then:
  309. if (is<DocumentFragment>(*node)) {
  310. // 4.1 Remove its children with the suppress observers flag set.
  311. node->remove_all_children(true);
  312. // 4.2 FIXME: Queue a tree mutation record for node with « », nodes, null, and null.
  313. // NOTE: This step intentionally does not pay attention to the suppress observers flag.
  314. }
  315. // 5. If child is non-null, then:
  316. if (child) {
  317. // 5.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.
  318. for (auto& range : Range::live_ranges()) {
  319. if (range->start_container() == this && range->start_offset() > child->index())
  320. range->set_start(*range->start_container(), range->start_offset() + count);
  321. }
  322. // 5.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.
  323. for (auto& range : Range::live_ranges()) {
  324. if (range->end_container() == this && range->end_offset() > child->index())
  325. range->set_end(*range->end_container(), range->end_offset() + count);
  326. }
  327. }
  328. // 6. FIXME: Let previousSibling be child’s previous sibling or parent’s last child if child is null. (Currently unused so not included)
  329. // 7. For each node in nodes, in tree order:
  330. // FIXME: In tree order
  331. for (auto& node_to_insert : nodes) {
  332. // 7.1 Adopt node into parent’s node document.
  333. document().adopt_node(node_to_insert);
  334. // 7.2 If child is null, then append node to parent’s children.
  335. if (!child)
  336. TreeNode<Node>::append_child(node_to_insert);
  337. else
  338. // 7.3 Otherwise, insert node into parent’s children before child’s index.
  339. TreeNode<Node>::insert_before(node_to_insert, child);
  340. // FIXME: 7.4 If parent is a shadow host and node is a slottable, then assign a slot for node.
  341. // FIXME: 7.5 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.
  342. // FIXME: 7.6 Run assign slottables for a tree with node’s root.
  343. // FIXME: This should be shadow-including.
  344. // 7.7 For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
  345. node_to_insert.for_each_in_inclusive_subtree([&](Node& inclusive_descendant) {
  346. // 7.7.1 Run the insertion steps with inclusiveDescendant.
  347. inclusive_descendant.inserted();
  348. // 7.7.2 If inclusiveDescendant is connected, then:
  349. if (inclusive_descendant.is_connected()) {
  350. // 7.7.2.1 FIXME: If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant,
  351. // callback name "connectedCallback", and an empty argument list.
  352. // 7.7.2.2 FIXME: Otherwise, try to upgrade inclusiveDescendant.
  353. // NOTE: If this successfully upgrades inclusiveDescendant, its connectedCallback will be enqueued automatically during the upgrade an element algorithm.
  354. }
  355. return IterationDecision::Continue;
  356. });
  357. }
  358. // 8. If suppress observers flag is unset, then queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  359. if (!suppress_observers) {
  360. // FIXME: queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  361. }
  362. // 9. Run the children changed steps for parent.
  363. children_changed();
  364. document().invalidate_style();
  365. }
  366. // https://dom.spec.whatwg.org/#concept-node-pre-insert
  367. ExceptionOr<NonnullRefPtr<Node>> Node::pre_insert(NonnullRefPtr<Node> node, RefPtr<Node> child)
  368. {
  369. // 1. Ensure pre-insertion validity of node into parent before child.
  370. TRY(ensure_pre_insertion_validity(node, child));
  371. // 2. Let referenceChild be child.
  372. auto reference_child = child;
  373. // 3. If referenceChild is node, then set referenceChild to node’s next sibling.
  374. if (reference_child == node)
  375. reference_child = node->next_sibling();
  376. // 4. Insert node into parent before referenceChild.
  377. insert_before(node, reference_child);
  378. // 5. Return node.
  379. return node;
  380. }
  381. // https://dom.spec.whatwg.org/#dom-node-removechild
  382. ExceptionOr<NonnullRefPtr<Node>> Node::remove_child(NonnullRefPtr<Node> child)
  383. {
  384. // The removeChild(child) method steps are to return the result of pre-removing child from this.
  385. return pre_remove(child);
  386. }
  387. // https://dom.spec.whatwg.org/#concept-node-pre-remove
  388. ExceptionOr<NonnullRefPtr<Node>> Node::pre_remove(NonnullRefPtr<Node> child)
  389. {
  390. // 1. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
  391. if (child->parent() != this)
  392. return DOM::NotFoundError::create("Child does not belong to this node");
  393. // 2. Remove child.
  394. child->remove();
  395. // 3. Return child.
  396. return child;
  397. }
  398. // https://dom.spec.whatwg.org/#concept-node-append
  399. ExceptionOr<NonnullRefPtr<Node>> Node::append_child(NonnullRefPtr<Node> node)
  400. {
  401. // To append a node to a parent, pre-insert node into parent before null.
  402. return pre_insert(node, nullptr);
  403. }
  404. // https://dom.spec.whatwg.org/#concept-node-remove
  405. void Node::remove(bool suppress_observers)
  406. {
  407. // 1. Let parent be node’s parent
  408. auto* parent = TreeNode<Node>::parent();
  409. // 2. Assert: parent is non-null.
  410. VERIFY(parent);
  411. // 3. Let index be node’s index.
  412. auto index = this->index();
  413. // 4. For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
  414. for (auto& range : Range::live_ranges()) {
  415. if (range->start_container()->is_inclusive_descendant_of(*this))
  416. range->set_start(*parent, index);
  417. }
  418. // 5. For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
  419. for (auto& range : Range::live_ranges()) {
  420. if (range->end_container()->is_inclusive_descendant_of(*this))
  421. range->set_end(*parent, index);
  422. }
  423. // 6. For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
  424. for (auto& range : Range::live_ranges()) {
  425. if (range->start_container() == parent && range->start_offset() > index)
  426. range->set_start(*range->start_container(), range->start_offset() - 1);
  427. }
  428. // 7. For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
  429. for (auto& range : Range::live_ranges()) {
  430. if (range->end_container() == parent && range->end_offset() > index)
  431. range->set_end(*range->end_container(), range->end_offset() - 1);
  432. }
  433. // 8. 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.
  434. document().for_each_node_iterator([&](NodeIterator& node_iterator) {
  435. node_iterator.run_pre_removing_steps(*this);
  436. });
  437. // 9. FIXME: Let oldPreviousSibling be node’s previous sibling. (Currently unused so not included)
  438. // 10. FIXME: Let oldNextSibling be node’s next sibling. (Currently unused so not included)
  439. // 11. Remove node from its parent’s children.
  440. parent->TreeNode::remove_child(*this);
  441. // 12. FIXME: If node is assigned, then run assign slottables for node’s assigned slot.
  442. // 13. 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.
  443. // 14. FIXME: If node has an inclusive descendant that is a slot, then:
  444. // 14.1 Run assign slottables for a tree with parent’s root.
  445. // 14.2 Run assign slottables for a tree with node.
  446. // 15. Run the removing steps with node and parent.
  447. removed_from(parent);
  448. // 16. FIXME: Let isParentConnected be parent’s connected. (Currently unused so not included)
  449. // 17. FIXME: If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node,
  450. // callback name "disconnectedCallback", and an empty argument list.
  451. // NOTE: It is intentional for now that custom elements do not get parent passed. This might change in the future if there is a need.
  452. // FIXME: This should be shadow-including.
  453. // 18. For each shadow-including descendant descendant of node, in shadow-including tree order, then:
  454. for_each_in_subtree([&](Node& descendant) {
  455. // 18.1 Run the removing steps with descendant
  456. descendant.removed_from(nullptr);
  457. // 18.2 FIXME: If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant,
  458. // callback name "disconnectedCallback", and an empty argument list.
  459. return IterationDecision::Continue;
  460. });
  461. // 19. FIXME: For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of inclusiveAncestor’s registered observer list,
  462. // if registered’s options["subtree"] is true, then append a new transient registered observer
  463. // whose observer is registered’s observer, options is registered’s options, and source is registered to node’s registered observer list.
  464. // 20. If suppress observers flag is unset, then queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  465. if (!suppress_observers) {
  466. // FIXME: queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  467. }
  468. // 21. Run the children changed steps for parent.
  469. parent->children_changed();
  470. document().invalidate_style();
  471. }
  472. // https://dom.spec.whatwg.org/#concept-node-replace
  473. ExceptionOr<NonnullRefPtr<Node>> Node::replace_child(NonnullRefPtr<Node> node, NonnullRefPtr<Node> child)
  474. {
  475. // If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  476. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  477. return DOM::HierarchyRequestError::create("Can only insert into a document, document fragment or element");
  478. // 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
  479. if (node->is_host_including_inclusive_ancestor_of(*this))
  480. return DOM::HierarchyRequestError::create("New node is an ancestor of this node");
  481. // 3. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
  482. if (child->parent() != this)
  483. return DOM::NotFoundError::create("This node is not the parent of the given child");
  484. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  485. // 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  486. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  487. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  488. // 5. If either node is a Text node and parent is a document, or node is a doctype and parent is not a document, then throw a "HierarchyRequestError" DOMException.
  489. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  490. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  491. // If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "HierarchyRequestError" DOMException.
  492. if (is<Document>(this)) {
  493. // DocumentFragment
  494. if (is<DocumentFragment>(*node)) {
  495. // If node has more than one element child or has a Text node child.
  496. // Otherwise, if node has one element child and either parent has an element child that is not child or a doctype is following child.
  497. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  498. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  499. || (node_element_child_count == 1 && (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>()))) {
  500. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  501. }
  502. } else if (is<Element>(*node)) {
  503. // Element
  504. // parent has an element child that is not child or a doctype is following child.
  505. if (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>())
  506. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  507. } else if (is<DocumentType>(*node)) {
  508. // DocumentType
  509. // parent has a doctype child that is not child, or an element is preceding child.
  510. if (first_child_of_type<DocumentType>() != node || child->has_preceding_node_of_type_in_tree_order<Element>())
  511. return DOM::HierarchyRequestError::create("Invalid node type for insertion");
  512. }
  513. }
  514. // 7. Let referenceChild be child’s next sibling.
  515. auto reference_child = child->next_sibling();
  516. // 8. If referenceChild is node, then set referenceChild to node’s next sibling.
  517. if (reference_child == node)
  518. reference_child = node->next_sibling();
  519. // 9. FIXME: Let previousSibling be child’s previous sibling. (Currently unused so not included)
  520. // 10. FIXME: Let removedNodes be the empty set. (Currently unused so not included)
  521. // 11. If child’s parent is non-null, then:
  522. // NOTE: The above can only be false if child is node.
  523. if (child->parent()) {
  524. // 11.1 FIXME: Set removedNodes to « child ».
  525. // 11.2 Remove child with the suppress observers flag set.
  526. child->remove(true);
  527. }
  528. // 12. FIXME: Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ». (Currently unused so not included)
  529. // 13. Insert node into parent before referenceChild with the suppress observers flag set.
  530. insert_before(node, reference_child, true);
  531. // 14. FIXME: Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
  532. // 15. Return child.
  533. return child;
  534. }
  535. // https://dom.spec.whatwg.org/#concept-node-clone
  536. NonnullRefPtr<Node> Node::clone_node(Document* document, bool clone_children)
  537. {
  538. // 1. If document is not given, let document be node’s node document.
  539. if (!document)
  540. document = m_document;
  541. RefPtr<Node> copy;
  542. // 2. If node is an element, then:
  543. if (is<Element>(this)) {
  544. // 2.1 Let copy be the result of creating an element, given document, node’s local name, node’s namespace, node’s namespace prefix, and node’s is value, with the synchronous custom elements flag unset.
  545. auto& element = *verify_cast<Element>(this);
  546. 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 */);
  547. // 2.2 For each attribute in node’s attribute list:
  548. element.for_each_attribute([&](auto& name, auto& value) {
  549. // 2.2.1 Let copyAttribute be a clone of attribute.
  550. // 2.2.2 Append copyAttribute to copy.
  551. element_copy->set_attribute(name, value);
  552. });
  553. copy = move(element_copy);
  554. } else if (is<Document>(this)) {
  555. // 3. Otherwise, let copy be a node that implements the same interfaces as node, and fulfills these additional requirements, switching on the interface node implements:
  556. // Document
  557. auto document_ = verify_cast<Document>(this);
  558. auto document_copy = Document::create(document_->url());
  559. // Set copy’s encoding, content type, URL, origin, type, and mode to those of node.
  560. document_copy->set_encoding(document_->encoding());
  561. document_copy->set_content_type(document_->content_type());
  562. document_copy->set_url(document_->url());
  563. document_copy->set_origin(document_->origin());
  564. // FIXME: Set type ("xml" or "html")
  565. document_copy->set_quirks_mode(document_->mode());
  566. copy = move(document_copy);
  567. } else if (is<DocumentType>(this)) {
  568. // DocumentType
  569. auto document_type = verify_cast<DocumentType>(this);
  570. auto document_type_copy = adopt_ref(*new DocumentType(*document));
  571. // Set copy’s name, public ID, and system ID to those of node.
  572. document_type_copy->set_name(document_type->name());
  573. document_type_copy->set_public_id(document_type->public_id());
  574. document_type_copy->set_system_id(document_type->system_id());
  575. copy = move(document_type_copy);
  576. } else if (is<Attribute>(this)) {
  577. // FIXME:
  578. // Attr
  579. // Set copy’s namespace, namespace prefix, local name, and value to those of node.
  580. dbgln("clone_node() not implemented for Attribute");
  581. } else if (is<Text>(this)) {
  582. // Text
  583. auto text = verify_cast<Text>(this);
  584. // Set copy’s data to that of node.
  585. auto text_copy = adopt_ref(*new Text(*document, text->data()));
  586. copy = move(text_copy);
  587. } else if (is<Comment>(this)) {
  588. // Comment
  589. auto comment = verify_cast<Comment>(this);
  590. // Set copy’s data to that of node.
  591. auto comment_copy = adopt_ref(*new Comment(*document, comment->data()));
  592. copy = move(comment_copy);
  593. } else if (is<ProcessingInstruction>(this)) {
  594. // ProcessingInstruction
  595. auto processing_instruction = verify_cast<ProcessingInstruction>(this);
  596. // Set copy’s target and data to those of node.
  597. auto processing_instruction_copy = adopt_ref(*new ProcessingInstruction(*document, processing_instruction->data(), processing_instruction->target()));
  598. copy = move(processing_instruction_copy);
  599. }
  600. // Otherwise, Do nothing.
  601. // 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.
  602. // 5. Run any cloning steps defined for node in other applicable specifications and pass copy, node, document and the clone children flag if set, as parameters.
  603. cloned(*copy, clone_children);
  604. // 6. If the clone children flag is set, clone all the children of node and append them to copy, with document as specified and the clone children flag being set.
  605. if (clone_children) {
  606. for_each_child([&](auto& child) {
  607. copy->append_child(child.clone_node(document, true));
  608. });
  609. }
  610. // 7. Return copy.
  611. return copy.release_nonnull();
  612. }
  613. // https://dom.spec.whatwg.org/#dom-node-clonenode
  614. ExceptionOr<NonnullRefPtr<Node>> Node::clone_node_binding(bool deep)
  615. {
  616. // 1. If this is a shadow root, then throw a "NotSupportedError" DOMException.
  617. if (is<ShadowRoot>(*this))
  618. return NotSupportedError::create("Cannot clone shadow root");
  619. // 2. Return a clone of this, with the clone children flag set if deep is true.
  620. return clone_node(nullptr, deep);
  621. }
  622. void Node::set_document(Badge<Document>, Document& document)
  623. {
  624. if (m_document == &document)
  625. return;
  626. document.ref_from_node({});
  627. m_document->unref_from_node({});
  628. m_document = &document;
  629. if (needs_style_update() || child_needs_style_update()) {
  630. // NOTE: We unset and reset the "needs style update" flag here.
  631. // This ensures that there's a pending style update in the new document
  632. // that will eventually assign some style to this node if needed.
  633. set_needs_style_update(false);
  634. set_needs_style_update(true);
  635. }
  636. }
  637. bool Node::is_editable() const
  638. {
  639. return parent() && parent()->is_editable();
  640. }
  641. JS::Object* Node::create_wrapper(JS::GlobalObject& global_object)
  642. {
  643. return wrap(global_object, *this);
  644. }
  645. void Node::removed_last_ref()
  646. {
  647. if (is<Document>(*this)) {
  648. verify_cast<Document>(*this).removed_last_ref();
  649. return;
  650. }
  651. m_deletion_has_begun = true;
  652. delete this;
  653. }
  654. void Node::set_layout_node(Badge<Layout::Node>, Layout::Node* layout_node) const
  655. {
  656. if (layout_node)
  657. m_layout_node = layout_node->make_weak_ptr();
  658. else
  659. m_layout_node = nullptr;
  660. }
  661. EventTarget* Node::get_parent(Event const&)
  662. {
  663. // FIXME: returns the node’s assigned slot, if node is assigned, and node’s parent otherwise.
  664. return parent();
  665. }
  666. void Node::set_needs_style_update(bool value)
  667. {
  668. if (m_needs_style_update == value)
  669. return;
  670. m_needs_style_update = value;
  671. if (m_needs_style_update) {
  672. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
  673. ancestor->m_child_needs_style_update = true;
  674. }
  675. document().schedule_style_update();
  676. }
  677. }
  678. void Node::inserted()
  679. {
  680. set_needs_style_update(true);
  681. }
  682. ParentNode* Node::parent_or_shadow_host()
  683. {
  684. if (is<ShadowRoot>(*this))
  685. return verify_cast<ShadowRoot>(*this).host();
  686. return verify_cast<ParentNode>(parent());
  687. }
  688. NonnullRefPtr<NodeList> Node::child_nodes()
  689. {
  690. // FIXME: This should return the same LiveNodeList object every time,
  691. // but that would cause a reference cycle since NodeList refs the root.
  692. return LiveNodeList::create(*this, [this](auto& node) {
  693. return is_parent_of(node);
  694. });
  695. }
  696. NonnullRefPtrVector<Node> Node::children_as_vector() const
  697. {
  698. NonnullRefPtrVector<Node> nodes;
  699. for_each_child([&](auto& child) {
  700. nodes.append(child);
  701. });
  702. return nodes;
  703. }
  704. void Node::remove_all_children(bool suppress_observers)
  705. {
  706. while (RefPtr<Node> child = first_child())
  707. child->remove(suppress_observers);
  708. }
  709. // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
  710. u16 Node::compare_document_position(RefPtr<Node> other)
  711. {
  712. enum Position : u16 {
  713. DOCUMENT_POSITION_EQUAL = 0,
  714. DOCUMENT_POSITION_DISCONNECTED = 1,
  715. DOCUMENT_POSITION_PRECEDING = 2,
  716. DOCUMENT_POSITION_FOLLOWING = 4,
  717. DOCUMENT_POSITION_CONTAINS = 8,
  718. DOCUMENT_POSITION_CONTAINED_BY = 16,
  719. DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32,
  720. };
  721. // 1. If this is other, then return zero.
  722. if (this == other)
  723. return DOCUMENT_POSITION_EQUAL;
  724. // 2. Let node1 be other and node2 be this.
  725. Node* node1 = other.ptr();
  726. Node* node2 = this;
  727. // 3. Let attr1 and attr2 be null.
  728. Attribute* attr1;
  729. Attribute* attr2;
  730. // 4. If node1 is an attribute, then set attr1 to node1 and node1 to attr1’s element.
  731. if (is<Attribute>(node1)) {
  732. attr1 = verify_cast<Attribute>(node1);
  733. node1 = const_cast<Element*>(attr1->owner_element());
  734. }
  735. // 5. If node2 is an attribute, then:
  736. if (is<Attribute>(node2)) {
  737. // 5.1 Set attr2 to node2 and node2 to attr2’s element.
  738. attr2 = verify_cast<Attribute>(node2);
  739. node2 = const_cast<Element*>(attr2->owner_element());
  740. // 5.2 If attr1 and node1 are non-null, and node2 is node1, then:
  741. if (attr1 && node1 && node2 == node1) {
  742. // 5.2.1 FIXME: For each attr in node2’s attribute list:
  743. // 5.2.1.1 FIXME: If attr equals attr1, then return the result of adding DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC and DOCUMENT_POSITION_PRECEDING.
  744. // 5.2.1.2 FIXME: If attr equals attr2, then return the result of adding DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC and DOCUMENT_POSITION_FOLLOWING.
  745. }
  746. }
  747. // 6. If node1 or node2 is null, or node1’s root is not node2’s root, then return the result of adding
  748. // DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, and either DOCUMENT_POSITION_PRECEDING or DOCUMENT_POSITION_FOLLOWING, with the constraint that this is to be consistent, together.
  749. if ((node1 == nullptr || node2 == nullptr) || (&node1->root() != &node2->root()))
  750. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | (node1 > node2 ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING);
  751. // 7. If node1 is an ancestor of node2 and attr1 is null, or node1 is node2 and attr2 is non-null, then return the result of adding DOCUMENT_POSITION_CONTAINS to DOCUMENT_POSITION_PRECEDING.
  752. if ((node1->is_ancestor_of(*node2) && !attr1) || (node1 == node2 && attr2))
  753. return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
  754. // 8. If node1 is a descendant of node2 and attr2 is null, or node1 is node2 and attr1 is non-null, then return the result of adding DOCUMENT_POSITION_CONTAINED_BY to DOCUMENT_POSITION_FOLLOWING.
  755. if ((node2->is_ancestor_of(*node1) && !attr2) || (node1 == node2 && attr1))
  756. return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
  757. // 9. If node1 is preceding node2, then return DOCUMENT_POSITION_PRECEDING.
  758. if (node1->is_before(*node2))
  759. return DOCUMENT_POSITION_PRECEDING;
  760. // 10. Return DOCUMENT_POSITION_FOLLOWING.
  761. return DOCUMENT_POSITION_FOLLOWING;
  762. }
  763. // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
  764. bool Node::is_host_including_inclusive_ancestor_of(Node const& other) const
  765. {
  766. // An object A is a host-including inclusive ancestor of an object B,
  767. // if either A is an inclusive ancestor of B,
  768. if (is_inclusive_ancestor_of(other))
  769. return true;
  770. // or if B’s root has a non-null host and A is a host-including inclusive ancestor of B’s root’s host
  771. if (is<DocumentFragment>(other.root())
  772. && static_cast<DocumentFragment const&>(other.root()).host()
  773. && is_inclusive_ancestor_of(*static_cast<DocumentFragment const&>(other.root()).host())) {
  774. return true;
  775. }
  776. return false;
  777. }
  778. // https://dom.spec.whatwg.org/#dom-node-ownerdocument
  779. RefPtr<Document> Node::owner_document() const
  780. {
  781. // The ownerDocument getter steps are to return null, if this is a document; otherwise this’s node document.
  782. if (is_document())
  783. return nullptr;
  784. return m_document;
  785. }
  786. // This function tells us whether a node is interesting enough to show up
  787. // in the DOM inspector. This hides two things:
  788. // - Non-rendered whitespace
  789. // - Rendered whitespace between block-level elements
  790. bool Node::is_uninteresting_whitespace_node() const
  791. {
  792. if (!is<Text>(*this))
  793. return false;
  794. if (!static_cast<Text const&>(*this).data().is_whitespace())
  795. return false;
  796. if (!layout_node())
  797. return true;
  798. if (layout_node()->parent()->is_anonymous())
  799. return true;
  800. return false;
  801. }
  802. void Node::serialize_tree_as_json(JsonObjectSerializer<StringBuilder>& object) const
  803. {
  804. MUST(object.add("name", node_name().view()));
  805. MUST(object.add("id", id()));
  806. if (is_document()) {
  807. MUST(object.add("type", "document"));
  808. } else if (is_element()) {
  809. MUST(object.add("type", "element"));
  810. auto const* element = static_cast<DOM::Element const*>(this);
  811. if (element->has_attributes()) {
  812. auto attributes = MUST(object.add_object("attributes"));
  813. element->for_each_attribute([&attributes](auto& name, auto& value) {
  814. MUST(attributes.add(name, value));
  815. });
  816. MUST(attributes.finish());
  817. }
  818. if (element->is_browsing_context_container()) {
  819. auto const* container = static_cast<HTML::BrowsingContextContainer const*>(element);
  820. if (auto const* content_document = container->content_document()) {
  821. auto children = MUST(object.add_array("children"));
  822. JsonObjectSerializer<StringBuilder> content_document_object = MUST(children.add_object());
  823. content_document->serialize_tree_as_json(content_document_object);
  824. MUST(content_document_object.finish());
  825. MUST(children.finish());
  826. }
  827. }
  828. } else if (is_text()) {
  829. MUST(object.add("type", "text"));
  830. auto text_node = static_cast<DOM::Text const*>(this);
  831. MUST(object.add("text", text_node->data()));
  832. } else if (is_comment()) {
  833. MUST(object.add("type"sv, "comment"sv));
  834. MUST(object.add("data"sv, static_cast<DOM::Comment const&>(*this).data()));
  835. }
  836. MUST((object.add("visible"sv, !!layout_node())));
  837. if (has_child_nodes()) {
  838. auto children = MUST(object.add_array("children"));
  839. for_each_child([&children](DOM::Node& child) {
  840. if (child.is_uninteresting_whitespace_node())
  841. return;
  842. JsonObjectSerializer<StringBuilder> child_object = MUST(children.add_object());
  843. child.serialize_tree_as_json(child_object);
  844. MUST(child_object.finish());
  845. });
  846. // Pseudo-elements don't have DOM nodes,so we have to add them separately.
  847. if (is_element()) {
  848. auto const* element = static_cast<DOM::Element const*>(this);
  849. element->serialize_pseudo_elements_as_json(children);
  850. }
  851. MUST(children.finish());
  852. }
  853. }
  854. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-script
  855. bool Node::is_scripting_enabled() const
  856. {
  857. // Scripting is enabled for a node node if node's node document's browsing context is non-null, and scripting is enabled for node's relevant settings object.
  858. return document().browsing_context() && const_cast<Document&>(document()).relevant_settings_object().is_scripting_enabled();
  859. }
  860. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-noscript
  861. bool Node::is_scripting_disabled() const
  862. {
  863. // Scripting is disabled for a node when scripting is not enabled, i.e., when its node document's browsing context is null or when scripting is disabled for its relevant settings object.
  864. return !is_scripting_enabled();
  865. }
  866. // https://dom.spec.whatwg.org/#dom-node-contains
  867. bool Node::contains(RefPtr<Node> other) const
  868. {
  869. // The contains(other) method steps are to return true if other is an inclusive descendant of this; otherwise false (including when other is null).
  870. return other && other->is_inclusive_descendant_of(*this);
  871. }
  872. // https://dom.spec.whatwg.org/#concept-shadow-including-descendant
  873. bool Node::is_shadow_including_descendant_of(Node const& other) const
  874. {
  875. // An object A is a shadow-including descendant of an object B,
  876. // if A is a descendant of B,
  877. if (is_descendant_of(other))
  878. return true;
  879. // or A’s root is a shadow root
  880. if (!is<ShadowRoot>(root()))
  881. return false;
  882. // and A’s root’s host is a shadow-including inclusive descendant of B.
  883. auto& shadow_root = verify_cast<ShadowRoot>(root());
  884. // NOTE: While host is nullable because of inheriting from DocumentFragment, shadow roots always have a host.
  885. return shadow_root.host()->is_shadow_including_inclusive_descendant_of(other);
  886. }
  887. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
  888. bool Node::is_shadow_including_inclusive_descendant_of(Node const& other) const
  889. {
  890. // A shadow-including inclusive descendant is an object or one of its shadow-including descendants.
  891. return &other == this || is_shadow_including_descendant_of(other);
  892. }
  893. // https://dom.spec.whatwg.org/#concept-shadow-including-ancestor
  894. bool Node::is_shadow_including_ancestor_of(Node const& other) const
  895. {
  896. // An object A is a shadow-including ancestor of an object B, if and only if B is a shadow-including descendant of A.
  897. return other.is_shadow_including_descendant_of(*this);
  898. }
  899. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor
  900. bool Node::is_shadow_including_inclusive_ancestor_of(Node const& other) const
  901. {
  902. // A shadow-including inclusive ancestor is an object or one of its shadow-including ancestors.
  903. return other.is_shadow_including_inclusive_descendant_of(*this);
  904. }
  905. // https://dom.spec.whatwg.org/#concept-node-replace-all
  906. void Node::replace_all(RefPtr<Node> node)
  907. {
  908. // 1. FIXME: Let removedNodes be parent’s children. (Current unused so not included)
  909. // 2. FIXME: Let addedNodes be the empty set. (Currently unused so not included)
  910. // 3. FIXME: If node is a DocumentFragment node, then set addedNodes to node’s children.
  911. // 4. FIXME: Otherwise, if node is non-null, set addedNodes to « node ».
  912. // 5. Remove all parent’s children, in tree order, with the suppress observers flag set.
  913. remove_all_children(true);
  914. // 6. If node is non-null, then insert node into parent before null with the suppress observers flag set.
  915. if (node)
  916. insert_before(*node, nullptr, true);
  917. // 7. FIXME: If either addedNodes or removedNodes is not empty, then queue a tree mutation record for parent with addedNodes, removedNodes, null, and null.
  918. }
  919. // https://dom.spec.whatwg.org/#string-replace-all
  920. void Node::string_replace_all(String const& string)
  921. {
  922. // 1. Let node be null.
  923. RefPtr<Node> node;
  924. // 2. If string is not the empty string, then set node to a new Text node whose data is string and node document is parent’s node document.
  925. if (!string.is_empty())
  926. node = make_ref_counted<Text>(document(), string);
  927. // 3. Replace all with node within parent.
  928. replace_all(node);
  929. }
  930. // https://w3c.github.io/DOM-Parsing/#dfn-fragment-serializing-algorithm
  931. String Node::serialize_fragment(/* FIXME: Requires well-formed flag */) const
  932. {
  933. // 1. FIXME: Let context document be the value of node's node document.
  934. // 2. FIXME: If context document is an HTML document, return an HTML serialization of node.
  935. // (We currently always do this)
  936. return HTML::HTMLParser::serialize_html_fragment(*this);
  937. // 3. FIXME: Otherwise, context document is an XML document; return an XML serialization of node passing the flag require well-formed.
  938. }
  939. // https://dom.spec.whatwg.org/#dom-node-issamenode
  940. bool Node::is_same_node(Node const* other_node) const
  941. {
  942. // The isSameNode(otherNode) method steps are to return true if otherNode is this; otherwise false.
  943. return this == other_node;
  944. }
  945. // https://dom.spec.whatwg.org/#dom-node-isequalnode
  946. bool Node::is_equal_node(Node const* other_node) const
  947. {
  948. // The isEqualNode(otherNode) method steps are to return true if otherNode is non-null and this equals otherNode; otherwise false.
  949. if (!other_node)
  950. return false;
  951. // Fast path for testing a node against itself.
  952. if (this == other_node)
  953. return true;
  954. // A node A equals a node B if all of the following conditions are true:
  955. // A and B implement the same interfaces.
  956. if (node_name() != other_node->node_name())
  957. return false;
  958. // The following are equal, switching on the interface A implements:
  959. switch (node_type()) {
  960. case (u16)NodeType::DOCUMENT_TYPE_NODE: {
  961. // Its name, public ID, and system ID.
  962. auto& this_doctype = verify_cast<DocumentType>(*this);
  963. auto& other_doctype = verify_cast<DocumentType>(*other_node);
  964. if (this_doctype.name() != other_doctype.name()
  965. || this_doctype.public_id() != other_doctype.public_id()
  966. || this_doctype.system_id() != other_doctype.system_id())
  967. return false;
  968. break;
  969. }
  970. case (u16)NodeType::ELEMENT_NODE: {
  971. // Its namespace, namespace prefix, local name, and its attribute list’s size.
  972. auto& this_element = verify_cast<Element>(*this);
  973. auto& other_element = verify_cast<Element>(*other_node);
  974. if (this_element.namespace_() != other_element.namespace_()
  975. || this_element.prefix() != other_element.prefix()
  976. || this_element.local_name() != other_element.local_name()
  977. || this_element.attribute_list_size() != other_element.attribute_list_size())
  978. return false;
  979. // If A is an element, each attribute in its attribute list has an attribute that equals an attribute in B’s attribute list.
  980. bool has_same_attributes = true;
  981. this_element.for_each_attribute([&](auto& name, auto& value) {
  982. if (other_element.get_attribute(name) != value)
  983. has_same_attributes = false;
  984. });
  985. if (!has_same_attributes)
  986. return false;
  987. break;
  988. }
  989. case (u16)NodeType::COMMENT_NODE:
  990. case (u16)NodeType::TEXT_NODE: {
  991. // Its data.
  992. auto& this_cdata = verify_cast<CharacterData>(*this);
  993. auto& other_cdata = verify_cast<CharacterData>(*other_node);
  994. if (this_cdata.data() != other_cdata.data())
  995. return false;
  996. break;
  997. }
  998. case (u16)NodeType::PROCESSING_INSTRUCTION_NODE:
  999. case (u16)NodeType::ATTRIBUTE_NODE:
  1000. TODO();
  1001. default:
  1002. break;
  1003. }
  1004. // A and B have the same number of children.
  1005. size_t this_child_count = child_count();
  1006. size_t other_child_count = other_node->child_count();
  1007. if (this_child_count != other_child_count)
  1008. return false;
  1009. // Each child of A equals the child of B at the identical index.
  1010. // FIXME: This can be made nicer. child_at_index() is O(n).
  1011. for (size_t i = 0; i < this_child_count; ++i) {
  1012. auto* this_child = child_at_index(i);
  1013. auto* other_child = other_node->child_at_index(i);
  1014. VERIFY(this_child);
  1015. VERIFY(other_child);
  1016. if (!this_child->is_equal_node(other_child))
  1017. return false;
  1018. }
  1019. return true;
  1020. }
  1021. // https://dom.spec.whatwg.org/#in-a-document-tree
  1022. bool Node::in_a_document_tree() const
  1023. {
  1024. // An element is in a document tree if its root is a document.
  1025. return root().is_document();
  1026. }
  1027. // https://dom.spec.whatwg.org/#dom-node-getrootnode
  1028. NonnullRefPtr<Node> Node::get_root_node(GetRootNodeOptions const& options)
  1029. {
  1030. // The getRootNode(options) method steps are to return this’s shadow-including root if options["composed"] is true;
  1031. if (options.composed)
  1032. return shadow_including_root();
  1033. // otherwise this’s root.
  1034. return root();
  1035. }
  1036. String Node::debug_description() const
  1037. {
  1038. StringBuilder builder;
  1039. builder.append(node_name().to_lowercase());
  1040. if (is_element()) {
  1041. auto& element = static_cast<DOM::Element const&>(*this);
  1042. if (auto id = element.get_attribute(HTML::AttributeNames::id); !id.is_null())
  1043. builder.appendff("#{}", id);
  1044. for (auto const& class_name : element.class_names())
  1045. builder.appendff(".{}", class_name);
  1046. }
  1047. return builder.to_string();
  1048. }
  1049. // https://dom.spec.whatwg.org/#concept-node-length
  1050. size_t Node::length() const
  1051. {
  1052. // 1. If node is a DocumentType or Attr node, then return 0.
  1053. if (is_document_type() || is_attribute())
  1054. return 0;
  1055. // 2. If node is a CharacterData node, then return node’s data’s length.
  1056. if (is_character_data()) {
  1057. auto* character_data_node = verify_cast<CharacterData>(this);
  1058. return character_data_node->data().length();
  1059. }
  1060. // 3. Return the number of node’s children.
  1061. return child_count();
  1062. }
  1063. Painting::Paintable const* Node::paintable() const
  1064. {
  1065. if (!layout_node())
  1066. return nullptr;
  1067. return layout_node()->paintable();
  1068. }
  1069. Painting::PaintableBox const* Node::paint_box() const
  1070. {
  1071. if (!layout_node())
  1072. return nullptr;
  1073. if (!layout_node()->is_box())
  1074. return nullptr;
  1075. return static_cast<Layout::Box const&>(*layout_node()).paint_box();
  1076. }
  1077. }