Node.cpp 59 KB

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