Node.cpp 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534
  1. /*
  2. * Copyright (c) 2018-2024, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/HashTable.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibGC/DeferGC.h>
  11. #include <LibJS/Runtime/FunctionObject.h>
  12. #include <LibRegex/Regex.h>
  13. #include <LibURL/Origin.h>
  14. #include <LibWeb/Bindings/MainThreadVM.h>
  15. #include <LibWeb/Bindings/NodePrototype.h>
  16. #include <LibWeb/DOM/Attr.h>
  17. #include <LibWeb/DOM/CDATASection.h>
  18. #include <LibWeb/DOM/Comment.h>
  19. #include <LibWeb/DOM/DocumentType.h>
  20. #include <LibWeb/DOM/Element.h>
  21. #include <LibWeb/DOM/ElementFactory.h>
  22. #include <LibWeb/DOM/Event.h>
  23. #include <LibWeb/DOM/EventDispatcher.h>
  24. #include <LibWeb/DOM/IDLEventListener.h>
  25. #include <LibWeb/DOM/LiveNodeList.h>
  26. #include <LibWeb/DOM/MutationType.h>
  27. #include <LibWeb/DOM/NamedNodeMap.h>
  28. #include <LibWeb/DOM/Node.h>
  29. #include <LibWeb/DOM/NodeIterator.h>
  30. #include <LibWeb/DOM/ProcessingInstruction.h>
  31. #include <LibWeb/DOM/Range.h>
  32. #include <LibWeb/DOM/ShadowRoot.h>
  33. #include <LibWeb/DOM/StaticNodeList.h>
  34. #include <LibWeb/DOM/XMLDocument.h>
  35. #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
  36. #include <LibWeb/HTML/HTMLAnchorElement.h>
  37. #include <LibWeb/HTML/HTMLDocument.h>
  38. #include <LibWeb/HTML/HTMLImageElement.h>
  39. #include <LibWeb/HTML/HTMLInputElement.h>
  40. #include <LibWeb/HTML/HTMLSelectElement.h>
  41. #include <LibWeb/HTML/HTMLSlotElement.h>
  42. #include <LibWeb/HTML/HTMLStyleElement.h>
  43. #include <LibWeb/HTML/Navigable.h>
  44. #include <LibWeb/HTML/NavigableContainer.h>
  45. #include <LibWeb/HTML/Parser/HTMLParser.h>
  46. #include <LibWeb/Infra/CharacterTypes.h>
  47. #include <LibWeb/Layout/Node.h>
  48. #include <LibWeb/Layout/TextNode.h>
  49. #include <LibWeb/Layout/Viewport.h>
  50. #include <LibWeb/Namespace.h>
  51. #include <LibWeb/Painting/Paintable.h>
  52. #include <LibWeb/Painting/PaintableBox.h>
  53. namespace Web::DOM {
  54. static UniqueNodeID s_next_unique_id;
  55. static HashMap<UniqueNodeID, Node*> s_node_directory;
  56. static UniqueNodeID allocate_unique_id(Node* node)
  57. {
  58. auto id = s_next_unique_id;
  59. ++s_next_unique_id;
  60. s_node_directory.set(id, node);
  61. return id;
  62. }
  63. static void deallocate_unique_id(UniqueNodeID node_id)
  64. {
  65. if (!s_node_directory.remove(node_id))
  66. VERIFY_NOT_REACHED();
  67. }
  68. Node* Node::from_unique_id(UniqueNodeID unique_id)
  69. {
  70. return s_node_directory.get(unique_id).value_or(nullptr);
  71. }
  72. Node::Node(JS::Realm& realm, Document& document, NodeType type)
  73. : EventTarget(realm)
  74. , m_document(&document)
  75. , m_type(type)
  76. , m_unique_id(allocate_unique_id(this))
  77. {
  78. }
  79. Node::Node(Document& document, NodeType type)
  80. : Node(document.realm(), document, type)
  81. {
  82. }
  83. Node::~Node() = default;
  84. void Node::finalize()
  85. {
  86. Base::finalize();
  87. deallocate_unique_id(m_unique_id);
  88. }
  89. void Node::visit_edges(Cell::Visitor& visitor)
  90. {
  91. Base::visit_edges(visitor);
  92. visitor.visit(m_document);
  93. visitor.visit(m_parent);
  94. visitor.visit(m_first_child);
  95. visitor.visit(m_last_child);
  96. visitor.visit(m_next_sibling);
  97. visitor.visit(m_previous_sibling);
  98. visitor.visit(m_child_nodes);
  99. visitor.visit(m_layout_node);
  100. visitor.visit(m_paintable);
  101. if (m_registered_observer_list) {
  102. visitor.visit(*m_registered_observer_list);
  103. }
  104. }
  105. // https://dom.spec.whatwg.org/#dom-node-baseuri
  106. String Node::base_uri() const
  107. {
  108. // Return this’s node document’s document base URL, serialized.
  109. return MUST(document().base_url().to_string());
  110. }
  111. const HTML::HTMLAnchorElement* Node::enclosing_link_element() const
  112. {
  113. for (auto* node = this; node; node = node->parent()) {
  114. if (!is<HTML::HTMLAnchorElement>(*node))
  115. continue;
  116. auto const& anchor_element = static_cast<HTML::HTMLAnchorElement const&>(*node);
  117. if (anchor_element.has_attribute(HTML::AttributeNames::href))
  118. return &anchor_element;
  119. }
  120. return nullptr;
  121. }
  122. const HTML::HTMLElement* Node::enclosing_html_element() const
  123. {
  124. return first_ancestor_of_type<HTML::HTMLElement>();
  125. }
  126. const HTML::HTMLElement* Node::enclosing_html_element_with_attribute(FlyString const& attribute) const
  127. {
  128. for (auto* node = this; node; node = node->parent()) {
  129. if (is<HTML::HTMLElement>(*node) && verify_cast<HTML::HTMLElement>(*node).has_attribute(attribute))
  130. return verify_cast<HTML::HTMLElement>(node);
  131. }
  132. return nullptr;
  133. }
  134. Optional<String> Node::alternative_text() const
  135. {
  136. return {};
  137. }
  138. // https://dom.spec.whatwg.org/#concept-descendant-text-content
  139. String Node::descendant_text_content() const
  140. {
  141. StringBuilder builder;
  142. for_each_in_subtree_of_type<Text>([&](auto& text_node) {
  143. builder.append(text_node.data());
  144. return TraversalDecision::Continue;
  145. });
  146. return builder.to_string_without_validation();
  147. }
  148. // https://dom.spec.whatwg.org/#dom-node-textcontent
  149. Optional<String> Node::text_content() const
  150. {
  151. // The textContent getter steps are to return the following, switching on the interface this implements:
  152. // If DocumentFragment or Element, return the descendant text content of this.
  153. if (is<DocumentFragment>(this) || is<Element>(this))
  154. return descendant_text_content();
  155. // If CharacterData, return this’s data.
  156. if (is<CharacterData>(this))
  157. return static_cast<CharacterData const&>(*this).data();
  158. // If Attr node, return this's value.
  159. if (is<Attr>(*this))
  160. return static_cast<Attr const&>(*this).value();
  161. // Otherwise, return null
  162. return {};
  163. }
  164. // https://dom.spec.whatwg.org/#ref-for-dom-node-textcontent%E2%91%A0
  165. void Node::set_text_content(Optional<String> const& maybe_content)
  166. {
  167. // The textContent setter steps are to, if the given value is null, act as if it was the empty string instead,
  168. // and then do as described below, switching on the interface this implements:
  169. auto content = maybe_content.value_or(String {});
  170. // If DocumentFragment or Element, string replace all with the given value within this.
  171. if (is<DocumentFragment>(this) || is<Element>(this)) {
  172. string_replace_all(content);
  173. }
  174. // If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
  175. else if (is<CharacterData>(this)) {
  176. auto* character_data_node = verify_cast<CharacterData>(this);
  177. character_data_node->set_data(content);
  178. // FIXME: CharacterData::set_data is not spec compliant. Make this match the spec when set_data becomes spec compliant.
  179. // Do note that this will make this function able to throw an exception.
  180. }
  181. // If Attr, set an existing attribute value with this and the given value.
  182. if (is<Attr>(*this)) {
  183. static_cast<Attr&>(*this).set_value(content);
  184. }
  185. // Otherwise, do nothing.
  186. if (is_connected()) {
  187. invalidate_style(StyleInvalidationReason::NodeSetTextContent);
  188. document().invalidate_layout_tree();
  189. }
  190. document().bump_dom_tree_version();
  191. }
  192. // https://dom.spec.whatwg.org/#dom-node-normalize
  193. WebIDL::ExceptionOr<void> Node::normalize()
  194. {
  195. auto contiguous_exclusive_text_nodes_excluding_self = [](Node& node) {
  196. // https://dom.spec.whatwg.org/#contiguous-exclusive-text-nodes
  197. // The contiguous exclusive Text nodes of a node node are node, node’s previous sibling exclusive Text node, if any,
  198. // and its contiguous exclusive Text nodes, and node’s next sibling exclusive Text node, if any,
  199. // and its contiguous exclusive Text nodes, avoiding any duplicates.
  200. // NOTE: The callers of this method require node itself to be excluded.
  201. Vector<Text*> nodes;
  202. auto* current_node = node.previous_sibling();
  203. while (current_node) {
  204. if (!current_node->is_text())
  205. break;
  206. nodes.append(static_cast<Text*>(current_node));
  207. current_node = current_node->previous_sibling();
  208. }
  209. // Reverse the order of the nodes so that they are in tree order.
  210. nodes.reverse();
  211. current_node = node.next_sibling();
  212. while (current_node) {
  213. if (!current_node->is_text())
  214. break;
  215. nodes.append(static_cast<Text*>(current_node));
  216. current_node = current_node->next_sibling();
  217. }
  218. return nodes;
  219. };
  220. // The normalize() method steps are to run these steps for each descendant exclusive Text node node of this
  221. Vector<Text&> descendant_exclusive_text_nodes;
  222. for_each_in_inclusive_subtree_of_type<Text>([&](Text const& node) {
  223. if (!node.is_cdata_section())
  224. descendant_exclusive_text_nodes.append(const_cast<Text&>(node));
  225. return TraversalDecision::Continue;
  226. });
  227. for (auto& node : descendant_exclusive_text_nodes) {
  228. // 1. Let length be node’s length.
  229. auto& character_data = static_cast<CharacterData&>(node);
  230. auto length = character_data.length_in_utf16_code_units();
  231. // 2. If length is zero, then remove node and continue with the next exclusive Text node, if any.
  232. if (length == 0) {
  233. if (node.parent())
  234. node.remove();
  235. continue;
  236. }
  237. // 3. Let data be the concatenation of the data of node’s contiguous exclusive Text nodes (excluding itself), in tree order.
  238. StringBuilder data;
  239. for (auto const& text_node : contiguous_exclusive_text_nodes_excluding_self(node))
  240. data.append(text_node->data());
  241. // 4. Replace data with node node, offset length, count 0, and data data.
  242. TRY(character_data.replace_data(length, 0, MUST(data.to_string())));
  243. // 5. Let currentNode be node’s next sibling.
  244. auto* current_node = node.next_sibling();
  245. // 6. While currentNode is an exclusive Text node:
  246. while (current_node && is<Text>(*current_node)) {
  247. // 1. For each live range whose start node is currentNode, add length to its start offset and set its start node to node.
  248. for (auto& range : Range::live_ranges()) {
  249. if (range->start_container() == current_node)
  250. TRY(range->set_start(node, range->start_offset() + length));
  251. }
  252. // 2. For each live range whose end node is currentNode, add length to its end offset and set its end node to node.
  253. for (auto& range : Range::live_ranges()) {
  254. if (range->end_container() == current_node)
  255. TRY(range->set_end(node, range->end_offset() + length));
  256. }
  257. // 3. For each live range whose start node is currentNode’s parent and start offset is currentNode’s index, set its start node to node and its start offset to length.
  258. for (auto& range : Range::live_ranges()) {
  259. if (range->start_container() == current_node->parent() && range->start_offset() == current_node->index())
  260. TRY(range->set_start(node, length));
  261. }
  262. // 4. For each live range whose end node is currentNode’s parent and end offset is currentNode’s index, set its end node to node and its end offset to length.
  263. for (auto& range : Range::live_ranges()) {
  264. if (range->end_container() == current_node->parent() && range->end_offset() == current_node->index())
  265. TRY(range->set_end(node, length));
  266. }
  267. // 5. Add currentNode’s length to length.
  268. length += static_cast<Text&>(*current_node).length();
  269. // 6. Set currentNode to its next sibling.
  270. current_node = current_node->next_sibling();
  271. }
  272. // 7. Remove node’s contiguous exclusive Text nodes (excluding itself), in tree order.
  273. for (auto const& text_node : contiguous_exclusive_text_nodes_excluding_self(node))
  274. text_node->remove();
  275. }
  276. return {};
  277. }
  278. // https://dom.spec.whatwg.org/#dom-node-nodevalue
  279. Optional<String> Node::node_value() const
  280. {
  281. // The nodeValue getter steps are to return the following, switching on the interface this implements:
  282. // If Attr, return this’s value.
  283. if (is<Attr>(this)) {
  284. return verify_cast<Attr>(this)->value();
  285. }
  286. // If CharacterData, return this’s data.
  287. if (is<CharacterData>(this)) {
  288. return verify_cast<CharacterData>(this)->data();
  289. }
  290. // Otherwise, return null.
  291. return {};
  292. }
  293. // https://dom.spec.whatwg.org/#ref-for-dom-node-nodevalue%E2%91%A0
  294. void Node::set_node_value(Optional<String> const& maybe_value)
  295. {
  296. // The nodeValue setter steps are to, if the given value is null, act as if it was the empty string instead,
  297. // and then do as described below, switching on the interface this implements:
  298. auto value = maybe_value.value_or(String {});
  299. // If Attr, set an existing attribute value with this and the given value.
  300. if (is<Attr>(this)) {
  301. verify_cast<Attr>(this)->set_value(move(value));
  302. } else if (is<CharacterData>(this)) {
  303. // If CharacterData, replace data with node this, offset 0, count this’s length, and data the given value.
  304. verify_cast<CharacterData>(this)->set_data(value);
  305. }
  306. // Otherwise, do nothing.
  307. }
  308. // https://html.spec.whatwg.org/multipage/document-sequences.html#node-navigable
  309. GC::Ptr<HTML::Navigable> Node::navigable() const
  310. {
  311. auto& document = const_cast<Document&>(this->document());
  312. if (auto cached_navigable = document.cached_navigable()) {
  313. if (cached_navigable->active_document() == &document)
  314. return cached_navigable;
  315. }
  316. // To get the node navigable of a node node, return the navigable whose active document is node's node document,
  317. // or null if there is no such navigable.
  318. auto navigable = HTML::Navigable::navigable_with_active_document(document);
  319. document.set_cached_navigable(navigable);
  320. return navigable;
  321. }
  322. [[maybe_unused]] static StringView to_string(StyleInvalidationReason reason)
  323. {
  324. #define __ENUMERATE_STYLE_INVALIDATION_REASON(reason) \
  325. case StyleInvalidationReason::reason: \
  326. return #reason##sv;
  327. switch (reason) {
  328. ENUMERATE_STYLE_INVALIDATION_REASONS(__ENUMERATE_STYLE_INVALIDATION_REASON)
  329. default:
  330. VERIFY_NOT_REACHED();
  331. }
  332. }
  333. void Node::invalidate_style(StyleInvalidationReason reason)
  334. {
  335. if (is_character_data())
  336. return;
  337. // FIXME: This is very not optimal! We should figure out a smaller set of elements to invalidate,
  338. // but right now the :has() selector means we have to invalidate everything.
  339. if (!is_document() && document().style_computer().has_has_selectors()) {
  340. document().invalidate_style(reason);
  341. return;
  342. }
  343. if (!needs_style_update() && !document().needs_full_style_update()) {
  344. dbgln_if(STYLE_INVALIDATION_DEBUG, "Invalidate style ({}): {}", to_string(reason), debug_description());
  345. }
  346. if (is_document()) {
  347. auto& document = static_cast<DOM::Document&>(*this);
  348. document.set_needs_full_style_update(true);
  349. document.schedule_style_update();
  350. return;
  351. }
  352. // If the document is already marked for a full style update, there's no need to do anything here.
  353. if (document().needs_full_style_update()) {
  354. return;
  355. }
  356. // When invalidating style for a node, we actually invalidate:
  357. // - the node itself
  358. // - all of its descendants
  359. // - all of its preceding siblings and their descendants (only on DOM insert/remove)
  360. // - all of its subsequent siblings and their descendants
  361. // FIXME: This is a lot of invalidation and we should implement more sophisticated invalidation to do less work!
  362. auto invalidate_entire_subtree = [&](Node& subtree_root) {
  363. subtree_root.for_each_in_inclusive_subtree([&](Node& node) {
  364. node.m_needs_style_update = true;
  365. if (node.has_children())
  366. node.m_child_needs_style_update = true;
  367. if (auto shadow_root = node.is_element() ? static_cast<DOM::Element&>(node).shadow_root() : nullptr) {
  368. node.m_child_needs_style_update = true;
  369. shadow_root->m_needs_style_update = true;
  370. if (shadow_root->has_children())
  371. shadow_root->m_child_needs_style_update = true;
  372. }
  373. return TraversalDecision::Continue;
  374. });
  375. };
  376. invalidate_entire_subtree(*this);
  377. if (reason == StyleInvalidationReason::NodeInsertBefore || reason == StyleInvalidationReason::NodeRemove) {
  378. for (auto* sibling = previous_sibling(); sibling; sibling = sibling->previous_sibling()) {
  379. if (sibling->is_element())
  380. invalidate_entire_subtree(*sibling);
  381. }
  382. }
  383. for (auto* sibling = next_sibling(); sibling; sibling = sibling->next_sibling()) {
  384. if (sibling->is_element())
  385. invalidate_entire_subtree(*sibling);
  386. }
  387. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host())
  388. ancestor->m_child_needs_style_update = true;
  389. document().schedule_style_update();
  390. }
  391. String Node::child_text_content() const
  392. {
  393. if (!is<ParentNode>(*this))
  394. return String {};
  395. StringBuilder builder;
  396. verify_cast<ParentNode>(*this).for_each_child([&](auto& child) {
  397. if (is<Text>(child)) {
  398. auto maybe_content = verify_cast<Text>(child).text_content();
  399. if (maybe_content.has_value())
  400. builder.append(maybe_content.value());
  401. }
  402. return IterationDecision::Continue;
  403. });
  404. return MUST(builder.to_string());
  405. }
  406. // https://dom.spec.whatwg.org/#concept-tree-root
  407. Node& Node::root()
  408. {
  409. // The root of an object is itself, if its parent is null, or else it is the root of its parent.
  410. // The root of a tree is any object participating in that tree whose parent is null.
  411. Node* root = this;
  412. while (root->parent())
  413. root = root->parent();
  414. return *root;
  415. }
  416. // https://dom.spec.whatwg.org/#concept-shadow-including-root
  417. Node& Node::shadow_including_root()
  418. {
  419. // The shadow-including root of an object is its root’s host’s shadow-including root,
  420. // if the object’s root is a shadow root; otherwise its root.
  421. auto& node_root = root();
  422. if (is<ShadowRoot>(node_root)) {
  423. if (auto* host = static_cast<ShadowRoot&>(node_root).host(); host)
  424. return host->shadow_including_root();
  425. }
  426. return node_root;
  427. }
  428. // https://dom.spec.whatwg.org/#connected
  429. bool Node::is_connected() const
  430. {
  431. // An element is connected if its shadow-including root is a document.
  432. return shadow_including_root().is_document();
  433. }
  434. // https://html.spec.whatwg.org/multipage/infrastructure.html#browsing-context-connected
  435. bool Node::is_browsing_context_connected() const
  436. {
  437. // A node is browsing-context connected when it is connected and its shadow-including root's browsing context is non-null.
  438. return is_connected() && shadow_including_root().document().browsing_context();
  439. }
  440. // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  441. WebIDL::ExceptionOr<void> Node::ensure_pre_insertion_validity(GC::Ref<Node> node, GC::Ptr<Node> child) const
  442. {
  443. // 1. If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  444. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  445. return WebIDL::HierarchyRequestError::create(realm(), "Can only insert into a document, document fragment or element"_string);
  446. // 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
  447. if (node->is_host_including_inclusive_ancestor_of(*this))
  448. return WebIDL::HierarchyRequestError::create(realm(), "New node is an ancestor of this node"_string);
  449. // 3. If child is non-null and its parent is not parent, then throw a "NotFoundError" DOMException.
  450. if (child && child->parent() != this)
  451. return WebIDL::NotFoundError::create(realm(), "This node is not the parent of the given child"_string);
  452. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  453. // 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  454. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node) && !is<CDATASection>(*node))
  455. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  456. // 5. If either node is a Text node and parent is a document, or node is a doctype and parent is not a document, then throw a "HierarchyRequestError" DOMException.
  457. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  458. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  459. // 6. If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "HierarchyRequestError" DOMException.
  460. if (is<Document>(this)) {
  461. // DocumentFragment
  462. if (is<DocumentFragment>(*node)) {
  463. // If node has more than one element child or has a Text node child.
  464. // Otherwise, if node has one element child and either parent has an element child, child is a doctype, or child is non-null and a doctype is following child.
  465. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  466. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  467. || (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>())))) {
  468. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  469. }
  470. } else if (is<Element>(*node)) {
  471. // Element
  472. // If parent has an element child, child is a doctype, or child is non-null and a doctype is following child.
  473. if (has_child_of_type<Element>() || is<DocumentType>(child.ptr()) || (child && child->has_following_node_of_type_in_tree_order<DocumentType>()))
  474. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  475. } else if (is<DocumentType>(*node)) {
  476. // DocumentType
  477. // parent has a doctype child, child is non-null and an element is preceding child, or child is null and parent has an element child.
  478. if (has_child_of_type<DocumentType>() || (child && child->has_preceding_node_of_type_in_tree_order<Element>()) || (!child && has_child_of_type<Element>()))
  479. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  480. }
  481. }
  482. return {};
  483. }
  484. // https://dom.spec.whatwg.org/#concept-node-insert
  485. void Node::insert_before(GC::Ref<Node> node, GC::Ptr<Node> child, bool suppress_observers)
  486. {
  487. // 1. Let nodes be node’s children, if node is a DocumentFragment node; otherwise « node ».
  488. Vector<GC::Root<Node>> nodes;
  489. if (is<DocumentFragment>(*node))
  490. nodes = node->children_as_vector();
  491. else
  492. nodes.append(GC::make_root(*node));
  493. // 2. Let count be nodes’s size.
  494. auto count = nodes.size();
  495. // 3. If count is 0, then return.
  496. if (count == 0)
  497. return;
  498. // 4. If node is a DocumentFragment node, then:
  499. if (is<DocumentFragment>(*node)) {
  500. // 1. Remove its children with the suppress observers flag set.
  501. node->remove_all_children(true);
  502. // 2. Queue a tree mutation record for node with « », nodes, null, and null.
  503. // NOTE: This step intentionally does not pay attention to the suppress observers flag.
  504. node->queue_tree_mutation_record({}, nodes, nullptr, nullptr);
  505. }
  506. // 5. If child is non-null, then:
  507. if (child) {
  508. // 1. For each live range whose start node is parent and start offset is greater than child’s index, increase its start offset by count.
  509. for (auto& range : Range::live_ranges()) {
  510. if (range->start_container() == this && range->start_offset() > child->index())
  511. range->increase_start_offset({}, count);
  512. }
  513. // 2. For each live range whose end node is parent and end offset is greater than child’s index, increase its end offset by count.
  514. for (auto& range : Range::live_ranges()) {
  515. if (range->end_container() == this && range->end_offset() > child->index())
  516. range->increase_end_offset({}, count);
  517. }
  518. }
  519. // 6. Let previousSibling be child’s previous sibling or parent’s last child if child is null.
  520. GC::Ptr<Node> previous_sibling;
  521. if (child)
  522. previous_sibling = child->previous_sibling();
  523. else
  524. previous_sibling = last_child();
  525. // 7. For each node in nodes, in tree order:
  526. // FIXME: In tree order
  527. for (auto& node_to_insert : nodes) {
  528. // 1. Adopt node into parent’s node document.
  529. document().adopt_node(*node_to_insert);
  530. // 2. If child is null, then append node to parent’s children.
  531. if (!child)
  532. append_child_impl(*node_to_insert);
  533. // 3. Otherwise, insert node into parent’s children before child’s index.
  534. else
  535. insert_before_impl(*node_to_insert, child);
  536. // 4. If parent is a shadow host whose shadow root’s slot assignment is "named" and node is a slottable, then
  537. // assign a slot for node.
  538. if (is_element()) {
  539. auto& element = static_cast<DOM::Element&>(*this);
  540. auto is_named_shadow_host = element.is_shadow_host()
  541. && element.shadow_root()->slot_assignment() == Bindings::SlotAssignmentMode::Named;
  542. if (is_named_shadow_host && node_to_insert->is_slottable())
  543. assign_a_slot(node_to_insert->as_slottable());
  544. }
  545. // 5. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run
  546. // signal a slot change for parent.
  547. if (root().is_shadow_root() && is<HTML::HTMLSlotElement>(*this)) {
  548. auto& slot = static_cast<HTML::HTMLSlotElement&>(*this);
  549. if (slot.assigned_nodes_internal().is_empty())
  550. signal_a_slot_change(slot);
  551. }
  552. // 6. Run assign slottables for a tree with node’s root.
  553. assign_slottables_for_a_tree(node_to_insert->root());
  554. node_to_insert->invalidate_style(StyleInvalidationReason::NodeInsertBefore);
  555. // 7. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
  556. node_to_insert->for_each_shadow_including_inclusive_descendant([&](Node& inclusive_descendant) {
  557. // 1. Run the insertion steps with inclusiveDescendant.
  558. inclusive_descendant.inserted();
  559. // 2. If inclusiveDescendant is connected, then:
  560. // NOTE: This is not specified here in the spec, but these steps can only be performed on an element.
  561. if (inclusive_descendant.is_connected() && is<DOM::Element>(inclusive_descendant)) {
  562. auto& element = static_cast<DOM::Element&>(inclusive_descendant);
  563. // 1. If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant,
  564. // callback name "connectedCallback", and an empty argument list.
  565. if (element.is_custom()) {
  566. GC::MarkedVector<JS::Value> empty_arguments { vm().heap() };
  567. element.enqueue_a_custom_element_callback_reaction(HTML::CustomElementReactionNames::connectedCallback, move(empty_arguments));
  568. }
  569. // 2. Otherwise, try to upgrade inclusiveDescendant.
  570. // NOTE: If this successfully upgrades inclusiveDescendant, its connectedCallback will be enqueued automatically during
  571. // the upgrade an element algorithm.
  572. else {
  573. element.try_to_upgrade();
  574. }
  575. }
  576. return TraversalDecision::Continue;
  577. });
  578. }
  579. // 8. If suppress observers flag is unset, then queue a tree mutation record for parent with nodes, « », previousSibling, and child.
  580. if (!suppress_observers) {
  581. queue_tree_mutation_record(move(nodes), {}, previous_sibling.ptr(), child.ptr());
  582. }
  583. // 9. Run the children changed steps for parent.
  584. children_changed();
  585. if (is_connected()) {
  586. // FIXME: This will need to become smarter when we implement the :has() selector.
  587. invalidate_style(StyleInvalidationReason::ParentOfInsertedNode);
  588. document().invalidate_layout_tree();
  589. }
  590. document().bump_dom_tree_version();
  591. }
  592. // https://dom.spec.whatwg.org/#concept-node-pre-insert
  593. WebIDL::ExceptionOr<GC::Ref<Node>> Node::pre_insert(GC::Ref<Node> node, GC::Ptr<Node> child)
  594. {
  595. // 1. Ensure pre-insertion validity of node into parent before child.
  596. TRY(ensure_pre_insertion_validity(node, child));
  597. // 2. Let referenceChild be child.
  598. auto reference_child = child;
  599. // 3. If referenceChild is node, then set referenceChild to node’s next sibling.
  600. if (reference_child == node)
  601. reference_child = node->next_sibling();
  602. // 4. Insert node into parent before referenceChild.
  603. insert_before(node, reference_child);
  604. // 5. Return node.
  605. return node;
  606. }
  607. // https://dom.spec.whatwg.org/#dom-node-removechild
  608. WebIDL::ExceptionOr<GC::Ref<Node>> Node::remove_child(GC::Ref<Node> child)
  609. {
  610. // The removeChild(child) method steps are to return the result of pre-removing child from this.
  611. return pre_remove(child);
  612. }
  613. // https://dom.spec.whatwg.org/#concept-node-pre-remove
  614. WebIDL::ExceptionOr<GC::Ref<Node>> Node::pre_remove(GC::Ref<Node> child)
  615. {
  616. // 1. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
  617. if (child->parent() != this)
  618. return WebIDL::NotFoundError::create(realm(), "Child does not belong to this node"_string);
  619. // 2. Remove child.
  620. child->remove();
  621. // 3. Return child.
  622. return child;
  623. }
  624. // https://dom.spec.whatwg.org/#concept-node-append
  625. WebIDL::ExceptionOr<GC::Ref<Node>> Node::append_child(GC::Ref<Node> node)
  626. {
  627. // To append a node to a parent, pre-insert node into parent before null.
  628. return pre_insert(node, nullptr);
  629. }
  630. // https://dom.spec.whatwg.org/#concept-node-remove
  631. void Node::remove(bool suppress_observers)
  632. {
  633. // 1. Let parent be node’s parent
  634. auto* parent = this->parent();
  635. // 2. Assert: parent is non-null.
  636. VERIFY(parent);
  637. // 3. Let index be node’s index.
  638. auto index = this->index();
  639. // 4. For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
  640. for (auto& range : Range::live_ranges()) {
  641. if (range->start_container()->is_inclusive_descendant_of(*this))
  642. MUST(range->set_start(*parent, index));
  643. }
  644. // 5. For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
  645. for (auto& range : Range::live_ranges()) {
  646. if (range->end_container()->is_inclusive_descendant_of(*this))
  647. MUST(range->set_end(*parent, index));
  648. }
  649. // 6. For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
  650. for (auto& range : Range::live_ranges()) {
  651. if (range->start_container() == parent && range->start_offset() > index)
  652. range->decrease_start_offset({}, 1);
  653. }
  654. // 7. For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
  655. for (auto& range : Range::live_ranges()) {
  656. if (range->end_container() == parent && range->end_offset() > index)
  657. range->decrease_end_offset({}, 1);
  658. }
  659. // 8. For each NodeIterator object iterator whose root’s node document is node’s node document, run the NodeIterator pre-removing steps given node and iterator.
  660. document().for_each_node_iterator([&](NodeIterator& node_iterator) {
  661. node_iterator.run_pre_removing_steps(*this);
  662. });
  663. // 9. Let oldPreviousSibling be node’s previous sibling.
  664. GC::Ptr<Node> old_previous_sibling = previous_sibling();
  665. // 10. Let oldNextSibling be node’s next sibling.
  666. GC::Ptr<Node> old_next_sibling = next_sibling();
  667. if (is_connected()) {
  668. // Since the tree structure is about to change, we need to invalidate both style and layout.
  669. // In the future, we should find a way to only invalidate the parts that actually need it.
  670. invalidate_style(StyleInvalidationReason::NodeRemove);
  671. // NOTE: If we didn't have a layout node before, rebuilding the layout tree isn't gonna give us one
  672. // after we've been removed from the DOM.
  673. if (layout_node()) {
  674. document().invalidate_layout_tree();
  675. }
  676. }
  677. // 11. Remove node from its parent’s children.
  678. parent->remove_child_impl(*this);
  679. // 12. If node is assigned, then run assign slottables for node’s assigned slot.
  680. if (auto assigned_slot = assigned_slot_for_node(*this))
  681. assign_slottables(*assigned_slot);
  682. // 13. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run
  683. // signal a slot change for parent.
  684. if (parent->root().is_shadow_root() && is<HTML::HTMLSlotElement>(parent)) {
  685. auto& slot = static_cast<HTML::HTMLSlotElement&>(*parent);
  686. if (slot.assigned_nodes_internal().is_empty())
  687. signal_a_slot_change(slot);
  688. }
  689. // 14. If node has an inclusive descendant that is a slot, then:
  690. auto has_descendent_slot = false;
  691. for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto const&) {
  692. has_descendent_slot = true;
  693. return TraversalDecision::Break;
  694. });
  695. if (has_descendent_slot) {
  696. // 1. Run assign slottables for a tree with parent’s root.
  697. assign_slottables_for_a_tree(parent->root());
  698. // 2. Run assign slottables for a tree with node.
  699. assign_slottables_for_a_tree(*this);
  700. }
  701. // 15. Run the removing steps with node and parent.
  702. removed_from(parent);
  703. // 16. Let isParentConnected be parent’s connected.
  704. bool is_parent_connected = parent->is_connected();
  705. // 17. If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node,
  706. // callback name "disconnectedCallback", and an empty argument list.
  707. // Spec Note: It is intentional for now that custom elements do not get parent passed.
  708. // This might change in the future if there is a need.
  709. if (is<DOM::Element>(*this)) {
  710. auto& element = static_cast<DOM::Element&>(*this);
  711. if (element.is_custom() && is_parent_connected) {
  712. GC::MarkedVector<JS::Value> empty_arguments { vm().heap() };
  713. element.enqueue_a_custom_element_callback_reaction(HTML::CustomElementReactionNames::disconnectedCallback, move(empty_arguments));
  714. }
  715. }
  716. // 18. For each shadow-including descendant descendant of node, in shadow-including tree order, then:
  717. for_each_shadow_including_descendant([&](Node& descendant) {
  718. // 1. Run the removing steps with descendant
  719. descendant.removed_from(nullptr);
  720. // 2. If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant,
  721. // callback name "disconnectedCallback", and an empty argument list.
  722. if (is<DOM::Element>(descendant)) {
  723. auto& element = static_cast<DOM::Element&>(descendant);
  724. if (element.is_custom() && is_parent_connected) {
  725. GC::MarkedVector<JS::Value> empty_arguments { vm().heap() };
  726. element.enqueue_a_custom_element_callback_reaction(HTML::CustomElementReactionNames::disconnectedCallback, move(empty_arguments));
  727. }
  728. }
  729. return TraversalDecision::Continue;
  730. });
  731. // 19. For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of inclusiveAncestor’s registered observer list,
  732. // if registered’s options["subtree"] is true, then append a new transient registered observer
  733. // whose observer is registered’s observer, options is registered’s options, and source is registered to node’s registered observer list.
  734. for (auto* inclusive_ancestor = parent; inclusive_ancestor; inclusive_ancestor = inclusive_ancestor->parent()) {
  735. if (!inclusive_ancestor->m_registered_observer_list)
  736. continue;
  737. for (auto& registered : *inclusive_ancestor->m_registered_observer_list) {
  738. if (registered->options().subtree) {
  739. auto transient_observer = TransientRegisteredObserver::create(registered->observer(), registered->options(), registered);
  740. add_registered_observer(move(transient_observer));
  741. }
  742. }
  743. }
  744. // 20. If suppress observers flag is unset, then queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
  745. if (!suppress_observers) {
  746. parent->queue_tree_mutation_record({}, { *this }, old_previous_sibling.ptr(), old_next_sibling.ptr());
  747. }
  748. // 21. Run the children changed steps for parent.
  749. parent->children_changed();
  750. document().bump_dom_tree_version();
  751. }
  752. // https://dom.spec.whatwg.org/#concept-node-replace
  753. WebIDL::ExceptionOr<GC::Ref<Node>> Node::replace_child(GC::Ref<Node> node, GC::Ref<Node> child)
  754. {
  755. // If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  756. if (!is<Document>(this) && !is<DocumentFragment>(this) && !is<Element>(this))
  757. return WebIDL::HierarchyRequestError::create(realm(), "Can only insert into a document, document fragment or element"_string);
  758. // 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
  759. if (node->is_host_including_inclusive_ancestor_of(*this))
  760. return WebIDL::HierarchyRequestError::create(realm(), "New node is an ancestor of this node"_string);
  761. // 3. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
  762. if (child->parent() != this)
  763. return WebIDL::NotFoundError::create(realm(), "This node is not the parent of the given child"_string);
  764. // FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.
  765. // 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  766. if (!is<DocumentFragment>(*node) && !is<DocumentType>(*node) && !is<Element>(*node) && !is<Text>(*node) && !is<Comment>(*node) && !is<ProcessingInstruction>(*node))
  767. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  768. // 5. If either node is a Text node and parent is a document, or node is a doctype and parent is not a document, then throw a "HierarchyRequestError" DOMException.
  769. if ((is<Text>(*node) && is<Document>(this)) || (is<DocumentType>(*node) && !is<Document>(this)))
  770. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  771. // If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "HierarchyRequestError" DOMException.
  772. if (is<Document>(this)) {
  773. // DocumentFragment
  774. if (is<DocumentFragment>(*node)) {
  775. // If node has more than one element child or has a Text node child.
  776. // Otherwise, if node has one element child and either parent has an element child that is not child or a doctype is following child.
  777. auto node_element_child_count = verify_cast<DocumentFragment>(*node).child_element_count();
  778. if ((node_element_child_count > 1 || node->has_child_of_type<Text>())
  779. || (node_element_child_count == 1 && (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>()))) {
  780. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  781. }
  782. } else if (is<Element>(*node)) {
  783. // Element
  784. // parent has an element child that is not child or a doctype is following child.
  785. if (first_child_of_type<Element>() != child || child->has_following_node_of_type_in_tree_order<DocumentType>())
  786. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  787. } else if (is<DocumentType>(*node)) {
  788. // DocumentType
  789. // parent has a doctype child that is not child, or an element is preceding child.
  790. if (first_child_of_type<DocumentType>() != node || child->has_preceding_node_of_type_in_tree_order<Element>())
  791. return WebIDL::HierarchyRequestError::create(realm(), "Invalid node type for insertion"_string);
  792. }
  793. }
  794. // 7. Let referenceChild be child’s next sibling.
  795. GC::Ptr<Node> reference_child = child->next_sibling();
  796. // 8. If referenceChild is node, then set referenceChild to node’s next sibling.
  797. if (reference_child == node)
  798. reference_child = node->next_sibling();
  799. // 9. Let previousSibling be child’s previous sibling.
  800. GC::Ptr<Node> previous_sibling = child->previous_sibling();
  801. // 10. Let removedNodes be the empty set.
  802. Vector<GC::Root<Node>> removed_nodes;
  803. // 11. If child’s parent is non-null, then:
  804. // NOTE: The above can only be false if child is node.
  805. if (child->parent()) {
  806. // 1. Set removedNodes to « child ».
  807. removed_nodes.append(GC::make_root(*child));
  808. // 2. Remove child with the suppress observers flag set.
  809. child->remove(true);
  810. }
  811. // 12. Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ».
  812. Vector<GC::Root<Node>> nodes;
  813. if (is<DocumentFragment>(*node))
  814. nodes = node->children_as_vector();
  815. else
  816. nodes.append(GC::make_root(*node));
  817. // 13. Insert node into parent before referenceChild with the suppress observers flag set.
  818. insert_before(node, reference_child, true);
  819. // 14. Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
  820. queue_tree_mutation_record(move(nodes), move(removed_nodes), previous_sibling.ptr(), reference_child.ptr());
  821. // 15. Return child.
  822. return child;
  823. }
  824. // https://dom.spec.whatwg.org/#concept-node-clone
  825. WebIDL::ExceptionOr<GC::Ref<Node>> Node::clone_node(Document* document, bool clone_children)
  826. {
  827. // 1. If document is not given, let document be node’s node document.
  828. if (!document)
  829. document = m_document.ptr();
  830. GC::Ptr<Node> copy;
  831. // 2. If node is an element, then:
  832. if (is<Element>(this)) {
  833. // 1. Let copy be the result of creating an element, given document, node’s local name, node’s namespace, node’s namespace prefix, and node’s is value, with the synchronous custom elements flag unset.
  834. auto& element = *verify_cast<Element>(this);
  835. auto element_copy = DOM::create_element(*document, element.local_name(), element.namespace_uri(), element.prefix(), element.is_value(), false).release_value_but_fixme_should_propagate_errors();
  836. // 2. For each attribute in node’s attribute list:
  837. element.for_each_attribute([&](auto& name, auto& value) {
  838. // 1. Let copyAttribute be a clone of attribute.
  839. // 2. Append copyAttribute to copy.
  840. element_copy->append_attribute(name, value);
  841. });
  842. copy = move(element_copy);
  843. }
  844. // 3. Otherwise, let copy be a node that implements the same interfaces as node, and fulfills these additional requirements, switching on the interface node implements:
  845. else if (is<Document>(this)) {
  846. // Document
  847. auto document_ = verify_cast<Document>(this);
  848. auto document_copy = [&] -> GC::Ref<Document> {
  849. switch (document_->document_type()) {
  850. case Document::Type::XML:
  851. return XMLDocument::create(realm(), document_->url());
  852. case Document::Type::HTML:
  853. return HTML::HTMLDocument::create(realm(), document_->url());
  854. default:
  855. return Document::create(realm(), document_->url());
  856. }
  857. }();
  858. // Set copy’s encoding, content type, URL, origin, type, and mode to those of node.
  859. document_copy->set_encoding(document_->encoding());
  860. document_copy->set_content_type(document_->content_type());
  861. document_copy->set_url(document_->url());
  862. document_copy->set_origin(document_->origin());
  863. document_copy->set_document_type(document_->document_type());
  864. document_copy->set_quirks_mode(document_->mode());
  865. copy = move(document_copy);
  866. } else if (is<DocumentType>(this)) {
  867. // DocumentType
  868. auto document_type = verify_cast<DocumentType>(this);
  869. auto document_type_copy = realm().create<DocumentType>(*document);
  870. // Set copy’s name, public ID, and system ID to those of node.
  871. document_type_copy->set_name(document_type->name());
  872. document_type_copy->set_public_id(document_type->public_id());
  873. document_type_copy->set_system_id(document_type->system_id());
  874. copy = move(document_type_copy);
  875. } else if (is<Attr>(this)) {
  876. // Attr
  877. // Set copy’s namespace, namespace prefix, local name, and value to those of node.
  878. auto& attr = static_cast<Attr&>(*this);
  879. copy = attr.clone(*document);
  880. } else if (is<Text>(this)) {
  881. // Text
  882. auto& text = static_cast<Text&>(*this);
  883. // Set copy’s data to that of node.
  884. copy = [&]() -> GC::Ref<Text> {
  885. switch (type()) {
  886. case NodeType::TEXT_NODE:
  887. return realm().create<Text>(*document, text.data());
  888. case NodeType::CDATA_SECTION_NODE:
  889. return realm().create<CDATASection>(*document, text.data());
  890. default:
  891. VERIFY_NOT_REACHED();
  892. }
  893. }();
  894. } else if (is<Comment>(this)) {
  895. // Comment
  896. auto comment = verify_cast<Comment>(this);
  897. // Set copy’s data to that of node.
  898. auto comment_copy = realm().create<Comment>(*document, comment->data());
  899. copy = move(comment_copy);
  900. } else if (is<ProcessingInstruction>(this)) {
  901. // ProcessingInstruction
  902. auto processing_instruction = verify_cast<ProcessingInstruction>(this);
  903. // Set copy’s target and data to those of node.
  904. auto processing_instruction_copy = realm().create<ProcessingInstruction>(*document, processing_instruction->data(), processing_instruction->target());
  905. copy = processing_instruction_copy;
  906. }
  907. // Otherwise, Do nothing.
  908. else if (is<DocumentFragment>(this)) {
  909. copy = realm().create<DocumentFragment>(*document);
  910. }
  911. // 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.
  912. // 5. Run any cloning steps defined for node in other applicable specifications and pass copy, node, document and the clone children flag if set, as parameters.
  913. TRY(cloned(*copy, clone_children));
  914. // 6. If the clone children flag is set, clone all the children of node and append them to copy, with document as specified and the clone children flag being set.
  915. if (clone_children) {
  916. for (auto child = first_child(); child; child = child->next_sibling()) {
  917. TRY(copy->append_child(TRY(child->clone_node(document, true))));
  918. }
  919. }
  920. // 7. If node is a shadow host whose shadow root’s clonable is true:
  921. if (is_element() && static_cast<Element const&>(*this).is_shadow_host() && static_cast<Element const&>(*this).shadow_root()->clonable()) {
  922. // 1. Assert: copy is not a shadow host.
  923. VERIFY(!copy->is_element() || !static_cast<Element const&>(*copy).is_shadow_host());
  924. // 2. Run attach a shadow root with copy, node’s shadow root’s mode, true, node’s shadow root’s serializable,
  925. // node’s shadow root’s delegates focus, and node’s shadow root’s slot assignment.
  926. auto& node_shadow_root = *static_cast<Element&>(*this).shadow_root();
  927. TRY(static_cast<Element&>(*copy).attach_a_shadow_root(node_shadow_root.mode(), true, node_shadow_root.serializable(), node_shadow_root.delegates_focus(), node_shadow_root.slot_assignment()));
  928. // 3. Set copy’s shadow root’s declarative to node’s shadow root’s declarative.
  929. static_cast<Element&>(*copy).shadow_root()->set_declarative(node_shadow_root.declarative());
  930. // 4. For each child child of node’s shadow root, in tree order:
  931. // append the result of cloning child with document and the clone children flag set, to copy’s shadow root.
  932. for (auto child = node_shadow_root.first_child(); child; child = child->next_sibling()) {
  933. TRY(static_cast<Element&>(*copy).shadow_root()->append_child(TRY(child->clone_node(document, true))));
  934. }
  935. }
  936. // 7. Return copy.
  937. VERIFY(copy);
  938. return GC::Ref { *copy };
  939. }
  940. // https://dom.spec.whatwg.org/#dom-node-clonenode
  941. WebIDL::ExceptionOr<GC::Ref<Node>> Node::clone_node_binding(bool deep)
  942. {
  943. // 1. If this is a shadow root, then throw a "NotSupportedError" DOMException.
  944. if (is<ShadowRoot>(*this))
  945. return WebIDL::NotSupportedError::create(realm(), "Cannot clone shadow root"_string);
  946. // 2. Return a clone of this, with the clone children flag set if deep is true.
  947. return clone_node(nullptr, deep);
  948. }
  949. void Node::set_document(Badge<Document>, Document& document)
  950. {
  951. if (m_document.ptr() == &document)
  952. return;
  953. m_document = &document;
  954. if (needs_style_update() || child_needs_style_update()) {
  955. // NOTE: We unset and reset the "needs style update" flag here.
  956. // This ensures that there's a pending style update in the new document
  957. // that will eventually assign some style to this node if needed.
  958. set_needs_style_update(false);
  959. set_needs_style_update(true);
  960. }
  961. }
  962. bool Node::is_editable() const
  963. {
  964. return parent() && parent()->is_editable();
  965. }
  966. void Node::set_layout_node(Badge<Layout::Node>, GC::Ref<Layout::Node> layout_node)
  967. {
  968. m_layout_node = layout_node;
  969. }
  970. void Node::detach_layout_node(Badge<Layout::TreeBuilder>)
  971. {
  972. m_layout_node = nullptr;
  973. }
  974. EventTarget* Node::get_parent(Event const&)
  975. {
  976. // A node’s get the parent algorithm, given an event, returns the node’s assigned slot, if node is assigned;
  977. // otherwise node’s parent.
  978. if (auto assigned_slot = assigned_slot_for_node(*this))
  979. return assigned_slot.ptr();
  980. return parent();
  981. }
  982. void Node::set_needs_style_update(bool value)
  983. {
  984. if (m_needs_style_update == value)
  985. return;
  986. m_needs_style_update = value;
  987. if (m_needs_style_update) {
  988. for (auto* ancestor = parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
  989. if (ancestor->m_child_needs_style_update)
  990. break;
  991. ancestor->m_child_needs_style_update = true;
  992. }
  993. document().schedule_style_update();
  994. }
  995. }
  996. void Node::inserted()
  997. {
  998. set_needs_style_update(true);
  999. }
  1000. void Node::removed_from(Node*)
  1001. {
  1002. m_layout_node = nullptr;
  1003. m_paintable = nullptr;
  1004. }
  1005. ParentNode* Node::parent_or_shadow_host()
  1006. {
  1007. if (is<ShadowRoot>(*this))
  1008. return static_cast<ShadowRoot&>(*this).host();
  1009. return verify_cast<ParentNode>(parent());
  1010. }
  1011. Element* Node::parent_or_shadow_host_element()
  1012. {
  1013. if (is<ShadowRoot>(*this))
  1014. return static_cast<ShadowRoot&>(*this).host();
  1015. if (!parent())
  1016. return nullptr;
  1017. if (is<Element>(*parent()))
  1018. return static_cast<Element*>(parent());
  1019. if (is<ShadowRoot>(*parent()))
  1020. return static_cast<ShadowRoot&>(*parent()).host();
  1021. return nullptr;
  1022. }
  1023. Slottable Node::as_slottable()
  1024. {
  1025. VERIFY(is_slottable());
  1026. if (is_element())
  1027. return GC::Ref { static_cast<Element&>(*this) };
  1028. return GC::Ref { static_cast<Text&>(*this) };
  1029. }
  1030. GC::Ref<NodeList> Node::child_nodes()
  1031. {
  1032. if (!m_child_nodes) {
  1033. m_child_nodes = LiveNodeList::create(realm(), *this, LiveNodeList::Scope::Children, [](auto&) {
  1034. return true;
  1035. });
  1036. }
  1037. return *m_child_nodes;
  1038. }
  1039. Vector<GC::Root<Node>> Node::children_as_vector() const
  1040. {
  1041. Vector<GC::Root<Node>> nodes;
  1042. for_each_child([&](auto& child) {
  1043. nodes.append(GC::make_root(child));
  1044. return IterationDecision::Continue;
  1045. });
  1046. return nodes;
  1047. }
  1048. void Node::remove_all_children(bool suppress_observers)
  1049. {
  1050. while (GC::Ptr<Node> child = first_child())
  1051. child->remove(suppress_observers);
  1052. }
  1053. // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
  1054. u16 Node::compare_document_position(GC::Ptr<Node> other)
  1055. {
  1056. // 1. If this is other, then return zero.
  1057. if (this == other.ptr())
  1058. return DOCUMENT_POSITION_EQUAL;
  1059. // 2. Let node1 be other and node2 be this.
  1060. Node* node1 = other.ptr();
  1061. Node* node2 = this;
  1062. // 3. Let attr1 and attr2 be null.
  1063. Attr* attr1 = nullptr;
  1064. Attr* attr2 = nullptr;
  1065. // 4. If node1 is an attribute, then set attr1 to node1 and node1 to attr1’s element.
  1066. if (is<Attr>(node1)) {
  1067. attr1 = verify_cast<Attr>(node1);
  1068. node1 = const_cast<Element*>(attr1->owner_element());
  1069. }
  1070. // 5. If node2 is an attribute, then:
  1071. if (is<Attr>(node2)) {
  1072. // 1. Set attr2 to node2 and node2 to attr2’s element.
  1073. attr2 = verify_cast<Attr>(node2);
  1074. node2 = const_cast<Element*>(attr2->owner_element());
  1075. // 2. If attr1 and node1 are non-null, and node2 is node1, then:
  1076. if (attr1 && node1 && node2 == node1) {
  1077. // FIXME: 1. For each attr in node2’s attribute list:
  1078. // 1. If attr equals attr1, then return the result of adding DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC and DOCUMENT_POSITION_PRECEDING.
  1079. // 2. If attr equals attr2, then return the result of adding DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC and DOCUMENT_POSITION_FOLLOWING.
  1080. }
  1081. }
  1082. // 6. If node1 or node2 is null, or node1’s root is not node2’s root, then return the result of adding
  1083. // DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, and either DOCUMENT_POSITION_PRECEDING or DOCUMENT_POSITION_FOLLOWING, with the constraint that this is to be consistent, together.
  1084. if ((node1 == nullptr || node2 == nullptr) || (&node1->root() != &node2->root()))
  1085. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | (node1 > node2 ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING);
  1086. Vector<Node*> node1_ancestors;
  1087. for (auto* node = node1; node; node = node->parent())
  1088. node1_ancestors.append(node);
  1089. Vector<Node*> node2_ancestors;
  1090. for (auto* node = node2; node; node = node->parent())
  1091. node2_ancestors.append(node);
  1092. auto it_node1_ancestors = node1_ancestors.rbegin();
  1093. auto it_node2_ancestors = node2_ancestors.rbegin();
  1094. // Walk ancestor chains of both nodes starting from root
  1095. while (it_node1_ancestors != node1_ancestors.rend() && it_node2_ancestors != node2_ancestors.rend()) {
  1096. auto* ancestor1 = *it_node1_ancestors;
  1097. auto* ancestor2 = *it_node2_ancestors;
  1098. // If ancestors of nodes at the same level in the tree are different then preceding node is the one with lower sibling position
  1099. if (ancestor1 != ancestor2) {
  1100. auto* node = ancestor1;
  1101. while (node) {
  1102. if (node == ancestor2)
  1103. return DOCUMENT_POSITION_PRECEDING;
  1104. node = node->next_sibling();
  1105. }
  1106. return DOCUMENT_POSITION_FOLLOWING;
  1107. }
  1108. it_node1_ancestors++;
  1109. it_node2_ancestors++;
  1110. }
  1111. // NOTE: If nodes in ancestors chains are the same but one chain is longer, then one node is ancestor of another.
  1112. // The node with shorter ancestors chain is the ancestor.
  1113. // The node with longer ancestors chain is the descendant.
  1114. // 7. If node1 is an ancestor of node2 and attr1 is null, or node1 is node2 and attr2 is non-null, then return the result of adding DOCUMENT_POSITION_CONTAINS to DOCUMENT_POSITION_PRECEDING.
  1115. if ((node1_ancestors.size() < node2_ancestors.size() && !attr1) || (node1 == node2 && attr2))
  1116. return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
  1117. // 8. If node1 is a descendant of node2 and attr2 is null, or node1 is node2 and attr1 is non-null, then return the result of adding DOCUMENT_POSITION_CONTAINED_BY to DOCUMENT_POSITION_FOLLOWING.
  1118. if ((node1_ancestors.size() > node2_ancestors.size() && !attr2) || (node1 == node2 && attr1))
  1119. return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
  1120. // 9. If node1 is preceding node2, then return DOCUMENT_POSITION_PRECEDING.
  1121. if (node1_ancestors.size() < node2_ancestors.size())
  1122. return DOCUMENT_POSITION_PRECEDING;
  1123. // 10. Return DOCUMENT_POSITION_FOLLOWING.
  1124. return DOCUMENT_POSITION_FOLLOWING;
  1125. }
  1126. // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
  1127. bool Node::is_host_including_inclusive_ancestor_of(Node const& other) const
  1128. {
  1129. // An object A is a host-including inclusive ancestor of an object B,
  1130. // if either A is an inclusive ancestor of B,
  1131. if (is_inclusive_ancestor_of(other))
  1132. return true;
  1133. // or if B’s root has a non-null host and A is a host-including inclusive ancestor of B’s root’s host
  1134. if (is<DocumentFragment>(other.root())
  1135. && static_cast<DocumentFragment const&>(other.root()).host()
  1136. && is_inclusive_ancestor_of(*static_cast<DocumentFragment const&>(other.root()).host())) {
  1137. return true;
  1138. }
  1139. return false;
  1140. }
  1141. // https://dom.spec.whatwg.org/#dom-node-ownerdocument
  1142. GC::Ptr<Document> Node::owner_document() const
  1143. {
  1144. // The ownerDocument getter steps are to return null, if this is a document; otherwise this’s node document.
  1145. if (is_document())
  1146. return nullptr;
  1147. return m_document;
  1148. }
  1149. // This function tells us whether a node is interesting enough to show up
  1150. // in the DOM inspector. This hides two things:
  1151. // - Non-rendered whitespace
  1152. // - Rendered whitespace between block-level elements
  1153. bool Node::is_uninteresting_whitespace_node() const
  1154. {
  1155. if (!is<Text>(*this))
  1156. return false;
  1157. if (!static_cast<Text const&>(*this).data().bytes_as_string_view().is_whitespace())
  1158. return false;
  1159. if (!layout_node())
  1160. return true;
  1161. if (auto parent = layout_node()->parent(); parent && parent->is_anonymous())
  1162. return true;
  1163. return false;
  1164. }
  1165. void Node::serialize_tree_as_json(JsonObjectSerializer<StringBuilder>& object) const
  1166. {
  1167. MUST(object.add("name"sv, node_name()));
  1168. MUST(object.add("id"sv, unique_id().value()));
  1169. if (is_document()) {
  1170. MUST(object.add("type"sv, "document"));
  1171. } else if (is_element()) {
  1172. MUST(object.add("type"sv, "element"));
  1173. auto const* element = static_cast<DOM::Element const*>(this);
  1174. if (element->has_attributes()) {
  1175. auto attributes = MUST(object.add_object("attributes"sv));
  1176. element->for_each_attribute([&attributes](auto& name, auto& value) {
  1177. MUST(attributes.add(name, value));
  1178. });
  1179. MUST(attributes.finish());
  1180. }
  1181. if (element->is_navigable_container()) {
  1182. auto const* container = static_cast<HTML::NavigableContainer const*>(element);
  1183. if (auto const* content_document = container->content_document()) {
  1184. auto children = MUST(object.add_array("children"sv));
  1185. JsonObjectSerializer<StringBuilder> content_document_object = MUST(children.add_object());
  1186. content_document->serialize_tree_as_json(content_document_object);
  1187. MUST(content_document_object.finish());
  1188. MUST(children.finish());
  1189. }
  1190. }
  1191. } else if (is_text()) {
  1192. MUST(object.add("type"sv, "text"));
  1193. auto text_node = static_cast<DOM::Text const*>(this);
  1194. MUST(object.add("text"sv, text_node->data()));
  1195. } else if (is_comment()) {
  1196. MUST(object.add("type"sv, "comment"sv));
  1197. MUST(object.add("data"sv, static_cast<DOM::Comment const&>(*this).data()));
  1198. } else if (is_shadow_root()) {
  1199. MUST(object.add("type"sv, "shadow-root"));
  1200. MUST(object.add("mode"sv, static_cast<DOM::ShadowRoot const&>(*this).mode() == Bindings::ShadowRootMode::Open ? "open"sv : "closed"sv));
  1201. }
  1202. MUST((object.add("visible"sv, !!layout_node())));
  1203. auto const* element = is_element() ? static_cast<DOM::Element const*>(this) : nullptr;
  1204. if (has_child_nodes()
  1205. || (element && (element->is_shadow_host() || element->has_pseudo_elements()))) {
  1206. auto children = MUST(object.add_array("children"sv));
  1207. auto add_child = [&children](DOM::Node const& child) {
  1208. if (child.is_uninteresting_whitespace_node())
  1209. return IterationDecision::Continue;
  1210. JsonObjectSerializer<StringBuilder> child_object = MUST(children.add_object());
  1211. child.serialize_tree_as_json(child_object);
  1212. MUST(child_object.finish());
  1213. return IterationDecision::Continue;
  1214. };
  1215. for_each_child(add_child);
  1216. if (element) {
  1217. // Pseudo-elements don't have DOM nodes,so we have to add them separately.
  1218. element->serialize_pseudo_elements_as_json(children);
  1219. if (element->is_shadow_host())
  1220. add_child(*element->shadow_root());
  1221. }
  1222. MUST(children.finish());
  1223. }
  1224. }
  1225. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-script
  1226. // https://whatpr.org/html/9893/webappapis.html#concept-n-script
  1227. bool Node::is_scripting_enabled() const
  1228. {
  1229. // Scripting is enabled for a node node if node's node document's browsing context is non-null, and scripting is enabled for node's relevant realm.
  1230. return document().browsing_context() && HTML::is_scripting_enabled(HTML::relevant_realm(*this));
  1231. }
  1232. // https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-noscript
  1233. // https://whatpr.org/html/9893/webappapis.html#concept-n-script
  1234. bool Node::is_scripting_disabled() const
  1235. {
  1236. // Scripting is disabled for a node when scripting is not enabled, i.e., when its node document's browsing context is null or when scripting is disabled for its relevant realm.
  1237. return !is_scripting_enabled();
  1238. }
  1239. // https://dom.spec.whatwg.org/#dom-node-contains
  1240. bool Node::contains(GC::Ptr<Node> other) const
  1241. {
  1242. // The contains(other) method steps are to return true if other is an inclusive descendant of this; otherwise false (including when other is null).
  1243. return other && other->is_inclusive_descendant_of(*this);
  1244. }
  1245. // https://dom.spec.whatwg.org/#concept-shadow-including-descendant
  1246. bool Node::is_shadow_including_descendant_of(Node const& other) const
  1247. {
  1248. // An object A is a shadow-including descendant of an object B,
  1249. // if A is a descendant of B,
  1250. if (is_descendant_of(other))
  1251. return true;
  1252. // or A’s root is a shadow root
  1253. if (!is<ShadowRoot>(root()))
  1254. return false;
  1255. // and A’s root’s host is a shadow-including inclusive descendant of B.
  1256. auto& shadow_root = verify_cast<ShadowRoot>(root());
  1257. return shadow_root.host() && shadow_root.host()->is_shadow_including_inclusive_descendant_of(other);
  1258. }
  1259. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
  1260. bool Node::is_shadow_including_inclusive_descendant_of(Node const& other) const
  1261. {
  1262. // A shadow-including inclusive descendant is an object or one of its shadow-including descendants.
  1263. return &other == this || is_shadow_including_descendant_of(other);
  1264. }
  1265. // https://dom.spec.whatwg.org/#concept-shadow-including-ancestor
  1266. bool Node::is_shadow_including_ancestor_of(Node const& other) const
  1267. {
  1268. // An object A is a shadow-including ancestor of an object B, if and only if B is a shadow-including descendant of A.
  1269. return other.is_shadow_including_descendant_of(*this);
  1270. }
  1271. // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor
  1272. bool Node::is_shadow_including_inclusive_ancestor_of(Node const& other) const
  1273. {
  1274. // A shadow-including inclusive ancestor is an object or one of its shadow-including ancestors.
  1275. return other.is_shadow_including_inclusive_descendant_of(*this);
  1276. }
  1277. // https://dom.spec.whatwg.org/#concept-node-replace-all
  1278. void Node::replace_all(GC::Ptr<Node> node)
  1279. {
  1280. // 1. Let removedNodes be parent’s children.
  1281. auto removed_nodes = children_as_vector();
  1282. // 2. Let addedNodes be the empty set.
  1283. Vector<GC::Root<Node>> added_nodes;
  1284. // 3. If node is a DocumentFragment node, then set addedNodes to node’s children.
  1285. if (node && is<DocumentFragment>(*node)) {
  1286. added_nodes = node->children_as_vector();
  1287. }
  1288. // 4. Otherwise, if node is non-null, set addedNodes to « node ».
  1289. else if (node) {
  1290. added_nodes.append(GC::make_root(*node));
  1291. }
  1292. // 5. Remove all parent’s children, in tree order, with the suppress observers flag set.
  1293. remove_all_children(true);
  1294. // 6. If node is non-null, then insert node into parent before null with the suppress observers flag set.
  1295. if (node)
  1296. insert_before(*node, nullptr, true);
  1297. // 7. If either addedNodes or removedNodes is not empty, then queue a tree mutation record for parent with addedNodes, removedNodes, null, and null.
  1298. if (!added_nodes.is_empty() || !removed_nodes.is_empty()) {
  1299. queue_tree_mutation_record(move(added_nodes), move(removed_nodes), nullptr, nullptr);
  1300. }
  1301. }
  1302. // https://dom.spec.whatwg.org/#string-replace-all
  1303. void Node::string_replace_all(String const& string)
  1304. {
  1305. // 1. Let node be null.
  1306. GC::Ptr<Node> node;
  1307. // 2. If string is not the empty string, then set node to a new Text node whose data is string and node document is parent’s node document.
  1308. if (!string.is_empty())
  1309. node = realm().create<Text>(document(), string);
  1310. // 3. Replace all with node within parent.
  1311. replace_all(node);
  1312. }
  1313. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#fragment-serializing-algorithm-steps
  1314. WebIDL::ExceptionOr<String> Node::serialize_fragment(DOMParsing::RequireWellFormed require_well_formed, FragmentSerializationMode fragment_serialization_mode) const
  1315. {
  1316. // 1. Let context document be the value of node's node document.
  1317. auto const& context_document = document();
  1318. // 2. If context document is an HTML document, return the result of HTML fragment serialization algorithm with node, false, and « ».
  1319. if (context_document.is_html_document())
  1320. return HTML::HTMLParser::serialize_html_fragment(*this, HTML::HTMLParser::SerializableShadowRoots::No, {}, fragment_serialization_mode);
  1321. // 3. Return the XML serialization of node given require well-formed.
  1322. // AD-HOC: XML serialization algorithm returns the "outer" XML serialization of the node.
  1323. // For inner, concatenate the serialization of all children.
  1324. if (fragment_serialization_mode == FragmentSerializationMode::Inner) {
  1325. StringBuilder markup;
  1326. for (auto* child = first_child(); child; child = child->next_sibling()) {
  1327. auto child_markup = TRY(DOMParsing::serialize_node_to_xml_string(*child, require_well_formed));
  1328. markup.append(child_markup.bytes_as_string_view());
  1329. }
  1330. return MUST(markup.to_string());
  1331. }
  1332. return DOMParsing::serialize_node_to_xml_string(*this, require_well_formed);
  1333. }
  1334. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#unsafely-set-html
  1335. WebIDL::ExceptionOr<void> Node::unsafely_set_html(Element& context_element, StringView html)
  1336. {
  1337. // 1. Let newChildren be the result of the HTML fragment parsing algorithm given contextElement, html, and true.
  1338. auto new_children = HTML::HTMLParser::parse_html_fragment(context_element, html, HTML::HTMLParser::AllowDeclarativeShadowRoots::Yes);
  1339. // 2. Let fragment be a new DocumentFragment whose node document is contextElement’s node document.
  1340. auto fragment = realm().create<DocumentFragment>(context_element.document());
  1341. // 3. For each node in newChildren, append node to fragment.
  1342. for (auto& child : new_children)
  1343. // I don't know if this can throw here, but let's be safe.
  1344. (void)TRY(fragment->append_child(*child));
  1345. // 4. Replace all with fragment within contextElement.
  1346. replace_all(fragment);
  1347. return {};
  1348. }
  1349. // https://dom.spec.whatwg.org/#dom-node-issamenode
  1350. bool Node::is_same_node(Node const* other_node) const
  1351. {
  1352. // The isSameNode(otherNode) method steps are to return true if otherNode is this; otherwise false.
  1353. return this == other_node;
  1354. }
  1355. // https://dom.spec.whatwg.org/#dom-node-isequalnode
  1356. bool Node::is_equal_node(Node const* other_node) const
  1357. {
  1358. // The isEqualNode(otherNode) method steps are to return true if otherNode is non-null and this equals otherNode; otherwise false.
  1359. if (!other_node)
  1360. return false;
  1361. // Fast path for testing a node against itself.
  1362. if (this == other_node)
  1363. return true;
  1364. // A node A equals a node B if all of the following conditions are true:
  1365. // A and B implement the same interfaces.
  1366. if (!node_name().equals_ignoring_ascii_case(other_node->node_name()))
  1367. return false;
  1368. // The following are equal, switching on the interface A implements:
  1369. switch (node_type()) {
  1370. case (u16)NodeType::DOCUMENT_TYPE_NODE: {
  1371. // Its name, public ID, and system ID.
  1372. auto& this_doctype = verify_cast<DocumentType>(*this);
  1373. auto& other_doctype = verify_cast<DocumentType>(*other_node);
  1374. if (this_doctype.name() != other_doctype.name()
  1375. || this_doctype.public_id() != other_doctype.public_id()
  1376. || this_doctype.system_id() != other_doctype.system_id())
  1377. return false;
  1378. break;
  1379. }
  1380. case (u16)NodeType::ELEMENT_NODE: {
  1381. // Its namespace, namespace prefix, local name, and its attribute list’s size.
  1382. auto& this_element = verify_cast<Element>(*this);
  1383. auto& other_element = verify_cast<Element>(*other_node);
  1384. if (this_element.namespace_uri() != other_element.namespace_uri()
  1385. || this_element.prefix() != other_element.prefix()
  1386. || this_element.local_name() != other_element.local_name()
  1387. || this_element.attribute_list_size() != other_element.attribute_list_size())
  1388. return false;
  1389. // If A is an element, each attribute in its attribute list has an attribute that equals an attribute in B’s attribute list.
  1390. bool has_same_attributes = true;
  1391. this_element.for_each_attribute([&](auto const& attribute) {
  1392. if (other_element.get_attribute_ns(attribute.namespace_uri(), attribute.local_name()) != attribute.value())
  1393. has_same_attributes = false;
  1394. });
  1395. if (!has_same_attributes)
  1396. return false;
  1397. break;
  1398. }
  1399. case (u16)NodeType::COMMENT_NODE:
  1400. case (u16)NodeType::TEXT_NODE: {
  1401. // Its data.
  1402. auto& this_cdata = verify_cast<CharacterData>(*this);
  1403. auto& other_cdata = verify_cast<CharacterData>(*other_node);
  1404. if (this_cdata.data() != other_cdata.data())
  1405. return false;
  1406. break;
  1407. }
  1408. case (u16)NodeType::ATTRIBUTE_NODE: {
  1409. // Its namespace, local name, and value.
  1410. auto& this_attr = verify_cast<Attr>(*this);
  1411. auto& other_attr = verify_cast<Attr>(*other_node);
  1412. if (this_attr.namespace_uri() != other_attr.namespace_uri())
  1413. return false;
  1414. if (this_attr.local_name() != other_attr.local_name())
  1415. return false;
  1416. if (this_attr.value() != other_attr.value())
  1417. return false;
  1418. break;
  1419. }
  1420. case (u16)NodeType::PROCESSING_INSTRUCTION_NODE: {
  1421. // Its target and data.
  1422. auto& this_processing_instruction = verify_cast<ProcessingInstruction>(*this);
  1423. auto& other_processing_instruction = verify_cast<ProcessingInstruction>(*other_node);
  1424. if (this_processing_instruction.target() != other_processing_instruction.target())
  1425. return false;
  1426. if (this_processing_instruction.data() != other_processing_instruction.data())
  1427. return false;
  1428. break;
  1429. }
  1430. default:
  1431. break;
  1432. }
  1433. // A and B have the same number of children.
  1434. size_t this_child_count = child_count();
  1435. size_t other_child_count = other_node->child_count();
  1436. if (this_child_count != other_child_count)
  1437. return false;
  1438. // Each child of A equals the child of B at the identical index.
  1439. // FIXME: This can be made nicer. child_at_index() is O(n).
  1440. for (size_t i = 0; i < this_child_count; ++i) {
  1441. auto* this_child = child_at_index(i);
  1442. auto* other_child = other_node->child_at_index(i);
  1443. VERIFY(this_child);
  1444. VERIFY(other_child);
  1445. if (!this_child->is_equal_node(other_child))
  1446. return false;
  1447. }
  1448. return true;
  1449. }
  1450. // https://dom.spec.whatwg.org/#locate-a-namespace
  1451. Optional<String> Node::locate_a_namespace(Optional<String> const& prefix) const
  1452. {
  1453. // To locate a namespace for a node using prefix, switch on the interface node implements:
  1454. // Element
  1455. if (is<Element>(*this)) {
  1456. // 1. If prefix is "xml", then return the XML namespace.
  1457. if (prefix == "xml")
  1458. return Web::Namespace::XML.to_string();
  1459. // 2. If prefix is "xmlns", then return the XMLNS namespace.
  1460. if (prefix == "xmlns")
  1461. return Web::Namespace::XMLNS.to_string();
  1462. // 3. If its namespace is non-null and its namespace prefix is prefix, then return namespace.
  1463. auto& element = verify_cast<Element>(*this);
  1464. if (element.namespace_uri().has_value() && element.prefix() == prefix)
  1465. return element.namespace_uri()->to_string();
  1466. // 4. If it has an attribute whose namespace is the XMLNS namespace, namespace prefix is "xmlns", and local name is prefix,
  1467. // or if prefix is null and it has an attribute whose namespace is the XMLNS namespace, namespace prefix is null,
  1468. // and local name is "xmlns", then return its value if it is not the empty string, and null otherwise.
  1469. if (auto* attributes = element.attributes()) {
  1470. for (size_t i = 0; i < attributes->length(); ++i) {
  1471. auto& attr = *attributes->item(i);
  1472. if (attr.namespace_uri() == Web::Namespace::XMLNS) {
  1473. if ((attr.prefix() == "xmlns" && attr.local_name() == prefix) || (!prefix.has_value() && !attr.prefix().has_value() && attr.local_name() == "xmlns")) {
  1474. auto value = attr.value();
  1475. if (!value.is_empty())
  1476. return value;
  1477. return {};
  1478. }
  1479. }
  1480. }
  1481. }
  1482. // 5. If its parent element is null, then return null.
  1483. auto* parent_element = element.parent_element();
  1484. if (!element.parent_element())
  1485. return {};
  1486. // 6. Return the result of running locate a namespace on its parent element using prefix.
  1487. return parent_element->locate_a_namespace(prefix);
  1488. }
  1489. // Document
  1490. if (is<Document>(*this)) {
  1491. // 1. If its document element is null, then return null.
  1492. auto* document_element = verify_cast<Document>(*this).document_element();
  1493. if (!document_element)
  1494. return {};
  1495. // 2. Return the result of running locate a namespace on its document element using prefix.
  1496. return document_element->locate_a_namespace(prefix);
  1497. }
  1498. // DocumentType
  1499. // DocumentFragment
  1500. if (is<DocumentType>(*this) || is<DocumentFragment>(*this)) {
  1501. // Return null.
  1502. return {};
  1503. }
  1504. // Attr
  1505. if (is<Attr>(*this)) {
  1506. // 1. If its element is null, then return null.
  1507. auto* element = verify_cast<Attr>(*this).owner_element();
  1508. if (!element)
  1509. return {};
  1510. // 2. Return the result of running locate a namespace on its element using prefix.
  1511. return element->locate_a_namespace(prefix);
  1512. }
  1513. // Otherwise
  1514. // 1. If its parent element is null, then return null.
  1515. auto* parent_element = this->parent_element();
  1516. if (!parent_element)
  1517. return {};
  1518. // 2. Return the result of running locate a namespace on its parent element using prefix.
  1519. return parent_element->locate_a_namespace(prefix);
  1520. }
  1521. // https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri
  1522. Optional<String> Node::lookup_namespace_uri(Optional<String> prefix) const
  1523. {
  1524. // 1. If prefix is the empty string, then set it to null.
  1525. if (prefix.has_value() && prefix->is_empty())
  1526. prefix = {};
  1527. // 2. Return the result of running locate a namespace for this using prefix.
  1528. return locate_a_namespace(prefix);
  1529. }
  1530. // https://dom.spec.whatwg.org/#dom-node-lookupprefix
  1531. Optional<String> Node::lookup_prefix(Optional<String> namespace_) const
  1532. {
  1533. // 1. If namespace is null or the empty string, then return null.
  1534. if (!namespace_.has_value() || namespace_->is_empty())
  1535. return {};
  1536. // 2. Switch on the interface this implements:
  1537. // Element
  1538. if (is<Element>(*this)) {
  1539. // Return the result of locating a namespace prefix for it using namespace.
  1540. auto& element = verify_cast<Element>(*this);
  1541. return element.locate_a_namespace_prefix(namespace_);
  1542. }
  1543. // Document
  1544. if (is<Document>(*this)) {
  1545. // Return the result of locating a namespace prefix for its document element, if its document element is non-null; otherwise null.
  1546. auto* document_element = verify_cast<Document>(*this).document_element();
  1547. if (!document_element)
  1548. return {};
  1549. return document_element->locate_a_namespace_prefix(namespace_);
  1550. }
  1551. // DocumentType
  1552. // DocumentFragment
  1553. if (is<DocumentType>(*this) || is<DocumentFragment>(*this))
  1554. // Return null
  1555. return {};
  1556. // Attr
  1557. if (is<Attr>(*this)) {
  1558. // Return the result of locating a namespace prefix for its element, if its element is non-null; otherwise null.
  1559. auto* element = verify_cast<Attr>(*this).owner_element();
  1560. if (!element)
  1561. return {};
  1562. return element->locate_a_namespace_prefix(namespace_);
  1563. }
  1564. // Otherwise
  1565. // Return the result of locating a namespace prefix for its parent element, if its parent element is non-null; otherwise null.
  1566. auto* parent_element = this->parent_element();
  1567. if (!parent_element)
  1568. return {};
  1569. return parent_element->locate_a_namespace_prefix(namespace_);
  1570. }
  1571. // https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace
  1572. bool Node::is_default_namespace(Optional<String> namespace_) const
  1573. {
  1574. // 1. If namespace is the empty string, then set it to null.
  1575. if (namespace_.has_value() && namespace_->is_empty())
  1576. namespace_ = {};
  1577. // 2. Let defaultNamespace be the result of running locate a namespace for this using null.
  1578. auto default_namespace = locate_a_namespace({});
  1579. // 3. Return true if defaultNamespace is the same as namespace; otherwise false.
  1580. return default_namespace == namespace_;
  1581. }
  1582. // https://dom.spec.whatwg.org/#in-a-document-tree
  1583. bool Node::in_a_document_tree() const
  1584. {
  1585. // An element is in a document tree if its root is a document.
  1586. return root().is_document();
  1587. }
  1588. // https://dom.spec.whatwg.org/#dom-node-getrootnode
  1589. GC::Ref<Node> Node::get_root_node(GetRootNodeOptions const& options)
  1590. {
  1591. // The getRootNode(options) method steps are to return this’s shadow-including root if options["composed"] is true;
  1592. if (options.composed)
  1593. return shadow_including_root();
  1594. // otherwise this’s root.
  1595. return root();
  1596. }
  1597. String Node::debug_description() const
  1598. {
  1599. StringBuilder builder;
  1600. builder.append(node_name().to_deprecated_fly_string().to_lowercase());
  1601. if (is_element()) {
  1602. auto const& element = static_cast<DOM::Element const&>(*this);
  1603. if (element.id().has_value())
  1604. builder.appendff("#{}", element.id().value());
  1605. for (auto const& class_name : element.class_names())
  1606. builder.appendff(".{}", class_name);
  1607. }
  1608. return MUST(builder.to_string());
  1609. }
  1610. // https://dom.spec.whatwg.org/#concept-node-length
  1611. size_t Node::length() const
  1612. {
  1613. // 1. If node is a DocumentType or Attr node, then return 0.
  1614. if (is_document_type() || is_attribute())
  1615. return 0;
  1616. // 2. If node is a CharacterData node, then return node’s data’s length.
  1617. if (is_character_data())
  1618. return verify_cast<CharacterData>(*this).length_in_utf16_code_units();
  1619. // 3. Return the number of node’s children.
  1620. return child_count();
  1621. }
  1622. void Node::set_paintable(GC::Ptr<Painting::Paintable> paintable)
  1623. {
  1624. m_paintable = paintable;
  1625. }
  1626. void Node::clear_paintable()
  1627. {
  1628. m_paintable = nullptr;
  1629. }
  1630. Painting::Paintable const* Node::paintable() const
  1631. {
  1632. return m_paintable;
  1633. }
  1634. Painting::Paintable* Node::paintable()
  1635. {
  1636. return m_paintable;
  1637. }
  1638. Painting::PaintableBox const* Node::paintable_box() const
  1639. {
  1640. if (paintable() && paintable()->is_paintable_box())
  1641. return static_cast<Painting::PaintableBox const*>(paintable());
  1642. return nullptr;
  1643. }
  1644. Painting::PaintableBox* Node::paintable_box()
  1645. {
  1646. if (paintable() && paintable()->is_paintable_box())
  1647. return static_cast<Painting::PaintableBox*>(paintable());
  1648. return nullptr;
  1649. }
  1650. // https://dom.spec.whatwg.org/#queue-a-mutation-record
  1651. void Node::queue_mutation_record(FlyString const& type, Optional<FlyString> const& attribute_name, Optional<FlyString> const& attribute_namespace, Optional<String> const& old_value, Vector<GC::Root<Node>> added_nodes, Vector<GC::Root<Node>> removed_nodes, Node* previous_sibling, Node* next_sibling) const
  1652. {
  1653. // NOTE: We defer garbage collection until the end of the scope, since we can't safely use MutationObserver* as a hashmap key otherwise.
  1654. // FIXME: This is a total hack.
  1655. GC::DeferGC defer_gc(heap());
  1656. // 1. Let interestedObservers be an empty map.
  1657. // mutationObserver -> mappedOldValue
  1658. OrderedHashMap<MutationObserver*, Optional<String>> interested_observers;
  1659. // 2. Let nodes be the inclusive ancestors of target.
  1660. // 3. For each node in nodes, and then for each registered of node’s registered observer list:
  1661. for (auto* node = this; node; node = node->parent()) {
  1662. if (!node->m_registered_observer_list)
  1663. continue;
  1664. for (auto& registered_observer : *node->m_registered_observer_list) {
  1665. // 1. Let options be registered’s options.
  1666. auto& options = registered_observer->options();
  1667. // 2. If none of the following are true
  1668. // - node is not target and options["subtree"] is false
  1669. // - type is "attributes" and options["attributes"] either does not exist or is false
  1670. // - type is "attributes", options["attributeFilter"] exists, and options["attributeFilter"] does not contain name or namespace is non-null
  1671. // - type is "characterData" and options["characterData"] either does not exist or is false
  1672. // - type is "childList" and options["childList"] is false
  1673. // then:
  1674. if (!(node != this && !options.subtree)
  1675. && !(type == MutationType::attributes && (!options.attributes.has_value() || !options.attributes.value()))
  1676. && !(type == MutationType::attributes && options.attribute_filter.has_value() && (attribute_namespace.has_value() || !options.attribute_filter->contains_slow(attribute_name.value_or(String {}))))
  1677. && !(type == MutationType::characterData && (!options.character_data.has_value() || !options.character_data.value()))
  1678. && !(type == MutationType::childList && !options.child_list)) {
  1679. // 1. Let mo be registered’s observer.
  1680. auto mutation_observer = registered_observer->observer();
  1681. // 2. If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.
  1682. if (!interested_observers.contains(mutation_observer))
  1683. interested_observers.set(mutation_observer, {});
  1684. // 3. If either type is "attributes" and options["attributeOldValue"] is true, or type is "characterData" and options["characterDataOldValue"] is true, then set interestedObservers[mo] to oldValue.
  1685. if ((type == MutationType::attributes && options.attribute_old_value.has_value() && options.attribute_old_value.value()) || (type == MutationType::characterData && options.character_data_old_value.has_value() && options.character_data_old_value.value()))
  1686. interested_observers.set(mutation_observer, old_value);
  1687. }
  1688. }
  1689. }
  1690. // OPTIMIZATION: If there are no interested observers, bail without doing any more work.
  1691. if (interested_observers.is_empty())
  1692. return;
  1693. auto added_nodes_list = StaticNodeList::create(realm(), move(added_nodes));
  1694. auto removed_nodes_list = StaticNodeList::create(realm(), move(removed_nodes));
  1695. // 4. For each observer → mappedOldValue of interestedObservers:
  1696. for (auto& interested_observer : interested_observers) {
  1697. // FIXME: The MutationRecord constructor shuld take an Optional<FlyString> attribute name and namespace
  1698. Optional<String> string_attribute_name;
  1699. if (attribute_name.has_value())
  1700. string_attribute_name = attribute_name->to_string();
  1701. Optional<String> string_attribute_namespace;
  1702. if (attribute_namespace.has_value())
  1703. string_attribute_name = attribute_namespace->to_string();
  1704. // 1. Let record be a new MutationRecord object with its type set to type, target set to target, attributeName set to name, attributeNamespace set to namespace, oldValue set to mappedOldValue,
  1705. // addedNodes set to addedNodes, removedNodes set to removedNodes, previousSibling set to previousSibling, and nextSibling set to nextSibling.
  1706. auto record = MutationRecord::create(realm(), type, *this, added_nodes_list, removed_nodes_list, previous_sibling, next_sibling, string_attribute_name, string_attribute_namespace, /* mappedOldValue */ interested_observer.value);
  1707. // 2. Enqueue record to observer’s record queue.
  1708. interested_observer.key->enqueue_record({}, move(record));
  1709. }
  1710. // 5. Queue a mutation observer microtask.
  1711. Bindings::queue_mutation_observer_microtask(document());
  1712. }
  1713. // https://dom.spec.whatwg.org/#queue-a-tree-mutation-record
  1714. void Node::queue_tree_mutation_record(Vector<GC::Root<Node>> added_nodes, Vector<GC::Root<Node>> removed_nodes, Node* previous_sibling, Node* next_sibling)
  1715. {
  1716. // 1. Assert: either addedNodes or removedNodes is not empty.
  1717. VERIFY(added_nodes.size() > 0 || removed_nodes.size() > 0);
  1718. // 2. Queue a mutation record of "childList" for target with null, null, null, addedNodes, removedNodes, previousSibling, and nextSibling.
  1719. queue_mutation_record(MutationType::childList, {}, {}, {}, move(added_nodes), move(removed_nodes), previous_sibling, next_sibling);
  1720. }
  1721. void Node::append_child_impl(GC::Ref<Node> node)
  1722. {
  1723. VERIFY(!node->m_parent);
  1724. if (!is_child_allowed(*node))
  1725. return;
  1726. if (m_last_child)
  1727. m_last_child->m_next_sibling = node.ptr();
  1728. node->m_previous_sibling = m_last_child;
  1729. node->m_parent = this;
  1730. m_last_child = node.ptr();
  1731. if (!m_first_child)
  1732. m_first_child = m_last_child;
  1733. }
  1734. void Node::insert_before_impl(GC::Ref<Node> node, GC::Ptr<Node> child)
  1735. {
  1736. if (!child)
  1737. return append_child_impl(move(node));
  1738. VERIFY(!node->m_parent);
  1739. VERIFY(child->parent() == this);
  1740. node->m_previous_sibling = child->m_previous_sibling;
  1741. node->m_next_sibling = child;
  1742. if (child->m_previous_sibling)
  1743. child->m_previous_sibling->m_next_sibling = node;
  1744. if (m_first_child == child)
  1745. m_first_child = node;
  1746. child->m_previous_sibling = node;
  1747. node->m_parent = this;
  1748. }
  1749. void Node::remove_child_impl(GC::Ref<Node> node)
  1750. {
  1751. VERIFY(node->m_parent.ptr() == this);
  1752. if (m_first_child == node)
  1753. m_first_child = node->m_next_sibling;
  1754. if (m_last_child == node)
  1755. m_last_child = node->m_previous_sibling;
  1756. if (node->m_next_sibling)
  1757. node->m_next_sibling->m_previous_sibling = node->m_previous_sibling;
  1758. if (node->m_previous_sibling)
  1759. node->m_previous_sibling->m_next_sibling = node->m_next_sibling;
  1760. node->m_next_sibling = nullptr;
  1761. node->m_previous_sibling = nullptr;
  1762. node->m_parent = nullptr;
  1763. }
  1764. bool Node::is_ancestor_of(Node const& other) const
  1765. {
  1766. for (auto* ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) {
  1767. if (ancestor == this)
  1768. return true;
  1769. }
  1770. return false;
  1771. }
  1772. bool Node::is_inclusive_ancestor_of(Node const& other) const
  1773. {
  1774. return &other == this || is_ancestor_of(other);
  1775. }
  1776. bool Node::is_descendant_of(Node const& other) const
  1777. {
  1778. return other.is_ancestor_of(*this);
  1779. }
  1780. bool Node::is_inclusive_descendant_of(Node const& other) const
  1781. {
  1782. return other.is_inclusive_ancestor_of(*this);
  1783. }
  1784. // https://dom.spec.whatwg.org/#concept-tree-following
  1785. bool Node::is_following(Node const& other) const
  1786. {
  1787. // An object A is following an object B if A and B are in the same tree and A comes after B in tree order.
  1788. for (auto* node = previous_in_pre_order(); node; node = node->previous_in_pre_order()) {
  1789. if (node == &other)
  1790. return true;
  1791. }
  1792. return false;
  1793. }
  1794. void Node::build_accessibility_tree(AccessibilityTreeNode& parent)
  1795. {
  1796. if (is_uninteresting_whitespace_node())
  1797. return;
  1798. if (is_document()) {
  1799. auto* document = static_cast<DOM::Document*>(this);
  1800. auto* document_element = document->document_element();
  1801. if (document_element && document_element->include_in_accessibility_tree()) {
  1802. parent.set_value(document_element);
  1803. if (document_element->has_child_nodes())
  1804. document_element->for_each_child([&parent](DOM::Node& child) {
  1805. child.build_accessibility_tree(parent);
  1806. return IterationDecision::Continue;
  1807. });
  1808. }
  1809. } else if (is_element()) {
  1810. auto const* element = static_cast<DOM::Element const*>(this);
  1811. if (is<HTML::HTMLScriptElement>(element) || is<HTML::HTMLStyleElement>(element))
  1812. return;
  1813. if (element->include_in_accessibility_tree()) {
  1814. auto current_node = AccessibilityTreeNode::create(&document(), this);
  1815. parent.append_child(current_node);
  1816. if (has_child_nodes()) {
  1817. for_each_child([&current_node](DOM::Node& child) {
  1818. child.build_accessibility_tree(*current_node);
  1819. return IterationDecision::Continue;
  1820. });
  1821. }
  1822. } else if (has_child_nodes()) {
  1823. for_each_child([&parent](DOM::Node& child) {
  1824. child.build_accessibility_tree(parent);
  1825. return IterationDecision::Continue;
  1826. });
  1827. }
  1828. } else if (is_text()) {
  1829. parent.append_child(AccessibilityTreeNode::create(&document(), this));
  1830. if (has_child_nodes()) {
  1831. for_each_child([&parent](DOM::Node& child) {
  1832. child.build_accessibility_tree(parent);
  1833. return IterationDecision::Continue;
  1834. });
  1835. }
  1836. }
  1837. }
  1838. // https://www.w3.org/TR/accname-1.2/#mapping_additional_nd_te
  1839. ErrorOr<String> Node::name_or_description(NameOrDescription target, Document const& document, HashTable<UniqueNodeID>& visited_nodes, IsDescendant is_descendant) const
  1840. {
  1841. // The text alternative for a given element is computed as follows:
  1842. // 1. Set the root node to the given element, the current node to the root node, and the total accumulated text to the empty string (""). If the root node's role prohibits naming, return the empty string ("").
  1843. auto const* root_node = this;
  1844. auto const* current_node = root_node;
  1845. StringBuilder total_accumulated_text;
  1846. visited_nodes.set(unique_id());
  1847. if (is_element()) {
  1848. auto const* element = static_cast<DOM::Element const*>(this);
  1849. auto role = element->role_or_default();
  1850. bool is_referenced = false;
  1851. auto id = element->id();
  1852. if (id.has_value()) {
  1853. this->root().for_each_in_inclusive_subtree_of_type<HTML::HTMLElement>([&](auto& element) {
  1854. auto aria_data = MUST(Web::ARIA::AriaData::build_data(element));
  1855. if (aria_data->aria_labelled_by_or_default().contains_slow(id.value())) {
  1856. is_referenced = true;
  1857. return TraversalDecision::Break;
  1858. }
  1859. return TraversalDecision::Continue;
  1860. });
  1861. }
  1862. // 2. Compute the text alternative for the current node:
  1863. // A. If the current node is hidden and is not directly referenced by aria-labelledby or aria-describedby, nor directly referenced by a native host language text alternative element (e.g. label in HTML) or attribute, return the empty string.
  1864. // FIXME: Check for references
  1865. if (element->aria_hidden() == "true")
  1866. return String {};
  1867. // B. Otherwise:
  1868. // - if computing a name, and the current node has an aria-labelledby attribute that contains at least one valid IDREF, and the current node is not already part of an aria-labelledby traversal,
  1869. // process its IDREFs in the order they occur:
  1870. // - or, if computing a description, and the current node has an aria-describedby attribute that contains at least one valid IDREF, and the current node is not already part of an aria-describedby traversal,
  1871. // process its IDREFs in the order they occur:
  1872. auto aria_labelled_by = element->aria_labelled_by();
  1873. auto aria_described_by = element->aria_described_by();
  1874. if ((target == NameOrDescription::Name && aria_labelled_by.has_value() && Node::first_valid_id(*aria_labelled_by, document).has_value())
  1875. || (target == NameOrDescription::Description && aria_described_by.has_value() && Node::first_valid_id(*aria_described_by, document).has_value())) {
  1876. // i. Set the accumulated text to the empty string.
  1877. total_accumulated_text.clear();
  1878. Vector<StringView> id_list;
  1879. if (target == NameOrDescription::Name) {
  1880. id_list = aria_labelled_by->bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
  1881. } else {
  1882. id_list = aria_described_by->bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
  1883. }
  1884. // ii. For each IDREF:
  1885. for (auto const& id_ref : id_list) {
  1886. auto node = document.get_element_by_id(MUST(FlyString::from_utf8(id_ref)));
  1887. if (!node)
  1888. continue;
  1889. // AD-HOC: The “For each IDREF” substep in the spec doesn’t seem to explicitly require the following
  1890. // check for an aria-label value; but the “div group explicitly labelledby self and heading” subtest at
  1891. // https://wpt.fyi/results/accname/name/comp_labelledby.html won’t pass unless we do this check.
  1892. if (target == NameOrDescription::Name && node->aria_label().has_value() && !node->aria_label()->is_empty() && !node->aria_label()->bytes_as_string_view().is_whitespace()) {
  1893. total_accumulated_text.append(' ');
  1894. total_accumulated_text.append(node->aria_label().value());
  1895. }
  1896. if (visited_nodes.contains(node->unique_id()))
  1897. continue;
  1898. // a. Set the current node to the node referenced by the IDREF.
  1899. current_node = node;
  1900. // b. Compute the text alternative of the current node beginning with step 2. Set the result to that text alternative.
  1901. auto result = TRY(node->name_or_description(target, document, visited_nodes));
  1902. // c. Append the result, with a space, to the accumulated text.
  1903. total_accumulated_text.append(' ');
  1904. total_accumulated_text.append(result);
  1905. }
  1906. // iii. Return the accumulated text.
  1907. return total_accumulated_text.to_string();
  1908. }
  1909. // C. Embedded Control: Otherwise, if the current node is a control embedded
  1910. // within the label (e.g. any element directly referenced by aria-labelledby) for
  1911. // another widget, where the user can adjust the embedded control's value, then
  1912. // return the embedded control as part of the text alternative in the following
  1913. // manner:
  1914. GC::Ptr<DOM::NodeList> labels;
  1915. if (is<HTML::HTMLElement>(this))
  1916. labels = (const_cast<HTML::HTMLElement&>(static_cast<HTML::HTMLElement const&>(*current_node))).labels();
  1917. if (labels != nullptr && labels->length() > 0) {
  1918. StringBuilder builder;
  1919. for (u32 i = 0; i < labels->length(); i++) {
  1920. auto nodes = labels->item(i)->children_as_vector();
  1921. for (auto const& node : nodes) {
  1922. if (node->is_element()) {
  1923. auto const& element = static_cast<DOM::Element const&>(*node);
  1924. auto role = element.role_or_default();
  1925. if (role == ARIA::Role::textbox) {
  1926. // i. Textbox: If the embedded control has role textbox, return its value.
  1927. if (is<HTML::HTMLInputElement>(*node)) {
  1928. auto const& element = static_cast<HTML::HTMLInputElement const&>(*node);
  1929. if (element.has_attribute("value"_string))
  1930. builder.append(element.value());
  1931. } else
  1932. builder.append(node->text_content().value());
  1933. } else if (role == ARIA::Role::combobox) {
  1934. // ii. Combobox/Listbox: If the embedded control has role combobox or listbox, return the text alternative of the chosen option.
  1935. if (is<HTML::HTMLInputElement>(*node)) {
  1936. auto const& element = static_cast<HTML::HTMLInputElement const&>(*node);
  1937. if (element.has_attribute("value"_string))
  1938. builder.append(element.value());
  1939. } else if (is<HTML::HTMLSelectElement>(*node)) {
  1940. auto const& element = static_cast<HTML::HTMLSelectElement const&>(*node);
  1941. builder.append(element.value());
  1942. } else
  1943. builder.append(node->text_content().value());
  1944. } else if (role == ARIA::Role::listbox) {
  1945. // ii. Combobox/Listbox: If the embedded control has role combobox or listbox, return the text alternative of the chosen option.
  1946. if (is<HTML::HTMLSelectElement>(*node)) {
  1947. auto const& element = static_cast<HTML::HTMLSelectElement const&>(*node);
  1948. builder.append(element.value());
  1949. }
  1950. auto children = node->children_as_vector();
  1951. for (auto& child : children) {
  1952. if (child->is_element()) {
  1953. auto const& element = static_cast<DOM::Element const&>(*child);
  1954. auto role = element.role_or_default();
  1955. if (role == ARIA::Role::option && element.aria_selected() == "true")
  1956. builder.append(element.text_content().value());
  1957. }
  1958. }
  1959. } else if (role == ARIA::Role::spinbutton || role == ARIA::Role::slider) {
  1960. // iii. Range: If the embedded control has role range (e.g., a spinbutton or slider):
  1961. // a. If the aria-valuetext property is present, return its value,
  1962. if (element.has_attribute("aria-valuetext"_string))
  1963. builder.append(element.get_attribute("aria-valuetext"_string).value());
  1964. // b. Otherwise, if the aria-valuenow property is present, return its value
  1965. else if (element.has_attribute("aria-valuenow"_string))
  1966. builder.append(element.get_attribute("aria-valuenow"_string).value());
  1967. // c. Otherwise, use the value as specified by a host language attribute.
  1968. else if (is<HTML::HTMLInputElement>(*node)) {
  1969. auto const& element = static_cast<HTML::HTMLInputElement const&>(*node);
  1970. if (element.has_attribute("value"_string))
  1971. builder.append(element.value());
  1972. }
  1973. }
  1974. } else if (node->is_text()) {
  1975. auto const& text_node = static_cast<DOM::Text const&>(*node);
  1976. builder.append(text_node.data());
  1977. }
  1978. }
  1979. }
  1980. return builder.to_string();
  1981. }
  1982. // D. AriaLabel: Otherwise, if the current node has an aria-label attribute whose
  1983. // value is not undefined, not the empty string, nor, when trimmed of whitespace,
  1984. // is not the empty string:
  1985. if (target == NameOrDescription::Name && element->aria_label().has_value() && !element->aria_label()->is_empty() && !element->aria_label()->bytes_as_string_view().is_whitespace()) {
  1986. // TODO: - If traversal of the current node is due to recursion and the current node is an embedded control as defined in step 2E, ignore aria-label and skip to rule 2E.
  1987. // - Otherwise, return the value of aria-label.
  1988. return element->aria_label().value();
  1989. }
  1990. // E. Host Language Label: Otherwise, if the current node's native markup provides an attribute (e.g. alt) or
  1991. // element (e.g. HTML label or SVG title) that defines a text alternative, return that alternative in the form
  1992. // of a flat string as defined by the host language, unless the element is marked as presentational
  1993. // (role="presentation" or role="none").
  1994. if (role != ARIA::Role::presentation && role != ARIA::Role::none && is<HTML::HTMLImageElement>(*element)) {
  1995. return element->alternative_text().release_value();
  1996. // TODO: Add handling for SVGTitleElement, and also confirm (through existing WPT test cases) whether
  1997. // HTMLLabelElement is already handled (by the code for step C. “Embedded Control” above) in conformance
  1998. // with the spec requirements — and if not, then add handling for it here.
  1999. }
  2000. // F. Otherwise, if the current node's role allows name from content, or if the current node is referenced by aria-labelledby, aria-describedby, or is a native host language text alternative element (e.g. label in HTML), or is a descendant of a native host language text alternative element:
  2001. if ((role.has_value() && ARIA::allows_name_from_content(role.value())) || is_referenced || is_descendant == IsDescendant::Yes) {
  2002. // i. Set the accumulated text to the empty string.
  2003. total_accumulated_text.clear();
  2004. // ii. Name From Generated Content: Check for CSS generated textual content associated with the current node and include
  2005. // it in the accumulated text. The CSS ::before and ::after pseudo elements [CSS2] can provide textual content for
  2006. // elements that have a content model.
  2007. // a. For ::before pseudo elements, User agents MUST prepend CSS textual content, without a space, to the textual
  2008. // content of the current node.
  2009. // b. For ::after pseudo elements, User agents MUST append CSS textual content, without a space, to the textual content
  2010. // of the current node. NOTE: The code for handling the ::after pseudo elements case is further below,
  2011. // following the “iii. For each child node of the current node” code.
  2012. if (auto before = element->get_pseudo_element_node(CSS::Selector::PseudoElement::Type::Before)) {
  2013. if (before->computed_values().content().alt_text.has_value())
  2014. total_accumulated_text.append(before->computed_values().content().alt_text.release_value());
  2015. else
  2016. total_accumulated_text.append(before->computed_values().content().data);
  2017. }
  2018. // iii. For each child node of the current node:
  2019. element->for_each_child([&total_accumulated_text, current_node, target, &document, &visited_nodes](
  2020. DOM::Node const& child_node) mutable {
  2021. if (!child_node.is_element() && !child_node.is_text())
  2022. return IterationDecision::Continue;
  2023. bool should_add_space = true;
  2024. const_cast<DOM::Document&>(document).update_layout();
  2025. auto const* layout_node = child_node.layout_node();
  2026. if (layout_node) {
  2027. auto display = layout_node->display();
  2028. if (display.is_inline_outside() && display.is_flow_inside()) {
  2029. should_add_space = false;
  2030. }
  2031. }
  2032. if (visited_nodes.contains(child_node.unique_id()))
  2033. return IterationDecision::Continue;
  2034. // a. Set the current node to the child node.
  2035. current_node = &child_node;
  2036. // b. Compute the text alternative of the current node beginning with step 2. Set the result to that text alternative.
  2037. auto result = MUST(current_node->name_or_description(target, document, visited_nodes, IsDescendant::Yes));
  2038. // Append a space character and the result of each step above to the total accumulated text.
  2039. // AD-HOC: Doing the space-adding here is in a different order from what the spec states.
  2040. if (should_add_space)
  2041. total_accumulated_text.append(' ');
  2042. // c. Append the result to the accumulated text.
  2043. total_accumulated_text.append(result);
  2044. return IterationDecision::Continue;
  2045. });
  2046. // NOTE: See step ii.b above.
  2047. if (auto after = element->get_pseudo_element_node(CSS::Selector::PseudoElement::Type::After)) {
  2048. if (after->computed_values().content().alt_text.has_value())
  2049. total_accumulated_text.append(after->computed_values().content().alt_text.release_value());
  2050. else
  2051. total_accumulated_text.append(after->computed_values().content().data);
  2052. }
  2053. // v. Return the accumulated text if it is not the empty string ("").
  2054. if (!total_accumulated_text.is_empty())
  2055. return total_accumulated_text.to_string();
  2056. // Important: Each node in the subtree is consulted only once. If text has been collected from a descendant, but is referenced by another IDREF in some descendant node, then that second, or subsequent, reference is not followed. This is done to avoid infinite loops.
  2057. }
  2058. }
  2059. // G. Text Node: Otherwise, if the current node is a Text Node, return its textual contents.
  2060. if (is_text()) {
  2061. if (layout_node() && layout_node()->is_text_node())
  2062. return verify_cast<Layout::TextNode>(layout_node())->text_for_rendering();
  2063. return text_content().value();
  2064. }
  2065. // TODO: H. Otherwise, if the current node is a descendant of an element whose Accessible Name or Accessible Description is being computed, and contains descendants, proceed to 2F.i.
  2066. // I. Otherwise, if the current node has a Tooltip attribute, return its value.
  2067. // https://www.w3.org/TR/accname-1.2/#dfn-tooltip-attribute
  2068. // Any host language attribute that would result in a user agent generating a tooltip such as in response to a mouse hover in desktop user agents.
  2069. // FIXME: Support SVG tooltips and CSS tooltips
  2070. if (is<HTML::HTMLElement>(this)) {
  2071. auto const* element = static_cast<HTML::HTMLElement const*>(this);
  2072. auto tooltip = element->title();
  2073. if (tooltip.has_value() && !tooltip->is_empty())
  2074. return tooltip.release_value();
  2075. }
  2076. // After all steps are completed, the total accumulated text is used as the accessible name or accessible description of the element that initiated the computation.
  2077. return total_accumulated_text.to_string();
  2078. }
  2079. // https://www.w3.org/TR/accname-1.2/#mapping_additional_nd_name
  2080. ErrorOr<String> Node::accessible_name(Document const& document) const
  2081. {
  2082. HashTable<UniqueNodeID> visited_nodes;
  2083. // User agents MUST compute an accessible name using the rules outlined below in the section titled Accessible Name and Description Computation.
  2084. return name_or_description(NameOrDescription::Name, document, visited_nodes);
  2085. }
  2086. // https://www.w3.org/TR/accname-1.2/#mapping_additional_nd_description
  2087. ErrorOr<String> Node::accessible_description(Document const& document) const
  2088. {
  2089. // If aria-describedby is present, user agents MUST compute the accessible description by concatenating the text alternatives for elements referenced by an aria-describedby attribute on the current element.
  2090. // The text alternatives for the referenced elements are computed using a number of methods, outlined below in the section titled Accessible Name and Description Computation.
  2091. if (!is_element())
  2092. return String {};
  2093. auto const* element = static_cast<Element const*>(this);
  2094. auto described_by = element->aria_described_by();
  2095. if (!described_by.has_value())
  2096. return String {};
  2097. HashTable<UniqueNodeID> visited_nodes;
  2098. StringBuilder builder;
  2099. auto id_list = described_by->bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
  2100. for (auto const& id : id_list) {
  2101. if (auto description_element = document.get_element_by_id(MUST(FlyString::from_utf8(id)))) {
  2102. auto description = TRY(
  2103. description_element->name_or_description(NameOrDescription::Description, document,
  2104. visited_nodes));
  2105. if (!description.is_empty()) {
  2106. if (builder.is_empty()) {
  2107. builder.append(description);
  2108. } else {
  2109. builder.append(" "sv);
  2110. builder.append(description);
  2111. }
  2112. }
  2113. }
  2114. }
  2115. return builder.to_string();
  2116. }
  2117. Optional<StringView> Node::first_valid_id(StringView value, Document const& document)
  2118. {
  2119. auto id_list = value.split_view_if(Infra::is_ascii_whitespace);
  2120. for (auto const& id : id_list) {
  2121. if (document.get_element_by_id(MUST(FlyString::from_utf8(id))))
  2122. return id;
  2123. }
  2124. return {};
  2125. }
  2126. void Node::add_registered_observer(RegisteredObserver& registered_observer)
  2127. {
  2128. if (!m_registered_observer_list)
  2129. m_registered_observer_list = make<Vector<GC::Ref<RegisteredObserver>>>();
  2130. m_registered_observer_list->append(registered_observer);
  2131. }
  2132. }
  2133. namespace IPC {
  2134. template<>
  2135. ErrorOr<void> encode(Encoder& encoder, Web::UniqueNodeID const& value)
  2136. {
  2137. return encode(encoder, value.value());
  2138. }
  2139. template<>
  2140. ErrorOr<Web::UniqueNodeID> decode(Decoder& decoder)
  2141. {
  2142. auto value = TRY(decoder.decode<i64>());
  2143. return Web::UniqueNodeID(value);
  2144. }
  2145. }