HTMLElement.cpp 16 KB

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