Node.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  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/Heap/DeferGC.h>
  12. #include <LibJS/Runtime/FunctionObject.h>
  13. #include <LibWeb/Bindings/MainThreadVM.h>
  14. #include <LibWeb/Bindings/NodePrototype.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/MutationType.h>
  24. #include <LibWeb/DOM/Node.h>
  25. #include <LibWeb/DOM/NodeIterator.h>
  26. #include <LibWeb/DOM/ProcessingInstruction.h>
  27. #include <LibWeb/DOM/Range.h>
  28. #include <LibWeb/DOM/ShadowRoot.h>
  29. #include <LibWeb/DOM/StaticNodeList.h>
  30. #include <LibWeb/HTML/BrowsingContextContainer.h>
  31. #include <LibWeb/HTML/HTMLAnchorElement.h>
  32. #include <LibWeb/HTML/Origin.h>
  33. #include <LibWeb/HTML/Parser/HTMLParser.h>
  34. #include <LibWeb/Layout/InitialContainingBlock.h>
  35. #include <LibWeb/Layout/Node.h>
  36. #include <LibWeb/Layout/TextNode.h>
  37. namespace Web::DOM {
  38. static IDAllocator s_node_id_allocator;
  39. static HashMap<i32, Node*> s_node_directory;
  40. static i32 allocate_node_id(Node* node)
  41. {
  42. i32 id = s_node_id_allocator.allocate();
  43. s_node_directory.set(id, node);
  44. return id;
  45. }
  46. static void deallocate_node_id(i32 node_id)
  47. {
  48. if (!s_node_directory.remove(node_id))
  49. VERIFY_NOT_REACHED();
  50. s_node_id_allocator.deallocate(node_id);
  51. }
  52. Node* Node::from_id(i32 node_id)
  53. {
  54. return s_node_directory.get(node_id).value_or(nullptr);
  55. }
  56. Node::Node(JS::Realm& realm, Document& document, NodeType type)
  57. : EventTarget(realm)
  58. , m_document(&document)
  59. , m_type(type)
  60. , m_id(allocate_node_id(this))
  61. {
  62. }
  63. Node::Node(Document& document, NodeType type)
  64. : Node(document.realm(), document, type)
  65. {
  66. }
  67. Node::~Node()
  68. {
  69. if (layout_node() && layout_node()->parent())
  70. layout_node()->parent()->remove_child(*layout_node());
  71. deallocate_node_id(m_id);
  72. }
  73. void Node::visit_edges(Cell::Visitor& visitor)
  74. {
  75. Base::visit_edges(visitor);
  76. visitor.visit(m_document.ptr());
  77. visitor.visit(m_parent.ptr());
  78. visitor.visit(m_first_child.ptr());
  79. visitor.visit(m_last_child.ptr());
  80. visitor.visit(m_next_sibling.ptr());
  81. visitor.visit(m_previous_sibling.ptr());
  82. visitor.visit(m_child_nodes);
  83. for (auto& registered_observer : m_registered_observer_list)
  84. visitor.visit(registered_observer);
  85. }
  86. // https://dom.spec.whatwg.org/#dom-node-baseuri
  87. String Node::base_uri() const
  88. {
  89. // Return this’s node document’s document base URL, serialized.
  90. return document().base_url().to_string();
  91. }
  92. const HTML::HTMLAnchorElement* Node::enclosing_link_element() const
  93. {
  94. for (auto* node = this; node; node = node->parent()) {
  95. if (!is<HTML::HTMLAnchorElement>(*node))
  96. continue;
  97. auto const& anchor_element = static_cast<HTML::HTMLAnchorElement const&>(*node);
  98. if (anchor_element.has_attribute(HTML::AttributeNames::href))
  99. return &anchor_element;
  100. }
  101. return nullptr;
  102. }
  103. const HTML::HTMLElement* Node::enclosing_html_element() const
  104. {
  105. return first_ancestor_of_type<HTML::HTMLElement>();
  106. }
  107. const HTML::HTMLElement* Node::enclosing_html_element_with_attribute(FlyString const& attribute) const
  108. {
  109. for (auto* node = this; node; node = node->parent()) {
  110. if (is<HTML::HTMLElement>(*node) && verify_cast<HTML::HTMLElement>(*node).has_attribute(attribute))
  111. return verify_cast<HTML::HTMLElement>(node);
  112. }
  113. return nullptr;
  114. }
  115. // https://dom.spec.whatwg.org/#concept-descendant-text-content
  116. String Node::descendant_text_content() const
  117. {
  118. StringBuilder builder;
  119. for_each_in_subtree_of_type<Text>([&](auto& text_node) {
  120. builder.append(text_node.data());
  121. return IterationDecision::Continue;
  122. });
  123. return builder.to_string();
  124. }
  125. // https://dom.spec.whatwg.org/#dom-node-textcontent
  126. String Node::text_content() const
  127. {
  128. // The textContent getter steps are to return the following, switching on the interface this implements:
  129. // If DocumentFragment or Element, return the descendant text content of this.
  130. if (is<DocumentFragment>(this) || is<Element>(this))
  131. return descendant_text_content();
  132. // If CharacterData, return this’s data.
  133. if (is<CharacterData>(this))
  134. return static_cast<CharacterData const&>(*this).data();
  135. // If Attr node, return this's value.
  136. if (is<Attr>(*this))
  137. return static_cast<Attr const&>(*this).value();
  138. // Otherwise, return null
  139. return {};
  140. }
  141. // https://dom.spec.whatwg.org/#ref-for-dom-node-textcontent%E2%91%A0
  142. void Node::set_text_content(String const& content)
  143. {
  144. // The textContent setter steps are to, if the given value is null, act as if it was the empty string instead,
  145. // and then do as described below, switching on the interface this implements:
  146. // If DocumentFragment or Element, string replace all with the given value within this.
  147. if (is<DocumentFragment>(this) || is<Element>(this)) {
  148. string_replace_all(content);
  149. }
  150. // If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
  151. else if (is<CharacterData>(this)) {
  152. auto* character_data_node = verify_cast<CharacterData>(this);
  153. character_data_node->set_data(content);
  154. // FIXME: CharacterData::set_data is not spec compliant. Make this match the spec when set_data becomes spec compliant.
  155. // Do note that this will make this function able to throw an exception.
  156. }
  157. // If Attr, set an existing attribute value with this and the given value.
  158. if (is<Attr>(*this)) {
  159. static_cast<Attr&>(*this).set_value(content);
  160. }
  161. // Otherwise, do nothing.
  162. set_needs_style_update(true);
  163. }
  164. // https://dom.spec.whatwg.org/#dom-node-nodevalue
  165. String Node::node_value() const
  166. {
  167. // The nodeValue getter steps are to return the following, switching on the interface this implements:
  168. // If Attr, return this’s value.
  169. if (is<Attr>(this)) {
  170. return verify_cast<Attr>(this)->value();
  171. }
  172. // If CharacterData, return this’s data.
  173. if (is<CharacterData>(this)) {
  174. return verify_cast<CharacterData>(this)->data();
  175. }
  176. // Otherwise, return null.
  177. return {};
  178. }
  179. // https://dom.spec.whatwg.org/#ref-for-dom-node-nodevalue%E2%91%A0
  180. void Node::set_node_value(String const& value)
  181. {
  182. // The nodeValue setter steps are to, if the given value is null, act as if it was the empty string instead,
  183. // and then do as described below, switching on the interface this implements:
  184. // If Attr, set an existing attribute value with this and the given value.
  185. if (is<Attr>(this)) {
  186. verify_cast<Attr>(this)->set_value(value);
  187. } else if (is<CharacterData>(this)) {
  188. // If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
  189. verify_cast<CharacterData>(this)->set_data(value);
  190. }
  191. // Otherwise, do nothing.
  192. }
  193. void Node::invalidate_style()
  194. {
  195. if (is_document()) {
  196. auto& document = static_cast<DOM::Document&>(*this);
  197. document.set_needs_full_style_update(true);
  198. document.schedule_style_update();
  199. return;
  200. }
  201. for_each_in_inclusive_subtree([&](Node& node) {
  202. node.m_needs_style_update = true;
  203. if (node.has_children())
  204. node.m_child_needs_style_update = true;
  205. if (auto* shadow_root = node.is_element() ? static_cast<DOM::Element&>(node).shadow_root() : nullptr) {
  206. node.m_child_needs_style_update = true;
  207. shadow_root->m_needs_style_update = true;
  208. if (shadow_root->has_children())
  209. shadow_root->m_child_needs_style_update = true;
  210. }
  211. return IterationDecision::Continue;
  212. });
  213. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host())
  214. ancestor->m_child_needs_style_update = true;
  215. document().schedule_style_update();
  216. }
  217. String Node::child_text_content() const
  218. {
  219. if (!is<ParentNode>(*this))
  220. return String::empty();
  221. StringBuilder builder;
  222. verify_cast<ParentNode>(*this).for_each_child([&](auto& child) {
  223. if (is<Text>(child))
  224. builder.append(verify_cast<Text>(child).text_content());
  225. });
  226. return builder.build();
  227. }
  228. // https://dom.spec.whatwg.org/#concept-tree-root
  229. Node& Node::root()
  230. {
  231. // The root of an object is itself, if its parent is null, or else it is the root of its parent.
  232. // The root of a tree is any object participating in that tree whose parent is null.
  233. Node* root = this;
  234. while (root->parent())
  235. root = root->parent();
  236. return *root;
  237. }
  238. // https://dom.spec.whatwg.org/#concept-shadow-including-root
  239. Node& Node::shadow_including_root()
  240. {
  241. // The shadow-including root of an object is its root’s host’s shadow-including root,
  242. // if the object’s root is a shadow root; otherwise its root.
  243. auto& node_root = root();
  244. if (is<ShadowRoot>(node_root))
  245. return verify_cast<ShadowRoot>(node_root).host()->shadow_including_root();
  246. return node_root;
  247. }
  248. // https://dom.spec.whatwg.org/#connected
  249. bool Node::is_connected() const
  250. {
  251. // An element is connected if its shadow-including root is a document.
  252. return shadow_including_root().is_document();
  253. }
  254. Element* Node::parent_element()
  255. {
  256. if (!parent() || !is<Element>(parent()))
  257. return nullptr;
  258. return verify_cast<Element>(parent());
  259. }
  260. Element const* Node::parent_element() const
  261. {
  262. if (!parent() || !is<Element>(parent()))
  263. return nullptr;
  264. return verify_cast<Element>(parent());
  265. }
  266. // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  267. ExceptionOr<void> Node::ensure_pre_insertion_validity(JS::NonnullGCPtr<Node> node, JS::GCPtr<Node> child) const
  268. {
  269. // 1. If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  270. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  271. return DOM::HierarchyRequestError::create(global_object(), "Can only insert into a document, document fragment or element");
  272. // 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
  273. if (node->is_host_including_inclusive_ancestor_of(*this))
  274. return DOM::HierarchyRequestError::create(global_object(), "New node is an ancestor of this node");
  275. // 3. If child is non-null and its parent is not parent, then throw a "NotFoundError" DOMException.
  276. if (child && child->parent() != this)
  277. return DOM::NotFoundError::create(global_object(), "This node is not the parent of the given child");
  278. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  279. // 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  280. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  281. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  282. // 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.
  283. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  284. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  285. // 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.
  286. if (is<Document>(this)) {
  287. // DocumentFragment
  288. if (is<DocumentFragment>(*node)) {
  289. // If node has more than one element child or has a Text node child.
  290. // 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.
  291. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  292. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  293. || (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>())))) {
  294. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  295. }
  296. } else if (is<Element>(*node)) {
  297. // Element
  298. // If parent has an element child, child is a doctype, or child is non-null and a doctype is following child.
  299. if (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) || (child && child->has_following_node_of_type_in_tree_order<DocumentType>()))
  300. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  301. } else if (is<DocumentType>(*node)) {
  302. // DocumentType
  303. // 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.
  304. if (has_child_of_type<DocumentType>() || (child && child->has_preceding_node_of_type_in_tree_order<Element>()) || (!child && has_child_of_type<Element>()))
  305. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  306. }
  307. }
  308. return {};
  309. }
  310. // https://dom.spec.whatwg.org/#concept-node-insert
  311. void Node::insert_before(JS::NonnullGCPtr<Node> node, JS::GCPtr<Node> child, bool suppress_observers)
  312. {
  313. // 1. Let nodes be node’s children, if node is a DocumentFragment node; otherwise « node ».
  314. Vector<JS::Handle<Node>> nodes;
  315. if (is<DocumentFragment>(*node))
  316. nodes = node->children_as_vector();
  317. else
  318. nodes.append(JS::make_handle(*node));
  319. // 2. Let count be nodes’s size.
  320. auto count = nodes.size();
  321. // 3. If count is 0, then return.
  322. if (count == 0)
  323. return;
  324. // 4. If node is a DocumentFragment node, then:
  325. if (is<DocumentFragment>(*node)) {
  326. // 1. Remove its children with the suppress observers flag set.
  327. node->remove_all_children(true);
  328. // 2. Queue a tree mutation record for node with « », nodes, null, and null.
  329. // NOTE: This step intentionally does not pay attention to the suppress observers flag.
  330. node->queue_tree_mutation_record(StaticNodeList::create(window(), {}), StaticNodeList::create(window(), nodes), nullptr, nullptr);
  331. }
  332. // 5. If child is non-null, then:
  333. if (child) {
  334. // 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.
  335. for (auto& range : Range::live_ranges()) {
  336. if (range->start_container() == this && range->start_offset() > child->index())
  337. range->set_start(*range->start_container(), range->start_offset() + count);
  338. }
  339. // 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.
  340. for (auto& range : Range::live_ranges()) {
  341. if (range->end_container() == this && range->end_offset() > child->index())
  342. range->set_end(*range->end_container(), range->end_offset() + count);
  343. }
  344. }
  345. // 6. Let previousSibling be child’s previous sibling or parent’s last child if child is null.
  346. JS::GCPtr<Node> previous_sibling;
  347. if (child)
  348. previous_sibling = child->previous_sibling();
  349. else
  350. previous_sibling = last_child();
  351. // 7. For each node in nodes, in tree order:
  352. // FIXME: In tree order
  353. for (auto& node_to_insert : nodes) {
  354. // 1. Adopt node into parent’s node document.
  355. document().adopt_node(*node_to_insert);
  356. // 2. If child is null, then append node to parent’s children.
  357. if (!child)
  358. append_child_impl(*node_to_insert);
  359. // 3. Otherwise, insert node into parent’s children before child’s index.
  360. else
  361. insert_before_impl(*node_to_insert, child);
  362. // FIXME: 4. If parent is a shadow host and node is a slottable, then assign a slot for node.
  363. // FIXME: 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.
  364. // FIXME: 6. Run assign slottables for a tree with node’s root.
  365. // FIXME: This should be shadow-including.
  366. // 7. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
  367. node_to_insert->for_each_in_inclusive_subtree([&](Node& inclusive_descendant) {
  368. // 1. Run the insertion steps with inclusiveDescendant.
  369. inclusive_descendant.inserted();
  370. // 2. If inclusiveDescendant is connected, then:
  371. if (inclusive_descendant.is_connected()) {
  372. // FIXME: 1. If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant, callback name "connectedCallback", and an empty argument list.
  373. // FIXME: 2. Otherwise, try to upgrade inclusiveDescendant.
  374. // NOTE: If this successfully upgrades inclusiveDescendant, its connectedCallback will be enqueued automatically during the upgrade an element algorithm.
  375. }
  376. return IterationDecision::Continue;
  377. });
  378. }
  379. // 8. If suppress observers flag is unset, then queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  380. if (!suppress_observers)
  381. queue_tree_mutation_record(StaticNodeList::create(window(), move(nodes)), StaticNodeList::create(window(), {}), previous_sibling.ptr(), child.ptr());
  382. // 9. Run the children changed steps for parent.
  383. children_changed();
  384. document().invalidate_style();
  385. }
  386. // https://dom.spec.whatwg.org/#concept-node-pre-insert
  387. ExceptionOr<JS::NonnullGCPtr<Node>> Node::pre_insert(JS::NonnullGCPtr<Node> node, JS::GCPtr<Node> child)
  388. {
  389. // 1. Ensure pre-insertion validity of node into parent before child.
  390. TRY(ensure_pre_insertion_validity(node, child));
  391. // 2. Let referenceChild be child.
  392. auto reference_child = child;
  393. // 3. If referenceChild is node, then set referenceChild to node’s next sibling.
  394. if (reference_child == node)
  395. reference_child = node->next_sibling();
  396. // 4. Insert node into parent before referenceChild.
  397. insert_before(node, reference_child);
  398. // 5. Return node.
  399. return node;
  400. }
  401. // https://dom.spec.whatwg.org/#dom-node-removechild
  402. ExceptionOr<JS::NonnullGCPtr<Node>> Node::remove_child(JS::NonnullGCPtr<Node> child)
  403. {
  404. // The removeChild(child) method steps are to return the result of pre-removing child from this.
  405. return pre_remove(child);
  406. }
  407. // https://dom.spec.whatwg.org/#concept-node-pre-remove
  408. ExceptionOr<JS::NonnullGCPtr<Node>> Node::pre_remove(JS::NonnullGCPtr<Node> child)
  409. {
  410. // 1. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
  411. if (child->parent() != this)
  412. return DOM::NotFoundError::create(global_object(), "Child does not belong to this node");
  413. // 2. Remove child.
  414. child->remove();
  415. // 3. Return child.
  416. return child;
  417. }
  418. // https://dom.spec.whatwg.org/#concept-node-append
  419. ExceptionOr<JS::NonnullGCPtr<Node>> Node::append_child(JS::NonnullGCPtr<Node> node)
  420. {
  421. // To append a node to a parent, pre-insert node into parent before null.
  422. return pre_insert(node, nullptr);
  423. }
  424. // https://dom.spec.whatwg.org/#concept-node-remove
  425. void Node::remove(bool suppress_observers)
  426. {
  427. // 1. Let parent be node’s parent
  428. auto* parent = this->parent();
  429. // 2. Assert: parent is non-null.
  430. VERIFY(parent);
  431. // 3. Let index be node’s index.
  432. auto index = this->index();
  433. // 4. For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
  434. for (auto& range : Range::live_ranges()) {
  435. if (range->start_container()->is_inclusive_descendant_of(*this))
  436. range->set_start(*parent, index);
  437. }
  438. // 5. For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
  439. for (auto& range : Range::live_ranges()) {
  440. if (range->end_container()->is_inclusive_descendant_of(*this))
  441. range->set_end(*parent, index);
  442. }
  443. // 6. For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
  444. for (auto& range : Range::live_ranges()) {
  445. if (range->start_container() == parent && range->start_offset() > index)
  446. range->set_start(*range->start_container(), range->start_offset() - 1);
  447. }
  448. // 7. For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
  449. for (auto& range : Range::live_ranges()) {
  450. if (range->end_container() == parent && range->end_offset() > index)
  451. range->set_end(*range->end_container(), range->end_offset() - 1);
  452. }
  453. // 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.
  454. document().for_each_node_iterator([&](NodeIterator& node_iterator) {
  455. node_iterator.run_pre_removing_steps(*this);
  456. });
  457. // 9. Let oldPreviousSibling be node’s previous sibling.
  458. JS::GCPtr<Node> old_previous_sibling = previous_sibling();
  459. // 10. Let oldNextSibling be node’s next sibling.
  460. JS::GCPtr<Node> old_next_sibling = next_sibling();
  461. // 11. Remove node from its parent’s children.
  462. parent->remove_child_impl(*this);
  463. // FIXME: 12. If node is assigned, then run assign slottables for node’s assigned slot.
  464. // FIXME: 13. 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.
  465. // FIXME: 14. If node has an inclusive descendant that is a slot, then:
  466. // 1. Run assign slottables for a tree with parent’s root.
  467. // 2. Run assign slottables for a tree with node.
  468. // 15. Run the removing steps with node and parent.
  469. removed_from(parent);
  470. // FIXME: 16. Let isParentConnected be parent’s connected. (Currently unused so not included)
  471. // FIXME: 17. If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node,
  472. // callback name "disconnectedCallback", and an empty argument list.
  473. // 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.
  474. // FIXME: This should be shadow-including.
  475. // 18. For each shadow-including descendant descendant of node, in shadow-including tree order, then:
  476. for_each_in_subtree([&](Node& descendant) {
  477. // 1. Run the removing steps with descendant
  478. descendant.removed_from(nullptr);
  479. // FIXME: 2. If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant,
  480. // callback name "disconnectedCallback", and an empty argument list.
  481. return IterationDecision::Continue;
  482. });
  483. // 19. For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of inclusiveAncestor’s registered observer list,
  484. // if registered’s options["subtree"] is true, then append a new transient registered observer
  485. // whose observer is registered’s observer, options is registered’s options, and source is registered to node’s registered observer list.
  486. for (auto* inclusive_ancestor = parent; inclusive_ancestor; inclusive_ancestor = inclusive_ancestor->parent()) {
  487. for (auto& registered : inclusive_ancestor->m_registered_observer_list) {
  488. if (registered.options().subtree) {
  489. auto transient_observer = TransientRegisteredObserver::create(registered.observer(), registered.options(), registered);
  490. m_registered_observer_list.append(move(transient_observer));
  491. }
  492. }
  493. }
  494. // 20. If suppress observers flag is unset, then queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  495. if (!suppress_observers) {
  496. Vector<JS::Handle<Node>> removed_nodes;
  497. removed_nodes.append(JS::make_handle(*this));
  498. parent->queue_tree_mutation_record(StaticNodeList::create(window(), {}), StaticNodeList::create(window(), move(removed_nodes)), old_previous_sibling.ptr(), old_next_sibling.ptr());
  499. }
  500. // 21. Run the children changed steps for parent.
  501. parent->children_changed();
  502. document().invalidate_style();
  503. }
  504. // https://dom.spec.whatwg.org/#concept-node-replace
  505. ExceptionOr<JS::NonnullGCPtr<Node>> Node::replace_child(JS::NonnullGCPtr<Node> node, JS::NonnullGCPtr<Node> child)
  506. {
  507. // If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  508. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  509. return DOM::HierarchyRequestError::create(global_object(), "Can only insert into a document, document fragment or element");
  510. // 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
  511. if (node->is_host_including_inclusive_ancestor_of(*this))
  512. return DOM::HierarchyRequestError::create(global_object(), "New node is an ancestor of this node");
  513. // 3. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
  514. if (child->parent() != this)
  515. return DOM::NotFoundError::create(global_object(), "This node is not the parent of the given child");
  516. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  517. // 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  518. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  519. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  520. // 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.
  521. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  522. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  523. // If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "HierarchyRequestError" DOMException.
  524. if (is<Document>(this)) {
  525. // DocumentFragment
  526. if (is<DocumentFragment>(*node)) {
  527. // If node has more than one element child or has a Text node child.
  528. // Otherwise, if node has one element child and either parent has an element child that is not child or a doctype is following child.
  529. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  530. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  531. || (node_element_child_count == 1 && (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>()))) {
  532. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  533. }
  534. } else if (is<Element>(*node)) {
  535. // Element
  536. // parent has an element child that is not child or a doctype is following child.
  537. if (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>())
  538. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  539. } else if (is<DocumentType>(*node)) {
  540. // DocumentType
  541. // parent has a doctype child that is not child, or an element is preceding child.
  542. if (first_child_of_type<DocumentType>() != node || child->has_preceding_node_of_type_in_tree_order<Element>())
  543. return DOM::HierarchyRequestError::create(global_object(), "Invalid node type for insertion");
  544. }
  545. }
  546. // 7. Let referenceChild be child’s next sibling.
  547. JS::GCPtr<Node> reference_child = child->next_sibling();
  548. // 8. If referenceChild is node, then set referenceChild to node’s next sibling.
  549. if (reference_child == node)
  550. reference_child = node->next_sibling();
  551. // 9. Let previousSibling be child’s previous sibling.
  552. JS::GCPtr<Node> previous_sibling = child->previous_sibling();
  553. // 10. Let removedNodes be the empty set.
  554. Vector<JS::Handle<Node>> removed_nodes;
  555. // 11. If child’s parent is non-null, then:
  556. // NOTE: The above can only be false if child is node.
  557. if (child->parent()) {
  558. // 1. Set removedNodes to « child ».
  559. removed_nodes.append(JS::make_handle(*child));
  560. // 2. Remove child with the suppress observers flag set.
  561. child->remove(true);
  562. }
  563. // 12. Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ».
  564. Vector<JS::Handle<Node>> nodes;
  565. if (is<DocumentFragment>(*node))
  566. nodes = node->children_as_vector();
  567. else
  568. nodes.append(JS::make_handle(*node));
  569. // 13. Insert node into parent before referenceChild with the suppress observers flag set.
  570. insert_before(node, reference_child, true);
  571. // 14. Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
  572. queue_tree_mutation_record(StaticNodeList::create(window(), move(nodes)), StaticNodeList::create(window(), move(removed_nodes)), previous_sibling.ptr(), reference_child.ptr());
  573. // 15. Return child.
  574. return child;
  575. }
  576. // https://dom.spec.whatwg.org/#concept-node-clone
  577. JS::NonnullGCPtr<Node> Node::clone_node(Document* document, bool clone_children)
  578. {
  579. // 1. If document is not given, let document be node’s node document.
  580. if (!document)
  581. document = m_document.ptr();
  582. JS::GCPtr<Node> copy;
  583. // 2. If node is an element, then:
  584. if (is<Element>(this)) {
  585. // 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.
  586. auto& element = *verify_cast<Element>(this);
  587. 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 */);
  588. // 2. For each attribute in node’s attribute list:
  589. element.for_each_attribute([&](auto& name, auto& value) {
  590. // 1. Let copyAttribute be a clone of attribute.
  591. // 2. Append copyAttribute to copy.
  592. element_copy->set_attribute(name, value);
  593. });
  594. copy = move(element_copy);
  595. }
  596. // 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:
  597. else if (is<Document>(this)) {
  598. // Document
  599. auto document_ = verify_cast<Document>(this);
  600. auto document_copy = Document::create(Bindings::main_thread_internal_window_object(), document_->url());
  601. // Set copy’s encoding, content type, URL, origin, type, and mode to those of node.
  602. document_copy->set_encoding(document_->encoding());
  603. document_copy->set_content_type(document_->content_type());
  604. document_copy->set_url(document_->url());
  605. document_copy->set_origin(document_->origin());
  606. document_copy->set_document_type(document_->document_type());
  607. document_copy->set_quirks_mode(document_->mode());
  608. copy = move(document_copy);
  609. } else if (is<DocumentType>(this)) {
  610. // DocumentType
  611. auto document_type = verify_cast<DocumentType>(this);
  612. auto document_type_copy = heap().allocate<DocumentType>(realm(), *document);
  613. // Set copy’s name, public ID, and system ID to those of node.
  614. document_type_copy->set_name(document_type->name());
  615. document_type_copy->set_public_id(document_type->public_id());
  616. document_type_copy->set_system_id(document_type->system_id());
  617. copy = move(document_type_copy);
  618. } else if (is<Attr>(this)) {
  619. // FIXME:
  620. // Attr
  621. // Set copy’s namespace, namespace prefix, local name, and value to those of node.
  622. dbgln("clone_node() not implemented for Attribute");
  623. } else if (is<Text>(this)) {
  624. // Text
  625. auto text = verify_cast<Text>(this);
  626. // Set copy’s data to that of node.
  627. auto text_copy = heap().allocate<Text>(realm(), *document, text->data());
  628. copy = move(text_copy);
  629. } else if (is<Comment>(this)) {
  630. // Comment
  631. auto comment = verify_cast<Comment>(this);
  632. // Set copy’s data to that of node.
  633. auto comment_copy = heap().allocate<Comment>(realm(), *document, comment->data());
  634. copy = move(comment_copy);
  635. } else if (is<ProcessingInstruction>(this)) {
  636. // ProcessingInstruction
  637. auto processing_instruction = verify_cast<ProcessingInstruction>(this);
  638. // Set copy’s target and data to those of node.
  639. auto processing_instruction_copy = heap().allocate<ProcessingInstruction>(realm(), *document, processing_instruction->data(), processing_instruction->target());
  640. copy = processing_instruction_copy;
  641. }
  642. // Otherwise, Do nothing.
  643. else if (is<DocumentFragment>(this)) {
  644. copy = heap().allocate<DocumentFragment>(realm(), *document);
  645. }
  646. // 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.
  647. // 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.
  648. cloned(*copy, clone_children);
  649. // 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.
  650. if (clone_children) {
  651. for_each_child([&](auto& child) {
  652. copy->append_child(child.clone_node(document, true));
  653. });
  654. }
  655. // 7. Return copy.
  656. return *copy;
  657. }
  658. // https://dom.spec.whatwg.org/#dom-node-clonenode
  659. ExceptionOr<JS::NonnullGCPtr<Node>> Node::clone_node_binding(bool deep)
  660. {
  661. // 1. If this is a shadow root, then throw a "NotSupportedError" DOMException.
  662. if (is<ShadowRoot>(*this))
  663. return NotSupportedError::create(global_object(), "Cannot clone shadow root");
  664. // 2. Return a clone of this, with the clone children flag set if deep is true.
  665. return clone_node(nullptr, deep);
  666. }
  667. void Node::set_document(Badge<Document>, Document& document)
  668. {
  669. if (m_document.ptr() == &document)
  670. return;
  671. m_document = &document;
  672. if (needs_style_update() || child_needs_style_update()) {
  673. // NOTE: We unset and reset the "needs style update" flag here.
  674. // This ensures that there's a pending style update in the new document
  675. // that will eventually assign some style to this node if needed.
  676. set_needs_style_update(false);
  677. set_needs_style_update(true);
  678. }
  679. }
  680. bool Node::is_editable() const
  681. {
  682. return parent() && parent()->is_editable();
  683. }
  684. void Node::set_layout_node(Badge<Layout::Node>, Layout::Node* layout_node) const
  685. {
  686. m_layout_node = layout_node;
  687. }
  688. EventTarget* Node::get_parent(Event const&)
  689. {
  690. // FIXME: returns the node’s assigned slot, if node is assigned, and node’s parent otherwise.
  691. return parent();
  692. }
  693. void Node::set_needs_style_update(bool value)
  694. {
  695. if (m_needs_style_update == value)
  696. return;
  697. m_needs_style_update = value;
  698. if (m_needs_style_update) {
  699. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
  700. ancestor->m_child_needs_style_update = true;
  701. }
  702. document().schedule_style_update();
  703. }
  704. }
  705. void Node::inserted()
  706. {
  707. set_needs_style_update(true);
  708. }
  709. ParentNode* Node::parent_or_shadow_host()
  710. {
  711. if (is<ShadowRoot>(*this))
  712. return verify_cast<ShadowRoot>(*this).host();
  713. return verify_cast<ParentNode>(parent());
  714. }
  715. JS::NonnullGCPtr<NodeList> Node::child_nodes()
  716. {
  717. if (!m_child_nodes) {
  718. m_child_nodes = LiveNodeList::create(window(), *this, [this](auto& node) {
  719. return is_parent_of(node);
  720. });
  721. }
  722. return *m_child_nodes;
  723. }
  724. Vector<JS::Handle<Node>> Node::children_as_vector() const
  725. {
  726. Vector<JS::Handle<Node>> nodes;
  727. for_each_child([&](auto& child) {
  728. nodes.append(JS::make_handle(child));
  729. });
  730. return nodes;
  731. }
  732. void Node::remove_all_children(bool suppress_observers)
  733. {
  734. while (JS::GCPtr<Node> child = first_child())
  735. child->remove(suppress_observers);
  736. }
  737. // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
  738. u16 Node::compare_document_position(JS::GCPtr<Node> other)
  739. {
  740. enum Position : u16 {
  741. DOCUMENT_POSITION_EQUAL = 0,
  742. DOCUMENT_POSITION_DISCONNECTED = 1,
  743. DOCUMENT_POSITION_PRECEDING = 2,
  744. DOCUMENT_POSITION_FOLLOWING = 4,
  745. DOCUMENT_POSITION_CONTAINS = 8,
  746. DOCUMENT_POSITION_CONTAINED_BY = 16,
  747. DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32,
  748. };
  749. // 1. If this is other, then return zero.
  750. if (this == other.ptr())
  751. return DOCUMENT_POSITION_EQUAL;
  752. // 2. Let node1 be other and node2 be this.
  753. Node* node1 = other.ptr();
  754. Node* node2 = this;
  755. // 3. Let attr1 and attr2 be null.
  756. Attr* attr1;
  757. Attr* attr2;
  758. // 4. If node1 is an attribute, then set attr1 to node1 and node1 to attr1’s element.
  759. if (is<Attr>(node1)) {
  760. attr1 = verify_cast<Attr>(node1);
  761. node1 = const_cast<Element*>(attr1->owner_element());
  762. }
  763. // 5. If node2 is an attribute, then:
  764. if (is<Attr>(node2)) {
  765. // 1. Set attr2 to node2 and node2 to attr2’s element.
  766. attr2 = verify_cast<Attr>(node2);
  767. node2 = const_cast<Element*>(attr2->owner_element());
  768. // 2. If attr1 and node1 are non-null, and node2 is node1, then:
  769. if (attr1 && node1 && node2 == node1) {
  770. // FIXME: 1. For each attr in node2’s attribute list:
  771. // 1. If attr equals attr1, then return the result of adding DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC and DOCUMENT_POSITION_PRECEDING.
  772. // 2. If attr equals attr2, then return the result of adding DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC and DOCUMENT_POSITION_FOLLOWING.
  773. }
  774. }
  775. // 6. If node1 or node2 is null, or node1’s root is not node2’s root, then return the result of adding
  776. // 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.
  777. if ((node1 == nullptr || node2 == nullptr) || (&node1->root() != &node2->root()))
  778. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | (node1 > node2 ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING);
  779. // 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.
  780. if ((node1->is_ancestor_of(*node2) && !attr1) || (node1 == node2 && attr2))
  781. return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
  782. // 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.
  783. if ((node2->is_ancestor_of(*node1) && !attr2) || (node1 == node2 && attr1))
  784. return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
  785. // 9. If node1 is preceding node2, then return DOCUMENT_POSITION_PRECEDING.
  786. if (node1->is_before(*node2))
  787. return DOCUMENT_POSITION_PRECEDING;
  788. // 10. Return DOCUMENT_POSITION_FOLLOWING.
  789. return DOCUMENT_POSITION_FOLLOWING;
  790. }
  791. // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
  792. bool Node::is_host_including_inclusive_ancestor_of(Node const& other) const
  793. {
  794. // An object A is a host-including inclusive ancestor of an object B,
  795. // if either A is an inclusive ancestor of B,
  796. if (is_inclusive_ancestor_of(other))
  797. return true;
  798. // or if B’s root has a non-null host and A is a host-including inclusive ancestor of B’s root’s host
  799. if (is<DocumentFragment>(other.root())
  800. && static_cast<DocumentFragment const&>(other.root()).host()
  801. && is_inclusive_ancestor_of(*static_cast<DocumentFragment const&>(other.root()).host())) {
  802. return true;
  803. }
  804. return false;
  805. }
  806. // https://dom.spec.whatwg.org/#dom-node-ownerdocument
  807. JS::GCPtr<Document> Node::owner_document() const
  808. {
  809. // The ownerDocument getter steps are to return null, if this is a document; otherwise this’s node document.
  810. if (is_document())
  811. return nullptr;
  812. return m_document;
  813. }
  814. // This function tells us whether a node is interesting enough to show up
  815. // in the DOM inspector. This hides two things:
  816. // - Non-rendered whitespace
  817. // - Rendered whitespace between block-level elements
  818. bool Node::is_uninteresting_whitespace_node() const
  819. {
  820. if (!is<Text>(*this))
  821. return false;
  822. if (!static_cast<Text const&>(*this).data().is_whitespace())
  823. return false;
  824. if (!layout_node())
  825. return true;
  826. if (layout_node()->parent()->is_anonymous())
  827. return true;
  828. return false;
  829. }
  830. void Node::serialize_tree_as_json(JsonObjectSerializer<StringBuilder>& object) const
  831. {
  832. MUST(object.add("name"sv, node_name().view()));
  833. MUST(object.add("id"sv, id()));
  834. if (is_document()) {
  835. MUST(object.add("type"sv, "document"));
  836. } else if (is_element()) {
  837. MUST(object.add("type"sv, "element"));
  838. auto const* element = static_cast<DOM::Element const*>(this);
  839. if (element->has_attributes()) {
  840. auto attributes = MUST(object.add_object("attributes"sv));
  841. element->for_each_attribute([&attributes](auto& name, auto& value) {
  842. MUST(attributes.add(name, value));
  843. });
  844. MUST(attributes.finish());
  845. }
  846. if (element->is_browsing_context_container()) {
  847. auto const* container = static_cast<HTML::BrowsingContextContainer const*>(element);
  848. if (auto const* content_document = container->content_document()) {
  849. auto children = MUST(object.add_array("children"sv));
  850. JsonObjectSerializer<StringBuilder> content_document_object = MUST(children.add_object());
  851. content_document->serialize_tree_as_json(content_document_object);
  852. MUST(content_document_object.finish());
  853. MUST(children.finish());
  854. }
  855. }
  856. } else if (is_text()) {
  857. MUST(object.add("type"sv, "text"));
  858. auto text_node = static_cast<DOM::Text const*>(this);
  859. MUST(object.add("text"sv, text_node->data()));
  860. } else if (is_comment()) {
  861. MUST(object.add("type"sv, "comment"sv));
  862. MUST(object.add("data"sv, static_cast<DOM::Comment const&>(*this).data()));
  863. }
  864. MUST((object.add("visible"sv, !!layout_node())));
  865. if (has_child_nodes()) {
  866. auto children = MUST(object.add_array("children"sv));
  867. for_each_child([&children](DOM::Node& child) {
  868. if (child.is_uninteresting_whitespace_node())
  869. return;
  870. JsonObjectSerializer<StringBuilder> child_object = MUST(children.add_object());
  871. child.serialize_tree_as_json(child_object);
  872. MUST(child_object.finish());
  873. });
  874. // Pseudo-elements don't have DOM nodes,so we have to add them separately.
  875. if (is_element()) {
  876. auto const* element = static_cast<DOM::Element const*>(this);
  877. element->serialize_pseudo_elements_as_json(children);
  878. }
  879. MUST(children.finish());
  880. }
  881. }
  882. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-script
  883. bool Node::is_scripting_enabled() const
  884. {
  885. // 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.
  886. return document().browsing_context() && const_cast<Document&>(document()).relevant_settings_object().is_scripting_enabled();
  887. }
  888. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-noscript
  889. bool Node::is_scripting_disabled() const
  890. {
  891. // 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.
  892. return !is_scripting_enabled();
  893. }
  894. // https://dom.spec.whatwg.org/#dom-node-contains
  895. bool Node::contains(JS::GCPtr<Node> other) const
  896. {
  897. // The contains(other) method steps are to return true if other is an inclusive descendant of this; otherwise false (including when other is null).
  898. return other && other->is_inclusive_descendant_of(*this);
  899. }
  900. // https://dom.spec.whatwg.org/#concept-shadow-including-descendant
  901. bool Node::is_shadow_including_descendant_of(Node const& other) const
  902. {
  903. // An object A is a shadow-including descendant of an object B,
  904. // if A is a descendant of B,
  905. if (is_descendant_of(other))
  906. return true;
  907. // or A’s root is a shadow root
  908. if (!is<ShadowRoot>(root()))
  909. return false;
  910. // and A’s root’s host is a shadow-including inclusive descendant of B.
  911. auto& shadow_root = verify_cast<ShadowRoot>(root());
  912. // NOTE: While host is nullable because of inheriting from DocumentFragment, shadow roots always have a host.
  913. return shadow_root.host()->is_shadow_including_inclusive_descendant_of(other);
  914. }
  915. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
  916. bool Node::is_shadow_including_inclusive_descendant_of(Node const& other) const
  917. {
  918. // A shadow-including inclusive descendant is an object or one of its shadow-including descendants.
  919. return &other == this || is_shadow_including_descendant_of(other);
  920. }
  921. // https://dom.spec.whatwg.org/#concept-shadow-including-ancestor
  922. bool Node::is_shadow_including_ancestor_of(Node const& other) const
  923. {
  924. // An object A is a shadow-including ancestor of an object B, if and only if B is a shadow-including descendant of A.
  925. return other.is_shadow_including_descendant_of(*this);
  926. }
  927. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor
  928. bool Node::is_shadow_including_inclusive_ancestor_of(Node const& other) const
  929. {
  930. // A shadow-including inclusive ancestor is an object or one of its shadow-including ancestors.
  931. return other.is_shadow_including_inclusive_descendant_of(*this);
  932. }
  933. // https://dom.spec.whatwg.org/#concept-node-replace-all
  934. void Node::replace_all(JS::GCPtr<Node> node)
  935. {
  936. // 1. Let removedNodes be parent’s children.
  937. auto removed_nodes = children_as_vector();
  938. // 2. Let addedNodes be the empty set.
  939. Vector<JS::Handle<Node>> added_nodes;
  940. // 3. If node is a DocumentFragment node, then set addedNodes to node’s children.
  941. if (node && is<DocumentFragment>(*node)) {
  942. added_nodes = node->children_as_vector();
  943. }
  944. // 4. Otherwise, if node is non-null, set addedNodes to « node ».
  945. else if (node) {
  946. added_nodes.append(JS::make_handle(*node));
  947. }
  948. // 5. Remove all parent’s children, in tree order, with the suppress observers flag set.
  949. remove_all_children(true);
  950. // 6. If node is non-null, then insert node into parent before null with the suppress observers flag set.
  951. if (node)
  952. insert_before(*node, nullptr, true);
  953. // 7. If either addedNodes or removedNodes is not empty, then queue a tree mutation record for parent with addedNodes, removedNodes, null, and null.
  954. if (!added_nodes.is_empty() || !removed_nodes.is_empty())
  955. queue_tree_mutation_record(StaticNodeList::create(window(), move(added_nodes)), StaticNodeList::create(window(), move(removed_nodes)), nullptr, nullptr);
  956. }
  957. // https://dom.spec.whatwg.org/#string-replace-all
  958. void Node::string_replace_all(String const& string)
  959. {
  960. // 1. Let node be null.
  961. JS::GCPtr<Node> node;
  962. // 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.
  963. if (!string.is_empty())
  964. node = heap().allocate<Text>(realm(), document(), string);
  965. // 3. Replace all with node within parent.
  966. replace_all(node);
  967. }
  968. // https://w3c.github.io/DOM-Parsing/#dfn-fragment-serializing-algorithm
  969. String Node::serialize_fragment(/* FIXME: Requires well-formed flag */) const
  970. {
  971. // FIXME: 1. Let context document be the value of node's node document.
  972. // FIXME: 2. If context document is an HTML document, return an HTML serialization of node.
  973. // (We currently always do this)
  974. return HTML::HTMLParser::serialize_html_fragment(*this);
  975. // FIXME: 3. Otherwise, context document is an XML document; return an XML serialization of node passing the flag require well-formed.
  976. }
  977. // https://dom.spec.whatwg.org/#dom-node-issamenode
  978. bool Node::is_same_node(Node const* other_node) const
  979. {
  980. // The isSameNode(otherNode) method steps are to return true if otherNode is this; otherwise false.
  981. return this == other_node;
  982. }
  983. // https://dom.spec.whatwg.org/#dom-node-isequalnode
  984. bool Node::is_equal_node(Node const* other_node) const
  985. {
  986. // The isEqualNode(otherNode) method steps are to return true if otherNode is non-null and this equals otherNode; otherwise false.
  987. if (!other_node)
  988. return false;
  989. // Fast path for testing a node against itself.
  990. if (this == other_node)
  991. return true;
  992. // A node A equals a node B if all of the following conditions are true:
  993. // A and B implement the same interfaces.
  994. if (node_name() != other_node->node_name())
  995. return false;
  996. // The following are equal, switching on the interface A implements:
  997. switch (node_type()) {
  998. case (u16)NodeType::DOCUMENT_TYPE_NODE: {
  999. // Its name, public ID, and system ID.
  1000. auto& this_doctype = verify_cast<DocumentType>(*this);
  1001. auto& other_doctype = verify_cast<DocumentType>(*other_node);
  1002. if (this_doctype.name() != other_doctype.name()
  1003. || this_doctype.public_id() != other_doctype.public_id()
  1004. || this_doctype.system_id() != other_doctype.system_id())
  1005. return false;
  1006. break;
  1007. }
  1008. case (u16)NodeType::ELEMENT_NODE: {
  1009. // Its namespace, namespace prefix, local name, and its attribute list’s size.
  1010. auto& this_element = verify_cast<Element>(*this);
  1011. auto& other_element = verify_cast<Element>(*other_node);
  1012. if (this_element.namespace_() != other_element.namespace_()
  1013. || this_element.prefix() != other_element.prefix()
  1014. || this_element.local_name() != other_element.local_name()
  1015. || this_element.attribute_list_size() != other_element.attribute_list_size())
  1016. return false;
  1017. // If A is an element, each attribute in its attribute list has an attribute that equals an attribute in B’s attribute list.
  1018. bool has_same_attributes = true;
  1019. this_element.for_each_attribute([&](auto& name, auto& value) {
  1020. if (other_element.get_attribute(name) != value)
  1021. has_same_attributes = false;
  1022. });
  1023. if (!has_same_attributes)
  1024. return false;
  1025. break;
  1026. }
  1027. case (u16)NodeType::COMMENT_NODE:
  1028. case (u16)NodeType::TEXT_NODE: {
  1029. // Its data.
  1030. auto& this_cdata = verify_cast<CharacterData>(*this);
  1031. auto& other_cdata = verify_cast<CharacterData>(*other_node);
  1032. if (this_cdata.data() != other_cdata.data())
  1033. return false;
  1034. break;
  1035. }
  1036. case (u16)NodeType::PROCESSING_INSTRUCTION_NODE:
  1037. case (u16)NodeType::ATTRIBUTE_NODE:
  1038. TODO();
  1039. default:
  1040. break;
  1041. }
  1042. // A and B have the same number of children.
  1043. size_t this_child_count = child_count();
  1044. size_t other_child_count = other_node->child_count();
  1045. if (this_child_count != other_child_count)
  1046. return false;
  1047. // Each child of A equals the child of B at the identical index.
  1048. // FIXME: This can be made nicer. child_at_index() is O(n).
  1049. for (size_t i = 0; i < this_child_count; ++i) {
  1050. auto* this_child = child_at_index(i);
  1051. auto* other_child = other_node->child_at_index(i);
  1052. VERIFY(this_child);
  1053. VERIFY(other_child);
  1054. if (!this_child->is_equal_node(other_child))
  1055. return false;
  1056. }
  1057. return true;
  1058. }
  1059. // https://dom.spec.whatwg.org/#in-a-document-tree
  1060. bool Node::in_a_document_tree() const
  1061. {
  1062. // An element is in a document tree if its root is a document.
  1063. return root().is_document();
  1064. }
  1065. // https://dom.spec.whatwg.org/#dom-node-getrootnode
  1066. JS::NonnullGCPtr<Node> Node::get_root_node(GetRootNodeOptions const& options)
  1067. {
  1068. // The getRootNode(options) method steps are to return this’s shadow-including root if options["composed"] is true;
  1069. if (options.composed)
  1070. return shadow_including_root();
  1071. // otherwise this’s root.
  1072. return root();
  1073. }
  1074. String Node::debug_description() const
  1075. {
  1076. StringBuilder builder;
  1077. builder.append(node_name().to_lowercase());
  1078. if (is_element()) {
  1079. auto& element = static_cast<DOM::Element const&>(*this);
  1080. if (auto id = element.get_attribute(HTML::AttributeNames::id); !id.is_null())
  1081. builder.appendff("#{}", id);
  1082. for (auto const& class_name : element.class_names())
  1083. builder.appendff(".{}", class_name);
  1084. }
  1085. return builder.to_string();
  1086. }
  1087. // https://dom.spec.whatwg.org/#concept-node-length
  1088. size_t Node::length() const
  1089. {
  1090. // 1. If node is a DocumentType or Attr node, then return 0.
  1091. if (is_document_type() || is_attribute())
  1092. return 0;
  1093. // 2. If node is a CharacterData node, then return node’s data’s length.
  1094. if (is_character_data()) {
  1095. auto* character_data_node = verify_cast<CharacterData>(this);
  1096. return character_data_node->data().length();
  1097. }
  1098. // 3. Return the number of node’s children.
  1099. return child_count();
  1100. }
  1101. Painting::Paintable const* Node::paintable() const
  1102. {
  1103. if (!layout_node())
  1104. return nullptr;
  1105. return layout_node()->paintable();
  1106. }
  1107. Painting::PaintableBox const* Node::paint_box() const
  1108. {
  1109. if (!layout_node())
  1110. return nullptr;
  1111. if (!layout_node()->is_box())
  1112. return nullptr;
  1113. return static_cast<Layout::Box const&>(*layout_node()).paint_box();
  1114. }
  1115. // https://dom.spec.whatwg.org/#queue-a-mutation-record
  1116. void Node::queue_mutation_record(FlyString const& type, String attribute_name, String attribute_namespace, String old_value, JS::NonnullGCPtr<NodeList> added_nodes, JS::NonnullGCPtr<NodeList> removed_nodes, Node* previous_sibling, Node* next_sibling)
  1117. {
  1118. // NOTE: We defer garbage collection until the end of the scope, since we can't safely use MutationObserver* as a hashmap key otherwise.
  1119. // FIXME: This is a total hack.
  1120. JS::DeferGC defer_gc(heap());
  1121. // 1. Let interestedObservers be an empty map.
  1122. // mutationObserver -> mappedOldValue
  1123. OrderedHashMap<MutationObserver*, String> interested_observers;
  1124. // 2. Let nodes be the inclusive ancestors of target.
  1125. Vector<JS::Handle<Node>> nodes;
  1126. nodes.append(JS::make_handle(*this));
  1127. for (auto* parent_node = parent(); parent_node; parent_node = parent_node->parent())
  1128. nodes.append(JS::make_handle(*parent_node));
  1129. // 3. For each node in nodes, and then for each registered of node’s registered observer list:
  1130. for (auto& node : nodes) {
  1131. for (auto& registered_observer : node->m_registered_observer_list) {
  1132. // 1. Let options be registered’s options.
  1133. auto& options = registered_observer.options();
  1134. // 2. If none of the following are true
  1135. // - node is not target and options["subtree"] is false
  1136. // - type is "attributes" and options["attributes"] either does not exist or is false
  1137. // - type is "attributes", options["attributeFilter"] exists, and options["attributeFilter"] does not contain name or namespace is non-null
  1138. // - type is "characterData" and options["characterData"] either does not exist or is false
  1139. // - type is "childList" and options["childList"] is false
  1140. // then:
  1141. if (!(node.ptr() != this && !options.subtree)
  1142. && !(type == MutationType::attributes && (!options.attributes.has_value() || !options.attributes.value()))
  1143. && !(type == MutationType::attributes && options.attribute_filter.has_value() && (!attribute_namespace.is_null() || !options.attribute_filter->contains_slow(attribute_name)))
  1144. && !(type == MutationType::characterData && (!options.character_data.has_value() || !options.character_data.value()))
  1145. && !(type == MutationType::childList && !options.child_list)) {
  1146. // 1. Let mo be registered’s observer.
  1147. auto mutation_observer = registered_observer.observer();
  1148. // 2. If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.
  1149. if (!interested_observers.contains(mutation_observer))
  1150. interested_observers.set(mutation_observer, {});
  1151. // 3. If either type is "attributes" and options["attributeOldValue"] is true, or type is "characterData" and options["characterDataOldValue"] is true, then set interestedObservers[mo] to oldValue.
  1152. if ((type == MutationType::attributes && options.attribute_old_value.has_value() && options.attribute_old_value.value()) || (type == MutationType::characterData && options.character_data_old_value.has_value() && options.character_data_old_value.value()))
  1153. interested_observers.set(mutation_observer, old_value);
  1154. }
  1155. }
  1156. }
  1157. // 4. For each observer → mappedOldValue of interestedObservers:
  1158. for (auto& interested_observer : interested_observers) {
  1159. // 1. Let record be a new MutationRecord object with its type set to type, target set to target, attributeName set to name, attributeNamespace set to namespace, oldValue set to mappedOldValue,
  1160. // addedNodes set to addedNodes, removedNodes set to removedNodes, previousSibling set to previousSibling, and nextSibling set to nextSibling.
  1161. auto record = MutationRecord::create(window(), type, *this, added_nodes, removed_nodes, previous_sibling, next_sibling, attribute_name, attribute_namespace, /* mappedOldValue */ interested_observer.value);
  1162. // 2. Enqueue record to observer’s record queue.
  1163. interested_observer.key->enqueue_record({}, move(record));
  1164. }
  1165. // 5. Queue a mutation observer microtask.
  1166. Bindings::queue_mutation_observer_microtask(document());
  1167. }
  1168. // https://dom.spec.whatwg.org/#queue-a-tree-mutation-record
  1169. void Node::queue_tree_mutation_record(JS::NonnullGCPtr<NodeList> added_nodes, JS::NonnullGCPtr<NodeList> removed_nodes, Node* previous_sibling, Node* next_sibling)
  1170. {
  1171. // 1. Assert: either addedNodes or removedNodes is not empty.
  1172. VERIFY(added_nodes->length() > 0 || removed_nodes->length() > 0);
  1173. // 2. Queue a mutation record of "childList" for target with null, null, null, addedNodes, removedNodes, previousSibling, and nextSibling.
  1174. queue_mutation_record(MutationType::childList, {}, {}, {}, move(added_nodes), move(removed_nodes), previous_sibling, next_sibling);
  1175. }
  1176. void Node::append_child_impl(JS::NonnullGCPtr<Node> node)
  1177. {
  1178. VERIFY(!node->m_parent);
  1179. if (!is_child_allowed(*node))
  1180. return;
  1181. if (m_last_child)
  1182. m_last_child->m_next_sibling = node.ptr();
  1183. node->m_previous_sibling = m_last_child;
  1184. node->m_parent = this;
  1185. m_last_child = node.ptr();
  1186. if (!m_first_child)
  1187. m_first_child = m_last_child;
  1188. }
  1189. void Node::insert_before_impl(JS::NonnullGCPtr<Node> node, JS::GCPtr<Node> child)
  1190. {
  1191. if (!child)
  1192. return append_child_impl(move(node));
  1193. VERIFY(!node->m_parent);
  1194. VERIFY(child->parent() == this);
  1195. node->m_previous_sibling = child->m_previous_sibling;
  1196. node->m_next_sibling = child;
  1197. if (child->m_previous_sibling)
  1198. child->m_previous_sibling->m_next_sibling = node;
  1199. if (m_first_child == child)
  1200. m_first_child = node;
  1201. child->m_previous_sibling = node;
  1202. node->m_parent = this;
  1203. }
  1204. void Node::remove_child_impl(JS::NonnullGCPtr<Node> node)
  1205. {
  1206. VERIFY(node->m_parent.ptr() == this);
  1207. if (m_first_child == node)
  1208. m_first_child = node->m_next_sibling;
  1209. if (m_last_child == node)
  1210. m_last_child = node->m_previous_sibling;
  1211. if (node->m_next_sibling)
  1212. node->m_next_sibling->m_previous_sibling = node->m_previous_sibling;
  1213. if (node->m_previous_sibling)
  1214. node->m_previous_sibling->m_next_sibling = node->m_next_sibling;
  1215. node->m_next_sibling = nullptr;
  1216. node->m_previous_sibling = nullptr;
  1217. node->m_parent = nullptr;
  1218. }
  1219. bool Node::is_ancestor_of(Node const& other) const
  1220. {
  1221. for (auto* ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) {
  1222. if (ancestor == this)
  1223. return true;
  1224. }
  1225. return false;
  1226. }
  1227. bool Node::is_inclusive_ancestor_of(Node const& other) const
  1228. {
  1229. return &other == this || is_ancestor_of(other);
  1230. }
  1231. bool Node::is_descendant_of(Node const& other) const
  1232. {
  1233. return other.is_ancestor_of(*this);
  1234. }
  1235. bool Node::is_inclusive_descendant_of(Node const& other) const
  1236. {
  1237. return other.is_inclusive_ancestor_of(*this);
  1238. }
  1239. // https://dom.spec.whatwg.org/#concept-tree-following
  1240. bool Node::is_following(Node const& other) const
  1241. {
  1242. // An object A is following an object B if A and B are in the same tree and A comes after B in tree order.
  1243. for (auto* node = previous_in_pre_order(); node; node = node->previous_in_pre_order()) {
  1244. if (node == &other)
  1245. return true;
  1246. }
  1247. return false;
  1248. }
  1249. HTML::Window& Node::window() const
  1250. {
  1251. return document().window();
  1252. }
  1253. }