Node.cpp 119 KB

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