HTMLElement.cpp 18 KB

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