HTMLElement.cpp 16 KB

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