Element.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022-2023, San Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/AnyOf.h>
  8. #include <AK/Debug.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibUnicode/CharacterTypes.h>
  11. #include <LibUnicode/UnicodeData.h>
  12. #include <LibWeb/Bindings/ElementPrototype.h>
  13. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  14. #include <LibWeb/Bindings/MainThreadVM.h>
  15. #include <LibWeb/CSS/Parser/Parser.h>
  16. #include <LibWeb/CSS/PropertyID.h>
  17. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  18. #include <LibWeb/CSS/SelectorEngine.h>
  19. #include <LibWeb/CSS/StyleComputer.h>
  20. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  21. #include <LibWeb/DOM/Attr.h>
  22. #include <LibWeb/DOM/DOMTokenList.h>
  23. #include <LibWeb/DOM/Document.h>
  24. #include <LibWeb/DOM/Element.h>
  25. #include <LibWeb/DOM/HTMLCollection.h>
  26. #include <LibWeb/DOM/NamedNodeMap.h>
  27. #include <LibWeb/DOM/ShadowRoot.h>
  28. #include <LibWeb/DOM/Text.h>
  29. #include <LibWeb/DOMParsing/InnerHTML.h>
  30. #include <LibWeb/Geometry/DOMRect.h>
  31. #include <LibWeb/Geometry/DOMRectList.h>
  32. #include <LibWeb/HTML/BrowsingContext.h>
  33. #include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
  34. #include <LibWeb/HTML/CustomElements/CustomElementName.h>
  35. #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
  36. #include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
  37. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  38. #include <LibWeb/HTML/HTMLBodyElement.h>
  39. #include <LibWeb/HTML/HTMLButtonElement.h>
  40. #include <LibWeb/HTML/HTMLFieldSetElement.h>
  41. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  42. #include <LibWeb/HTML/HTMLHtmlElement.h>
  43. #include <LibWeb/HTML/HTMLInputElement.h>
  44. #include <LibWeb/HTML/HTMLOptGroupElement.h>
  45. #include <LibWeb/HTML/HTMLOptionElement.h>
  46. #include <LibWeb/HTML/HTMLSelectElement.h>
  47. #include <LibWeb/HTML/HTMLStyleElement.h>
  48. #include <LibWeb/HTML/HTMLTextAreaElement.h>
  49. #include <LibWeb/HTML/Numbers.h>
  50. #include <LibWeb/HTML/Parser/HTMLParser.h>
  51. #include <LibWeb/HTML/TraversableNavigable.h>
  52. #include <LibWeb/HTML/Window.h>
  53. #include <LibWeb/Infra/CharacterTypes.h>
  54. #include <LibWeb/Infra/Strings.h>
  55. #include <LibWeb/Layout/BlockContainer.h>
  56. #include <LibWeb/Layout/InlineNode.h>
  57. #include <LibWeb/Layout/ListItemBox.h>
  58. #include <LibWeb/Layout/TreeBuilder.h>
  59. #include <LibWeb/Layout/Viewport.h>
  60. #include <LibWeb/Namespace.h>
  61. #include <LibWeb/Page/Page.h>
  62. #include <LibWeb/Painting/PaintableBox.h>
  63. #include <LibWeb/WebIDL/AbstractOperations.h>
  64. #include <LibWeb/WebIDL/DOMException.h>
  65. #include <LibWeb/WebIDL/ExceptionOr.h>
  66. namespace Web::DOM {
  67. Element::Element(Document& document, DOM::QualifiedName qualified_name)
  68. : ParentNode(document, NodeType::ELEMENT_NODE)
  69. , m_qualified_name(move(qualified_name))
  70. {
  71. make_html_uppercased_qualified_name();
  72. // https://dom.spec.whatwg.org/#ref-for-concept-element-attributes-change-ext①
  73. add_attribute_change_steps([this](auto const& local_name, auto const& old_value, auto const& value, auto const& namespace_) {
  74. // 1. If localName is slot and namespace is null, then:
  75. if (local_name == HTML::AttributeNames::slot && namespace_.is_null()) {
  76. // 1. If value is oldValue, then return.
  77. if (value == old_value)
  78. return;
  79. // 2. If value is null and oldValue is the empty string, then return.
  80. if (value.is_null() && old_value == DeprecatedString::empty())
  81. return;
  82. // 3. If value is the empty string and oldValue is null, then return.
  83. if (value == DeprecatedString::empty() && old_value.is_null())
  84. return;
  85. // 4. If value is null or the empty string, then set element’s name to the empty string.
  86. if (value.is_empty())
  87. set_slottable_name({});
  88. // 5. Otherwise, set element’s name to value.
  89. else
  90. set_slottable_name(MUST(String::from_deprecated_string(value)));
  91. // 6. If element is assigned, then run assign slottables for element’s assigned slot.
  92. if (auto assigned_slot = assigned_slot_internal())
  93. assign_slottables(*assigned_slot);
  94. // 7. Run assign a slot for element.
  95. assign_a_slot(JS::NonnullGCPtr { *this });
  96. }
  97. });
  98. }
  99. Element::~Element() = default;
  100. void Element::initialize(JS::Realm& realm)
  101. {
  102. Base::initialize(realm);
  103. set_prototype(&Bindings::ensure_web_prototype<Bindings::ElementPrototype>(realm, "Element"));
  104. m_attributes = NamedNodeMap::create(*this);
  105. }
  106. void Element::visit_edges(Cell::Visitor& visitor)
  107. {
  108. Base::visit_edges(visitor);
  109. SlottableMixin::visit_edges(visitor);
  110. visitor.visit(m_attributes.ptr());
  111. visitor.visit(m_inline_style.ptr());
  112. visitor.visit(m_class_list.ptr());
  113. visitor.visit(m_shadow_root.ptr());
  114. visitor.visit(m_custom_element_definition.ptr());
  115. for (auto& pseudo_element_layout_node : m_pseudo_element_nodes)
  116. visitor.visit(pseudo_element_layout_node);
  117. }
  118. // https://dom.spec.whatwg.org/#dom-element-getattribute
  119. DeprecatedString Element::get_attribute(DeprecatedFlyString const& name) const
  120. {
  121. // 1. Let attr be the result of getting an attribute given qualifiedName and this.
  122. auto const* attribute = m_attributes->get_attribute(name);
  123. // 2. If attr is null, return null.
  124. if (!attribute)
  125. return {};
  126. // 3. Return attr’s value.
  127. return attribute->value().to_deprecated_string();
  128. }
  129. // https://dom.spec.whatwg.org/#concept-element-attributes-get-value
  130. DeprecatedString Element::get_attribute_value(DeprecatedFlyString const& local_name, DeprecatedFlyString const& namespace_) const
  131. {
  132. // 1. Let attr be the result of getting an attribute given namespace, localName, and element.
  133. auto const* attribute = m_attributes->get_attribute_ns(namespace_, local_name);
  134. // 2. If attr is null, then return the empty string.
  135. if (!attribute)
  136. return DeprecatedString::empty();
  137. // 3. Return attr’s value.
  138. return attribute->value().to_deprecated_string();
  139. }
  140. // https://dom.spec.whatwg.org/#dom-element-getattributenode
  141. JS::GCPtr<Attr> Element::get_attribute_node(DeprecatedFlyString const& name) const
  142. {
  143. // The getAttributeNode(qualifiedName) method steps are to return the result of getting an attribute given qualifiedName and this.
  144. return m_attributes->get_attribute(name);
  145. }
  146. // https://dom.spec.whatwg.org/#dom-element-setattribute
  147. WebIDL::ExceptionOr<void> Element::set_attribute(DeprecatedFlyString const& name, DeprecatedString const& value)
  148. {
  149. // 1. If qualifiedName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
  150. // FIXME: Proper name validation
  151. if (name.is_empty())
  152. return WebIDL::InvalidCharacterError::create(realm(), "Attribute name must not be empty"_fly_string);
  153. // 2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.
  154. // FIXME: Handle the second condition, assume it is an HTML document for now.
  155. bool insert_as_lowercase = namespace_() == Namespace::HTML;
  156. // 3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
  157. auto* attribute = m_attributes->get_attribute(name);
  158. // 4. If attribute is null, create an attribute whose local name is qualifiedName, value is value, and node document
  159. // is this’s node document, then append this attribute to this, and then return.
  160. if (!attribute) {
  161. auto new_attribute = Attr::create(document(), MUST(String::from_deprecated_string(insert_as_lowercase ? name.to_lowercase() : name)), MUST(String::from_deprecated_string(value)));
  162. m_attributes->append_attribute(new_attribute);
  163. return {};
  164. }
  165. // 5. Change attribute to value.
  166. attribute->change_attribute(MUST(String::from_deprecated_string(value)));
  167. return {};
  168. }
  169. WebIDL::ExceptionOr<void> Element::set_attribute(DeprecatedFlyString const& name, Optional<String> const& value)
  170. {
  171. if (!value.has_value())
  172. return set_attribute(name, DeprecatedString {});
  173. return set_attribute(name, value->to_deprecated_string());
  174. }
  175. // https://dom.spec.whatwg.org/#validate-and-extract
  176. WebIDL::ExceptionOr<QualifiedName> validate_and_extract(JS::Realm& realm, DeprecatedFlyString namespace_, DeprecatedFlyString qualified_name)
  177. {
  178. // 1. If namespace is the empty string, then set it to null.
  179. if (namespace_.is_empty())
  180. namespace_ = {};
  181. // 2. Validate qualifiedName.
  182. TRY(Document::validate_qualified_name(realm, qualified_name));
  183. // 3. Let prefix be null.
  184. DeprecatedFlyString prefix = {};
  185. // 4. Let localName be qualifiedName.
  186. auto local_name = qualified_name;
  187. // 5. If qualifiedName contains a U+003A (:), then strictly split the string on it and set prefix to the part before and localName to the part after.
  188. if (qualified_name.view().contains(':')) {
  189. auto parts = qualified_name.view().split_view(':');
  190. prefix = parts[0];
  191. local_name = parts[1];
  192. }
  193. // 6. If prefix is non-null and namespace is null, then throw a "NamespaceError" DOMException.
  194. if (!prefix.is_null() && namespace_.is_null())
  195. return WebIDL::NamespaceError::create(realm, "Prefix is non-null and namespace is null."_fly_string);
  196. // 7. If prefix is "xml" and namespace is not the XML namespace, then throw a "NamespaceError" DOMException.
  197. if (prefix == "xml"sv && namespace_ != Namespace::XML)
  198. return WebIDL::NamespaceError::create(realm, "Prefix is 'xml' and namespace is not the XML namespace."_fly_string);
  199. // 8. If either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace, then throw a "NamespaceError" DOMException.
  200. if ((qualified_name == "xmlns"sv || prefix == "xmlns"sv) && namespace_ != Namespace::XMLNS)
  201. return WebIDL::NamespaceError::create(realm, "Either qualifiedName or prefix is 'xmlns' and namespace is not the XMLNS namespace."_fly_string);
  202. // 9. If namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns", then throw a "NamespaceError" DOMException.
  203. if (namespace_ == Namespace::XMLNS && !(qualified_name == "xmlns"sv || prefix == "xmlns"sv))
  204. return WebIDL::NamespaceError::create(realm, "Namespace is the XMLNS namespace and neither qualifiedName nor prefix is 'xmlns'."_fly_string);
  205. // 10. Return namespace, prefix, and localName.
  206. return QualifiedName { MUST(FlyString::from_deprecated_fly_string(local_name)), prefix, namespace_ };
  207. }
  208. // https://dom.spec.whatwg.org/#dom-element-setattributens
  209. WebIDL::ExceptionOr<void> Element::set_attribute_ns(DeprecatedFlyString const& namespace_, DeprecatedFlyString const& qualified_name, DeprecatedString const& value)
  210. {
  211. // 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
  212. auto extracted_qualified_name = TRY(validate_and_extract(realm(), namespace_, qualified_name));
  213. // 2. Set an attribute value for this using localName, value, and also prefix and namespace.
  214. set_attribute_value(extracted_qualified_name.local_name().to_deprecated_fly_string(), value, extracted_qualified_name.deprecated_prefix(), extracted_qualified_name.deprecated_namespace_());
  215. return {};
  216. }
  217. // https://dom.spec.whatwg.org/#concept-element-attributes-set-value
  218. void Element::set_attribute_value(DeprecatedFlyString const& local_name, DeprecatedString const& value, DeprecatedFlyString const& prefix, DeprecatedFlyString const& namespace_)
  219. {
  220. // 1. Let attribute be the result of getting an attribute given namespace, localName, and element.
  221. auto* attribute = m_attributes->get_attribute_ns(namespace_, local_name);
  222. // 2. If attribute is null, create an attribute whose namespace is namespace, namespace prefix is prefix, local name
  223. // is localName, value is value, and node document is element’s node document, then append this attribute to element,
  224. // and then return.
  225. if (!attribute) {
  226. QualifiedName name { MUST(FlyString::from_deprecated_fly_string(local_name)), prefix, namespace_ };
  227. auto new_attribute = Attr::create(document(), move(name), MUST(String::from_deprecated_string(value)));
  228. m_attributes->append_attribute(new_attribute);
  229. return;
  230. }
  231. // 3. Change attribute to value.
  232. attribute->change_attribute(MUST(String::from_deprecated_string(value)));
  233. }
  234. // https://dom.spec.whatwg.org/#dom-element-setattributenode
  235. WebIDL::ExceptionOr<JS::GCPtr<Attr>> Element::set_attribute_node(Attr& attr)
  236. {
  237. // The setAttributeNode(attr) and setAttributeNodeNS(attr) methods steps are to return the result of setting an attribute given attr and this.
  238. return m_attributes->set_attribute(attr);
  239. }
  240. // https://dom.spec.whatwg.org/#dom-element-setattributenodens
  241. WebIDL::ExceptionOr<JS::GCPtr<Attr>> Element::set_attribute_node_ns(Attr& attr)
  242. {
  243. // The setAttributeNode(attr) and setAttributeNodeNS(attr) methods steps are to return the result of setting an attribute given attr and this.
  244. return m_attributes->set_attribute(attr);
  245. }
  246. // https://dom.spec.whatwg.org/#dom-element-removeattribute
  247. void Element::remove_attribute(StringView name)
  248. {
  249. // The removeAttribute(qualifiedName) method steps are to remove an attribute given qualifiedName and this, and then return undefined.
  250. m_attributes->remove_attribute(name);
  251. }
  252. // https://dom.spec.whatwg.org/#dom-element-hasattribute
  253. bool Element::has_attribute(DeprecatedFlyString const& name) const
  254. {
  255. return m_attributes->get_attribute(name) != nullptr;
  256. }
  257. // https://dom.spec.whatwg.org/#dom-element-hasattributens
  258. bool Element::has_attribute_ns(DeprecatedFlyString namespace_, DeprecatedFlyString const& name) const
  259. {
  260. // 1. If namespace is the empty string, then set it to null.
  261. if (namespace_.is_empty())
  262. namespace_ = {};
  263. // 2. Return true if this has an attribute whose namespace is namespace and local name is localName; otherwise false.
  264. return m_attributes->get_attribute_ns(namespace_, name) != nullptr;
  265. }
  266. // https://dom.spec.whatwg.org/#dom-element-toggleattribute
  267. WebIDL::ExceptionOr<bool> Element::toggle_attribute(DeprecatedFlyString const& name, Optional<bool> force)
  268. {
  269. // 1. If qualifiedName does not match the Name production in XML, then throw an "InvalidCharacterError" DOMException.
  270. // FIXME: Proper name validation
  271. if (name.is_empty())
  272. return WebIDL::InvalidCharacterError::create(realm(), "Attribute name must not be empty"_fly_string);
  273. // 2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.
  274. // FIXME: Handle the second condition, assume it is an HTML document for now.
  275. bool insert_as_lowercase = namespace_() == Namespace::HTML;
  276. // 3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
  277. auto* attribute = m_attributes->get_attribute(name);
  278. // 4. If attribute is null, then:
  279. if (!attribute) {
  280. // 1. If force is not given or is true, create an attribute whose local name is qualifiedName, value is the empty
  281. // string, and node document is this’s node document, then append this attribute to this, and then return true.
  282. if (!force.has_value() || force.value()) {
  283. auto new_attribute = Attr::create(document(), MUST(String::from_deprecated_string(insert_as_lowercase ? name.to_lowercase() : name)), String {});
  284. m_attributes->append_attribute(new_attribute);
  285. return true;
  286. }
  287. // 2. Return false.
  288. return false;
  289. }
  290. // 5. Otherwise, if force is not given or is false, remove an attribute given qualifiedName and this, and then return false.
  291. if (!force.has_value() || !force.value()) {
  292. m_attributes->remove_attribute(name);
  293. return false;
  294. }
  295. // 6. Return true.
  296. return true;
  297. }
  298. // https://dom.spec.whatwg.org/#dom-element-getattributenames
  299. Vector<DeprecatedString> Element::get_attribute_names() const
  300. {
  301. // The getAttributeNames() method steps are to return the qualified names of the attributes in this’s attribute list, in order; otherwise a new list.
  302. Vector<DeprecatedString> names;
  303. for (size_t i = 0; i < m_attributes->length(); ++i) {
  304. auto const* attribute = m_attributes->item(i);
  305. names.append(attribute->name().to_deprecated_fly_string());
  306. }
  307. return names;
  308. }
  309. bool Element::has_class(FlyString const& class_name, CaseSensitivity case_sensitivity) const
  310. {
  311. if (case_sensitivity == CaseSensitivity::CaseSensitive) {
  312. return any_of(m_classes, [&](auto& it) {
  313. return it == class_name;
  314. });
  315. } else {
  316. return any_of(m_classes, [&](auto& it) {
  317. return it.equals_ignoring_ascii_case(class_name);
  318. });
  319. }
  320. }
  321. JS::GCPtr<Layout::Node> Element::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  322. {
  323. if (local_name() == "noscript" && document().is_scripting_enabled())
  324. return nullptr;
  325. auto display = style->display();
  326. return create_layout_node_for_display_type(document(), display, move(style), this);
  327. }
  328. JS::GCPtr<Layout::Node> Element::create_layout_node_for_display_type(DOM::Document& document, CSS::Display const& display, NonnullRefPtr<CSS::StyleProperties> style, Element* element)
  329. {
  330. if (display.is_table_inside() || display.is_table_row_group() || display.is_table_header_group() || display.is_table_footer_group() || display.is_table_row())
  331. return document.heap().allocate_without_realm<Layout::Box>(document, element, move(style));
  332. if (display.is_list_item())
  333. return document.heap().allocate_without_realm<Layout::ListItemBox>(document, element, move(style));
  334. if (display.is_table_cell())
  335. return document.heap().allocate_without_realm<Layout::BlockContainer>(document, element, move(style));
  336. if (display.is_table_column() || display.is_table_column_group() || display.is_table_caption()) {
  337. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  338. return document.heap().allocate_without_realm<Layout::BlockContainer>(document, element, move(style));
  339. }
  340. if (display.is_math_inside()) {
  341. // https://w3c.github.io/mathml-core/#new-display-math-value
  342. // MathML elements with a computed display value equal to block math or inline math control box generation
  343. // and layout according to their tag name, as described in the relevant sections.
  344. // FIXME: Figure out what kind of node we should make for them. For now, we'll stick with a generic Box.
  345. return document.heap().allocate_without_realm<Layout::Box>(document, element, move(style));
  346. }
  347. if (display.is_inline_outside()) {
  348. if (display.is_flow_root_inside())
  349. return document.heap().allocate_without_realm<Layout::BlockContainer>(document, element, move(style));
  350. if (display.is_flow_inside())
  351. return document.heap().allocate_without_realm<Layout::InlineNode>(document, element, move(style));
  352. if (display.is_flex_inside())
  353. return document.heap().allocate_without_realm<Layout::Box>(document, element, move(style));
  354. if (display.is_grid_inside())
  355. return document.heap().allocate_without_realm<Layout::Box>(document, element, move(style));
  356. dbgln_if(LIBWEB_CSS_DEBUG, "FIXME: Support display: {}", display.to_string());
  357. return document.heap().allocate_without_realm<Layout::InlineNode>(document, element, move(style));
  358. }
  359. if (display.is_flex_inside() || display.is_grid_inside())
  360. return document.heap().allocate_without_realm<Layout::Box>(document, element, move(style));
  361. if (display.is_flow_inside() || display.is_flow_root_inside() || display.is_contents())
  362. return document.heap().allocate_without_realm<Layout::BlockContainer>(document, element, move(style));
  363. dbgln("FIXME: CSS display '{}' not implemented yet.", display.to_string());
  364. return document.heap().allocate_without_realm<Layout::InlineNode>(document, element, move(style));
  365. }
  366. CSS::CSSStyleDeclaration const* Element::inline_style() const
  367. {
  368. return m_inline_style.ptr();
  369. }
  370. void Element::add_attribute_change_steps(AttributeChangeSteps steps)
  371. {
  372. m_attribute_change_steps.append(move(steps));
  373. }
  374. void Element::run_attribute_change_steps(DeprecatedFlyString const& local_name, DeprecatedString const& old_value, DeprecatedString const& value, DeprecatedFlyString const& namespace_)
  375. {
  376. for (auto const& attribute_change_steps : m_attribute_change_steps)
  377. attribute_change_steps(local_name, old_value, value, namespace_);
  378. // AD-HOC: Run our own internal attribute change handler.
  379. attribute_changed(local_name, value);
  380. invalidate_style_after_attribute_change(local_name);
  381. }
  382. void Element::attribute_changed(DeprecatedFlyString const& name, DeprecatedString const& value)
  383. {
  384. if (name == HTML::AttributeNames::class_) {
  385. auto new_classes = value.split_view(Infra::is_ascii_whitespace);
  386. m_classes.clear();
  387. m_classes.ensure_capacity(new_classes.size());
  388. for (auto& new_class : new_classes) {
  389. m_classes.unchecked_append(FlyString::from_utf8(new_class).release_value_but_fixme_should_propagate_errors());
  390. }
  391. if (m_class_list)
  392. m_class_list->associated_attribute_changed(value);
  393. } else if (name == HTML::AttributeNames::style) {
  394. if (value.is_null()) {
  395. if (!m_inline_style) {
  396. m_inline_style = nullptr;
  397. set_needs_style_update(true);
  398. }
  399. } else {
  400. // https://drafts.csswg.org/cssom/#ref-for-cssstyledeclaration-updating-flag
  401. if (m_inline_style && m_inline_style->is_updating())
  402. return;
  403. m_inline_style = parse_css_style_attribute(CSS::Parser::ParsingContext(document()), value, *this);
  404. set_needs_style_update(true);
  405. }
  406. } else if (name == HTML::AttributeNames::dir) {
  407. // https://html.spec.whatwg.org/multipage/dom.html#attr-dir
  408. if (value.equals_ignoring_ascii_case("ltr"sv))
  409. m_dir = Dir::Ltr;
  410. else if (value.equals_ignoring_ascii_case("rtl"sv))
  411. m_dir = Dir::Rtl;
  412. else if (value.equals_ignoring_ascii_case("auto"sv))
  413. m_dir = Dir::Auto;
  414. else
  415. m_dir = {};
  416. }
  417. }
  418. static Element::RequiredInvalidationAfterStyleChange compute_required_invalidation(CSS::StyleProperties const& old_style, CSS::StyleProperties const& new_style)
  419. {
  420. Element::RequiredInvalidationAfterStyleChange invalidation;
  421. if (&old_style.computed_font() != &new_style.computed_font())
  422. invalidation.relayout = true;
  423. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  424. auto property_id = static_cast<CSS::PropertyID>(i);
  425. auto const& old_value = old_style.properties()[i];
  426. auto const& new_value = new_style.properties()[i];
  427. if (!old_value.has_value() && !new_value.has_value())
  428. continue;
  429. bool const property_value_changed = (!old_value.has_value() || !new_value.has_value()) || *old_value->style != *new_value->style;
  430. if (!property_value_changed)
  431. continue;
  432. // NOTE: If the computed CSS display property changes, we have to rebuild the entire layout tree.
  433. // In the future, we should figure out ways to rebuild a smaller part of the tree.
  434. if (property_id == CSS::PropertyID::Display) {
  435. return Element::RequiredInvalidationAfterStyleChange::full();
  436. }
  437. // OPTIMIZATION: Special handling for CSS `visibility`:
  438. if (property_id == CSS::PropertyID::Visibility) {
  439. // We don't need to relayout if the visibility changes from visible to hidden or vice versa. Only collapse requires relayout.
  440. if ((old_value.has_value() && old_value->style->to_identifier() == CSS::ValueID::Collapse) != (new_value.has_value() && new_value->style->to_identifier() == CSS::ValueID::Collapse))
  441. invalidation.relayout = true;
  442. // Of course, we still have to repaint on any visibility change.
  443. invalidation.repaint = true;
  444. } else if (CSS::property_affects_layout(property_id)) {
  445. invalidation.relayout = true;
  446. }
  447. if (property_id == CSS::PropertyID::Opacity) {
  448. // OPTIMIZATION: An element creates a stacking context when its opacity changes from 1 to less than 1
  449. // and stops to create one when opacity returns to 1. So stacking context tree rebuild is
  450. // not required for opacity changes within the range below 1.
  451. auto old_value_opacity = old_style.opacity();
  452. auto new_value_opacity = new_style.opacity();
  453. if (old_value_opacity != new_value_opacity && (old_value_opacity == 1 || new_value_opacity == 1)) {
  454. invalidation.rebuild_stacking_context_tree = true;
  455. }
  456. } else if (CSS::property_affects_stacking_context(property_id)) {
  457. invalidation.rebuild_stacking_context_tree = true;
  458. }
  459. invalidation.repaint = true;
  460. }
  461. return invalidation;
  462. }
  463. Element::RequiredInvalidationAfterStyleChange Element::recompute_style()
  464. {
  465. set_needs_style_update(false);
  466. VERIFY(parent());
  467. // FIXME propagate errors
  468. auto new_computed_css_values = MUST(document().style_computer().compute_style(*this));
  469. RequiredInvalidationAfterStyleChange invalidation;
  470. if (m_computed_css_values)
  471. invalidation = compute_required_invalidation(*m_computed_css_values, *new_computed_css_values);
  472. else
  473. invalidation = RequiredInvalidationAfterStyleChange::full();
  474. if (invalidation.is_none())
  475. return invalidation;
  476. m_computed_css_values = move(new_computed_css_values);
  477. if (!invalidation.rebuild_layout_tree && layout_node()) {
  478. // If we're keeping the layout tree, we can just apply the new style to the existing layout tree.
  479. layout_node()->apply_style(*m_computed_css_values);
  480. if (invalidation.repaint)
  481. layout_node()->set_needs_display();
  482. }
  483. return invalidation;
  484. }
  485. NonnullRefPtr<CSS::StyleProperties> Element::resolved_css_values()
  486. {
  487. auto element_computed_style = CSS::ResolvedCSSStyleDeclaration::create(*this);
  488. auto properties = CSS::StyleProperties::create();
  489. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  490. auto property_id = (CSS::PropertyID)i;
  491. auto maybe_value = element_computed_style->property(property_id);
  492. if (!maybe_value.has_value())
  493. continue;
  494. properties->set_property(property_id, maybe_value.release_value().value, nullptr);
  495. }
  496. return properties;
  497. }
  498. DOMTokenList* Element::class_list()
  499. {
  500. if (!m_class_list)
  501. m_class_list = DOMTokenList::create(*this, FlyString::from_deprecated_fly_string(HTML::AttributeNames::class_).release_value());
  502. return m_class_list;
  503. }
  504. // https://dom.spec.whatwg.org/#dom-element-attachshadow
  505. WebIDL::ExceptionOr<JS::NonnullGCPtr<ShadowRoot>> Element::attach_shadow(ShadowRootInit init)
  506. {
  507. // 1. If this’s namespace is not the HTML namespace, then throw a "NotSupportedError" DOMException.
  508. if (namespace_() != Namespace::HTML)
  509. return WebIDL::NotSupportedError::create(realm(), "Element's namespace is not the HTML namespace"_fly_string);
  510. // 2. If this’s local name is not one of the following:
  511. // - a valid custom element name
  512. // - "article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", or "span"
  513. if (!HTML::is_valid_custom_element_name(local_name())
  514. && !local_name().is_one_of("article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", "span")) {
  515. // then throw a "NotSupportedError" DOMException.
  516. return WebIDL::NotSupportedError::create(realm(), MUST(String::formatted("Element '{}' cannot be a shadow host", local_name())));
  517. }
  518. // 3. If this’s local name is a valid custom element name, or this’s is value is not null, then:
  519. if (HTML::is_valid_custom_element_name(local_name()) || m_is_value.has_value()) {
  520. // 1. Let definition be the result of looking up a custom element definition given this’s node document, its namespace, its local name, and its is value.
  521. auto definition = document().lookup_custom_element_definition(namespace_(), local_name(), m_is_value);
  522. // 2. If definition is not null and definition’s disable shadow is true, then throw a "NotSupportedError" DOMException.
  523. if (definition && definition->disable_shadow())
  524. return WebIDL::NotSupportedError::create(realm(), "Cannot attach a shadow root to a custom element that has disabled shadow roots"_fly_string);
  525. }
  526. // 4. If this is a shadow host, then throw an "NotSupportedError" DOMException.
  527. if (is_shadow_host())
  528. return WebIDL::NotSupportedError::create(realm(), "Element already is a shadow host"_fly_string);
  529. // 5. Let shadow be a new shadow root whose node document is this’s node document, host is this, and mode is init["mode"].
  530. auto shadow = heap().allocate<ShadowRoot>(realm(), document(), *this, init.mode);
  531. // 6. Set shadow’s delegates focus to init["delegatesFocus"].
  532. shadow->set_delegates_focus(init.delegates_focus);
  533. // 7. If this’s custom element state is "precustomized" or "custom", then set shadow’s available to element internals to true.
  534. if (m_custom_element_state == CustomElementState::Precustomized || m_custom_element_state == CustomElementState::Custom)
  535. shadow->set_available_to_element_internals(true);
  536. // 8. Set shadow’s slot assignment to init["slotAssignment"].
  537. shadow->set_slot_assignment(init.slot_assignment);
  538. // 9. Set this’s shadow root to shadow.
  539. set_shadow_root(shadow);
  540. // 10. Return shadow.
  541. return shadow;
  542. }
  543. // https://dom.spec.whatwg.org/#dom-element-shadowroot
  544. JS::GCPtr<ShadowRoot> Element::shadow_root() const
  545. {
  546. // 1. Let shadow be this’s shadow root.
  547. auto shadow = m_shadow_root;
  548. // 2. If shadow is null or its mode is "closed", then return null.
  549. if (shadow == nullptr || shadow->mode() == Bindings::ShadowRootMode::Closed)
  550. return nullptr;
  551. // 3. Return shadow.
  552. return shadow;
  553. }
  554. // https://dom.spec.whatwg.org/#dom-element-matches
  555. WebIDL::ExceptionOr<bool> Element::matches(StringView selectors) const
  556. {
  557. // 1. Let s be the result of parse a selector from selectors.
  558. auto maybe_selectors = parse_selector(CSS::Parser::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
  559. // 2. If s is failure, then throw a "SyntaxError" DOMException.
  560. if (!maybe_selectors.has_value())
  561. return WebIDL::SyntaxError::create(realm(), "Failed to parse selector"_fly_string);
  562. // 3. If the result of match a selector against an element, using s, this, and scoping root this, returns success, then return true; otherwise, return false.
  563. auto sel = maybe_selectors.value();
  564. for (auto& s : sel) {
  565. if (SelectorEngine::matches(s, {}, *this, {}, static_cast<ParentNode const*>(this)))
  566. return true;
  567. }
  568. return false;
  569. }
  570. // https://dom.spec.whatwg.org/#dom-element-closest
  571. WebIDL::ExceptionOr<DOM::Element const*> Element::closest(StringView selectors) const
  572. {
  573. // 1. Let s be the result of parse a selector from selectors.
  574. auto maybe_selectors = parse_selector(CSS::Parser::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
  575. // 2. If s is failure, then throw a "SyntaxError" DOMException.
  576. if (!maybe_selectors.has_value())
  577. return WebIDL::SyntaxError::create(realm(), "Failed to parse selector"_fly_string);
  578. auto matches_selectors = [this](CSS::SelectorList const& selector_list, Element const* element) {
  579. // 4. For each element in elements, if match a selector against an element, using s, element, and scoping root this, returns success, return element.
  580. for (auto& selector : selector_list) {
  581. if (!SelectorEngine::matches(selector, {}, *element, {}, this))
  582. return false;
  583. }
  584. return true;
  585. };
  586. auto const selector_list = maybe_selectors.release_value();
  587. // 3. Let elements be this’s inclusive ancestors that are elements, in reverse tree order.
  588. for (auto* element = this; element; element = element->parent_element()) {
  589. if (!matches_selectors(selector_list, element))
  590. continue;
  591. return element;
  592. }
  593. // 5. Return null.
  594. return nullptr;
  595. }
  596. WebIDL::ExceptionOr<void> Element::set_inner_html(DeprecatedString const& markup)
  597. {
  598. TRY(DOMParsing::inner_html_setter(*this, markup));
  599. return {};
  600. }
  601. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  602. WebIDL::ExceptionOr<DeprecatedString> Element::inner_html() const
  603. {
  604. return serialize_fragment(DOMParsing::RequireWellFormed::Yes);
  605. }
  606. bool Element::is_focused() const
  607. {
  608. return document().focused_element() == this;
  609. }
  610. bool Element::is_active() const
  611. {
  612. return document().active_element() == this;
  613. }
  614. bool Element::is_target() const
  615. {
  616. return document().target_element() == this;
  617. }
  618. // https://dom.spec.whatwg.org/#document-element
  619. bool Element::is_document_element() const
  620. {
  621. return document().document_element() == this;
  622. }
  623. JS::NonnullGCPtr<HTMLCollection> Element::get_elements_by_class_name(DeprecatedFlyString const& class_names)
  624. {
  625. Vector<FlyString> list_of_class_names;
  626. for (auto& name : class_names.view().split_view_if(Infra::is_ascii_whitespace)) {
  627. list_of_class_names.append(FlyString::from_utf8(name).release_value_but_fixme_should_propagate_errors());
  628. }
  629. return HTMLCollection::create(*this, HTMLCollection::Scope::Descendants, [list_of_class_names = move(list_of_class_names), quirks_mode = document().in_quirks_mode()](Element const& element) {
  630. for (auto& name : list_of_class_names) {
  631. if (!element.has_class(name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive))
  632. return false;
  633. }
  634. return true;
  635. });
  636. }
  637. // https://dom.spec.whatwg.org/#element-shadow-host
  638. bool Element::is_shadow_host() const
  639. {
  640. // An element is a shadow host if its shadow root is non-null.
  641. return m_shadow_root != nullptr;
  642. }
  643. void Element::set_shadow_root(JS::GCPtr<ShadowRoot> shadow_root)
  644. {
  645. if (m_shadow_root == shadow_root)
  646. return;
  647. if (m_shadow_root)
  648. m_shadow_root->set_host(nullptr);
  649. m_shadow_root = move(shadow_root);
  650. if (m_shadow_root)
  651. m_shadow_root->set_host(this);
  652. invalidate_style();
  653. }
  654. CSS::CSSStyleDeclaration* Element::style_for_bindings()
  655. {
  656. if (!m_inline_style)
  657. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this, {}, {});
  658. return m_inline_style;
  659. }
  660. // https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name
  661. void Element::make_html_uppercased_qualified_name()
  662. {
  663. // This is allowed by the spec: "User agents could optimize qualified name and HTML-uppercased qualified name by storing them in internal slots."
  664. if (namespace_() == Namespace::HTML && document().document_type() == Document::Type::HTML)
  665. m_html_uppercased_qualified_name = DeprecatedString(qualified_name()).to_uppercase();
  666. else
  667. m_html_uppercased_qualified_name = qualified_name();
  668. }
  669. // https://html.spec.whatwg.org/multipage/webappapis.html#queue-an-element-task
  670. int Element::queue_an_element_task(HTML::Task::Source source, JS::SafeFunction<void()> steps)
  671. {
  672. auto task = HTML::Task::create(source, &document(), move(steps));
  673. auto id = task->id();
  674. HTML::main_thread_event_loop().task_queue().add(move(task));
  675. return id;
  676. }
  677. // https://html.spec.whatwg.org/multipage/syntax.html#void-elements
  678. bool Element::is_void_element() const
  679. {
  680. return local_name().is_one_of(HTML::TagNames::area, HTML::TagNames::base, HTML::TagNames::br, HTML::TagNames::col, HTML::TagNames::embed, HTML::TagNames::hr, HTML::TagNames::img, HTML::TagNames::input, HTML::TagNames::link, HTML::TagNames::meta, HTML::TagNames::param, HTML::TagNames::source, HTML::TagNames::track, HTML::TagNames::wbr);
  681. }
  682. // https://html.spec.whatwg.org/multipage/parsing.html#serializes-as-void
  683. bool Element::serializes_as_void() const
  684. {
  685. return is_void_element() || local_name().is_one_of(HTML::TagNames::basefont, HTML::TagNames::bgsound, HTML::TagNames::frame, HTML::TagNames::keygen);
  686. }
  687. // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
  688. JS::NonnullGCPtr<Geometry::DOMRect> Element::get_bounding_client_rect() const
  689. {
  690. // // NOTE: Ensure that layout is up-to-date before looking at metrics.
  691. const_cast<Document&>(document()).update_layout();
  692. // FIXME: Support inline layout nodes as well.
  693. auto* paintable_box = this->paintable_box();
  694. if (!paintable_box)
  695. return Geometry::DOMRect::construct_impl(realm(), 0, 0, 0, 0).release_value_but_fixme_should_propagate_errors();
  696. VERIFY(document().navigable());
  697. auto viewport_offset = document().navigable()->viewport_scroll_offset();
  698. return Geometry::DOMRect::create(realm(), paintable_box->absolute_rect().translated(-viewport_offset.x(), -viewport_offset.y()).to_type<float>());
  699. }
  700. // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
  701. JS::NonnullGCPtr<Geometry::DOMRectList> Element::get_client_rects() const
  702. {
  703. Vector<JS::Handle<Geometry::DOMRect>> rects;
  704. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  705. const_cast<Document&>(document()).update_layout();
  706. // 1. If the element on which it was invoked does not have an associated layout box return an empty DOMRectList object and stop this algorithm.
  707. if (!layout_node() || !layout_node()->is_box())
  708. return Geometry::DOMRectList::create(realm(), move(rects));
  709. // FIXME: 2. If the element has an associated SVG layout box return a DOMRectList object containing a single DOMRect object that describes
  710. // the bounding box of the element as defined by the SVG specification, applying the transforms that apply to the element and its ancestors.
  711. // FIXME: 3. Return a DOMRectList object containing DOMRect objects in content order, one for each box fragment,
  712. // describing its border area (including those with a height or width of zero) with the following constraints:
  713. // - Apply the transforms that apply to the element and its ancestors.
  714. // - If the element on which the method was invoked has a computed value for the display property of table
  715. // or inline-table include both the table box and the caption box, if any, but not the anonymous container box.
  716. // - Replace each anonymous block box with its child box(es) and repeat this until no anonymous block boxes are left in the final list.
  717. auto bounding_rect = get_bounding_client_rect();
  718. rects.append(*bounding_rect);
  719. return Geometry::DOMRectList::create(realm(), move(rects));
  720. }
  721. int Element::client_top() const
  722. {
  723. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  724. const_cast<Document&>(document()).update_layout();
  725. // 1. If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.
  726. if (!layout_node() || !layout_node()->is_box())
  727. return 0;
  728. // 2. Return the computed value of the border-top-width property
  729. // plus the height of any scrollbar rendered between the top padding edge and the top border edge,
  730. // ignoring any transforms that apply to the element and its ancestors.
  731. return static_cast<Layout::Box const&>(*layout_node()).computed_values().border_top().width.to_int();
  732. }
  733. // https://drafts.csswg.org/cssom-view/#dom-element-clientleft
  734. int Element::client_left() const
  735. {
  736. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  737. const_cast<Document&>(document()).update_layout();
  738. // 1. If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.
  739. if (!layout_node() || !layout_node()->is_box())
  740. return 0;
  741. // 2. Return the computed value of the border-left-width property
  742. // plus the width of any scrollbar rendered between the left padding edge and the left border edge,
  743. // ignoring any transforms that apply to the element and its ancestors.
  744. return static_cast<Layout::Box const&>(*layout_node()).computed_values().border_left().width.to_int();
  745. }
  746. // https://drafts.csswg.org/cssom-view/#dom-element-clientwidth
  747. int Element::client_width() const
  748. {
  749. // NOTE: We do step 2 before step 1 here since step 2 can exit early without needing to perform layout.
  750. // 2. If the element is the root element and the element’s node document is not in quirks mode,
  751. // or if the element is the HTML body element and the element’s node document is in quirks mode,
  752. // return the viewport width excluding the size of a rendered scroll bar (if any).
  753. if ((is<HTML::HTMLHtmlElement>(*this) && !document().in_quirks_mode())
  754. || (is<HTML::HTMLBodyElement>(*this) && document().in_quirks_mode())) {
  755. return document().viewport_rect().width().to_int();
  756. }
  757. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  758. const_cast<Document&>(document()).update_layout();
  759. // 1. If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.
  760. if (!paintable_box())
  761. return 0;
  762. // 3. Return the width of the padding edge excluding the width of any rendered scrollbar between the padding edge and the border edge,
  763. // ignoring any transforms that apply to the element and its ancestors.
  764. return paintable_box()->absolute_padding_box_rect().width().to_int();
  765. }
  766. // https://drafts.csswg.org/cssom-view/#dom-element-clientheight
  767. int Element::client_height() const
  768. {
  769. // NOTE: We do step 2 before step 1 here since step 2 can exit early without needing to perform layout.
  770. // 2. If the element is the root element and the element’s node document is not in quirks mode,
  771. // or if the element is the HTML body element and the element’s node document is in quirks mode,
  772. // return the viewport height excluding the size of a rendered scroll bar (if any).
  773. if ((is<HTML::HTMLHtmlElement>(*this) && !document().in_quirks_mode())
  774. || (is<HTML::HTMLBodyElement>(*this) && document().in_quirks_mode())) {
  775. return document().viewport_rect().height().to_int();
  776. }
  777. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  778. const_cast<Document&>(document()).update_layout();
  779. // 1. If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.
  780. if (!paintable_box())
  781. return 0;
  782. // 3. Return the height of the padding edge excluding the height of any rendered scrollbar between the padding edge and the border edge,
  783. // ignoring any transforms that apply to the element and its ancestors.
  784. return paintable_box()->absolute_padding_box_rect().height().to_int();
  785. }
  786. void Element::children_changed()
  787. {
  788. Node::children_changed();
  789. set_needs_style_update(true);
  790. }
  791. void Element::set_pseudo_element_node(Badge<Layout::TreeBuilder>, CSS::Selector::PseudoElement pseudo_element, JS::GCPtr<Layout::Node> pseudo_element_node)
  792. {
  793. m_pseudo_element_nodes[to_underlying(pseudo_element)] = pseudo_element_node;
  794. }
  795. JS::GCPtr<Layout::Node> Element::get_pseudo_element_node(CSS::Selector::PseudoElement pseudo_element) const
  796. {
  797. return m_pseudo_element_nodes[to_underlying(pseudo_element)];
  798. }
  799. void Element::clear_pseudo_element_nodes(Badge<Layout::TreeBuilder>)
  800. {
  801. m_pseudo_element_nodes.fill({});
  802. }
  803. void Element::serialize_pseudo_elements_as_json(JsonArraySerializer<StringBuilder>& children_array) const
  804. {
  805. for (size_t i = 0; i < m_pseudo_element_nodes.size(); ++i) {
  806. auto& pseudo_element_node = m_pseudo_element_nodes[i];
  807. if (!pseudo_element_node)
  808. continue;
  809. auto object = MUST(children_array.add_object());
  810. MUST(object.add("name"sv, DeprecatedString::formatted("::{}", CSS::pseudo_element_name(static_cast<CSS::Selector::PseudoElement>(i)))));
  811. MUST(object.add("type"sv, "pseudo-element"));
  812. MUST(object.add("parent-id"sv, id()));
  813. MUST(object.add("pseudo-element"sv, i));
  814. MUST(object.finish());
  815. }
  816. }
  817. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  818. i32 Element::default_tab_index_value() const
  819. {
  820. // The default value is 0 if the element is an a, area, button, frame, iframe, input, object, select, textarea, or SVG a element, or is a summary element that is a summary for its parent details.
  821. // The default value is −1 otherwise.
  822. // Note: The varying default value based on element type is a historical artifact.
  823. // FIXME: We currently do not have the SVG a element.
  824. return -1;
  825. }
  826. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  827. i32 Element::tab_index() const
  828. {
  829. auto maybe_table_index = Web::HTML::parse_integer(deprecated_attribute(HTML::AttributeNames::tabindex));
  830. if (!maybe_table_index.has_value())
  831. return default_tab_index_value();
  832. return maybe_table_index.value();
  833. }
  834. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  835. void Element::set_tab_index(i32 tab_index)
  836. {
  837. MUST(set_attribute(HTML::AttributeNames::tabindex, DeprecatedString::number(tab_index)));
  838. }
  839. // https://drafts.csswg.org/cssom-view/#potentially-scrollable
  840. bool Element::is_potentially_scrollable() const
  841. {
  842. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  843. const_cast<Document&>(document()).update_layout();
  844. // An element body (which will be the body element) is potentially scrollable if all of the following conditions are true:
  845. VERIFY(is<HTML::HTMLBodyElement>(this) || is<HTML::HTMLFrameSetElement>(this));
  846. // Since this should always be the body element, the body element must have a <html> element parent. See Document::body().
  847. VERIFY(parent());
  848. // - body has an associated box.
  849. // - body’s parent element’s computed value of the overflow-x or overflow-y properties is neither visible nor clip.
  850. // - body’s computed value of the overflow-x or overflow-y properties is neither visible nor clip.
  851. return layout_node()
  852. && (parent()->layout_node()
  853. && parent()->layout_node()->computed_values().overflow_x() != CSS::Overflow::Visible && parent()->layout_node()->computed_values().overflow_x() != CSS::Overflow::Clip
  854. && parent()->layout_node()->computed_values().overflow_y() != CSS::Overflow::Visible && parent()->layout_node()->computed_values().overflow_y() != CSS::Overflow::Clip)
  855. && (layout_node()->computed_values().overflow_x() != CSS::Overflow::Visible && layout_node()->computed_values().overflow_x() != CSS::Overflow::Clip
  856. && layout_node()->computed_values().overflow_y() != CSS::Overflow::Visible && layout_node()->computed_values().overflow_y() != CSS::Overflow::Clip);
  857. }
  858. // https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
  859. double Element::scroll_top() const
  860. {
  861. // 1. Let document be the element’s node document.
  862. auto& document = this->document();
  863. // 2. If document is not the active document, return zero and terminate these steps.
  864. if (!document.is_active())
  865. return 0.0;
  866. // 3. Let window be the value of document’s defaultView attribute.
  867. auto* window = document.default_view();
  868. // 4. If window is null, return zero and terminate these steps.
  869. if (!window)
  870. return 0.0;
  871. // 5. If the element is the root element and document is in quirks mode, return zero and terminate these steps.
  872. if (document.document_element() == this && document.in_quirks_mode())
  873. return 0.0;
  874. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  875. const_cast<Document&>(document).update_layout();
  876. // 6. If the element is the root element return the value of scrollY on window.
  877. if (document.document_element() == this)
  878. return window->scroll_y();
  879. // 7. If the element is the body element, document is in quirks mode, and the element is not potentially scrollable, return the value of scrollY on window.
  880. if (document.body() == this && document.in_quirks_mode() && !is_potentially_scrollable())
  881. return window->scroll_y();
  882. // 8. If the element does not have any associated box, return zero and terminate these steps.
  883. if (!layout_node() || !is<Layout::Box>(layout_node()))
  884. return 0.0;
  885. // 9. Return the y-coordinate of the scrolling area at the alignment point with the top of the padding edge of the element.
  886. // FIXME: Is this correct?
  887. return paintable_box()->scroll_offset().y().to_double();
  888. }
  889. double Element::scroll_left() const
  890. {
  891. // 1. Let document be the element’s node document.
  892. auto& document = this->document();
  893. // 2. If document is not the active document, return zero and terminate these steps.
  894. if (!document.is_active())
  895. return 0.0;
  896. // 3. Let window be the value of document’s defaultView attribute.
  897. auto* window = document.default_view();
  898. // 4. If window is null, return zero and terminate these steps.
  899. if (!window)
  900. return 0.0;
  901. // 5. If the element is the root element and document is in quirks mode, return zero and terminate these steps.
  902. if (document.document_element() == this && document.in_quirks_mode())
  903. return 0.0;
  904. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  905. const_cast<Document&>(document).update_layout();
  906. // 6. If the element is the root element return the value of scrollX on window.
  907. if (document.document_element() == this)
  908. return window->scroll_x();
  909. // 7. If the element is the body element, document is in quirks mode, and the element is not potentially scrollable, return the value of scrollX on window.
  910. if (document.body() == this && document.in_quirks_mode() && !is_potentially_scrollable())
  911. return window->scroll_x();
  912. // 8. If the element does not have any associated box, return zero and terminate these steps.
  913. if (!layout_node() || !is<Layout::Box>(layout_node()))
  914. return 0.0;
  915. // 9. Return the x-coordinate of the scrolling area at the alignment point with the left of the padding edge of the element.
  916. // FIXME: Is this correct?
  917. return paintable_box()->scroll_offset().x().to_double();
  918. }
  919. // https://drafts.csswg.org/cssom-view/#dom-element-scrollleft
  920. void Element::set_scroll_left(double x)
  921. {
  922. // 1. Let x be the given value.
  923. // 2. Normalize non-finite values for x.
  924. if (!isfinite(x))
  925. x = 0.0;
  926. // 3. Let document be the element’s node document.
  927. auto& document = this->document();
  928. // 4. If document is not the active document, terminate these steps.
  929. if (!document.is_active())
  930. return;
  931. // 5. Let window be the value of document’s defaultView attribute.
  932. auto* window = document.default_view();
  933. // 6. If window is null, terminate these steps.
  934. if (!window)
  935. return;
  936. // 7. If the element is the root element and document is in quirks mode, terminate these steps.
  937. if (document.document_element() == this && document.in_quirks_mode())
  938. return;
  939. // NOTE: Ensure that layout is up-to-date before looking at metrics or scrolling the page.
  940. const_cast<Document&>(document).update_layout();
  941. // 8. If the element is the root element invoke scroll() on window with x as first argument and scrollY on window as second argument, and terminate these steps.
  942. if (document.document_element() == this) {
  943. // FIXME: Implement this in terms of invoking scroll() on window.
  944. if (auto* page = document.page()) {
  945. if (document.browsing_context() == &page->top_level_browsing_context())
  946. page->client().page_did_request_scroll_to({ static_cast<float>(x), static_cast<float>(window->scroll_y()) });
  947. }
  948. return;
  949. }
  950. // 9. If the element is the body element, document is in quirks mode, and the element is not potentially scrollable, invoke scroll() on window with x as first argument and scrollY on window as second argument, and terminate these steps.
  951. if (document.body() == this && document.in_quirks_mode() && !is_potentially_scrollable()) {
  952. // FIXME: Implement this in terms of invoking scroll() on window.
  953. if (auto* page = document.page()) {
  954. if (document.browsing_context() == &page->top_level_browsing_context())
  955. page->client().page_did_request_scroll_to({ static_cast<float>(x), static_cast<float>(window->scroll_y()) });
  956. }
  957. return;
  958. }
  959. // 10. If the element does not have any associated box, the element has no associated scrolling box, or the element has no overflow, terminate these steps.
  960. if (!layout_node() || !is<Layout::Box>(layout_node()))
  961. return;
  962. auto* box = static_cast<Layout::Box*>(layout_node());
  963. if (!box->is_scroll_container())
  964. return;
  965. // FIXME: or the element has no overflow.
  966. // 11. Scroll the element to x,scrollTop, with the scroll behavior being "auto".
  967. // FIXME: Implement this in terms of calling "scroll the element".
  968. auto scroll_offset = paintable_box()->scroll_offset();
  969. scroll_offset.set_x(CSSPixels::nearest_value_for(x));
  970. paintable_box()->set_scroll_offset(scroll_offset);
  971. }
  972. void Element::set_scroll_top(double y)
  973. {
  974. // 1. Let y be the given value.
  975. // 2. Normalize non-finite values for y.
  976. if (!isfinite(y))
  977. y = 0.0;
  978. // 3. Let document be the element’s node document.
  979. auto& document = this->document();
  980. // 4. If document is not the active document, terminate these steps.
  981. if (!document.is_active())
  982. return;
  983. // 5. Let window be the value of document’s defaultView attribute.
  984. auto* window = document.default_view();
  985. // 6. If window is null, terminate these steps.
  986. if (!window)
  987. return;
  988. // 7. If the element is the root element and document is in quirks mode, terminate these steps.
  989. if (document.document_element() == this && document.in_quirks_mode())
  990. return;
  991. // NOTE: Ensure that layout is up-to-date before looking at metrics or scrolling the page.
  992. const_cast<Document&>(document).update_layout();
  993. // 8. If the element is the root element invoke scroll() on window with scrollX on window as first argument and y as second argument, and terminate these steps.
  994. if (document.document_element() == this) {
  995. // FIXME: Implement this in terms of invoking scroll() on window.
  996. if (auto* page = document.page()) {
  997. if (document.browsing_context() == &page->top_level_browsing_context())
  998. page->client().page_did_request_scroll_to({ static_cast<float>(window->scroll_x()), static_cast<float>(y) });
  999. }
  1000. return;
  1001. }
  1002. // 9. If the element is the body element, document is in quirks mode, and the element is not potentially scrollable, invoke scroll() on window with scrollX as first argument and y as second argument, and terminate these steps.
  1003. if (document.body() == this && document.in_quirks_mode() && !is_potentially_scrollable()) {
  1004. // FIXME: Implement this in terms of invoking scroll() on window.
  1005. if (auto* page = document.page()) {
  1006. if (document.browsing_context() == &page->top_level_browsing_context())
  1007. page->client().page_did_request_scroll_to({ static_cast<float>(window->scroll_x()), static_cast<float>(y) });
  1008. }
  1009. return;
  1010. }
  1011. // 10. If the element does not have any associated box, the element has no associated scrolling box, or the element has no overflow, terminate these steps.
  1012. if (!layout_node() || !is<Layout::Box>(layout_node()))
  1013. return;
  1014. auto* box = static_cast<Layout::Box*>(layout_node());
  1015. if (!box->is_scroll_container())
  1016. return;
  1017. // FIXME: or the element has no overflow.
  1018. // 11. Scroll the element to scrollLeft,y, with the scroll behavior being "auto".
  1019. // FIXME: Implement this in terms of calling "scroll the element".
  1020. auto scroll_offset = paintable_box()->scroll_offset();
  1021. scroll_offset.set_y(CSSPixels::nearest_value_for(y));
  1022. paintable_box()->set_scroll_offset(scroll_offset);
  1023. }
  1024. // https://drafts.csswg.org/cssom-view/#dom-element-scrollwidth
  1025. int Element::scroll_width() const
  1026. {
  1027. // 1. Let document be the element’s node document.
  1028. auto& document = this->document();
  1029. // 2. If document is not the active document, return zero and terminate these steps.
  1030. if (!document.is_active())
  1031. return 0;
  1032. // 3. Let viewport width be the width of the viewport excluding the width of the scroll bar, if any,
  1033. // or zero if there is no viewport.
  1034. auto viewport_width = document.viewport_rect().width().to_int();
  1035. auto viewport_scroll_width = document.navigable()->size().width().to_int();
  1036. // 4. If the element is the root element and document is not in quirks mode
  1037. // return max(viewport scrolling area width, viewport width).
  1038. if (document.document_element() == this && !document.in_quirks_mode())
  1039. return max(viewport_scroll_width, viewport_width);
  1040. // 5. If the element is the body element, document is in quirks mode and the element is not potentially scrollable,
  1041. // return max(viewport scrolling area width, viewport width).
  1042. if (document.body() == this && document.in_quirks_mode() && !is_potentially_scrollable())
  1043. return max(viewport_scroll_width, viewport_width);
  1044. // 6. If the element does not have any associated box return zero and terminate these steps.
  1045. if (!paintable_box())
  1046. return 0;
  1047. // 7. Return the width of the element’s scrolling area.
  1048. return paintable_box()->border_box_width().to_int();
  1049. }
  1050. // https://drafts.csswg.org/cssom-view/#dom-element-scrollheight
  1051. int Element::scroll_height() const
  1052. {
  1053. // 1. Let document be the element’s node document.
  1054. auto& document = this->document();
  1055. // 2. If document is not the active document, return zero and terminate these steps.
  1056. if (!document.is_active())
  1057. return 0;
  1058. // 3. Let viewport height be the height of the viewport excluding the height of the scroll bar, if any,
  1059. // or zero if there is no viewport.
  1060. auto viewport_height = document.viewport_rect().height().to_int();
  1061. auto viewport_scroll_height = document.navigable()->size().height().to_int();
  1062. // 4. If the element is the root element and document is not in quirks mode
  1063. // return max(viewport scrolling area height, viewport height).
  1064. if (document.document_element() == this && !document.in_quirks_mode())
  1065. return max(viewport_scroll_height, viewport_height);
  1066. // 5. If the element is the body element, document is in quirks mode and the element is not potentially scrollable,
  1067. // return max(viewport scrolling area height, viewport height).
  1068. if (document.body() == this && document.in_quirks_mode() && !is_potentially_scrollable())
  1069. return max(viewport_scroll_height, viewport_height);
  1070. // 6. If the element does not have any associated box return zero and terminate these steps.
  1071. if (!paintable_box())
  1072. return 0;
  1073. // 7. Return the height of the element’s scrolling area.
  1074. return paintable_box()->border_box_height().to_int();
  1075. }
  1076. // https://html.spec.whatwg.org/multipage/semantics-other.html#concept-element-disabled
  1077. bool Element::is_actually_disabled() const
  1078. {
  1079. // An element is said to be actually disabled if it is one of the following:
  1080. // - a button element that is disabled
  1081. // - an input element that is disabled
  1082. // - a select element that is disabled
  1083. // - a textarea element that is disabled
  1084. if (is<HTML::HTMLButtonElement>(this) || is<HTML::HTMLInputElement>(this) || is<HTML::HTMLSelectElement>(this) || is<HTML::HTMLTextAreaElement>(this)) {
  1085. auto const* form_associated_element = dynamic_cast<HTML::FormAssociatedElement const*>(this);
  1086. VERIFY(form_associated_element);
  1087. return !form_associated_element->enabled();
  1088. }
  1089. // - an optgroup element that has a disabled attribute
  1090. if (is<HTML::HTMLOptGroupElement>(this))
  1091. return has_attribute(HTML::AttributeNames::disabled);
  1092. // - an option element that is disabled
  1093. if (is<HTML::HTMLOptionElement>(this))
  1094. return static_cast<HTML::HTMLOptionElement const&>(*this).disabled();
  1095. // - a fieldset element that is a disabled fieldset
  1096. if (is<HTML::HTMLFieldSetElement>(this))
  1097. return static_cast<HTML::HTMLFieldSetElement const&>(*this).is_disabled();
  1098. // FIXME: - a form-associated custom element that is disabled
  1099. return false;
  1100. }
  1101. // https://w3c.github.io/DOM-Parsing/#dom-element-insertadjacenthtml
  1102. WebIDL::ExceptionOr<void> Element::insert_adjacent_html(DeprecatedString position, DeprecatedString text)
  1103. {
  1104. JS::GCPtr<Node> context;
  1105. // 1. Use the first matching item from this list:
  1106. // - If position is an ASCII case-insensitive match for the string "beforebegin"
  1107. // - If position is an ASCII case-insensitive match for the string "afterend"
  1108. if (Infra::is_ascii_case_insensitive_match(position, "beforebegin"sv)
  1109. || Infra::is_ascii_case_insensitive_match(position, "afterend"sv)) {
  1110. // Let context be the context object's parent.
  1111. context = this->parent();
  1112. // If context is null or a Document, throw a "NoModificationAllowedError" DOMException.
  1113. if (!context || context->is_document())
  1114. return WebIDL::NoModificationAllowedError::create(realm(), "insertAdjacentHTML: context is null or a Document"_fly_string);
  1115. }
  1116. // - If position is an ASCII case-insensitive match for the string "afterbegin"
  1117. // - If position is an ASCII case-insensitive match for the string "beforeend"
  1118. else if (Infra::is_ascii_case_insensitive_match(position, "afterbegin"sv)
  1119. || Infra::is_ascii_case_insensitive_match(position, "beforeend"sv)) {
  1120. // Let context be the context object.
  1121. context = this;
  1122. }
  1123. // Otherwise
  1124. else {
  1125. // Throw a "SyntaxError" DOMException.
  1126. return WebIDL::SyntaxError::create(realm(), "insertAdjacentHTML: invalid position argument"_fly_string);
  1127. }
  1128. // 2. If context is not an Element or the following are all true:
  1129. // - context's node document is an HTML document,
  1130. // - context's local name is "html", and
  1131. // - context's namespace is the HTML namespace;
  1132. if (!is<Element>(*context)
  1133. || (context->document().document_type() == Document::Type::HTML
  1134. && static_cast<Element const&>(*context).local_name() == "html"sv
  1135. && static_cast<Element const&>(*context).namespace_() == Namespace::HTML)) {
  1136. // FIXME: let context be a new Element with
  1137. // - body as its local name,
  1138. // - The HTML namespace as its namespace, and
  1139. // - The context object's node document as its node document.
  1140. TODO();
  1141. }
  1142. // 3. Let fragment be the result of invoking the fragment parsing algorithm with text as markup, and context as the context element.
  1143. auto fragment = TRY(DOMParsing::parse_fragment(text, verify_cast<Element>(*context)));
  1144. // 4. Use the first matching item from this list:
  1145. // - If position is an ASCII case-insensitive match for the string "beforebegin"
  1146. if (Infra::is_ascii_case_insensitive_match(position, "beforebegin"sv)) {
  1147. // Insert fragment into the context object's parent before the context object.
  1148. parent()->insert_before(fragment, this);
  1149. }
  1150. // - If position is an ASCII case-insensitive match for the string "afterbegin"
  1151. else if (Infra::is_ascii_case_insensitive_match(position, "afterbegin"sv)) {
  1152. // Insert fragment into the context object before its first child.
  1153. insert_before(fragment, first_child());
  1154. }
  1155. // - If position is an ASCII case-insensitive match for the string "beforeend"
  1156. else if (Infra::is_ascii_case_insensitive_match(position, "beforeend"sv)) {
  1157. // Append fragment to the context object.
  1158. TRY(append_child(fragment));
  1159. }
  1160. // - If position is an ASCII case-insensitive match for the string "afterend"
  1161. else if (Infra::is_ascii_case_insensitive_match(position, "afterend"sv)) {
  1162. // Insert fragment into the context object's parent before the context object's next sibling.
  1163. parent()->insert_before(fragment, next_sibling());
  1164. }
  1165. return {};
  1166. }
  1167. // https://dom.spec.whatwg.org/#insert-adjacent
  1168. WebIDL::ExceptionOr<JS::GCPtr<Node>> Element::insert_adjacent(DeprecatedString const& where, JS::NonnullGCPtr<Node> node)
  1169. {
  1170. // To insert adjacent, given an element element, string where, and a node node, run the steps associated with the first ASCII case-insensitive match for where:
  1171. if (Infra::is_ascii_case_insensitive_match(where, "beforebegin"sv)) {
  1172. // -> "beforebegin"
  1173. // If element’s parent is null, return null.
  1174. if (!parent())
  1175. return JS::GCPtr<Node> { nullptr };
  1176. // Return the result of pre-inserting node into element’s parent before element.
  1177. return JS::GCPtr<Node> { TRY(parent()->pre_insert(move(node), this)) };
  1178. }
  1179. if (Infra::is_ascii_case_insensitive_match(where, "afterbegin"sv)) {
  1180. // -> "afterbegin"
  1181. // Return the result of pre-inserting node into element before element’s first child.
  1182. return JS::GCPtr<Node> { TRY(pre_insert(move(node), first_child())) };
  1183. }
  1184. if (Infra::is_ascii_case_insensitive_match(where, "beforeend"sv)) {
  1185. // -> "beforeend"
  1186. // Return the result of pre-inserting node into element before null.
  1187. return JS::GCPtr<Node> { TRY(pre_insert(move(node), nullptr)) };
  1188. }
  1189. if (Infra::is_ascii_case_insensitive_match(where, "afterend"sv)) {
  1190. // -> "afterend"
  1191. // If element’s parent is null, return null.
  1192. if (!parent())
  1193. return JS::GCPtr<Node> { nullptr };
  1194. // Return the result of pre-inserting node into element’s parent before element’s next sibling.
  1195. return JS::GCPtr<Node> { TRY(parent()->pre_insert(move(node), next_sibling())) };
  1196. }
  1197. // -> Otherwise
  1198. // Throw a "SyntaxError" DOMException.
  1199. return WebIDL::SyntaxError::create(realm(), MUST(String::formatted("Unknown position '{}'. Must be one of 'beforebegin', 'afterbegin', 'beforeend' or 'afterend'"sv, where)));
  1200. }
  1201. // https://dom.spec.whatwg.org/#dom-element-insertadjacentelement
  1202. WebIDL::ExceptionOr<JS::GCPtr<Element>> Element::insert_adjacent_element(DeprecatedString const& where, JS::NonnullGCPtr<Element> element)
  1203. {
  1204. // The insertAdjacentElement(where, element) method steps are to return the result of running insert adjacent, give this, where, and element.
  1205. auto returned_node = TRY(insert_adjacent(where, move(element)));
  1206. if (!returned_node)
  1207. return JS::GCPtr<Element> { nullptr };
  1208. return JS::GCPtr<Element> { verify_cast<Element>(*returned_node) };
  1209. }
  1210. // https://dom.spec.whatwg.org/#dom-element-insertadjacenttext
  1211. WebIDL::ExceptionOr<void> Element::insert_adjacent_text(DeprecatedString const& where, DeprecatedString const& data)
  1212. {
  1213. // 1. Let text be a new Text node whose data is data and node document is this’s node document.
  1214. auto text = heap().allocate<DOM::Text>(realm(), document(), MUST(String::from_deprecated_string(data)));
  1215. // 2. Run insert adjacent, given this, where, and text.
  1216. // Spec Note: This method returns nothing because it existed before we had a chance to design it.
  1217. (void)TRY(insert_adjacent(where, text));
  1218. return {};
  1219. }
  1220. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scroll-an-element-into-view
  1221. static ErrorOr<void> scroll_an_element_into_view(DOM::Element& element, Bindings::ScrollBehavior behavior, Bindings::ScrollLogicalPosition block, Bindings::ScrollLogicalPosition inline_)
  1222. {
  1223. // FIXME: The below is ad-hoc, since we don't yet have scrollable elements.
  1224. // Return here and implement this according to spec once all overflow is made scrollable.
  1225. (void)behavior;
  1226. (void)block;
  1227. (void)inline_;
  1228. if (!element.document().browsing_context())
  1229. return Error::from_string_view("Element has no browsing context."sv);
  1230. auto* page = element.document().browsing_context()->page();
  1231. if (!page)
  1232. return Error::from_string_view("Element has no page."sv);
  1233. // If this element doesn't have a layout node, we can't scroll it into view.
  1234. element.document().update_layout();
  1235. if (!element.layout_node())
  1236. return Error::from_string_view("Element has no layout node."sv);
  1237. // Find the nearest layout node that is a box (since we need a box to get a usable rect)
  1238. auto* layout_node = element.layout_node();
  1239. while (layout_node && !layout_node->is_box())
  1240. layout_node = layout_node->parent();
  1241. if (!layout_node)
  1242. return Error::from_string_view("Element has no parent layout node that is a box."sv);
  1243. if (auto navigable = element.document().navigable()) {
  1244. element.document().navigable()->traversable_navigable()->page()->client().page_did_request_scroll_into_view(verify_cast<Layout::Box>(*layout_node).paintable_box()->absolute_padding_box_rect());
  1245. }
  1246. return {};
  1247. }
  1248. // https://w3c.github.io/csswg-drafts/cssom-view-1/#dom-element-scrollintoview
  1249. ErrorOr<void> Element::scroll_into_view(Optional<Variant<bool, ScrollIntoViewOptions>> arg)
  1250. {
  1251. // 1. Let behavior be "auto".
  1252. auto behavior = Bindings::ScrollBehavior::Auto;
  1253. // 2. Let block be "start".
  1254. auto block = Bindings::ScrollLogicalPosition::Start;
  1255. // 3. Let inline be "nearest".
  1256. auto inline_ = Bindings::ScrollLogicalPosition::Nearest;
  1257. // 4. If arg is a ScrollIntoViewOptions dictionary, then:
  1258. if (arg.has_value() && arg->has<ScrollIntoViewOptions>()) {
  1259. // 1. Set behavior to the behavior dictionary member of options.
  1260. behavior = arg->get<ScrollIntoViewOptions>().behavior;
  1261. // 2. Set block to the block dictionary member of options.
  1262. block = arg->get<ScrollIntoViewOptions>().block;
  1263. // 3. Set inline to the inline dictionary member of options.
  1264. inline_ = arg->get<ScrollIntoViewOptions>().inline_;
  1265. }
  1266. // 5. Otherwise, if arg is false, then set block to "end".
  1267. else if (arg.has_value() && arg->has<bool>() && arg->get<bool>() == false) {
  1268. block = Bindings::ScrollLogicalPosition::End;
  1269. }
  1270. // 6. If the element does not have any associated box, or is not available to user-agent features, then return.
  1271. document().update_layout();
  1272. if (!layout_node())
  1273. return Error::from_string_view("Element has no associated box"sv);
  1274. // 7. Scroll the element into view with behavior, block, and inline.
  1275. TRY(scroll_an_element_into_view(*this, behavior, block, inline_));
  1276. return {};
  1277. // FIXME: 8. Optionally perform some other action that brings the element to the user’s attention.
  1278. }
  1279. void Element::invalidate_style_after_attribute_change(DeprecatedFlyString const& attribute_name)
  1280. {
  1281. // FIXME: Only invalidate if the attribute can actually affect style.
  1282. (void)attribute_name;
  1283. // FIXME: This will need to become smarter when we implement the :has() selector.
  1284. invalidate_style();
  1285. }
  1286. // https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion
  1287. bool Element::exclude_from_accessibility_tree() const
  1288. {
  1289. // The following elements are not exposed via the accessibility API and user agents MUST NOT include them in the accessibility tree:
  1290. // Elements, including their descendent elements, that have host language semantics specifying that the element is not displayed, such as CSS display:none, visibility:hidden, or the HTML hidden attribute.
  1291. if (!layout_node())
  1292. return true;
  1293. // Elements with none or presentation as the first role in the role attribute. However, their exclusion is conditional. In addition, the element's descendants and text content are generally included. These exceptions and conditions are documented in the presentation (role) section.
  1294. // FIXME: Handle exceptions to excluding presentation role
  1295. auto role = role_or_default();
  1296. if (role == ARIA::Role::none || role == ARIA::Role::presentation)
  1297. return true;
  1298. // TODO: If not already excluded from the accessibility tree per the above rules, user agents SHOULD NOT include the following elements in the accessibility tree:
  1299. // Elements, including their descendants, that have aria-hidden set to true. In other words, aria-hidden="true" on a parent overrides aria-hidden="false" on descendants.
  1300. // Any descendants of elements that have the characteristic "Children Presentational: True" unless the descendant is not allowed to be presentational because it meets one of the conditions for exception described in Presentational Roles Conflict Resolution. However, the text content of any excluded descendants is included.
  1301. // Elements with the following roles have the characteristic "Children Presentational: True":
  1302. // button
  1303. // checkbox
  1304. // img
  1305. // menuitemcheckbox
  1306. // menuitemradio
  1307. // meter
  1308. // option
  1309. // progressbar
  1310. // radio
  1311. // scrollbar
  1312. // separator
  1313. // slider
  1314. // switch
  1315. // tab
  1316. return false;
  1317. }
  1318. // https://www.w3.org/TR/wai-aria-1.2/#tree_inclusion
  1319. bool Element::include_in_accessibility_tree() const
  1320. {
  1321. // If not excluded from or marked as hidden in the accessibility tree per the rules above in Excluding Elements in the Accessibility Tree, user agents MUST provide an accessible object in the accessibility tree for DOM elements that meet any of the following criteria:
  1322. if (exclude_from_accessibility_tree())
  1323. return false;
  1324. // Elements that are not hidden and may fire an accessibility API event, including:
  1325. // Elements that are currently focused, even if the element or one of its ancestor elements has its aria-hidden attribute set to true.
  1326. if (is_focused())
  1327. return true;
  1328. // TODO: Elements that are a valid target of an aria-activedescendant attribute.
  1329. // Elements that have an explicit role or a global WAI-ARIA attribute and do not have aria-hidden set to true. (See Excluding Elements in the Accessibility Tree for additional guidance on aria-hidden.)
  1330. // NOTE: The spec says only explicit roles count, but playing around in other browsers, this does not seem to be true in practice (for example button elements are always exposed with their implicit role if none is set)
  1331. // This issue https://github.com/w3c/aria/issues/1851 seeks clarification on this point
  1332. if ((role_or_default().has_value() || has_global_aria_attribute()) && aria_hidden() != "true")
  1333. return true;
  1334. // TODO: Elements that are not hidden and have an ID that is referenced by another element via a WAI-ARIA property.
  1335. return false;
  1336. }
  1337. // https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-an-element-on-the-appropriate-element-queue
  1338. void Element::enqueue_an_element_on_the_appropriate_element_queue()
  1339. {
  1340. // 1. Let reactionsStack be element's relevant agent's custom element reactions stack.
  1341. auto& relevant_agent = HTML::relevant_agent(*this);
  1342. auto* custom_data = verify_cast<Bindings::WebEngineCustomData>(relevant_agent.custom_data());
  1343. auto& reactions_stack = custom_data->custom_element_reactions_stack;
  1344. // 2. If reactionsStack is empty, then:
  1345. if (reactions_stack.element_queue_stack.is_empty()) {
  1346. // 1. Add element to reactionsStack's backup element queue.
  1347. reactions_stack.backup_element_queue.append(*this);
  1348. // 2. If reactionsStack's processing the backup element queue flag is set, then return.
  1349. if (reactions_stack.processing_the_backup_element_queue)
  1350. return;
  1351. // 3. Set reactionsStack's processing the backup element queue flag.
  1352. reactions_stack.processing_the_backup_element_queue = true;
  1353. // 4. Queue a microtask to perform the following steps:
  1354. // NOTE: `this` is protected by JS::SafeFunction
  1355. HTML::queue_a_microtask(&document(), [this]() {
  1356. auto& relevant_agent = HTML::relevant_agent(*this);
  1357. auto* custom_data = verify_cast<Bindings::WebEngineCustomData>(relevant_agent.custom_data());
  1358. auto& reactions_stack = custom_data->custom_element_reactions_stack;
  1359. // 1. Invoke custom element reactions in reactionsStack's backup element queue.
  1360. Bindings::invoke_custom_element_reactions(reactions_stack.backup_element_queue);
  1361. // 2. Unset reactionsStack's processing the backup element queue flag.
  1362. reactions_stack.processing_the_backup_element_queue = false;
  1363. });
  1364. return;
  1365. }
  1366. // 3. Otherwise, add element to element's relevant agent's current element queue.
  1367. custom_data->current_element_queue().append(*this);
  1368. }
  1369. // https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-a-custom-element-upgrade-reaction
  1370. void Element::enqueue_a_custom_element_upgrade_reaction(HTML::CustomElementDefinition& custom_element_definition)
  1371. {
  1372. // 1. Add a new upgrade reaction to element's custom element reaction queue, with custom element definition definition.
  1373. m_custom_element_reaction_queue.append(CustomElementUpgradeReaction { .custom_element_definition = custom_element_definition });
  1374. // 2. Enqueue an element on the appropriate element queue given element.
  1375. enqueue_an_element_on_the_appropriate_element_queue();
  1376. }
  1377. void Element::enqueue_a_custom_element_callback_reaction(FlyString const& callback_name, JS::MarkedVector<JS::Value> arguments)
  1378. {
  1379. // 1. Let definition be element's custom element definition.
  1380. auto& definition = m_custom_element_definition;
  1381. // 2. Let callback be the value of the entry in definition's lifecycle callbacks with key callbackName.
  1382. auto callback_iterator = definition->lifecycle_callbacks().find(callback_name);
  1383. // 3. If callback is null, then return.
  1384. if (callback_iterator == definition->lifecycle_callbacks().end())
  1385. return;
  1386. if (callback_iterator->value.is_null())
  1387. return;
  1388. // 4. If callbackName is "attributeChangedCallback", then:
  1389. if (callback_name == HTML::CustomElementReactionNames::attributeChangedCallback) {
  1390. // 1. Let attributeName be the first element of args.
  1391. VERIFY(!arguments.is_empty());
  1392. auto& attribute_name_value = arguments.first();
  1393. VERIFY(attribute_name_value.is_string());
  1394. auto attribute_name = attribute_name_value.as_string().utf8_string();
  1395. // 2. If definition's observed attributes does not contain attributeName, then return.
  1396. if (!definition->observed_attributes().contains_slow(attribute_name))
  1397. return;
  1398. }
  1399. // 5. Add a new callback reaction to element's custom element reaction queue, with callback function callback and arguments args.
  1400. m_custom_element_reaction_queue.append(CustomElementCallbackReaction { .callback = callback_iterator->value, .arguments = move(arguments) });
  1401. // 6. Enqueue an element on the appropriate element queue given element.
  1402. enqueue_an_element_on_the_appropriate_element_queue();
  1403. }
  1404. // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-upgrade-an-element
  1405. JS::ThrowCompletionOr<void> Element::upgrade_element(JS::NonnullGCPtr<HTML::CustomElementDefinition> custom_element_definition)
  1406. {
  1407. auto& realm = this->realm();
  1408. auto& vm = this->vm();
  1409. // 1. If element's custom element state is not "undefined" or "uncustomized", then return.
  1410. if (m_custom_element_state != CustomElementState::Undefined && m_custom_element_state != CustomElementState::Uncustomized)
  1411. return {};
  1412. // 2. Set element's custom element definition to definition.
  1413. m_custom_element_definition = custom_element_definition;
  1414. // 3. Set element's custom element state to "failed".
  1415. m_custom_element_state = CustomElementState::Failed;
  1416. // 4. For each attribute in element's attribute list, in order, enqueue a custom element callback reaction with element, callback name "attributeChangedCallback",
  1417. // and an argument list containing attribute's local name, null, attribute's value, and attribute's namespace.
  1418. for (size_t attribute_index = 0; attribute_index < m_attributes->length(); ++attribute_index) {
  1419. auto const* attribute = m_attributes->item(attribute_index);
  1420. VERIFY(attribute);
  1421. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  1422. arguments.append(JS::PrimitiveString::create(vm, attribute->local_name()));
  1423. arguments.append(JS::js_null());
  1424. arguments.append(JS::PrimitiveString::create(vm, attribute->value()));
  1425. arguments.append(attribute->namespace_uri().has_value() ? JS::PrimitiveString::create(vm, attribute->namespace_uri().value()) : JS::js_null());
  1426. enqueue_a_custom_element_callback_reaction(HTML::CustomElementReactionNames::attributeChangedCallback, move(arguments));
  1427. }
  1428. // 5. If element is connected, then enqueue a custom element callback reaction with element, callback name "connectedCallback", and an empty argument list.
  1429. if (is_connected()) {
  1430. JS::MarkedVector<JS::Value> empty_arguments { vm.heap() };
  1431. enqueue_a_custom_element_callback_reaction(HTML::CustomElementReactionNames::connectedCallback, move(empty_arguments));
  1432. }
  1433. // 6. Add element to the end of definition's construction stack.
  1434. custom_element_definition->construction_stack().append(JS::make_handle(this));
  1435. // 7. Let C be definition's constructor.
  1436. auto& constructor = custom_element_definition->constructor();
  1437. // 8. Run the following substeps while catching any exceptions:
  1438. auto attempt_to_construct_custom_element = [&]() -> JS::ThrowCompletionOr<void> {
  1439. // 1. If definition's disable shadow is true and element's shadow root is non-null, then throw a "NotSupportedError" DOMException.
  1440. if (custom_element_definition->disable_shadow() && shadow_root())
  1441. return JS::throw_completion(WebIDL::NotSupportedError::create(realm, "Custom element definition disables shadow DOM and the custom element has a shadow root"_fly_string));
  1442. // 2. Set element's custom element state to "precustomized".
  1443. m_custom_element_state = CustomElementState::Precustomized;
  1444. // 3. Let constructResult be the result of constructing C, with no arguments.
  1445. auto construct_result_optional = TRY(WebIDL::construct(constructor));
  1446. VERIFY(construct_result_optional.has_value());
  1447. auto construct_result = construct_result_optional.release_value();
  1448. // 4. If SameValue(constructResult, element) is false, then throw a TypeError.
  1449. if (!JS::same_value(construct_result, this))
  1450. return vm.throw_completion<JS::TypeError>("Constructing the custom element returned a different element from the custom element"sv);
  1451. return {};
  1452. };
  1453. auto maybe_exception = attempt_to_construct_custom_element();
  1454. // Then, perform the following substep, regardless of whether the above steps threw an exception or not:
  1455. // 1. Remove the last entry from the end of definition's construction stack.
  1456. (void)custom_element_definition->construction_stack().take_last();
  1457. // Finally, if the above steps threw an exception, then:
  1458. if (maybe_exception.is_throw_completion()) {
  1459. // 1. Set element's custom element definition to null.
  1460. m_custom_element_definition = nullptr;
  1461. // 2. Empty element's custom element reaction queue.
  1462. m_custom_element_reaction_queue.clear();
  1463. // 3. Rethrow the exception (thus terminating this algorithm).
  1464. return maybe_exception.release_error();
  1465. }
  1466. // FIXME: 9. If element is a form-associated custom element, then:
  1467. // 1. Reset the form owner of element. If element is associated with a form element, then enqueue a custom element callback reaction with element, callback name "formAssociatedCallback", and « the associated form ».
  1468. // 2. If element is disabled, then enqueue a custom element callback reaction with element, callback name "formDisabledCallback" and « true ».
  1469. // 10. Set element's custom element state to "custom".
  1470. m_custom_element_state = CustomElementState::Custom;
  1471. return {};
  1472. }
  1473. // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-try-upgrade
  1474. void Element::try_to_upgrade()
  1475. {
  1476. // 1. Let definition be the result of looking up a custom element definition given element's node document, element's namespace, element's local name, and element's is value.
  1477. auto definition = document().lookup_custom_element_definition(namespace_(), local_name(), m_is_value);
  1478. // 2. If definition is not null, then enqueue a custom element upgrade reaction given element and definition.
  1479. if (definition)
  1480. enqueue_a_custom_element_upgrade_reaction(*definition);
  1481. }
  1482. // https://dom.spec.whatwg.org/#concept-element-defined
  1483. bool Element::is_defined() const
  1484. {
  1485. // An element whose custom element state is "uncustomized" or "custom" is said to be defined.
  1486. return m_custom_element_state == CustomElementState::Uncustomized || m_custom_element_state == CustomElementState::Custom;
  1487. }
  1488. // https://dom.spec.whatwg.org/#concept-element-custom
  1489. bool Element::is_custom() const
  1490. {
  1491. // An element whose custom element state is "custom" is said to be custom.
  1492. return m_custom_element_state == CustomElementState::Custom;
  1493. }
  1494. // https://html.spec.whatwg.org/multipage/dom.html#html-element-constructors
  1495. void Element::setup_custom_element_from_constructor(HTML::CustomElementDefinition& custom_element_definition, Optional<String> const& is_value)
  1496. {
  1497. // 7.6. Set element's custom element state to "custom".
  1498. m_custom_element_state = CustomElementState::Custom;
  1499. // 7.7. Set element's custom element definition to definition.
  1500. m_custom_element_definition = custom_element_definition;
  1501. // 7.8. Set element's is value to is value.
  1502. m_is_value = is_value;
  1503. }
  1504. void Element::set_prefix(DeprecatedFlyString const& value)
  1505. {
  1506. m_qualified_name.set_prefix(MUST(FlyString::from_deprecated_fly_string(value)));
  1507. }
  1508. void Element::for_each_attribute(Function<void(DeprecatedFlyString const&, DeprecatedString const&)> callback) const
  1509. {
  1510. for (size_t i = 0; i < m_attributes->length(); ++i) {
  1511. auto const* attribute = m_attributes->item(i);
  1512. callback(attribute->name().to_deprecated_fly_string(), attribute->value().to_deprecated_string());
  1513. }
  1514. }
  1515. Layout::NodeWithStyle* Element::layout_node()
  1516. {
  1517. return static_cast<Layout::NodeWithStyle*>(Node::layout_node());
  1518. }
  1519. Layout::NodeWithStyle const* Element::layout_node() const
  1520. {
  1521. return static_cast<Layout::NodeWithStyle const*>(Node::layout_node());
  1522. }
  1523. bool Element::has_attributes() const
  1524. {
  1525. return !m_attributes->is_empty();
  1526. }
  1527. size_t Element::attribute_list_size() const
  1528. {
  1529. return m_attributes->length();
  1530. }
  1531. void Element::set_computed_css_values(RefPtr<CSS::StyleProperties> style)
  1532. {
  1533. m_computed_css_values = move(style);
  1534. }
  1535. void Element::set_custom_properties(Optional<CSS::Selector::PseudoElement> pseudo_element, HashMap<DeprecatedFlyString, CSS::StyleProperty> custom_properties)
  1536. {
  1537. if (!pseudo_element.has_value()) {
  1538. m_custom_properties = move(custom_properties);
  1539. return;
  1540. }
  1541. m_pseudo_element_custom_properties[to_underlying(pseudo_element.value())] = move(custom_properties);
  1542. }
  1543. HashMap<DeprecatedFlyString, CSS::StyleProperty> const& Element::custom_properties(Optional<CSS::Selector::PseudoElement> pseudo_element) const
  1544. {
  1545. if (!pseudo_element.has_value())
  1546. return m_custom_properties;
  1547. return m_pseudo_element_custom_properties[to_underlying(pseudo_element.value())];
  1548. }
  1549. // https://drafts.csswg.org/cssom-view/#dom-element-scroll
  1550. void Element::scroll(double x, double y)
  1551. {
  1552. // AD-HOC:
  1553. paintable_box()->scroll_by(x, y);
  1554. }
  1555. // https://drafts.csswg.org/cssom-view/#dom-element-scroll
  1556. void Element::scroll(HTML::ScrollToOptions const&)
  1557. {
  1558. dbgln("FIXME: Implement Element::scroll(ScrollToOptions)");
  1559. }
  1560. bool Element::id_reference_exists(DeprecatedString const& id_reference) const
  1561. {
  1562. return document().get_element_by_id(id_reference);
  1563. }
  1564. void Element::register_intersection_observer(Badge<IntersectionObserver::IntersectionObserver>, IntersectionObserver::IntersectionObserverRegistration registration)
  1565. {
  1566. m_registered_intersection_observers.append(move(registration));
  1567. }
  1568. void Element::unregister_intersection_observer(Badge<IntersectionObserver::IntersectionObserver>, JS::NonnullGCPtr<IntersectionObserver::IntersectionObserver> observer)
  1569. {
  1570. m_registered_intersection_observers.remove_first_matching([&observer](IntersectionObserver::IntersectionObserverRegistration const& entry) {
  1571. return entry.observer == observer;
  1572. });
  1573. }
  1574. IntersectionObserver::IntersectionObserverRegistration& Element::get_intersection_observer_registration(Badge<DOM::Document>, IntersectionObserver::IntersectionObserver const& observer)
  1575. {
  1576. auto registration_iterator = m_registered_intersection_observers.find_if([&observer](IntersectionObserver::IntersectionObserverRegistration const& entry) {
  1577. return entry.observer.ptr() == &observer;
  1578. });
  1579. VERIFY(!registration_iterator.is_end());
  1580. return *registration_iterator;
  1581. }
  1582. // https://html.spec.whatwg.org/multipage/dom.html#the-directionality
  1583. Element::Directionality Element::directionality() const
  1584. {
  1585. // The directionality of an element (any element, not just an HTML element) is either 'ltr' or 'rtl',
  1586. // and is determined as per the first appropriate set of steps from the following list:
  1587. auto dir = this->dir();
  1588. // -> If the element's dir attribute is in the ltr state
  1589. // -> If the element is a document element and the dir attribute is not in a defined state
  1590. // (i.e. it is not present or has an invalid value)
  1591. // -> If the element is an input element whose type attribute is in the Telephone state, and the
  1592. // dir attribute is not in a defined state (i.e. it is not present or has an invalid value)
  1593. if (dir == Dir::Ltr
  1594. || (is_document_element() && !dir.has_value())
  1595. || (is<HTML::HTMLInputElement>(this)
  1596. && static_cast<HTML::HTMLInputElement const&>(*this).type_state() == HTML::HTMLInputElement::TypeAttributeState::Telephone
  1597. && !dir.has_value())) {
  1598. // The directionality of the element is 'ltr'.
  1599. return Directionality::Ltr;
  1600. }
  1601. // -> If the element's dir attribute is in the rtl state
  1602. if (dir == Dir::Rtl) {
  1603. // The directionality of the element is 'rtl'.
  1604. return Directionality::Rtl;
  1605. }
  1606. // -> If the element is an input element whose type attribute is in the Text, Search, Telephone,
  1607. // URL, or Email state, and the dir attribute is in the auto state
  1608. // -> If the element is a textarea element and the dir attribute is in the auto state
  1609. if ((is<HTML::HTMLInputElement>(this)
  1610. && first_is_one_of(static_cast<HTML::HTMLInputElement const&>(*this).type_state(),
  1611. HTML::HTMLInputElement::TypeAttributeState::Text, HTML::HTMLInputElement::TypeAttributeState::Search,
  1612. HTML::HTMLInputElement::TypeAttributeState::Telephone, HTML::HTMLInputElement::TypeAttributeState::URL,
  1613. HTML::HTMLInputElement::TypeAttributeState::Email)
  1614. && dir == Dir::Auto)
  1615. || (is<HTML::HTMLTextAreaElement>(this) && dir == Dir::Auto)) {
  1616. auto value = is<HTML::HTMLInputElement>(this)
  1617. ? static_cast<HTML::HTMLInputElement const&>(*this).value()
  1618. : static_cast<HTML::HTMLTextAreaElement const&>(*this).value();
  1619. // If the element's value contains a character of bidirectional character type AL or R, and
  1620. // there is no character of bidirectional character type L anywhere before it in the element's
  1621. // value, then the directionality of the element is 'rtl'. [BIDI]
  1622. for (auto code_point : Utf8View(value)) {
  1623. auto bidi_class = Unicode::bidirectional_class(code_point);
  1624. if (bidi_class == Unicode::BidirectionalClass::L)
  1625. break;
  1626. if (bidi_class == Unicode::BidirectionalClass::AL || bidi_class == Unicode::BidirectionalClass::R)
  1627. return Directionality::Rtl;
  1628. }
  1629. // Otherwise, if the element's value is not the empty string, or if the element is a document element,
  1630. // the directionality of the element is 'ltr'.
  1631. if (!value.is_empty() || is_document_element()) {
  1632. return Directionality::Ltr;
  1633. }
  1634. // Otherwise, the directionality of the element is the same as the element's parent element's directionality.
  1635. else {
  1636. return parent_element()->directionality();
  1637. }
  1638. }
  1639. // -> If the element's dir attribute is in the auto state
  1640. // FIXME: -> If the element is a bdi element and the dir attribute is not in a defined state
  1641. // (i.e. it is not present or has an invalid value)
  1642. if (dir == Dir::Auto) {
  1643. // Find the first character in tree order that matches the following criteria:
  1644. // - The character is from a Text node that is a descendant of the element whose directionality is being determined.
  1645. // - The character is of bidirectional character type L, AL, or R. [BIDI]
  1646. // - The character is not in a Text node that has an ancestor element that is a descendant of
  1647. // the element whose directionality is being determined and that is either:
  1648. // - FIXME: A bdi element.
  1649. // - A script element.
  1650. // - A style element.
  1651. // - A textarea element.
  1652. // - An element with a dir attribute in a defined state.
  1653. Optional<u32> found_character;
  1654. Optional<Unicode::BidirectionalClass> found_character_bidi_class;
  1655. for_each_in_subtree_of_type<Text>([&](Text const& text_node) {
  1656. // Discard not-allowed ancestors
  1657. for (auto* ancestor = text_node.parent(); ancestor && ancestor != this; ancestor = ancestor->parent()) {
  1658. if (is<HTML::HTMLScriptElement>(*ancestor) || is<HTML::HTMLStyleElement>(*ancestor) || is<HTML::HTMLTextAreaElement>(*ancestor))
  1659. return IterationDecision::Continue;
  1660. if (ancestor->is_element()) {
  1661. auto ancestor_element = static_cast<Element const*>(ancestor);
  1662. if (ancestor_element->dir().has_value())
  1663. return IterationDecision::Continue;
  1664. }
  1665. }
  1666. // Look for matching characters
  1667. for (auto code_point : Utf8View(text_node.data())) {
  1668. auto bidi_class = Unicode::bidirectional_class(code_point);
  1669. if (first_is_one_of(bidi_class, Unicode::BidirectionalClass::L, Unicode::BidirectionalClass::AL, Unicode::BidirectionalClass::R)) {
  1670. found_character = code_point;
  1671. found_character_bidi_class = bidi_class;
  1672. return IterationDecision::Break;
  1673. }
  1674. }
  1675. return IterationDecision::Continue;
  1676. });
  1677. // If such a character is found and it is of bidirectional character type AL or R,
  1678. // the directionality of the element is 'rtl'.
  1679. if (found_character.has_value()
  1680. && first_is_one_of(found_character_bidi_class.value(), Unicode::BidirectionalClass::AL, Unicode::BidirectionalClass::R)) {
  1681. return Directionality::Rtl;
  1682. }
  1683. // If such a character is found and it is of bidirectional character type L,
  1684. // the directionality of the element is 'ltr'.
  1685. if (found_character.has_value() && found_character_bidi_class.value() == Unicode::BidirectionalClass::L) {
  1686. return Directionality::Ltr;
  1687. }
  1688. // Otherwise, if the element is a document element, the directionality of the element is 'ltr'.
  1689. else if (is_document_element()) {
  1690. return Directionality::Ltr;
  1691. }
  1692. // Otherwise, the directionality of the element is the same as the element's parent element's directionality.
  1693. else {
  1694. return parent_element()->directionality();
  1695. }
  1696. }
  1697. // If the element has a parent element and the dir attribute is not in a defined state
  1698. // (i.e. it is not present or has an invalid value)
  1699. if (parent_element() && !dir.has_value()) {
  1700. // The directionality of the element is the same as the element's parent element's directionality.
  1701. return parent_element()->directionality();
  1702. }
  1703. VERIFY_NOT_REACHED();
  1704. }
  1705. }