Element.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AnyOf.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibWeb/CSS/Parser/Parser.h>
  9. #include <LibWeb/CSS/PropertyID.h>
  10. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  11. #include <LibWeb/CSS/SelectorEngine.h>
  12. #include <LibWeb/CSS/StyleInvalidator.h>
  13. #include <LibWeb/DOM/DOMException.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOM/Element.h>
  16. #include <LibWeb/DOM/ExceptionOr.h>
  17. #include <LibWeb/DOM/HTMLCollection.h>
  18. #include <LibWeb/DOM/ShadowRoot.h>
  19. #include <LibWeb/DOM/Text.h>
  20. #include <LibWeb/DOMParsing/InnerHTML.h>
  21. #include <LibWeb/Geometry/DOMRect.h>
  22. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  23. #include <LibWeb/HTML/Parser/HTMLParser.h>
  24. #include <LibWeb/Layout/BlockContainer.h>
  25. #include <LibWeb/Layout/InlineNode.h>
  26. #include <LibWeb/Layout/ListItemBox.h>
  27. #include <LibWeb/Layout/TableBox.h>
  28. #include <LibWeb/Layout/TableCellBox.h>
  29. #include <LibWeb/Layout/TableRowBox.h>
  30. #include <LibWeb/Layout/TableRowGroupBox.h>
  31. #include <LibWeb/Layout/TreeBuilder.h>
  32. #include <LibWeb/Namespace.h>
  33. #include <LibWeb/Page/BrowsingContext.h>
  34. namespace Web::DOM {
  35. Element::Element(Document& document, QualifiedName qualified_name)
  36. : ParentNode(document, NodeType::ELEMENT_NODE)
  37. , m_qualified_name(move(qualified_name))
  38. {
  39. make_html_uppercased_qualified_name();
  40. }
  41. Element::~Element()
  42. {
  43. }
  44. Attribute* Element::find_attribute(const FlyString& name)
  45. {
  46. for (auto& attribute : m_attributes) {
  47. if (attribute.name() == name)
  48. return &attribute;
  49. }
  50. return nullptr;
  51. }
  52. const Attribute* Element::find_attribute(const FlyString& name) const
  53. {
  54. for (auto& attribute : m_attributes) {
  55. if (attribute.name() == name)
  56. return &attribute;
  57. }
  58. return nullptr;
  59. }
  60. String Element::attribute(const FlyString& name) const
  61. {
  62. if (auto* attribute = find_attribute(name))
  63. return attribute->value();
  64. return {};
  65. }
  66. ExceptionOr<void> Element::set_attribute(const FlyString& name, const String& value)
  67. {
  68. // FIXME: Proper name validation
  69. if (name.is_empty())
  70. return InvalidCharacterError::create("Attribute name must not be empty");
  71. CSS::StyleInvalidator style_invalidator(document());
  72. if (auto* attribute = find_attribute(name))
  73. attribute->set_value(value);
  74. else
  75. m_attributes.empend(name, value);
  76. parse_attribute(name, value);
  77. return {};
  78. }
  79. void Element::remove_attribute(const FlyString& name)
  80. {
  81. CSS::StyleInvalidator style_invalidator(document());
  82. m_attributes.remove_first_matching([&](auto& attribute) { return attribute.name() == name; });
  83. }
  84. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  85. {
  86. return any_of(m_classes, [&](auto& it) {
  87. return case_sensitivity == CaseSensitivity::CaseSensitive
  88. ? it == class_name
  89. : it.to_lowercase() == class_name.to_lowercase();
  90. });
  91. }
  92. RefPtr<Layout::Node> Element::create_layout_node()
  93. {
  94. auto style = document().style_computer().compute_style(*this);
  95. const_cast<Element&>(*this).m_specified_css_values = style;
  96. auto display = style->display();
  97. if (display.is_none())
  98. return nullptr;
  99. if (local_name() == "noscript" && document().is_scripting_enabled())
  100. return nullptr;
  101. if (display.is_table_inside())
  102. return adopt_ref(*new Layout::TableBox(document(), this, move(style)));
  103. if (display.is_list_item())
  104. return adopt_ref(*new Layout::ListItemBox(document(), *this, move(style)));
  105. if (display.is_table_row())
  106. return adopt_ref(*new Layout::TableRowBox(document(), this, move(style)));
  107. if (display.is_table_cell())
  108. return adopt_ref(*new Layout::TableCellBox(document(), this, move(style)));
  109. if (display.is_table_row_group() || display.is_table_header_group() || display.is_table_footer_group())
  110. return adopt_ref(*new Layout::TableRowGroupBox(document(), *this, move(style)));
  111. if (display.is_table_column() || display.is_table_column_group() || display.is_table_caption()) {
  112. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  113. return adopt_ref(*new Layout::BlockContainer(document(), this, move(style)));
  114. }
  115. if (display.is_inline_outside()) {
  116. if (display.is_flow_root_inside()) {
  117. auto block = adopt_ref(*new Layout::BlockContainer(document(), this, move(style)));
  118. block->set_inline(true);
  119. return block;
  120. }
  121. if (display.is_flow_inside())
  122. return adopt_ref(*new Layout::InlineNode(document(), *this, move(style)));
  123. TODO();
  124. }
  125. if (display.is_flow_inside() || display.is_flow_root_inside() || display.is_flex_inside())
  126. return adopt_ref(*new Layout::BlockContainer(document(), this, move(style)));
  127. TODO();
  128. }
  129. void Element::parse_attribute(const FlyString& name, const String& value)
  130. {
  131. if (name == HTML::AttributeNames::class_) {
  132. auto new_classes = value.split_view(' ');
  133. m_classes.clear();
  134. m_classes.ensure_capacity(new_classes.size());
  135. for (auto& new_class : new_classes) {
  136. m_classes.unchecked_append(new_class);
  137. }
  138. } else if (name == HTML::AttributeNames::style) {
  139. auto parsed_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  140. if (!parsed_style.is_null()) {
  141. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create_and_take_properties_from(*this, parsed_style.release_nonnull());
  142. set_needs_style_update(true);
  143. }
  144. }
  145. }
  146. enum class StyleDifference {
  147. None,
  148. NeedsRepaint,
  149. NeedsRelayout,
  150. };
  151. static StyleDifference compute_style_difference(CSS::StyleProperties const& old_style, CSS::StyleProperties const& new_style, Layout::NodeWithStyle const& node)
  152. {
  153. if (old_style == new_style)
  154. return StyleDifference::None;
  155. bool needs_repaint = false;
  156. bool needs_relayout = false;
  157. if (new_style.display() != old_style.display())
  158. needs_relayout = true;
  159. if (new_style.color_or_fallback(CSS::PropertyID::Color, node, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::Color, node, Color::Black))
  160. needs_repaint = true;
  161. else if (new_style.color_or_fallback(CSS::PropertyID::BackgroundColor, node, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::BackgroundColor, node, Color::Black))
  162. needs_repaint = true;
  163. if (needs_relayout)
  164. return StyleDifference::NeedsRelayout;
  165. if (needs_repaint)
  166. return StyleDifference::NeedsRepaint;
  167. return StyleDifference::None;
  168. }
  169. void Element::recompute_style()
  170. {
  171. set_needs_style_update(false);
  172. VERIFY(parent());
  173. auto old_specified_css_values = m_specified_css_values;
  174. auto new_specified_css_values = document().style_computer().compute_style(*this);
  175. m_specified_css_values = new_specified_css_values;
  176. if (!layout_node()) {
  177. if (new_specified_css_values->display().is_none())
  178. return;
  179. // We need a new layout tree here!
  180. Layout::TreeBuilder tree_builder;
  181. tree_builder.build(*this);
  182. return;
  183. }
  184. auto diff = StyleDifference::NeedsRelayout;
  185. if (old_specified_css_values && layout_node())
  186. diff = compute_style_difference(*old_specified_css_values, *new_specified_css_values, *layout_node());
  187. if (diff == StyleDifference::None)
  188. return;
  189. layout_node()->apply_style(*new_specified_css_values);
  190. if (diff == StyleDifference::NeedsRelayout) {
  191. document().set_needs_layout();
  192. return;
  193. }
  194. if (diff == StyleDifference::NeedsRepaint) {
  195. layout_node()->set_needs_display();
  196. }
  197. }
  198. NonnullRefPtr<CSS::StyleProperties> Element::computed_style()
  199. {
  200. auto element_computed_style = CSS::ResolvedCSSStyleDeclaration::create(*this);
  201. auto properties = CSS::StyleProperties::create();
  202. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  203. auto property_id = (CSS::PropertyID)i;
  204. auto maybe_value = element_computed_style->property(property_id);
  205. if (!maybe_value.has_value())
  206. continue;
  207. properties->set_property(property_id, maybe_value.release_value().value);
  208. }
  209. return properties;
  210. }
  211. // https://dom.spec.whatwg.org/#dom-element-matches
  212. DOM::ExceptionOr<bool> Element::matches(StringView selectors) const
  213. {
  214. auto maybe_selectors = parse_selector(CSS::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
  215. if (!maybe_selectors.has_value())
  216. return DOM::SyntaxError::create("Failed to parse selector");
  217. auto sel = maybe_selectors.value();
  218. for (auto& s : sel) {
  219. if (SelectorEngine::matches(s, *this))
  220. return true;
  221. }
  222. return false;
  223. }
  224. ExceptionOr<void> Element::set_inner_html(String const& markup)
  225. {
  226. auto result = DOMParsing::InnerHTML::inner_html_setter(*this, markup);
  227. if (result.is_exception())
  228. return result.exception();
  229. set_needs_style_update(true);
  230. return {};
  231. }
  232. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  233. String Element::inner_html() const
  234. {
  235. return serialize_fragment(/* FIXME: Providing true for the require well-formed flag (which may throw) */);
  236. }
  237. bool Element::is_focused() const
  238. {
  239. return document().focused_element() == this;
  240. }
  241. bool Element::is_active() const
  242. {
  243. return document().active_element() == this;
  244. }
  245. NonnullRefPtr<HTMLCollection> Element::get_elements_by_class_name(FlyString const& class_name)
  246. {
  247. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  248. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  249. });
  250. }
  251. void Element::set_shadow_root(RefPtr<ShadowRoot> shadow_root)
  252. {
  253. if (m_shadow_root == shadow_root)
  254. return;
  255. m_shadow_root = move(shadow_root);
  256. invalidate_style();
  257. }
  258. NonnullRefPtr<CSS::CSSStyleDeclaration> Element::style_for_bindings()
  259. {
  260. if (!m_inline_style)
  261. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this);
  262. return *m_inline_style;
  263. }
  264. // https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name
  265. void Element::make_html_uppercased_qualified_name()
  266. {
  267. // This is allowed by the spec: "User agents could optimize qualified name and HTML-uppercased qualified name by storing them in internal slots."
  268. if (namespace_() == Namespace::HTML /* FIXME: and its node document is an HTML document */)
  269. m_html_uppercased_qualified_name = qualified_name().to_uppercase();
  270. else
  271. m_html_uppercased_qualified_name = qualified_name();
  272. }
  273. // https://html.spec.whatwg.org/multipage/webappapis.html#queue-an-element-task
  274. void Element::queue_an_element_task(HTML::Task::Source source, Function<void()> steps)
  275. {
  276. auto task = HTML::Task::create(source, &document(), [strong_this = NonnullRefPtr(*this), steps = move(steps)] {
  277. steps();
  278. });
  279. HTML::main_thread_event_loop().task_queue().add(move(task));
  280. }
  281. // https://html.spec.whatwg.org/multipage/syntax.html#void-elements
  282. bool Element::is_void_element() const
  283. {
  284. return local_name().is_one_of(HTML::TagNames::area, HTML::TagNames::base, HTML::TagNames::br, HTML::TagNames::col, HTML::TagNames::embed, HTML::TagNames::hr, HTML::TagNames::img, HTML::TagNames::input, HTML::TagNames::link, HTML::TagNames::meta, HTML::TagNames::param, HTML::TagNames::source, HTML::TagNames::track, HTML::TagNames::wbr);
  285. }
  286. // https://html.spec.whatwg.org/multipage/parsing.html#serializes-as-void
  287. bool Element::serializes_as_void() const
  288. {
  289. return is_void_element() || local_name().is_one_of(HTML::TagNames::basefont, HTML::TagNames::bgsound, HTML::TagNames::frame, HTML::TagNames::keygen);
  290. }
  291. // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
  292. NonnullRefPtr<Geometry::DOMRect> Element::get_bounding_client_rect() const
  293. {
  294. // FIXME: Support inline layout nodes as well.
  295. if (!layout_node() || !layout_node()->is_box())
  296. return Geometry::DOMRect::create(0, 0, 0, 0);
  297. VERIFY(document().browsing_context());
  298. auto viewport_offset = document().browsing_context()->viewport_scroll_offset();
  299. auto& box = static_cast<Layout::Box const&>(*layout_node());
  300. return Geometry::DOMRect::create(box.absolute_rect().translated(-viewport_offset.x(), -viewport_offset.y()));
  301. }
  302. int Element::client_top() const
  303. {
  304. if (!layout_node() || !layout_node()->is_box())
  305. return 0;
  306. auto& box = static_cast<Layout::Box const&>(*layout_node());
  307. return box.absolute_rect().top();
  308. }
  309. int Element::client_left() const
  310. {
  311. if (!layout_node() || !layout_node()->is_box())
  312. return 0;
  313. auto& box = static_cast<Layout::Box const&>(*layout_node());
  314. return box.absolute_rect().left();
  315. }
  316. int Element::client_width() const
  317. {
  318. if (!layout_node() || !layout_node()->is_box())
  319. return 0;
  320. auto& box = static_cast<Layout::Box const&>(*layout_node());
  321. return box.absolute_rect().width();
  322. }
  323. int Element::client_height() const
  324. {
  325. if (!layout_node() || !layout_node()->is_box())
  326. return 0;
  327. auto& box = static_cast<Layout::Box const&>(*layout_node());
  328. return box.absolute_rect().height();
  329. }
  330. }