Node.cpp 36 KB

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