HTMLElement.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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/Document.h>
  9. #include <LibWeb/DOM/IDLEventListener.h>
  10. #include <LibWeb/DOM/ShadowRoot.h>
  11. #include <LibWeb/HTML/BrowsingContext.h>
  12. #include <LibWeb/HTML/BrowsingContextContainer.h>
  13. #include <LibWeb/HTML/DOMStringMap.h>
  14. #include <LibWeb/HTML/EventHandler.h>
  15. #include <LibWeb/HTML/Focus.h>
  16. #include <LibWeb/HTML/HTMLAnchorElement.h>
  17. #include <LibWeb/HTML/HTMLAreaElement.h>
  18. #include <LibWeb/HTML/HTMLBodyElement.h>
  19. #include <LibWeb/HTML/HTMLElement.h>
  20. #include <LibWeb/HTML/VisibilityState.h>
  21. #include <LibWeb/HTML/Window.h>
  22. #include <LibWeb/Layout/Box.h>
  23. #include <LibWeb/Layout/BreakNode.h>
  24. #include <LibWeb/Layout/TextNode.h>
  25. #include <LibWeb/Painting/PaintableBox.h>
  26. #include <LibWeb/UIEvents/EventNames.h>
  27. #include <LibWeb/UIEvents/FocusEvent.h>
  28. #include <LibWeb/UIEvents/MouseEvent.h>
  29. #include <LibWeb/WebIDL/DOMException.h>
  30. #include <LibWeb/WebIDL/ExceptionOr.h>
  31. namespace Web::HTML {
  32. HTMLElement::HTMLElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  33. : Element(document, move(qualified_name))
  34. {
  35. set_prototype(&Bindings::cached_web_prototype(realm(), "HTMLElement"));
  36. }
  37. HTMLElement::~HTMLElement() = default;
  38. void HTMLElement::initialize(JS::Realm& realm)
  39. {
  40. Base::initialize(realm);
  41. m_dataset = DOMStringMap::create(*this);
  42. }
  43. void HTMLElement::visit_edges(Cell::Visitor& visitor)
  44. {
  45. Base::visit_edges(visitor);
  46. visitor.visit(m_dataset.ptr());
  47. }
  48. // https://html.spec.whatwg.org/multipage/dom.html#dom-dir
  49. DeprecatedString HTMLElement::dir() const
  50. {
  51. auto dir = attribute(HTML::AttributeNames::dir);
  52. #define __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE(keyword) \
  53. if (dir.equals_ignoring_case(#keyword##sv)) \
  54. return #keyword##sv;
  55. ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTES
  56. #undef __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE
  57. return {};
  58. }
  59. void HTMLElement::set_dir(DeprecatedString const& dir)
  60. {
  61. MUST(set_attribute(HTML::AttributeNames::dir, dir));
  62. }
  63. HTMLElement::ContentEditableState HTMLElement::content_editable_state() const
  64. {
  65. auto contenteditable = attribute(HTML::AttributeNames::contenteditable);
  66. // "true", an empty string or a missing value map to the "true" state.
  67. if ((!contenteditable.is_null() && contenteditable.is_empty()) || contenteditable.equals_ignoring_case("true"sv))
  68. return ContentEditableState::True;
  69. // "false" maps to the "false" state.
  70. if (contenteditable.equals_ignoring_case("false"sv))
  71. return ContentEditableState::False;
  72. // Having no such attribute or an invalid value maps to the "inherit" state.
  73. return ContentEditableState::Inherit;
  74. }
  75. bool HTMLElement::is_editable() const
  76. {
  77. switch (content_editable_state()) {
  78. case ContentEditableState::True:
  79. return true;
  80. case ContentEditableState::False:
  81. return false;
  82. case ContentEditableState::Inherit:
  83. return parent() && parent()->is_editable();
  84. default:
  85. VERIFY_NOT_REACHED();
  86. }
  87. }
  88. DeprecatedString HTMLElement::content_editable() const
  89. {
  90. switch (content_editable_state()) {
  91. case ContentEditableState::True:
  92. return "true";
  93. case ContentEditableState::False:
  94. return "false";
  95. case ContentEditableState::Inherit:
  96. return "inherit";
  97. default:
  98. VERIFY_NOT_REACHED();
  99. }
  100. }
  101. // https://html.spec.whatwg.org/multipage/interaction.html#contenteditable
  102. WebIDL::ExceptionOr<void> HTMLElement::set_content_editable(DeprecatedString const& content_editable)
  103. {
  104. if (content_editable.equals_ignoring_case("inherit"sv)) {
  105. remove_attribute(HTML::AttributeNames::contenteditable);
  106. return {};
  107. }
  108. if (content_editable.equals_ignoring_case("true"sv)) {
  109. MUST(set_attribute(HTML::AttributeNames::contenteditable, "true"));
  110. return {};
  111. }
  112. if (content_editable.equals_ignoring_case("false"sv)) {
  113. MUST(set_attribute(HTML::AttributeNames::contenteditable, "false"));
  114. return {};
  115. }
  116. return WebIDL::SyntaxError::create(realm(), "Invalid contentEditable value, must be 'true', 'false', or 'inherit'");
  117. }
  118. void HTMLElement::set_inner_text(StringView text)
  119. {
  120. remove_all_children();
  121. MUST(append_child(document().create_text_node(text)));
  122. set_needs_style_update(true);
  123. }
  124. DeprecatedString HTMLElement::inner_text()
  125. {
  126. StringBuilder builder;
  127. // innerText for element being rendered takes visibility into account, so force a layout and then walk the layout tree.
  128. document().update_layout();
  129. if (!layout_node())
  130. return text_content();
  131. Function<void(Layout::Node const&)> recurse = [&](auto& node) {
  132. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  133. if (is<Layout::TextNode>(child))
  134. builder.append(verify_cast<Layout::TextNode>(*child).text_for_rendering());
  135. if (is<Layout::BreakNode>(child))
  136. builder.append('\n');
  137. recurse(*child);
  138. }
  139. };
  140. recurse(*layout_node());
  141. return builder.to_deprecated_string();
  142. }
  143. // // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsettop
  144. int HTMLElement::offset_top() const
  145. {
  146. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  147. const_cast<DOM::Document&>(document()).update_layout();
  148. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  149. return 0;
  150. auto position = layout_node()->box_type_agnostic_position();
  151. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  152. return position.y() - parent_position.y();
  153. }
  154. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetleft
  155. int HTMLElement::offset_left() const
  156. {
  157. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  158. const_cast<DOM::Document&>(document()).update_layout();
  159. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  160. return 0;
  161. auto position = layout_node()->box_type_agnostic_position();
  162. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  163. return position.x() - parent_position.x();
  164. }
  165. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth
  166. int HTMLElement::offset_width() const
  167. {
  168. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  169. const_cast<DOM::Document&>(document()).update_layout();
  170. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  171. if (!paint_box())
  172. return 0;
  173. // 2. Return the width of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  174. // ignoring any transforms that apply to the element and its ancestors.
  175. // FIXME: Account for inline boxes.
  176. return paint_box()->border_box_width().value();
  177. }
  178. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetheight
  179. int HTMLElement::offset_height() const
  180. {
  181. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  182. const_cast<DOM::Document&>(document()).update_layout();
  183. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  184. if (!paint_box())
  185. return 0;
  186. // 2. Return the height of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  187. // ignoring any transforms that apply to the element and its ancestors.
  188. // FIXME: Account for inline boxes.
  189. return paint_box()->border_box_height().value();
  190. }
  191. // https://html.spec.whatwg.org/multipage/links.html#cannot-navigate
  192. bool HTMLElement::cannot_navigate() const
  193. {
  194. // An element element cannot navigate if one of the following is true:
  195. // - element's node document is not fully active
  196. if (!document().is_fully_active())
  197. return true;
  198. // - element is not an a element and is not connected.
  199. return !is<HTML::HTMLAnchorElement>(this) && !is_connected();
  200. }
  201. void HTMLElement::parse_attribute(FlyString const& name, DeprecatedString const& value)
  202. {
  203. Element::parse_attribute(name, value);
  204. // 1. If namespace is not null, or localName is not the name of an event handler content attribute on element, then return.
  205. // FIXME: Add the namespace part once we support attribute namespaces.
  206. #undef __ENUMERATE
  207. #define __ENUMERATE(attribute_name, event_name) \
  208. if (name == HTML::AttributeNames::attribute_name) { \
  209. element_event_handler_attribute_changed(event_name, value); \
  210. }
  211. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
  212. #undef __ENUMERATE
  213. }
  214. // https://html.spec.whatwg.org/multipage/interaction.html#dom-focus
  215. void HTMLElement::focus()
  216. {
  217. // 1. If the element is marked as locked for focus, then return.
  218. if (m_locked_for_focus)
  219. return;
  220. // 2. Mark the element as locked for focus.
  221. m_locked_for_focus = true;
  222. // 3. Run the focusing steps for the element.
  223. run_focusing_steps(this);
  224. // FIXME: 4. If the value of the preventScroll dictionary member of options is false,
  225. // then scroll the element into view with scroll behavior "auto",
  226. // block flow direction position set to an implementation-defined value,
  227. // and inline base direction position set to an implementation-defined value.
  228. // 5. Unmark the element as locked for focus.
  229. m_locked_for_focus = false;
  230. }
  231. // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-pointer-event
  232. bool HTMLElement::fire_a_synthetic_pointer_event(FlyString const& type, DOM::Element& target, bool not_trusted)
  233. {
  234. // 1. Let event be the result of creating an event using PointerEvent.
  235. // 2. Initialize event's type attribute to e.
  236. // FIXME: Actually create a PointerEvent!
  237. auto event = UIEvents::MouseEvent::create(realm(), type);
  238. // 3. Initialize event's bubbles and cancelable attributes to true.
  239. event->set_bubbles(true);
  240. event->set_cancelable(true);
  241. // 4. Set event's composed flag.
  242. event->set_composed(true);
  243. // 5. If the not trusted flag is set, initialize event's isTrusted attribute to false.
  244. if (not_trusted) {
  245. event->set_is_trusted(false);
  246. }
  247. // FIXME: 6. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state
  248. // of the key input device, if any (false for any keys that are not available).
  249. // FIXME: 7. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.
  250. // FIXME: 8. event's getModifierState() method is to return values appropriately describing the current state of the key input device.
  251. // 9. Return the result of dispatching event at target.
  252. return target.dispatch_event(*event);
  253. }
  254. // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
  255. void HTMLElement::click()
  256. {
  257. // FIXME: 1. If this element is a form control that is disabled, then return.
  258. // 2. If this element's click in progress flag is set, then return.
  259. if (m_click_in_progress)
  260. return;
  261. // 3. Set this element's click in progress flag.
  262. m_click_in_progress = true;
  263. // FIXME: 4. Fire a synthetic pointer event named click at this element, with the not trusted flag set.
  264. fire_a_synthetic_pointer_event(HTML::EventNames::click, *this, true);
  265. // 5. Unset this element's click in progress flag.
  266. m_click_in_progress = false;
  267. }
  268. // https://html.spec.whatwg.org/multipage/interaction.html#dom-blur
  269. void HTMLElement::blur()
  270. {
  271. // The blur() method, when invoked, should run the unfocusing steps for the element on which the method was called.
  272. run_unfocusing_steps(this);
  273. // User agents may selectively or uniformly ignore calls to this method for usability reasons.
  274. }
  275. }