Node.cpp 33 KB

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