HTMLElement.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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/HTMLBaseElement.h>
  20. #include <LibWeb/HTML/HTMLBodyElement.h>
  21. #include <LibWeb/HTML/HTMLElement.h>
  22. #include <LibWeb/HTML/NavigableContainer.h>
  23. #include <LibWeb/HTML/VisibilityState.h>
  24. #include <LibWeb/HTML/Window.h>
  25. #include <LibWeb/Infra/CharacterTypes.h>
  26. #include <LibWeb/Infra/Strings.h>
  27. #include <LibWeb/Layout/Box.h>
  28. #include <LibWeb/Layout/BreakNode.h>
  29. #include <LibWeb/Layout/TextNode.h>
  30. #include <LibWeb/Painting/PaintableBox.h>
  31. #include <LibWeb/UIEvents/EventNames.h>
  32. #include <LibWeb/UIEvents/FocusEvent.h>
  33. #include <LibWeb/UIEvents/MouseEvent.h>
  34. #include <LibWeb/WebIDL/DOMException.h>
  35. #include <LibWeb/WebIDL/ExceptionOr.h>
  36. namespace Web::HTML {
  37. HTMLElement::HTMLElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  38. : Element(document, move(qualified_name))
  39. {
  40. }
  41. HTMLElement::~HTMLElement() = default;
  42. JS::ThrowCompletionOr<void> HTMLElement::initialize(JS::Realm& realm)
  43. {
  44. MUST_OR_THROW_OOM(Base::initialize(realm));
  45. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLElementPrototype>(realm, "HTMLElement"));
  46. m_dataset = TRY(Bindings::throw_dom_exception_if_needed(realm.vm(), [&]() {
  47. return DOMStringMap::create(*this);
  48. }));
  49. return {};
  50. }
  51. void HTMLElement::visit_edges(Cell::Visitor& visitor)
  52. {
  53. Base::visit_edges(visitor);
  54. visitor.visit(m_dataset.ptr());
  55. }
  56. // https://html.spec.whatwg.org/multipage/dom.html#dom-dir
  57. DeprecatedString HTMLElement::dir() const
  58. {
  59. auto dir = attribute(HTML::AttributeNames::dir);
  60. #define __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE(keyword) \
  61. if (dir.equals_ignoring_ascii_case(#keyword##sv)) \
  62. return #keyword##sv;
  63. ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTES
  64. #undef __ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTE
  65. return {};
  66. }
  67. void HTMLElement::set_dir(DeprecatedString const& dir)
  68. {
  69. MUST(set_attribute(HTML::AttributeNames::dir, dir));
  70. }
  71. bool HTMLElement::is_editable() const
  72. {
  73. switch (m_content_editable_state) {
  74. case ContentEditableState::True:
  75. return true;
  76. case ContentEditableState::False:
  77. return false;
  78. case ContentEditableState::Inherit:
  79. return parent() && parent()->is_editable();
  80. default:
  81. VERIFY_NOT_REACHED();
  82. }
  83. }
  84. DeprecatedString HTMLElement::content_editable() const
  85. {
  86. switch (m_content_editable_state) {
  87. case ContentEditableState::True:
  88. return "true";
  89. case ContentEditableState::False:
  90. return "false";
  91. case ContentEditableState::Inherit:
  92. return "inherit";
  93. default:
  94. VERIFY_NOT_REACHED();
  95. }
  96. }
  97. // https://html.spec.whatwg.org/multipage/interaction.html#contenteditable
  98. WebIDL::ExceptionOr<void> HTMLElement::set_content_editable(DeprecatedString const& content_editable)
  99. {
  100. if (content_editable.equals_ignoring_ascii_case("inherit"sv)) {
  101. remove_attribute(HTML::AttributeNames::contenteditable);
  102. return {};
  103. }
  104. if (content_editable.equals_ignoring_ascii_case("true"sv)) {
  105. MUST(set_attribute(HTML::AttributeNames::contenteditable, "true"));
  106. return {};
  107. }
  108. if (content_editable.equals_ignoring_ascii_case("false"sv)) {
  109. MUST(set_attribute(HTML::AttributeNames::contenteditable, "false"));
  110. return {};
  111. }
  112. return WebIDL::SyntaxError::create(realm(), "Invalid contentEditable value, must be 'true', 'false', or 'inherit'");
  113. }
  114. void HTMLElement::set_inner_text(StringView text)
  115. {
  116. remove_all_children();
  117. MUST(append_child(document().create_text_node(text)));
  118. set_needs_style_update(true);
  119. }
  120. DeprecatedString HTMLElement::inner_text()
  121. {
  122. StringBuilder builder;
  123. // innerText for element being rendered takes visibility into account, so force a layout and then walk the layout tree.
  124. document().update_layout();
  125. if (!layout_node())
  126. return text_content();
  127. Function<void(Layout::Node const&)> recurse = [&](auto& node) {
  128. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  129. if (is<Layout::TextNode>(child))
  130. builder.append(verify_cast<Layout::TextNode>(*child).text_for_rendering());
  131. if (is<Layout::BreakNode>(child))
  132. builder.append('\n');
  133. recurse(*child);
  134. }
  135. };
  136. recurse(*layout_node());
  137. return builder.to_deprecated_string();
  138. }
  139. // // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsettop
  140. int HTMLElement::offset_top() const
  141. {
  142. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  143. const_cast<DOM::Document&>(document()).update_layout();
  144. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  145. return 0;
  146. auto position = layout_node()->box_type_agnostic_position();
  147. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  148. return position.y().to_int() - parent_position.y().to_int();
  149. }
  150. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetleft
  151. int HTMLElement::offset_left() const
  152. {
  153. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  154. const_cast<DOM::Document&>(document()).update_layout();
  155. if (is<HTML::HTMLBodyElement>(this) || !layout_node() || !parent_element() || !parent_element()->layout_node())
  156. return 0;
  157. auto position = layout_node()->box_type_agnostic_position();
  158. auto parent_position = parent_element()->layout_node()->box_type_agnostic_position();
  159. return position.x().to_int() - parent_position.x().to_int();
  160. }
  161. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth
  162. int HTMLElement::offset_width() const
  163. {
  164. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  165. const_cast<DOM::Document&>(document()).update_layout();
  166. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  167. if (!paintable_box())
  168. return 0;
  169. // 2. Return the width of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  170. // ignoring any transforms that apply to the element and its ancestors.
  171. // FIXME: Account for inline boxes.
  172. return paintable_box()->border_box_width().to_int();
  173. }
  174. // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetheight
  175. int HTMLElement::offset_height() const
  176. {
  177. // NOTE: Ensure that layout is up-to-date before looking at metrics.
  178. const_cast<DOM::Document&>(document()).update_layout();
  179. // 1. If the element does not have any associated CSS layout box return zero and terminate this algorithm.
  180. if (!paintable_box())
  181. return 0;
  182. // 2. Return the height of the axis-aligned bounding box of the border boxes of all fragments generated by the element’s principal box,
  183. // ignoring any transforms that apply to the element and its ancestors.
  184. // FIXME: Account for inline boxes.
  185. return paintable_box()->border_box_height().to_int();
  186. }
  187. // https://html.spec.whatwg.org/multipage/links.html#cannot-navigate
  188. bool HTMLElement::cannot_navigate() const
  189. {
  190. // An element element cannot navigate if one of the following is true:
  191. // - element's node document is not fully active
  192. if (!document().is_fully_active())
  193. return true;
  194. // - element is not an a element and is not connected.
  195. return !is<HTML::HTMLAnchorElement>(this) && !is_connected();
  196. }
  197. void HTMLElement::parse_attribute(DeprecatedFlyString const& name, DeprecatedString const& value)
  198. {
  199. Element::parse_attribute(name, value);
  200. if (name == HTML::AttributeNames::contenteditable) {
  201. if ((!value.is_null() && value.is_empty()) || value.equals_ignoring_ascii_case("true"sv)) {
  202. // "true", an empty string or a missing value map to the "true" state.
  203. m_content_editable_state = ContentEditableState::True;
  204. } else if (value.equals_ignoring_ascii_case("false"sv)) {
  205. // "false" maps to the "false" state.
  206. m_content_editable_state = ContentEditableState::False;
  207. } else {
  208. // Having no such attribute or an invalid value maps to the "inherit" state.
  209. m_content_editable_state = ContentEditableState::Inherit;
  210. }
  211. }
  212. // 1. If namespace is not null, or localName is not the name of an event handler content attribute on element, then return.
  213. // FIXME: Add the namespace part once we support attribute namespaces.
  214. #undef __ENUMERATE
  215. #define __ENUMERATE(attribute_name, event_name) \
  216. if (name == HTML::AttributeNames::attribute_name) { \
  217. element_event_handler_attribute_changed(event_name, String::from_deprecated_string(value).release_value()); \
  218. }
  219. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
  220. #undef __ENUMERATE
  221. }
  222. void HTMLElement::did_remove_attribute(DeprecatedFlyString const& name)
  223. {
  224. Base::did_remove_attribute(name);
  225. if (name == HTML::AttributeNames::contenteditable) {
  226. m_content_editable_state = ContentEditableState::Inherit;
  227. }
  228. }
  229. // https://html.spec.whatwg.org/multipage/interaction.html#dom-focus
  230. void HTMLElement::focus()
  231. {
  232. // 1. If the element is marked as locked for focus, then return.
  233. if (m_locked_for_focus)
  234. return;
  235. // 2. Mark the element as locked for focus.
  236. m_locked_for_focus = true;
  237. // 3. Run the focusing steps for the element.
  238. run_focusing_steps(this);
  239. // FIXME: 4. If the value of the preventScroll dictionary member of options is false,
  240. // then scroll the element into view with scroll behavior "auto",
  241. // block flow direction position set to an implementation-defined value,
  242. // and inline base direction position set to an implementation-defined value.
  243. // 5. Unmark the element as locked for focus.
  244. m_locked_for_focus = false;
  245. }
  246. // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-pointer-event
  247. bool HTMLElement::fire_a_synthetic_pointer_event(FlyString const& type, DOM::Element& target, bool not_trusted)
  248. {
  249. // 1. Let event be the result of creating an event using PointerEvent.
  250. // 2. Initialize event's type attribute to e.
  251. // FIXME: Actually create a PointerEvent!
  252. auto event = UIEvents::MouseEvent::create(realm(), type).release_value_but_fixme_should_propagate_errors();
  253. // 3. Initialize event's bubbles and cancelable attributes to true.
  254. event->set_bubbles(true);
  255. event->set_cancelable(true);
  256. // 4. Set event's composed flag.
  257. event->set_composed(true);
  258. // 5. If the not trusted flag is set, initialize event's isTrusted attribute to false.
  259. if (not_trusted) {
  260. event->set_is_trusted(false);
  261. }
  262. // FIXME: 6. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state
  263. // of the key input device, if any (false for any keys that are not available).
  264. // FIXME: 7. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.
  265. // FIXME: 8. event's getModifierState() method is to return values appropriately describing the current state of the key input device.
  266. // 9. Return the result of dispatching event at target.
  267. return target.dispatch_event(event);
  268. }
  269. // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
  270. void HTMLElement::click()
  271. {
  272. // FIXME: 1. If this element is a form control that is disabled, then return.
  273. // 2. If this element's click in progress flag is set, then return.
  274. if (m_click_in_progress)
  275. return;
  276. // 3. Set this element's click in progress flag.
  277. m_click_in_progress = true;
  278. // FIXME: 4. Fire a synthetic pointer event named click at this element, with the not trusted flag set.
  279. fire_a_synthetic_pointer_event(HTML::EventNames::click, *this, true);
  280. // 5. Unset this element's click in progress flag.
  281. m_click_in_progress = false;
  282. }
  283. // https://html.spec.whatwg.org/multipage/interaction.html#dom-blur
  284. void HTMLElement::blur()
  285. {
  286. // The blur() method, when invoked, should run the unfocusing steps for the element on which the method was called.
  287. run_unfocusing_steps(this);
  288. // User agents may selectively or uniformly ignore calls to this method for usability reasons.
  289. }
  290. Optional<ARIA::Role> HTMLElement::default_role() const
  291. {
  292. // https://www.w3.org/TR/html-aria/#el-article
  293. if (local_name() == TagNames::article)
  294. return ARIA::Role::article;
  295. // https://www.w3.org/TR/html-aria/#el-aside
  296. if (local_name() == TagNames::aside)
  297. return ARIA::Role::complementary;
  298. // https://www.w3.org/TR/html-aria/#el-b
  299. if (local_name() == TagNames::b)
  300. return ARIA::Role::generic;
  301. // https://www.w3.org/TR/html-aria/#el-bdi
  302. if (local_name() == TagNames::bdi)
  303. return ARIA::Role::generic;
  304. // https://www.w3.org/TR/html-aria/#el-bdo
  305. if (local_name() == TagNames::bdo)
  306. return ARIA::Role::generic;
  307. // https://www.w3.org/TR/html-aria/#el-code
  308. if (local_name() == TagNames::code)
  309. return ARIA::Role::code;
  310. // https://www.w3.org/TR/html-aria/#el-dfn
  311. if (local_name() == TagNames::dfn)
  312. return ARIA::Role::term;
  313. // https://www.w3.org/TR/html-aria/#el-em
  314. if (local_name() == TagNames::em)
  315. return ARIA::Role::emphasis;
  316. // https://www.w3.org/TR/html-aria/#el-figure
  317. if (local_name() == TagNames::figure)
  318. return ARIA::Role::figure;
  319. // https://www.w3.org/TR/html-aria/#el-footer
  320. if (local_name() == TagNames::footer) {
  321. // 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
  322. // Otherwise, role=generic
  323. return ARIA::Role::generic;
  324. }
  325. // https://www.w3.org/TR/html-aria/#el-header
  326. if (local_name() == TagNames::header) {
  327. // 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
  328. // Otherwise, role=generic
  329. return ARIA::Role::generic;
  330. }
  331. // https://www.w3.org/TR/html-aria/#el-hgroup
  332. if (local_name() == TagNames::hgroup)
  333. return ARIA::Role::generic;
  334. // https://www.w3.org/TR/html-aria/#el-i
  335. if (local_name() == TagNames::i)
  336. return ARIA::Role::generic;
  337. // https://www.w3.org/TR/html-aria/#el-main
  338. if (local_name() == TagNames::main)
  339. return ARIA::Role::main;
  340. // https://www.w3.org/TR/html-aria/#el-nav
  341. if (local_name() == TagNames::nav)
  342. return ARIA::Role::navigation;
  343. // https://www.w3.org/TR/html-aria/#el-samp
  344. if (local_name() == TagNames::samp)
  345. return ARIA::Role::generic;
  346. // https://www.w3.org/TR/html-aria/#el-section
  347. if (local_name() == TagNames::section) {
  348. // TODO: role=region if the section element has an accessible name
  349. // Otherwise, no corresponding role
  350. return ARIA::Role::region;
  351. }
  352. // https://www.w3.org/TR/html-aria/#el-small
  353. if (local_name() == TagNames::small)
  354. return ARIA::Role::generic;
  355. // https://www.w3.org/TR/html-aria/#el-strong
  356. if (local_name() == TagNames::strong)
  357. return ARIA::Role::strong;
  358. // https://www.w3.org/TR/html-aria/#el-sub
  359. if (local_name() == TagNames::sub)
  360. return ARIA::Role::subscript;
  361. // https://www.w3.org/TR/html-aria/#el-summary
  362. if (local_name() == TagNames::summary)
  363. return ARIA::Role::button;
  364. // https://www.w3.org/TR/html-aria/#el-sup
  365. if (local_name() == TagNames::sup)
  366. return ARIA::Role::superscript;
  367. // https://www.w3.org/TR/html-aria/#el-u
  368. if (local_name() == TagNames::u)
  369. return ARIA::Role::generic;
  370. return {};
  371. }
  372. // https://html.spec.whatwg.org/multipage/semantics.html#get-an-element's-target
  373. DeprecatedString HTMLElement::get_an_elements_target() const
  374. {
  375. // To get an element's target, given an a, area, or form element element, run these steps:
  376. // 1. If element has a target attribute, then return that attribute's value.
  377. if (has_attribute(AttributeNames::target))
  378. return attribute(AttributeNames::target);
  379. // FIXME: 2. If element's node document contains a base element with a
  380. // target attribute, then return the value of the target attribute of the
  381. // first such base element.
  382. // 3. Return the empty string.
  383. return DeprecatedString::empty();
  384. }
  385. // https://html.spec.whatwg.org/multipage/links.html#get-an-element's-noopener
  386. TokenizedFeature::NoOpener HTMLElement::get_an_elements_noopener(StringView target) const
  387. {
  388. // To get an element's noopener, given an a, area, or form element element and a string target:
  389. auto rel = attribute(HTML::AttributeNames::rel).to_lowercase();
  390. auto link_types = rel.view().split_view_if(Infra::is_ascii_whitespace);
  391. // 1. If element's link types include the noopener or noreferrer keyword, then return true.
  392. if (link_types.contains_slow("noopener"sv) || link_types.contains_slow("noreferrer"sv))
  393. return TokenizedFeature::NoOpener::Yes;
  394. // 2. If element's link types do not include the opener keyword and
  395. // target is an ASCII case-insensitive match for "_blank", then return true.
  396. if (!link_types.contains_slow("opener"sv) && Infra::is_ascii_case_insensitive_match(target, "_blank"sv))
  397. return TokenizedFeature::NoOpener::Yes;
  398. // 3. Return false.
  399. return TokenizedFeature::NoOpener::No;
  400. }
  401. }