Element.cpp 107 KB

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