HTMLElement.cpp 20 KB

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