HTMLElement.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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/DOMException.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/DOM/ExceptionOr.h>
  12. #include <LibWeb/DOM/IDLEventListener.h>
  13. #include <LibWeb/HTML/BrowsingContext.h>
  14. #include <LibWeb/HTML/BrowsingContextContainer.h>
  15. #include <LibWeb/HTML/EventHandler.h>
  16. #include <LibWeb/HTML/HTMLAnchorElement.h>
  17. #include <LibWeb/HTML/HTMLBodyElement.h>
  18. #include <LibWeb/HTML/HTMLElement.h>
  19. #include <LibWeb/HTML/Window.h>
  20. #include <LibWeb/Layout/Box.h>
  21. #include <LibWeb/Layout/BreakNode.h>
  22. #include <LibWeb/Layout/TextNode.h>
  23. #include <LibWeb/Painting/PaintableBox.h>
  24. #include <LibWeb/UIEvents/EventNames.h>
  25. #include <LibWeb/UIEvents/FocusEvent.h>
  26. #include <LibWeb/UIEvents/MouseEvent.h>
  27. namespace Web::HTML {
  28. HTMLElement::HTMLElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  29. : Element(document, move(qualified_name))
  30. , m_dataset(DOMStringMap::create(*this))
  31. {
  32. }
  33. HTMLElement::~HTMLElement() = default;
  34. HTMLElement::ContentEditableState HTMLElement::content_editable_state() const
  35. {
  36. auto contenteditable = attribute(HTML::AttributeNames::contenteditable);
  37. // "true", an empty string or a missing value map to the "true" state.
  38. if ((!contenteditable.is_null() && contenteditable.is_empty()) || contenteditable.equals_ignoring_case("true"))
  39. return ContentEditableState::True;
  40. // "false" maps to the "false" state.
  41. if (contenteditable.equals_ignoring_case("false"))
  42. return ContentEditableState::False;
  43. // Having no such attribute or an invalid value maps to the "inherit" state.
  44. return ContentEditableState::Inherit;
  45. }
  46. bool HTMLElement::is_editable() const
  47. {
  48. switch (content_editable_state()) {
  49. case ContentEditableState::True:
  50. return true;
  51. case ContentEditableState::False:
  52. return false;
  53. case ContentEditableState::Inherit:
  54. return parent() && parent()->is_editable();
  55. default:
  56. VERIFY_NOT_REACHED();
  57. }
  58. }
  59. String HTMLElement::content_editable() const
  60. {
  61. switch (content_editable_state()) {
  62. case ContentEditableState::True:
  63. return "true";
  64. case ContentEditableState::False:
  65. return "false";
  66. case ContentEditableState::Inherit:
  67. return "inherit";
  68. default:
  69. VERIFY_NOT_REACHED();
  70. }
  71. }
  72. // https://html.spec.whatwg.org/multipage/interaction.html#contenteditable
  73. DOM::ExceptionOr<void> HTMLElement::set_content_editable(const String& content_editable)
  74. {
  75. if (content_editable.equals_ignoring_case("inherit")) {
  76. remove_attribute(HTML::AttributeNames::contenteditable);
  77. return {};
  78. }
  79. if (content_editable.equals_ignoring_case("true")) {
  80. set_attribute(HTML::AttributeNames::contenteditable, "true");
  81. return {};
  82. }
  83. if (content_editable.equals_ignoring_case("false")) {
  84. set_attribute(HTML::AttributeNames::contenteditable, "false");
  85. return {};
  86. }
  87. return DOM::SyntaxError::create("Invalid contentEditable value, must be 'true', 'false', or 'inherit'");
  88. }
  89. void HTMLElement::set_inner_text(StringView text)
  90. {
  91. remove_all_children();
  92. append_child(document().create_text_node(text));
  93. set_needs_style_update(true);
  94. }
  95. String HTMLElement::inner_text()
  96. {
  97. StringBuilder builder;
  98. // innerText for element being rendered takes visibility into account, so force a layout and then walk the layout tree.
  99. document().update_layout();
  100. if (!layout_node())
  101. return text_content();
  102. Function<void(const Layout::Node&)> recurse = [&](auto& node) {
  103. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  104. if (is<Layout::TextNode>(child))
  105. builder.append(verify_cast<Layout::TextNode>(*child).text_for_rendering());
  106. if (is<Layout::BreakNode>(child))
  107. builder.append('\n');
  108. recurse(*child);
  109. }
  110. };
  111. recurse(*layout_node());
  112. return builder.to_string();
  113. }
  114. // // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsettop
  115. int HTMLElement::offset_top() const
  116. {
  117. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  118. return 0;
  119. auto position = layout_node()->box_type_agnostic_position();
  120. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  121. return position.y() - parent_position.y();
  122. }
  123. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetleft
  124. int HTMLElement::offset_left() const
  125. {
  126. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  127. return 0;
  128. auto position = layout_node()->box_type_agnostic_position();
  129. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  130. return position.x() - parent_position.x();
  131. }
  132. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth
  133. int HTMLElement::offset_width() const
  134. {
  135. if (auto* paint_box = this->paint_box())
  136. return paint_box->border_box_width();
  137. return 0;
  138. }
  139. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetheight
  140. int HTMLElement::offset_height() const
  141. {
  142. if (auto* paint_box = this->paint_box())
  143. return paint_box->border_box_height();
  144. return 0;
  145. }
  146. bool HTMLElement::cannot_navigate() const
  147. {
  148. // FIXME: Return true if element's node document is not fully active
  149. return !is<HTML::HTMLAnchorElement>(this) && !is_connected();
  150. }
  151. void HTMLElement::parse_attribute(const FlyString& name, const String& value)
  152. {
  153. Element::parse_attribute(name, value);
  154. // 1. If namespace is not null, or localName is not the name of an event handler content attribute on element, then return.
  155. // FIXME: Add the namespace part once we support attribute namespaces.
  156. #undef __ENUMERATE
  157. #define __ENUMERATE(attribute_name, event_name) \
  158. if (name == HTML::AttributeNames::attribute_name) { \
  159. element_event_handler_attribute_changed(event_name, value); \
  160. }
  161. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
  162. #undef __ENUMERATE
  163. }
  164. // https://html.spec.whatwg.org/multipage/interaction.html#focus-update-steps
  165. static void run_focus_update_steps(NonnullRefPtrVector<DOM::Node> old_chain, NonnullRefPtrVector<DOM::Node> new_chain, DOM::Node& new_focus_target)
  166. {
  167. // 1. If the last entry in old chain and the last entry in new chain are the same,
  168. // pop the last entry from old chain and the last entry from new chain and redo this step.
  169. while (!old_chain.is_empty()
  170. && !new_chain.is_empty()
  171. && &old_chain.last() == &new_chain.last()) {
  172. (void)old_chain.take_last();
  173. (void)new_chain.take_last();
  174. }
  175. // 2. For each entry entry in old chain, in order, run these substeps:
  176. for (auto& entry : old_chain) {
  177. // FIXME: 1. If entry is an input element, and the change event applies to the element,
  178. // and the element does not have a defined activation behavior,
  179. // and the user has changed the element's value or its list of selected files
  180. // while the control was focused without committing that change
  181. // (such that it is different to what it was when the control was first focused),
  182. // then fire an event named change at the element,
  183. // with the bubbles attribute initialized to true.
  184. RefPtr<DOM::EventTarget> blur_event_target;
  185. if (is<DOM::Element>(entry)) {
  186. // 2. If entry is an element, let blur event target be entry.
  187. blur_event_target = entry;
  188. } else if (is<DOM::Document>(entry)) {
  189. // If entry is a Document object, let blur event target be that Document object's relevant global object.
  190. blur_event_target = static_cast<DOM::Document&>(entry).window();
  191. }
  192. // 3. If entry is the last entry in old chain, and entry is an Element,
  193. // and the last entry in new chain is also an Element,
  194. // then let related blur target be the last entry in new chain.
  195. // Otherwise, let related blur target be null.
  196. RefPtr<DOM::EventTarget> related_blur_target;
  197. if (!old_chain.is_empty()
  198. && &entry == &old_chain.last()
  199. && is<DOM::Element>(entry)
  200. && !new_chain.is_empty()
  201. && is<DOM::Element>(new_chain.last())) {
  202. related_blur_target = new_chain.last();
  203. }
  204. // 4. If blur event target is not null, fire a focus event named blur at blur event target,
  205. // with related blur target as the related target.
  206. if (blur_event_target) {
  207. // FIXME: Implement the "fire a focus event" spec operation.
  208. auto blur_event = UIEvents::FocusEvent::create(HTML::EventNames::blur);
  209. blur_event->set_related_target(related_blur_target);
  210. blur_event_target->dispatch_event(move(blur_event));
  211. }
  212. }
  213. // FIXME: 3. Apply any relevant platform-specific conventions for focusing new focus target.
  214. // (For example, some platforms select the contents of a text control when that control is focused.)
  215. (void)new_focus_target;
  216. // 4. For each entry entry in new chain, in reverse order, run these substeps:
  217. for (auto& entry : new_chain.in_reverse()) {
  218. // 1. If entry is a focusable area: designate entry as the focused area of the document.
  219. // FIXME: This isn't entirely right.
  220. if (is<DOM::Element>(entry))
  221. entry.document().set_focused_element(&static_cast<DOM::Element&>(entry));
  222. RefPtr<DOM::EventTarget> focus_event_target;
  223. if (is<DOM::Element>(entry)) {
  224. // 2. If entry is an element, let focus event target be entry.
  225. focus_event_target = entry;
  226. } else if (is<DOM::Document>(entry)) {
  227. // If entry is a Document object, let focus event target be that Document object's relevant global object.
  228. focus_event_target = static_cast<DOM::Document&>(entry).window();
  229. }
  230. // 3. If entry is the last entry in new chain, and entry is an Element,
  231. // and the last entry in old chain is also an Element,
  232. // then let related focus target be the last entry in old chain.
  233. // Otherwise, let related focus target be null.
  234. RefPtr<DOM::EventTarget> related_focus_target;
  235. if (!new_chain.is_empty()
  236. && &entry == &new_chain.last()
  237. && is<DOM::Element>(entry)
  238. && !old_chain.is_empty()
  239. && is<DOM::Element>(old_chain.last())) {
  240. related_focus_target = old_chain.last();
  241. }
  242. // 4. If focus event target is not null, fire a focus event named focus at focus event target,
  243. // with related focus target as the related target.
  244. if (focus_event_target) {
  245. // FIXME: Implement the "fire a focus event" spec operation.
  246. auto focus_event = UIEvents::FocusEvent::create(HTML::EventNames::focus);
  247. focus_event->set_related_target(related_focus_target);
  248. focus_event_target->dispatch_event(move(focus_event));
  249. }
  250. }
  251. }
  252. // https://html.spec.whatwg.org/multipage/interaction.html#focus-chain
  253. static NonnullRefPtrVector<DOM::Node> focus_chain(DOM::Node* subject)
  254. {
  255. // FIXME: Move this somewhere more spec-friendly.
  256. if (!subject)
  257. return {};
  258. // 1. Let output be an empty list.
  259. NonnullRefPtrVector<DOM::Node> output;
  260. // 2. Let currentObject be subject.
  261. auto* current_object = subject;
  262. // 3. While true:
  263. while (true) {
  264. // 1. Append currentObject to output.
  265. output.append(*current_object);
  266. // FIXME: 2. If currentObject is an area element's shape, then append that area element to output.
  267. // FIXME: Otherwise, if currentObject's DOM anchor is an element that is not currentObject itself, then append currentObject's DOM anchor to output.
  268. // FIXME: Everything below needs work. The conditions are not entirely right.
  269. if (!is<DOM::Document>(*current_object)) {
  270. // 3. If currentObject is a focusable area, then set currentObject to currentObject's DOM anchor's node document.
  271. current_object = &current_object->document();
  272. } else if (is<DOM::Document>(*current_object)
  273. && static_cast<DOM::Document&>(*current_object).browsing_context()
  274. && !static_cast<DOM::Document&>(*current_object).browsing_context()->is_top_level()) {
  275. // Otherwise, if currentObject is a Document whose browsing context is a child browsing context,
  276. // then set currentObject to currentObject's browsing context's container.
  277. current_object = static_cast<DOM::Document&>(*current_object).browsing_context()->container();
  278. } else {
  279. break;
  280. }
  281. }
  282. // 4. Return output.
  283. return output;
  284. }
  285. // https://html.spec.whatwg.org/multipage/interaction.html#focusing-steps
  286. // FIXME: This should accept more types.
  287. static void run_focusing_steps(DOM::Node* new_focus_target, DOM::Node* fallback_target = nullptr, [[maybe_unused]] Optional<String> focus_trigger = {})
  288. {
  289. // FIXME: 1. If new focus target is not a focusable area, then set new focus target
  290. // to the result of getting the focusable area for new focus target,
  291. // given focus trigger if it was passed.
  292. // 2. If new focus target is null, then:
  293. if (!new_focus_target) {
  294. // 1. If no fallback target was specified, then return.
  295. if (!fallback_target)
  296. return;
  297. // 2. Otherwise, set new focus target to the fallback target.
  298. new_focus_target = fallback_target;
  299. }
  300. // 3. If new focus target is a browsing context container with non-null nested browsing context,
  301. // then set new focus target to the nested browsing context's active document.
  302. if (is<BrowsingContextContainer>(*new_focus_target)) {
  303. auto& browsing_context_container = static_cast<BrowsingContextContainer&>(*new_focus_target);
  304. if (auto* nested_browsing_context = browsing_context_container.nested_browsing_context())
  305. new_focus_target = nested_browsing_context->active_document();
  306. }
  307. // FIXME: 4. If new focus target is a focusable area and its DOM anchor is inert, then return.
  308. // 5. If new focus target is the currently focused area of a top-level browsing context, then return.
  309. if (!new_focus_target->document().browsing_context())
  310. return;
  311. auto& top_level_browsing_context = new_focus_target->document().browsing_context()->top_level_browsing_context();
  312. if (new_focus_target == top_level_browsing_context.currently_focused_area())
  313. return;
  314. // 6. Let old chain be the current focus chain of the top-level browsing context in which
  315. // new focus target finds itself.
  316. auto old_chain = focus_chain(top_level_browsing_context.currently_focused_area());
  317. // 7. Let new chain be the focus chain of new focus target.
  318. auto new_chain = focus_chain(new_focus_target);
  319. run_focus_update_steps(old_chain, new_chain, *new_focus_target);
  320. }
  321. // https://html.spec.whatwg.org/multipage/interaction.html#dom-focus
  322. void HTMLElement::focus()
  323. {
  324. // 1. If the element is marked as locked for focus, then return.
  325. if (m_locked_for_focus)
  326. return;
  327. // 2. Mark the element as locked for focus.
  328. m_locked_for_focus = true;
  329. // 3. Run the focusing steps for the element.
  330. run_focusing_steps(this);
  331. // FIXME: 4. If the value of the preventScroll dictionary member of options is false,
  332. // then scroll the element into view with scroll behavior "auto",
  333. // block flow direction position set to an implementation-defined value,
  334. // and inline base direction position set to an implementation-defined value.
  335. // 5. Unmark the element as locked for focus.
  336. m_locked_for_focus = false;
  337. }
  338. // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-pointer-event
  339. bool HTMLElement::fire_a_synthetic_pointer_event(FlyString const& type, DOM::Element& target, bool not_trusted)
  340. {
  341. // 1. Let event be the result of creating an event using PointerEvent.
  342. // 2. Initialize event's type attribute to e.
  343. // FIXME: Actually create a PointerEvent!
  344. auto event = UIEvents::MouseEvent::create(type, 0.0, 0.0, 0.0, 0.0);
  345. // 3. Initialize event's bubbles and cancelable attributes to true.
  346. event->set_bubbles(true);
  347. event->set_cancelable(true);
  348. // 4. Set event's composed flag.
  349. event->set_composed(true);
  350. // 5. If the not trusted flag is set, initialize event's isTrusted attribute to false.
  351. if (not_trusted) {
  352. event->set_is_trusted(false);
  353. }
  354. // FIXME: 6. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state
  355. // of the key input device, if any (false for any keys that are not available).
  356. // FIXME: 7. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.
  357. // FIXME: 8. event's getModifierState() method is to return values appropriately describing the current state of the key input device.
  358. // 9. Return the result of dispatching event at target.
  359. return target.dispatch_event(move(event));
  360. }
  361. // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
  362. void HTMLElement::click()
  363. {
  364. // FIXME: 1. If this element is a form control that is disabled, then return.
  365. // 2. If this element's click in progress flag is set, then return.
  366. if (m_click_in_progress)
  367. return;
  368. // 3. Set this element's click in progress flag.
  369. m_click_in_progress = true;
  370. // FIXME: 4. Fire a synthetic pointer event named click at this element, with the not trusted flag set.
  371. fire_a_synthetic_pointer_event(HTML::EventNames::click, *this, true);
  372. // 5. Unset this element's click in progress flag.
  373. m_click_in_progress = false;
  374. }
  375. }