HTMLElement.cpp 32 KB

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