HTMLElement.cpp 11 KB

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