Element.cpp 109 KB

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