HTMLElement.cpp 41 KB

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