HTMLElement.cpp 38 KB

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