Node.cpp 62 KB

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