HTMLElement.cpp 38 KB

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