HTMLElement.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <LibJS/Interpreter.h>
  8. #include <LibWeb/ARIA/Roles.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/DOM/IDLEventListener.h>
  11. #include <LibWeb/DOM/ShadowRoot.h>
  12. #include <LibWeb/HTML/BrowsingContext.h>
  13. #include <LibWeb/HTML/BrowsingContextContainer.h>
  14. #include <LibWeb/HTML/DOMStringMap.h>
  15. #include <LibWeb/HTML/EventHandler.h>
  16. #include <LibWeb/HTML/Focus.h>
  17. #include <LibWeb/HTML/HTMLAnchorElement.h>
  18. #include <LibWeb/HTML/HTMLAreaElement.h>
  19. #include <LibWeb/HTML/HTMLBodyElement.h>
  20. #include <LibWeb/HTML/HTMLElement.h>
  21. #include <LibWeb/HTML/VisibilityState.h>
  22. #include <LibWeb/HTML/Window.h>
  23. #include <LibWeb/Layout/Box.h>
  24. #include <LibWeb/Layout/BreakNode.h>
  25. #include <LibWeb/Layout/TextNode.h>
  26. #include <LibWeb/Painting/PaintableBox.h>
  27. #include <LibWeb/UIEvents/EventNames.h>
  28. #include <LibWeb/UIEvents/FocusEvent.h>
  29. #include <LibWeb/UIEvents/MouseEvent.h>
  30. #include <LibWeb/WebIDL/DOMException.h>
  31. #include <LibWeb/WebIDL/ExceptionOr.h>
  32. namespace Web::HTML {
  33. HTMLElement::HTMLElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  34. : Element(document, move(qualified_name))
  35. {
  36. }
  37. HTMLElement::~HTMLElement() = default;
  38. JS::ThrowCompletionOr<void> HTMLElement::initialize(JS::Realm& realm)
  39. {
  40. MUST_OR_THROW_OOM(Base::initialize(realm));
  41. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLElementPrototype>(realm, "HTMLElement"));
  42. m_dataset = DOMStringMap::create(*this);
  43. return {};
  44. }
  45. void HTMLElement::visit_edges(Cell::Visitor& visitor)
  46. {
  47. Base::visit_edges(visitor);
  48. visitor.visit(m_dataset.ptr());
  49. }
  50. // https://html.spec.whatwg.org/multipage/dom.html#dom-dir
  51. DeprecatedString HTMLElement::dir() const
  52. {
  53. auto dir = attribute(HTML::AttributeNames::dir);
  54. #define __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE(keyword) \
  55. if (dir.equals_ignoring_case(#keyword##sv)) \
  56. return #keyword##sv;
  57. ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTES
  58. #undef __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE
  59. return {};
  60. }
  61. void HTMLElement::set_dir(DeprecatedString const& dir)
  62. {
  63. MUST(set_attribute(HTML::AttributeNames::dir, dir));
  64. }
  65. HTMLElement::ContentEditableState HTMLElement::content_editable_state() const
  66. {
  67. auto contenteditable = attribute(HTML::AttributeNames::contenteditable);
  68. // "true", an empty string or a missing value map to the "true" state.
  69. if ((!contenteditable.is_null() && contenteditable.is_empty()) || contenteditable.equals_ignoring_case("true"sv))
  70. return ContentEditableState::True;
  71. // "false" maps to the "false" state.
  72. if (contenteditable.equals_ignoring_case("false"sv))
  73. return ContentEditableState::False;
  74. // Having no such attribute or an invalid value maps to the "inherit" state.
  75. return ContentEditableState::Inherit;
  76. }
  77. bool HTMLElement::is_editable() const
  78. {
  79. switch (content_editable_state()) {
  80. case ContentEditableState::True:
  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. DeprecatedString HTMLElement::content_editable() const
  91. {
  92. switch (content_editable_state()) {
  93. case ContentEditableState::True:
  94. return "true";
  95. case ContentEditableState::False:
  96. return "false";
  97. case ContentEditableState::Inherit:
  98. return "inherit";
  99. default:
  100. VERIFY_NOT_REACHED();
  101. }
  102. }
  103. // https://html.spec.whatwg.org/multipage/interaction.html#contenteditable
  104. WebIDL::ExceptionOr<void> HTMLElement::set_content_editable(DeprecatedString const& content_editable)
  105. {
  106. if (content_editable.equals_ignoring_case("inherit"sv)) {
  107. remove_attribute(HTML::AttributeNames::contenteditable);
  108. return {};
  109. }
  110. if (content_editable.equals_ignoring_case("true"sv)) {
  111. MUST(set_attribute(HTML::AttributeNames::contenteditable, "true"));
  112. return {};
  113. }
  114. if (content_editable.equals_ignoring_case("false"sv)) {
  115. MUST(set_attribute(HTML::AttributeNames::contenteditable, "false"));
  116. return {};
  117. }
  118. return WebIDL::SyntaxError::create(realm(), "Invalid contentEditable value, must be 'true', 'false', or 'inherit'");
  119. }
  120. void HTMLElement::set_inner_text(StringView text)
  121. {
  122. remove_all_children();
  123. MUST(append_child(document().create_text_node(text)));
  124. set_needs_style_update(true);
  125. }
  126. DeprecatedString HTMLElement::inner_text()
  127. {
  128. StringBuilder builder;
  129. // innerText for element being rendered takes visibility into account, so force a layout and then walk the layout tree.
  130. document().update_layout();
  131. if (!layout_node())
  132. return text_content();
  133. Function<void(Layout::Node const&)> recurse = [&](auto& node) {
  134. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  135. if (is<Layout::TextNode>(child))
  136. builder.append(verify_cast<Layout::TextNode>(*child).text_for_rendering());
  137. if (is<Layout::BreakNode>(child))
  138. builder.append('\n');
  139. recurse(*child);
  140. }
  141. };
  142. recurse(*layout_node());
  143. return builder.to_deprecated_string();
  144. }
  145. // // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsettop
  146. int HTMLElement::offset_top() const
  147. {
  148. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  149. const_cast<DOM::Document&>(document()).update_layout();
  150. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  151. return 0;
  152. auto position = layout_node()->box_type_agnostic_position();
  153. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  154. return position.y().value() - parent_position.y().value();
  155. }
  156. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetleft
  157. int HTMLElement::offset_left() const
  158. {
  159. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  160. const_cast<DOM::Document&>(document()).update_layout();
  161. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  162. return 0;
  163. auto position = layout_node()->box_type_agnostic_position();
  164. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  165. return position.x().value() - parent_position.x().value();
  166. }
  167. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth
  168. int HTMLElement::offset_width() const
  169. {
  170. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  171. const_cast<DOM::Document&>(document()).update_layout();
  172. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  173. if (!paint_box())
  174. return 0;
  175. // 2. Return the width of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  176. // ignoring any transforms that apply to the element and its ancestors.
  177. // FIXME: Account for inline boxes.
  178. return paint_box()->border_box_width().value();
  179. }
  180. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetheight
  181. int HTMLElement::offset_height() const
  182. {
  183. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  184. const_cast<DOM::Document&>(document()).update_layout();
  185. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  186. if (!paint_box())
  187. return 0;
  188. // 2. Return the height of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  189. // ignoring any transforms that apply to the element and its ancestors.
  190. // FIXME: Account for inline boxes.
  191. return paint_box()->border_box_height().value();
  192. }
  193. // https://html.spec.whatwg.org/multipage/links.html#cannot-navigate
  194. bool HTMLElement::cannot_navigate() const
  195. {
  196. // An element element cannot navigate if one of the following is true:
  197. // - element's node document is not fully active
  198. if (!document().is_fully_active())
  199. return true;
  200. // - element is not an a element and is not connected.
  201. return !is<HTML::HTMLAnchorElement>(this) && !is_connected();
  202. }
  203. void HTMLElement::parse_attribute(DeprecatedFlyString const& name, DeprecatedString const& value)
  204. {
  205. Element::parse_attribute(name, value);
  206. // 1. If namespace is not null, or localName is not the name of an event handler content attribute on element, then return.
  207. // FIXME: Add the namespace part once we support attribute namespaces.
  208. #undef __ENUMERATE
  209. #define __ENUMERATE(attribute_name, event_name) \
  210. if (name == HTML::AttributeNames::attribute_name) { \
  211. element_event_handler_attribute_changed(event_name, value); \
  212. }
  213. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
  214. #undef __ENUMERATE
  215. }
  216. // https://html.spec.whatwg.org/multipage/interaction.html#dom-focus
  217. void HTMLElement::focus()
  218. {
  219. // 1. If the element is marked as locked for focus, then return.
  220. if (m_locked_for_focus)
  221. return;
  222. // 2. Mark the element as locked for focus.
  223. m_locked_for_focus = true;
  224. // 3. Run the focusing steps for the element.
  225. run_focusing_steps(this);
  226. // FIXME: 4. If the value of the preventScroll dictionary member of options is false,
  227. // then scroll the element into view with scroll behavior "auto",
  228. // block flow direction position set to an implementation-defined value,
  229. // and inline base direction position set to an implementation-defined value.
  230. // 5. Unmark the element as locked for focus.
  231. m_locked_for_focus = false;
  232. }
  233. // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-pointer-event
  234. bool HTMLElement::fire_a_synthetic_pointer_event(DeprecatedFlyString const& type, DOM::Element& target, bool not_trusted)
  235. {
  236. // 1. Let event be the result of creating an event using PointerEvent.
  237. // 2. Initialize event's type attribute to e.
  238. // FIXME: Actually create a PointerEvent!
  239. auto event = UIEvents::MouseEvent::create(realm(), type).release_value_but_fixme_should_propagate_errors();
  240. // 3. Initialize event's bubbles and cancelable attributes to true.
  241. event->set_bubbles(true);
  242. event->set_cancelable(true);
  243. // 4. Set event's composed flag.
  244. event->set_composed(true);
  245. // 5. If the not trusted flag is set, initialize event's isTrusted attribute to false.
  246. if (not_trusted) {
  247. event->set_is_trusted(false);
  248. }
  249. // FIXME: 6. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state
  250. // of the key input device, if any (false for any keys that are not available).
  251. // FIXME: 7. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.
  252. // FIXME: 8. event's getModifierState() method is to return values appropriately describing the current state of the key input device.
  253. // 9. Return the result of dispatching event at target.
  254. return target.dispatch_event(event);
  255. }
  256. // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
  257. void HTMLElement::click()
  258. {
  259. // FIXME: 1. If this element is a form control that is disabled, then return.
  260. // 2. If this element's click in progress flag is set, then return.
  261. if (m_click_in_progress)
  262. return;
  263. // 3. Set this element's click in progress flag.
  264. m_click_in_progress = true;
  265. // FIXME: 4. Fire a synthetic pointer event named click at this element, with the not trusted flag set.
  266. fire_a_synthetic_pointer_event(HTML::EventNames::click, *this, true);
  267. // 5. Unset this element's click in progress flag.
  268. m_click_in_progress = false;
  269. }
  270. // https://html.spec.whatwg.org/multipage/interaction.html#dom-blur
  271. void HTMLElement::blur()
  272. {
  273. // The blur() method, when invoked, should run the unfocusing steps for the element on which the method was called.
  274. run_unfocusing_steps(this);
  275. // User agents may selectively or uniformly ignore calls to this method for usability reasons.
  276. }
  277. Optional<ARIA::Role> HTMLElement::default_role() const
  278. {
  279. // https://www.w3.org/TR/html-aria/#el-article
  280. if (local_name() == TagNames::article)
  281. return ARIA::Role::article;
  282. // https://www.w3.org/TR/html-aria/#el-aside
  283. if (local_name() == TagNames::aside)
  284. return ARIA::Role::complementary;
  285. // https://www.w3.org/TR/html-aria/#el-b
  286. if (local_name() == TagNames::b)
  287. return ARIA::Role::generic;
  288. // https://www.w3.org/TR/html-aria/#el-bdi
  289. if (local_name() == TagNames::bdi)
  290. return ARIA::Role::generic;
  291. // https://www.w3.org/TR/html-aria/#el-bdo
  292. if (local_name() == TagNames::bdo)
  293. return ARIA::Role::generic;
  294. // https://www.w3.org/TR/html-aria/#el-code
  295. if (local_name() == TagNames::code)
  296. return ARIA::Role::code;
  297. // https://www.w3.org/TR/html-aria/#el-dfn
  298. if (local_name() == TagNames::dfn)
  299. return ARIA::Role::term;
  300. // https://www.w3.org/TR/html-aria/#el-em
  301. if (local_name() == TagNames::em)
  302. return ARIA::Role::emphasis;
  303. // https://www.w3.org/TR/html-aria/#el-figure
  304. if (local_name() == TagNames::figure)
  305. return ARIA::Role::figure;
  306. // https://www.w3.org/TR/html-aria/#el-footer
  307. if (local_name() == TagNames::footer) {
  308. // 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
  309. // Otherwise, role=generic
  310. return ARIA::Role::generic;
  311. }
  312. // https://www.w3.org/TR/html-aria/#el-header
  313. if (local_name() == TagNames::header) {
  314. // 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
  315. // Otherwise, role=generic
  316. return ARIA::Role::generic;
  317. }
  318. // https://www.w3.org/TR/html-aria/#el-hgroup
  319. if (local_name() == TagNames::hgroup)
  320. return ARIA::Role::generic;
  321. // https://www.w3.org/TR/html-aria/#el-i
  322. if (local_name() == TagNames::i)
  323. return ARIA::Role::generic;
  324. // https://www.w3.org/TR/html-aria/#el-main
  325. if (local_name() == TagNames::main)
  326. return ARIA::Role::main;
  327. // https://www.w3.org/TR/html-aria/#el-nav
  328. if (local_name() == TagNames::nav)
  329. return ARIA::Role::navigation;
  330. // https://www.w3.org/TR/html-aria/#el-samp
  331. if (local_name() == TagNames::samp)
  332. return ARIA::Role::generic;
  333. // https://www.w3.org/TR/html-aria/#el-section
  334. if (local_name() == TagNames::section) {
  335. // TODO: role=region if the section element has an accessible name
  336. // Otherwise, no corresponding role
  337. return ARIA::Role::region;
  338. }
  339. // https://www.w3.org/TR/html-aria/#el-small
  340. if (local_name() == TagNames::small)
  341. return ARIA::Role::generic;
  342. // https://www.w3.org/TR/html-aria/#el-strong
  343. if (local_name() == TagNames::strong)
  344. return ARIA::Role::strong;
  345. // https://www.w3.org/TR/html-aria/#el-sub
  346. if (local_name() == TagNames::sub)
  347. return ARIA::Role::subscript;
  348. // https://www.w3.org/TR/html-aria/#el-summary
  349. if (local_name() == TagNames::summary)
  350. return ARIA::Role::button;
  351. // https://www.w3.org/TR/html-aria/#el-sup
  352. if (local_name() == TagNames::sup)
  353. return ARIA::Role::superscript;
  354. // https://www.w3.org/TR/html-aria/#el-u
  355. if (local_name() == TagNames::u)
  356. return ARIA::Role::generic;
  357. return {};
  358. }
  359. }