HTMLElement.cpp 16 KB

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