Node.cpp 37 KB

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