HTMLElement.cpp 18 KB

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