HTMLElement.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. /*
  2. * Copyright (c) 2018-2024, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <LibWeb/ARIA/Roles.h>
  8. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  9. #include <LibWeb/Bindings/HTMLElementPrototype.h>
  10. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  11. #include <LibWeb/DOM/Document.h>
  12. #include <LibWeb/DOM/EditingHostManager.h>
  13. #include <LibWeb/DOM/ElementFactory.h>
  14. #include <LibWeb/DOM/IDLEventListener.h>
  15. #include <LibWeb/DOM/LiveNodeList.h>
  16. #include <LibWeb/DOM/Position.h>
  17. #include <LibWeb/DOM/ShadowRoot.h>
  18. #include <LibWeb/HTML/BrowsingContext.h>
  19. #include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
  20. #include <LibWeb/HTML/ElementInternals.h>
  21. #include <LibWeb/HTML/EventHandler.h>
  22. #include <LibWeb/HTML/HTMLAnchorElement.h>
  23. #include <LibWeb/HTML/HTMLBRElement.h>
  24. #include <LibWeb/HTML/HTMLBaseElement.h>
  25. #include <LibWeb/HTML/HTMLBodyElement.h>
  26. #include <LibWeb/HTML/HTMLElement.h>
  27. #include <LibWeb/HTML/HTMLLabelElement.h>
  28. #include <LibWeb/HTML/HTMLParagraphElement.h>
  29. #include <LibWeb/HTML/Window.h>
  30. #include <LibWeb/Infra/CharacterTypes.h>
  31. #include <LibWeb/Infra/Strings.h>
  32. #include <LibWeb/Layout/Box.h>
  33. #include <LibWeb/Layout/TextNode.h>
  34. #include <LibWeb/Namespace.h>
  35. #include <LibWeb/Painting/PaintableBox.h>
  36. #include <LibWeb/UIEvents/EventNames.h>
  37. #include <LibWeb/UIEvents/PointerEvent.h>
  38. #include <LibWeb/WebIDL/DOMException.h>
  39. #include <LibWeb/WebIDL/ExceptionOr.h>
  40. namespace Web::HTML {
  41. GC_DEFINE_ALLOCATOR(HTMLElement);
  42. HTMLElement::HTMLElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  43. : Element(document, move(qualified_name))
  44. {
  45. }
  46. HTMLElement::~HTMLElement() = default;
  47. void HTMLElement::initialize(JS::Realm& realm)
  48. {
  49. Base::initialize(realm);
  50. WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLElement);
  51. }
  52. void HTMLElement::visit_edges(Cell::Visitor& visitor)
  53. {
  54. Base::visit_edges(visitor);
  55. HTMLOrSVGElement::visit_edges(visitor);
  56. visitor.visit(m_labels);
  57. visitor.visit(m_attached_internals);
  58. }
  59. // https://html.spec.whatwg.org/multipage/dom.html#dom-dir
  60. StringView HTMLElement::dir() const
  61. {
  62. // FIXME: This should probably be `Reflect` in the IDL.
  63. // The dir IDL attribute on an element must reflect the dir content attribute of that element, limited to only known values.
  64. auto dir = get_attribute_value(HTML::AttributeNames::dir);
  65. #define __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE(keyword) \
  66. if (dir.equals_ignoring_ascii_case(#keyword##sv)) \
  67. return #keyword##sv;
  68. ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTES
  69. #undef __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE
  70. return {};
  71. }
  72. void HTMLElement::set_dir(String const& dir)
  73. {
  74. MUST(set_attribute(HTML::AttributeNames::dir, dir));
  75. }
  76. bool HTMLElement::is_editable() const
  77. {
  78. switch (m_content_editable_state) {
  79. case ContentEditableState::True:
  80. return true;
  81. case ContentEditableState::False:
  82. return false;
  83. case ContentEditableState::Inherit:
  84. return parent() && parent()->is_editable();
  85. default:
  86. VERIFY_NOT_REACHED();
  87. }
  88. }
  89. bool HTMLElement::is_focusable() const
  90. {
  91. return m_content_editable_state == ContentEditableState::True;
  92. }
  93. // https://html.spec.whatwg.org/multipage/interaction.html#dom-iscontenteditable
  94. bool HTMLElement::is_content_editable() const
  95. {
  96. // The isContentEditable IDL attribute, on getting, must return true if the element is either an editing host or
  97. // editable, and false otherwise.
  98. return is_editable();
  99. }
  100. StringView HTMLElement::content_editable() const
  101. {
  102. switch (m_content_editable_state) {
  103. case ContentEditableState::True:
  104. return "true"sv;
  105. case ContentEditableState::False:
  106. return "false"sv;
  107. case ContentEditableState::Inherit:
  108. return "inherit"sv;
  109. }
  110. VERIFY_NOT_REACHED();
  111. }
  112. // https://html.spec.whatwg.org/multipage/interaction.html#contenteditable
  113. WebIDL::ExceptionOr<void> HTMLElement::set_content_editable(StringView content_editable)
  114. {
  115. if (content_editable.equals_ignoring_ascii_case("inherit"sv)) {
  116. remove_attribute(HTML::AttributeNames::contenteditable);
  117. return {};
  118. }
  119. if (content_editable.equals_ignoring_ascii_case("true"sv)) {
  120. MUST(set_attribute(HTML::AttributeNames::contenteditable, "true"_string));
  121. return {};
  122. }
  123. if (content_editable.equals_ignoring_ascii_case("false"sv)) {
  124. MUST(set_attribute(HTML::AttributeNames::contenteditable, "false"_string));
  125. return {};
  126. }
  127. return WebIDL::SyntaxError::create(realm(), "Invalid contentEditable value, must be 'true', 'false', or 'inherit'"_string);
  128. }
  129. // https://html.spec.whatwg.org/multipage/dom.html#set-the-inner-text-steps
  130. void HTMLElement::set_inner_text(StringView text)
  131. {
  132. // 1. Let fragment be the rendered text fragment for value given element's node document.
  133. auto fragment = rendered_text_fragment(text);
  134. // 2. Replace all with fragment within element.
  135. replace_all(fragment);
  136. set_needs_style_update(true);
  137. }
  138. // https://html.spec.whatwg.org/multipage/dom.html#merge-with-the-next-text-node
  139. static void merge_with_the_next_text_node(DOM::Text& node)
  140. {
  141. // 1. Let next be node's next sibling.
  142. auto next = node.next_sibling();
  143. // 2. If next is not a Text node, then return.
  144. if (!is<DOM::Text>(next))
  145. return;
  146. // 3. Replace data with node, node's data's length, 0, and next's data.
  147. MUST(node.replace_data(node.length_in_utf16_code_units(), 0, static_cast<DOM::Text const&>(*next).data()));
  148. // 4. Remove next.
  149. next->remove();
  150. }
  151. // https://html.spec.whatwg.org/multipage/dom.html#the-innertext-idl-attribute:dom-outertext-2
  152. WebIDL::ExceptionOr<void> HTMLElement::set_outer_text(String const& value)
  153. {
  154. // 1. If this's parent is null, then throw a "NoModificationAllowedError" DOMException.
  155. if (!parent())
  156. return WebIDL::NoModificationAllowedError::create(realm(), "setOuterText: parent is null"_string);
  157. // 2. Let next be this's next sibling.
  158. auto* next = next_sibling();
  159. // 3. Let previous be this's previous sibling.
  160. auto* previous = previous_sibling();
  161. // 4. Let fragment be the rendered text fragment for the given value given this's node document.
  162. auto fragment = rendered_text_fragment(value);
  163. // 5. If fragment has no children, then append a new Text node whose data is the empty string and node document is this's node document to fragment.
  164. if (!fragment->has_children())
  165. MUST(fragment->append_child(document().create_text_node(String {})));
  166. // 6. Replace this with fragment within this's parent.
  167. MUST(parent()->replace_child(fragment, *this));
  168. // 7. If next is non-null and next's previous sibling is a Text node, then merge with the next text node given next's previous sibling.
  169. if (next && is<DOM::Text>(next->previous_sibling()))
  170. merge_with_the_next_text_node(static_cast<DOM::Text&>(*next->previous_sibling()));
  171. // 8. If previous is a Text node, then merge with the next text node given previous.
  172. if (is<DOM::Text>(previous))
  173. merge_with_the_next_text_node(static_cast<DOM::Text&>(*previous));
  174. set_needs_style_update(true);
  175. return {};
  176. }
  177. // https://html.spec.whatwg.org/multipage/dom.html#rendered-text-fragment
  178. GC::Ref<DOM::DocumentFragment> HTMLElement::rendered_text_fragment(StringView input)
  179. {
  180. // 1. Let fragment be a new DocumentFragment whose node document is document.
  181. // Instead of creating a DocumentFragment the nodes are appended directly.
  182. auto fragment = realm().create<DOM::DocumentFragment>(document());
  183. // 2. Let position be a position variable for input, initially pointing at the start of input.
  184. // 3. Let text be the empty string.
  185. // 4. While position is not past the end of input:
  186. while (!input.is_empty()) {
  187. // 1. Collect a sequence of code points that are not U+000A LF or U+000D CR from input given position, and set text to the result.
  188. auto newline_index = input.find_any_of("\n\r"sv);
  189. size_t const sequence_end_index = newline_index.value_or(input.length());
  190. StringView const text = input.substring_view(0, sequence_end_index);
  191. input = input.substring_view_starting_after_substring(text);
  192. // 2. If text is not the empty string, then append a new Text node whose data is text and node document is document to fragment.
  193. if (!text.is_empty()) {
  194. MUST(fragment->append_child(document().create_text_node(MUST(String::from_utf8(text)))));
  195. }
  196. // 3. While position is not past the end of input, and the code point at position is either U+000A LF or U+000D CR:
  197. while (input.starts_with('\n') || input.starts_with('\r')) {
  198. // 1. If the code point at position is U+000D CR and the next code point is U+000A LF, then advance position to the next code point in input.
  199. if (input.starts_with("\r\n"sv)) {
  200. // 2. Advance position to the next code point in input.
  201. input = input.substring_view(2);
  202. } else {
  203. // 2. Advance position to the next code point in input.
  204. input = input.substring_view(1);
  205. }
  206. // 3. Append the result of creating an element given document, br, and the HTML namespace to fragment.
  207. auto br_element = DOM::create_element(document(), HTML::TagNames::br, Namespace::HTML).release_value();
  208. MUST(fragment->append_child(br_element));
  209. }
  210. }
  211. // 5. Return fragment.
  212. return fragment;
  213. }
  214. struct RequiredLineBreakCount {
  215. int count { 0 };
  216. };
  217. // https://html.spec.whatwg.org/multipage/dom.html#rendered-text-collection-steps
  218. static Vector<Variant<String, RequiredLineBreakCount>> rendered_text_collection_steps(DOM::Node const& node)
  219. {
  220. // 1. Let items be the result of running the rendered text collection steps with each child node of node in tree order, and then concatenating the results to a single list.
  221. Vector<Variant<String, RequiredLineBreakCount>> items;
  222. node.for_each_child([&](auto const& child) {
  223. auto child_items = rendered_text_collection_steps(child);
  224. items.extend(move(child_items));
  225. return IterationDecision::Continue;
  226. });
  227. // NOTE: Steps are re-ordered here a bit.
  228. // 3. If node is not being rendered, then return items.
  229. // For the purpose of this step, the following elements must act as described
  230. // if the computed value of the 'display' property is not 'none':
  231. // FIXME: - select elements have an associated non-replaced inline CSS box whose child boxes include only those of optgroup and option element child nodes;
  232. // FIXME: - optgroup elements have an associated non-replaced block-level CSS box whose child boxes include only those of option element child nodes; and
  233. // FIXME: - option element have an associated non-replaced block-level CSS box whose child boxes are as normal for non-replaced block-level CSS boxes.
  234. auto* layout_node = node.layout_node();
  235. if (!layout_node)
  236. return items;
  237. auto const& computed_values = layout_node->computed_values();
  238. // 2. If node's computed value of 'visibility' is not 'visible', then return items.
  239. if (computed_values.visibility() != CSS::Visibility::Visible)
  240. return items;
  241. // AD-HOC: If node's computed value of 'content-visibility' is 'hidden', then return items.
  242. if (computed_values.content_visibility() == CSS::ContentVisibility::Hidden)
  243. return items;
  244. // 4. If node is a Text node, then for each CSS text box produced by node, in content order,
  245. // compute the text of the box after application of the CSS 'white-space' processing rules
  246. // and 'text-transform' rules, set items to the list of the resulting strings, and return items.
  247. // FIXME: The CSS 'white-space' processing rules are slightly modified:
  248. // collapsible spaces at the end of lines are always collapsed,
  249. // but they are only removed if the line is the last line of the block,
  250. // or it ends with a br element. Soft hyphens should be preserved. [CSSTEXT]
  251. if (is<DOM::Text>(node)) {
  252. auto const* layout_text_node = verify_cast<Layout::TextNode>(layout_node);
  253. items.append(layout_text_node->text_for_rendering());
  254. return items;
  255. }
  256. // 5. If node is a br element, then append a string containing a single U+000A LF code point to items.
  257. if (is<HTML::HTMLBRElement>(node)) {
  258. items.append("\n"_string);
  259. return items;
  260. }
  261. auto display = computed_values.display();
  262. // 6. If node's computed value of 'display' is 'table-cell', and node's CSS box is not the last 'table-cell' box of its enclosing 'table-row' box, then append a string containing a single U+0009 TAB code point to items.
  263. if (display.is_table_cell() && node.next_sibling())
  264. items.append("\t"_string);
  265. // 7. If node's computed value of 'display' is 'table-row', and node's CSS box is not the last 'table-row' box of the nearest ancestor 'table' box, then append a string containing a single U+000A LF code point to items.
  266. if (display.is_table_row() && node.next_sibling())
  267. items.append("\n"_string);
  268. // 8. If node is a p element, then append 2 (a required line break count) at the beginning and end of items.
  269. if (is<HTML::HTMLParagraphElement>(node)) {
  270. items.prepend(RequiredLineBreakCount { 2 });
  271. items.append(RequiredLineBreakCount { 2 });
  272. }
  273. // 9. If node's used value of 'display' is block-level or 'table-caption', then append 1 (a required line break count) at the beginning and end of items. [CSSDISPLAY]
  274. if (display.is_block_outside() || display.is_table_caption()) {
  275. items.prepend(RequiredLineBreakCount { 1 });
  276. items.append(RequiredLineBreakCount { 1 });
  277. }
  278. // 10. Return items.
  279. return items;
  280. }
  281. // https://html.spec.whatwg.org/multipage/dom.html#get-the-text-steps
  282. String HTMLElement::get_the_text_steps()
  283. {
  284. // 1. If element is not being rendered or if the user agent is a non-CSS user agent, then return element's descendant text content.
  285. document().update_layout();
  286. if (!layout_node())
  287. return descendant_text_content();
  288. // 2. Let results be a new empty list.
  289. Vector<Variant<String, RequiredLineBreakCount>> results;
  290. // 3. For each child node node of element:
  291. for_each_child([&](Node const& node) {
  292. // 1. Let current be the list resulting in running the rendered text collection steps with node.
  293. // Each item in results will either be a string or a positive integer (a required line break count).
  294. auto current = rendered_text_collection_steps(node);
  295. // 2. For each item item in current, append item to results.
  296. results.extend(move(current));
  297. return IterationDecision::Continue;
  298. });
  299. // 4. Remove any items from results that are the empty string.
  300. results.remove_all_matching([](auto& item) {
  301. return item.visit(
  302. [](String const& string) { return string.is_empty(); },
  303. [](RequiredLineBreakCount const&) { return false; });
  304. });
  305. // 5. Remove any runs of consecutive required line break count items at the start or end of results.
  306. while (!results.is_empty() && results.first().has<RequiredLineBreakCount>())
  307. results.take_first();
  308. while (!results.is_empty() && results.last().has<RequiredLineBreakCount>())
  309. results.take_last();
  310. // 6. Replace each remaining run of consecutive required line break count items
  311. // with a string consisting of as many U+000A LF code points as the maximum of the values
  312. // in the required line break count items.
  313. for (size_t i = 0; i < results.size(); ++i) {
  314. if (!results[i].has<RequiredLineBreakCount>())
  315. continue;
  316. int max_line_breaks = results[i].get<RequiredLineBreakCount>().count;
  317. size_t j = i + 1;
  318. while (j < results.size() && results[j].has<RequiredLineBreakCount>()) {
  319. max_line_breaks = max(max_line_breaks, results[j].get<RequiredLineBreakCount>().count);
  320. ++j;
  321. }
  322. results.remove(i, j - i);
  323. results.insert(i, MUST(String::repeated('\n', max_line_breaks)));
  324. }
  325. // 7. Return the concatenation of the string items in results.
  326. StringBuilder builder;
  327. for (auto& item : results) {
  328. item.visit(
  329. [&](String const& string) { builder.append(string); },
  330. [&](RequiredLineBreakCount const&) {});
  331. }
  332. return builder.to_string_without_validation();
  333. }
  334. // https://html.spec.whatwg.org/multipage/dom.html#dom-innertext
  335. String HTMLElement::inner_text()
  336. {
  337. // The innerText and outerText getter steps are to return the result of running get the text steps with this.
  338. return get_the_text_steps();
  339. }
  340. // https://html.spec.whatwg.org/multipage/dom.html#dom-outertext
  341. String HTMLElement::outer_text()
  342. {
  343. // The innerText and outerText getter steps are to return the result of running get the text steps with this.
  344. return get_the_text_steps();
  345. }
  346. // https://www.w3.org/TR/cssom-view-1/#dom-htmlelement-offsetparent
  347. GC::Ptr<DOM::Element> HTMLElement::offset_parent() const
  348. {
  349. const_cast<DOM::Document&>(document()).update_layout();
  350. // 1. If any of the following holds true return null and terminate this algorithm:
  351. // - The element does not have an associated CSS layout box.
  352. // - The element is the root element.
  353. // - The element is the HTML body element.
  354. // - The element’s computed value of the position property is fixed.
  355. if (!layout_node())
  356. return nullptr;
  357. if (is_document_element())
  358. return nullptr;
  359. if (is<HTML::HTMLBodyElement>(*this))
  360. return nullptr;
  361. if (layout_node()->is_fixed_position())
  362. return nullptr;
  363. // 2. Return the nearest ancestor element of the element for which at least one of the following is true
  364. // and terminate this algorithm if such an ancestor is found:
  365. // - The computed value of the position property is not static.
  366. // - It is the HTML body element.
  367. // - The computed value of the position property of the element is static
  368. // and the ancestor is one of the following HTML elements: td, th, or table.
  369. for (auto* ancestor = parent_element(); ancestor; ancestor = ancestor->parent_element()) {
  370. if (!ancestor->layout_node())
  371. continue;
  372. if (ancestor->layout_node()->is_positioned())
  373. return const_cast<Element*>(ancestor);
  374. if (is<HTML::HTMLBodyElement>(*ancestor))
  375. return const_cast<Element*>(ancestor);
  376. if (!ancestor->layout_node()->is_positioned() && ancestor->local_name().is_one_of(HTML::TagNames::td, HTML::TagNames::th, HTML::TagNames::table))
  377. return const_cast<Element*>(ancestor);
  378. }
  379. // 3. Return null.
  380. return nullptr;
  381. }
  382. // https://www.w3.org/TR/cssom-view-1/#dom-htmlelement-offsettop
  383. int HTMLElement::offset_top() const
  384. {
  385. // 1. If the element is the HTML body element or does not have any associated CSS layout box
  386. // return zero and terminate this algorithm.
  387. if (is<HTML::HTMLBodyElement>(*this))
  388. return 0;
  389. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  390. const_cast<DOM::Document&>(document()).update_layout();
  391. if (!layout_node())
  392. return 0;
  393. CSSPixels top_border_edge_of_element;
  394. if (paintable()->is_paintable_box()) {
  395. top_border_edge_of_element = paintable_box()->absolute_border_box_rect().y();
  396. } else {
  397. top_border_edge_of_element = paintable()->box_type_agnostic_position().y();
  398. }
  399. // 2. If the offsetParent of the element is null
  400. // return the y-coordinate of the top border edge of the first CSS layout box associated with the element,
  401. // relative to the initial containing block origin,
  402. // ignoring any transforms that apply to the element and its ancestors, and terminate this algorithm.
  403. auto offset_parent = this->offset_parent();
  404. if (!offset_parent || !offset_parent->layout_node()) {
  405. return top_border_edge_of_element.to_int();
  406. }
  407. // 3. Return the result of subtracting the y-coordinate of the top padding edge
  408. // of the first box associated with the offsetParent of the element
  409. // from the y-coordinate of the top border edge of the first box associated with the element,
  410. // relative to the initial containing block origin,
  411. // ignoring any transforms that apply to the element and its ancestors.
  412. // NOTE: We give special treatment to the body element to match other browsers.
  413. // Spec bug: https://github.com/w3c/csswg-drafts/issues/10549
  414. CSSPixels top_padding_edge_of_offset_parent;
  415. if (offset_parent->is_html_body_element() && !offset_parent->paintable()->is_positioned()) {
  416. top_padding_edge_of_offset_parent = 0;
  417. } else if (offset_parent->paintable()->is_paintable_box()) {
  418. top_padding_edge_of_offset_parent = offset_parent->paintable_box()->absolute_padding_box_rect().y();
  419. } else {
  420. top_padding_edge_of_offset_parent = offset_parent->paintable()->box_type_agnostic_position().y();
  421. }
  422. return (top_border_edge_of_element - top_padding_edge_of_offset_parent).to_int();
  423. }
  424. // https://www.w3.org/TR/cssom-view-1/#dom-htmlelement-offsetleft
  425. int HTMLElement::offset_left() const
  426. {
  427. // 1. If the element is the HTML body element or does not have any associated CSS layout box return zero and terminate this algorithm.
  428. if (is<HTML::HTMLBodyElement>(*this))
  429. return 0;
  430. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  431. const_cast<DOM::Document&>(document()).update_layout();
  432. if (!layout_node())
  433. return 0;
  434. CSSPixels left_border_edge_of_element;
  435. if (paintable()->is_paintable_box()) {
  436. left_border_edge_of_element = paintable_box()->absolute_border_box_rect().x();
  437. } else {
  438. left_border_edge_of_element = paintable()->box_type_agnostic_position().x();
  439. }
  440. // 2. If the offsetParent of the element is null
  441. // return the x-coordinate of the left border edge of the first CSS layout box associated with the element,
  442. // relative to the initial containing block origin,
  443. // ignoring any transforms that apply to the element and its ancestors, and terminate this algorithm.
  444. auto offset_parent = this->offset_parent();
  445. if (!offset_parent || !offset_parent->layout_node()) {
  446. return left_border_edge_of_element.to_int();
  447. }
  448. // 3. Return the result of subtracting the x-coordinate of the left padding edge
  449. // of the first CSS layout box associated with the offsetParent of the element
  450. // from the x-coordinate of the left border edge of the first CSS layout box associated with the element,
  451. // relative to the initial containing block origin,
  452. // ignoring any transforms that apply to the element and its ancestors.
  453. // NOTE: We give special treatment to the body element to match other browsers.
  454. // Spec bug: https://github.com/w3c/csswg-drafts/issues/10549
  455. CSSPixels left_padding_edge_of_offset_parent;
  456. if (offset_parent->is_html_body_element() && !offset_parent->paintable()->is_positioned()) {
  457. left_padding_edge_of_offset_parent = 0;
  458. } else if (offset_parent->paintable()->is_paintable_box()) {
  459. left_padding_edge_of_offset_parent = offset_parent->paintable_box()->absolute_padding_box_rect().x();
  460. } else {
  461. left_padding_edge_of_offset_parent = offset_parent->paintable()->box_type_agnostic_position().x();
  462. }
  463. return (left_border_edge_of_element - left_padding_edge_of_offset_parent).to_int();
  464. }
  465. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth
  466. int HTMLElement::offset_width() const
  467. {
  468. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  469. const_cast<DOM::Document&>(document()).update_layout();
  470. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  471. if (!paintable_box())
  472. return 0;
  473. // 2. Return the width of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  474. // ignoring any transforms that apply to the element and its ancestors.
  475. // FIXME: Account for inline boxes.
  476. return paintable_box()->border_box_width().to_int();
  477. }
  478. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetheight
  479. int HTMLElement::offset_height() const
  480. {
  481. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  482. const_cast<DOM::Document&>(document()).update_layout();
  483. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  484. if (!paintable_box())
  485. return 0;
  486. // 2. Return the height of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  487. // ignoring any transforms that apply to the element and its ancestors.
  488. // FIXME: Account for inline boxes.
  489. return paintable_box()->border_box_height().to_int();
  490. }
  491. // https://html.spec.whatwg.org/multipage/links.html#cannot-navigate
  492. bool HTMLElement::cannot_navigate() const
  493. {
  494. // An element element cannot navigate if one of the following is true:
  495. // - element's node document is not fully active
  496. if (!document().is_fully_active())
  497. return true;
  498. // - element is not an a element and is not connected.
  499. return !is<HTML::HTMLAnchorElement>(this) && !is_connected();
  500. }
  501. void HTMLElement::attribute_changed(FlyString const& name, Optional<String> const& old_value, Optional<String> const& value, Optional<FlyString> const& namespace_)
  502. {
  503. Base::attribute_changed(name, old_value, value, namespace_);
  504. HTMLOrSVGElement::attribute_changed(name, old_value, value, namespace_);
  505. if (name == HTML::AttributeNames::contenteditable) {
  506. if (!value.has_value()) {
  507. m_content_editable_state = ContentEditableState::Inherit;
  508. } else {
  509. if (value->is_empty() || value->equals_ignoring_ascii_case("true"sv)) {
  510. // "true", an empty string or a missing value map to the "true" state.
  511. m_content_editable_state = ContentEditableState::True;
  512. } else if (value->equals_ignoring_ascii_case("false"sv)) {
  513. // "false" maps to the "false" state.
  514. m_content_editable_state = ContentEditableState::False;
  515. } else {
  516. // Having no such attribute or an invalid value maps to the "inherit" state.
  517. m_content_editable_state = ContentEditableState::Inherit;
  518. }
  519. }
  520. }
  521. // 1. If namespace is not null, or localName is not the name of an event handler content attribute on element, then return.
  522. // FIXME: Add the namespace part once we support attribute namespaces.
  523. #undef __ENUMERATE
  524. #define __ENUMERATE(attribute_name, event_name) \
  525. if (name == HTML::AttributeNames::attribute_name) { \
  526. element_event_handler_attribute_changed(event_name, value); \
  527. }
  528. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
  529. #undef __ENUMERATE
  530. }
  531. WebIDL::ExceptionOr<void> HTMLElement::cloned(Web::DOM::Node& copy, bool clone_children)
  532. {
  533. TRY(Base::cloned(copy, clone_children));
  534. TRY(HTMLOrSVGElement::cloned(copy, clone_children));
  535. return {};
  536. }
  537. void HTMLElement::inserted()
  538. {
  539. Base::inserted();
  540. HTMLOrSVGElement::inserted();
  541. }
  542. // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-pointer-event
  543. bool HTMLElement::fire_a_synthetic_pointer_event(FlyString const& type, DOM::Element& target, bool not_trusted)
  544. {
  545. // 1. Let event be the result of creating an event using PointerEvent.
  546. // 2. Initialize event's type attribute to e.
  547. auto event = UIEvents::PointerEvent::create(realm(), type);
  548. // 3. Initialize event's bubbles and cancelable attributes to true.
  549. event->set_bubbles(true);
  550. event->set_cancelable(true);
  551. // 4. Set event's composed flag.
  552. event->set_composed(true);
  553. // 5. If the not trusted flag is set, initialize event's isTrusted attribute to false.
  554. if (not_trusted) {
  555. event->set_is_trusted(false);
  556. }
  557. // FIXME: 6. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state
  558. // of the key input device, if any (false for any keys that are not available).
  559. // FIXME: 7. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.
  560. // FIXME: 8. event's getModifierState() method is to return values appropriately describing the current state of the key input device.
  561. // 9. Return the result of dispatching event at target.
  562. return target.dispatch_event(event);
  563. }
  564. // https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels-dev
  565. GC::Ptr<DOM::NodeList> HTMLElement::labels()
  566. {
  567. // Labelable elements and all input elements have a live NodeList object associated with them that represents the list of label elements, in tree order,
  568. // whose labeled control is the element in question. The labels IDL attribute of labelable elements that are not form-associated custom elements,
  569. // and the labels IDL attribute of input elements, on getting, must return that NodeList object, and that same value must always be returned,
  570. // unless this element is an input element whose type attribute is in the Hidden state, in which case it must instead return null.
  571. if (!is_labelable())
  572. return {};
  573. if (!m_labels) {
  574. m_labels = DOM::LiveNodeList::create(realm(), root(), DOM::LiveNodeList::Scope::Descendants, [&](auto& node) {
  575. return is<HTMLLabelElement>(node) && verify_cast<HTMLLabelElement>(node).control() == this;
  576. });
  577. }
  578. return m_labels;
  579. }
  580. // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
  581. void HTMLElement::click()
  582. {
  583. // 1. If this element is a form control that is disabled, then return.
  584. if (auto* form_control = dynamic_cast<FormAssociatedElement*>(this)) {
  585. if (!form_control->enabled())
  586. return;
  587. }
  588. // 2. If this element's click in progress flag is set, then return.
  589. if (m_click_in_progress)
  590. return;
  591. // 3. Set this element's click in progress flag.
  592. m_click_in_progress = true;
  593. // 4. Fire a synthetic pointer event named click at this element, with the not trusted flag set.
  594. fire_a_synthetic_pointer_event(HTML::EventNames::click, *this, true);
  595. // 5. Unset this element's click in progress flag.
  596. m_click_in_progress = false;
  597. }
  598. Optional<ARIA::Role> HTMLElement::default_role() const
  599. {
  600. // https://www.w3.org/TR/html-aria/#el-address
  601. if (local_name() == TagNames::address)
  602. return ARIA::Role::group;
  603. // https://www.w3.org/TR/html-aria/#el-article
  604. if (local_name() == TagNames::article)
  605. return ARIA::Role::article;
  606. // https://www.w3.org/TR/html-aria/#el-aside
  607. if (local_name() == TagNames::aside)
  608. return ARIA::Role::complementary;
  609. // https://www.w3.org/TR/html-aria/#el-b
  610. if (local_name() == TagNames::b)
  611. return ARIA::Role::generic;
  612. // https://www.w3.org/TR/html-aria/#el-bdi
  613. if (local_name() == TagNames::bdi)
  614. return ARIA::Role::generic;
  615. // https://www.w3.org/TR/html-aria/#el-bdo
  616. if (local_name() == TagNames::bdo)
  617. return ARIA::Role::generic;
  618. // https://www.w3.org/TR/html-aria/#el-code
  619. if (local_name() == TagNames::code)
  620. return ARIA::Role::code;
  621. // https://www.w3.org/TR/html-aria/#el-dfn
  622. if (local_name() == TagNames::dfn)
  623. return ARIA::Role::term;
  624. // https://www.w3.org/TR/html-aria/#el-em
  625. if (local_name() == TagNames::em)
  626. return ARIA::Role::emphasis;
  627. // https://www.w3.org/TR/html-aria/#el-figure
  628. if (local_name() == TagNames::figure)
  629. return ARIA::Role::figure;
  630. // https://www.w3.org/TR/html-aria/#el-footer
  631. if (local_name() == TagNames::footer) {
  632. // TODO: If not a descendant of an article, aside, main, nav or section element, or an element with role=article, complementary, main, navigation or region then role=contentinfo
  633. // Otherwise, role=generic
  634. return ARIA::Role::generic;
  635. }
  636. // https://www.w3.org/TR/html-aria/#el-header
  637. if (local_name() == TagNames::header) {
  638. // TODO: If not a descendant of an article, aside, main, nav or section element, or an element with role=article, complementary, main, navigation or region then role=banner
  639. // Otherwise, role=generic
  640. return ARIA::Role::generic;
  641. }
  642. // https://www.w3.org/TR/html-aria/#el-hgroup
  643. if (local_name() == TagNames::hgroup)
  644. return ARIA::Role::group;
  645. // https://www.w3.org/TR/html-aria/#el-i
  646. if (local_name() == TagNames::i)
  647. return ARIA::Role::generic;
  648. // https://www.w3.org/TR/html-aria/#el-main
  649. if (local_name() == TagNames::main)
  650. return ARIA::Role::main;
  651. // https://www.w3.org/TR/html-aria/#el-nav
  652. if (local_name() == TagNames::nav)
  653. return ARIA::Role::navigation;
  654. // https://www.w3.org/TR/html-aria/#el-s
  655. if (local_name() == TagNames::s)
  656. return ARIA::Role::deletion;
  657. // https://www.w3.org/TR/html-aria/#el-samp
  658. if (local_name() == TagNames::samp)
  659. return ARIA::Role::generic;
  660. // https://www.w3.org/TR/html-aria/#el-search
  661. if (local_name() == TagNames::search)
  662. return ARIA::Role::search;
  663. // https://www.w3.org/TR/html-aria/#el-section
  664. if (local_name() == TagNames::section) {
  665. // TODO: role=region if the section element has an accessible name
  666. // Otherwise, no corresponding role
  667. return ARIA::Role::region;
  668. }
  669. // https://www.w3.org/TR/html-aria/#el-small
  670. if (local_name() == TagNames::small)
  671. return ARIA::Role::generic;
  672. // https://www.w3.org/TR/html-aria/#el-strong
  673. if (local_name() == TagNames::strong)
  674. return ARIA::Role::strong;
  675. // https://www.w3.org/TR/html-aria/#el-sub
  676. if (local_name() == TagNames::sub)
  677. return ARIA::Role::subscript;
  678. // https://www.w3.org/TR/html-aria/#el-summary
  679. if (local_name() == TagNames::summary)
  680. return ARIA::Role::button;
  681. // https://www.w3.org/TR/html-aria/#el-sup
  682. if (local_name() == TagNames::sup)
  683. return ARIA::Role::superscript;
  684. // https://www.w3.org/TR/html-aria/#el-u
  685. if (local_name() == TagNames::u)
  686. return ARIA::Role::generic;
  687. return {};
  688. }
  689. // https://html.spec.whatwg.org/multipage/semantics.html#get-an-element's-target
  690. String HTMLElement::get_an_elements_target() const
  691. {
  692. // To get an element's target, given an a, area, or form element element, run these steps:
  693. // 1. If element has a target attribute, then return that attribute's value.
  694. auto maybe_target = attribute(AttributeNames::target);
  695. if (maybe_target.has_value())
  696. return maybe_target.release_value();
  697. // FIXME: 2. If element's node document contains a base element with a
  698. // target attribute, then return the value of the target attribute of the
  699. // first such base element.
  700. // 3. Return the empty string.
  701. return String {};
  702. }
  703. // https://html.spec.whatwg.org/multipage/links.html#get-an-element's-noopener
  704. TokenizedFeature::NoOpener HTMLElement::get_an_elements_noopener(StringView target) const
  705. {
  706. // To get an element's noopener, given an a, area, or form element element and a string target:
  707. auto rel = MUST(get_attribute_value(HTML::AttributeNames::rel).to_lowercase());
  708. auto link_types = rel.bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
  709. // 1. If element's link types include the noopener or noreferrer keyword, then return true.
  710. if (link_types.contains_slow("noopener"sv) || link_types.contains_slow("noreferrer"sv))
  711. return TokenizedFeature::NoOpener::Yes;
  712. // 2. If element's link types do not include the opener keyword and
  713. // target is an ASCII case-insensitive match for "_blank", then return true.
  714. if (!link_types.contains_slow("opener"sv) && Infra::is_ascii_case_insensitive_match(target, "_blank"sv))
  715. return TokenizedFeature::NoOpener::Yes;
  716. // 3. Return false.
  717. return TokenizedFeature::NoOpener::No;
  718. }
  719. WebIDL::ExceptionOr<GC::Ref<ElementInternals>> HTMLElement::attach_internals()
  720. {
  721. // 1. If this's is value is not null, then throw a "NotSupportedError" DOMException.
  722. if (is_value().has_value())
  723. return WebIDL::NotSupportedError::create(realm(), "ElementInternals cannot be attached to a customized build-in element"_string);
  724. // 2. Let definition be the result of looking up a custom element definition given this's node document, its namespace, its local name, and null as the is value.
  725. auto definition = document().lookup_custom_element_definition(namespace_uri(), local_name(), is_value());
  726. // 3. If definition is null, then throw an "NotSupportedError" DOMException.
  727. if (!definition)
  728. return WebIDL::NotSupportedError::create(realm(), "ElementInternals cannot be attached to an element that is not a custom element"_string);
  729. // 4. If definition's disable internals is true, then throw a "NotSupportedError" DOMException.
  730. if (definition->disable_internals())
  731. return WebIDL::NotSupportedError::create(realm(), "ElementInternals are disabled for this custom element"_string);
  732. // 5. If this's attached internals is non-null, then throw an "NotSupportedError" DOMException.
  733. if (m_attached_internals)
  734. return WebIDL::NotSupportedError::create(realm(), "ElementInternals already attached"_string);
  735. // 6. If this's custom element state is not "precustomized" or "custom", then throw a "NotSupportedError" DOMException.
  736. if (!first_is_one_of(custom_element_state(), DOM::CustomElementState::Precustomized, DOM::CustomElementState::Custom))
  737. return WebIDL::NotSupportedError::create(realm(), "Custom element is in an invalid state to attach ElementInternals"_string);
  738. // 7. Set this's attached internals to a new ElementInternals instance whose target element is this.
  739. auto internals = ElementInternals::create(realm(), *this);
  740. m_attached_internals = internals;
  741. // 8. Return this's attached internals.
  742. return { internals };
  743. }
  744. // https://html.spec.whatwg.org/multipage/popover.html#dom-popover
  745. Optional<String> HTMLElement::popover() const
  746. {
  747. // FIXME: This should probably be `Reflect` in the IDL.
  748. // The popover IDL attribute must reflect the popover attribute, limited to only known values.
  749. auto value = get_attribute(HTML::AttributeNames::popover);
  750. if (!value.has_value())
  751. return {};
  752. if (value.value().is_empty() || value.value().equals_ignoring_ascii_case("auto"sv))
  753. return "auto"_string;
  754. return "manual"_string;
  755. }
  756. // https://html.spec.whatwg.org/multipage/popover.html#dom-popover
  757. WebIDL::ExceptionOr<void> HTMLElement::set_popover(Optional<String> value)
  758. {
  759. // FIXME: This should probably be `Reflect` in the IDL.
  760. // The popover IDL attribute must reflect the popover attribute, limited to only known values.
  761. if (value.has_value())
  762. return set_attribute(HTML::AttributeNames::popover, value.release_value());
  763. remove_attribute(HTML::AttributeNames::popover);
  764. return {};
  765. }
  766. void HTMLElement::adjust_computed_style(CSS::StyleProperties& style)
  767. {
  768. // https://drafts.csswg.org/css-display-3/#unbox
  769. if (local_name() == HTML::TagNames::wbr) {
  770. if (style.display().is_contents())
  771. style.set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::None)));
  772. }
  773. }
  774. void HTMLElement::did_receive_focus()
  775. {
  776. if (m_content_editable_state != ContentEditableState::True)
  777. return;
  778. auto editing_host = document().editing_host_manager();
  779. editing_host->set_active_contenteditable_element(this);
  780. DOM::Text* text = nullptr;
  781. for_each_in_inclusive_subtree_of_type<DOM::Text>([&](auto& node) {
  782. text = &node;
  783. return TraversalDecision::Continue;
  784. });
  785. if (!text) {
  786. editing_host->set_selection_anchor(*this, 0);
  787. return;
  788. }
  789. editing_host->set_selection_anchor(*text, text->length());
  790. }
  791. void HTMLElement::did_lose_focus()
  792. {
  793. if (m_content_editable_state != ContentEditableState::True)
  794. return;
  795. document().editing_host_manager()->set_active_contenteditable_element(nullptr);
  796. }
  797. // https://html.spec.whatwg.org/multipage/interaction.html#dom-accesskeylabel
  798. String HTMLElement::access_key_label() const
  799. {
  800. dbgln("FIXME: Implement HTMLElement::access_key_label()");
  801. return String {};
  802. }
  803. }