Element.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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/StyleInvalidator.h>
  12. #include <LibWeb/DOM/DOMException.h>
  13. #include <LibWeb/DOM/Document.h>
  14. #include <LibWeb/DOM/Element.h>
  15. #include <LibWeb/DOM/ExceptionOr.h>
  16. #include <LibWeb/DOM/HTMLCollection.h>
  17. #include <LibWeb/DOM/ShadowRoot.h>
  18. #include <LibWeb/DOM/Text.h>
  19. #include <LibWeb/DOMParsing/InnerHTML.h>
  20. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  21. #include <LibWeb/HTML/Parser/HTMLParser.h>
  22. #include <LibWeb/Layout/BlockBox.h>
  23. #include <LibWeb/Layout/InlineNode.h>
  24. #include <LibWeb/Layout/ListItemBox.h>
  25. #include <LibWeb/Layout/TableBox.h>
  26. #include <LibWeb/Layout/TableCellBox.h>
  27. #include <LibWeb/Layout/TableRowBox.h>
  28. #include <LibWeb/Layout/TableRowGroupBox.h>
  29. #include <LibWeb/Layout/TreeBuilder.h>
  30. #include <LibWeb/Namespace.h>
  31. namespace Web::DOM {
  32. Element::Element(Document& document, QualifiedName qualified_name)
  33. : ParentNode(document, NodeType::ELEMENT_NODE)
  34. , m_qualified_name(move(qualified_name))
  35. {
  36. make_html_uppercased_qualified_name();
  37. }
  38. Element::~Element()
  39. {
  40. }
  41. Attribute* Element::find_attribute(const FlyString& name)
  42. {
  43. for (auto& attribute : m_attributes) {
  44. if (attribute.name() == name)
  45. return &attribute;
  46. }
  47. return nullptr;
  48. }
  49. const Attribute* Element::find_attribute(const FlyString& name) const
  50. {
  51. for (auto& attribute : m_attributes) {
  52. if (attribute.name() == name)
  53. return &attribute;
  54. }
  55. return nullptr;
  56. }
  57. String Element::attribute(const FlyString& name) const
  58. {
  59. if (auto* attribute = find_attribute(name))
  60. return attribute->value();
  61. return {};
  62. }
  63. ExceptionOr<void> Element::set_attribute(const FlyString& name, const String& value)
  64. {
  65. // FIXME: Proper name validation
  66. if (name.is_empty())
  67. return InvalidCharacterError::create("Attribute name must not be empty");
  68. CSS::StyleInvalidator style_invalidator(document());
  69. if (auto* attribute = find_attribute(name))
  70. attribute->set_value(value);
  71. else
  72. m_attributes.empend(name, value);
  73. parse_attribute(name, value);
  74. return {};
  75. }
  76. void Element::remove_attribute(const FlyString& name)
  77. {
  78. CSS::StyleInvalidator style_invalidator(document());
  79. m_attributes.remove_first_matching([&](auto& attribute) { return attribute.name() == name; });
  80. }
  81. bool Element::has_class(const FlyString& class_name, CaseSensitivity case_sensitivity) const
  82. {
  83. return any_of(m_classes, [&](auto& it) {
  84. return case_sensitivity == CaseSensitivity::CaseSensitive
  85. ? it == class_name
  86. : it.to_lowercase() == class_name.to_lowercase();
  87. });
  88. }
  89. RefPtr<Layout::Node> Element::create_layout_node()
  90. {
  91. auto style = document().style_computer().compute_style(*this);
  92. const_cast<Element&>(*this).m_specified_css_values = style;
  93. auto display = style->display();
  94. if (display == CSS::Display::None)
  95. return nullptr;
  96. if (local_name() == "noscript" && document().is_scripting_enabled())
  97. return nullptr;
  98. switch (display) {
  99. case CSS::Display::None:
  100. VERIFY_NOT_REACHED();
  101. break;
  102. case CSS::Display::Block:
  103. return adopt_ref(*new Layout::BlockBox(document(), this, move(style)));
  104. case CSS::Display::Inline:
  105. if (style->float_().value_or(CSS::Float::None) != CSS::Float::None)
  106. return adopt_ref(*new Layout::BlockBox(document(), this, move(style)));
  107. return adopt_ref(*new Layout::InlineNode(document(), *this, move(style)));
  108. case CSS::Display::ListItem:
  109. return adopt_ref(*new Layout::ListItemBox(document(), *this, move(style)));
  110. case CSS::Display::Table:
  111. return adopt_ref(*new Layout::TableBox(document(), this, move(style)));
  112. case CSS::Display::TableRow:
  113. return adopt_ref(*new Layout::TableRowBox(document(), this, move(style)));
  114. case CSS::Display::TableCell:
  115. return adopt_ref(*new Layout::TableCellBox(document(), this, move(style)));
  116. case CSS::Display::TableRowGroup:
  117. case CSS::Display::TableHeaderGroup:
  118. case CSS::Display::TableFooterGroup:
  119. return adopt_ref(*new Layout::TableRowGroupBox(document(), *this, move(style)));
  120. case CSS::Display::InlineBlock: {
  121. auto inline_block = adopt_ref(*new Layout::BlockBox(document(), this, move(style)));
  122. inline_block->set_inline(true);
  123. return inline_block;
  124. }
  125. case CSS::Display::Flex:
  126. return adopt_ref(*new Layout::BlockBox(document(), this, move(style)));
  127. case CSS::Display::TableColumn:
  128. case CSS::Display::TableColumnGroup:
  129. case CSS::Display::TableCaption:
  130. // FIXME: This is just an incorrect placeholder until we improve table layout support.
  131. return adopt_ref(*new Layout::BlockBox(document(), this, move(style)));
  132. }
  133. VERIFY_NOT_REACHED();
  134. }
  135. void Element::parse_attribute(const FlyString& name, const String& value)
  136. {
  137. if (name == HTML::AttributeNames::class_) {
  138. auto new_classes = value.split_view(' ');
  139. m_classes.clear();
  140. m_classes.ensure_capacity(new_classes.size());
  141. for (auto& new_class : new_classes) {
  142. m_classes.unchecked_append(new_class);
  143. }
  144. } else if (name == HTML::AttributeNames::style) {
  145. auto parsed_style = parse_css_declaration(CSS::ParsingContext(document()), value);
  146. if (!parsed_style.is_null()) {
  147. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create_and_take_properties_from(*this, parsed_style.release_nonnull());
  148. set_needs_style_update(true);
  149. }
  150. }
  151. }
  152. enum class StyleDifference {
  153. None,
  154. NeedsRepaint,
  155. NeedsRelayout,
  156. };
  157. static StyleDifference compute_style_difference(CSS::StyleProperties const& old_style, CSS::StyleProperties const& new_style, Layout::NodeWithStyle const& node)
  158. {
  159. if (old_style == new_style)
  160. return StyleDifference::None;
  161. bool needs_repaint = false;
  162. bool needs_relayout = false;
  163. if (new_style.display() != old_style.display())
  164. needs_relayout = true;
  165. if (new_style.color_or_fallback(CSS::PropertyID::Color, node, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::Color, node, Color::Black))
  166. needs_repaint = true;
  167. else if (new_style.color_or_fallback(CSS::PropertyID::BackgroundColor, node, Color::Black) != old_style.color_or_fallback(CSS::PropertyID::BackgroundColor, node, Color::Black))
  168. needs_repaint = true;
  169. if (needs_relayout)
  170. return StyleDifference::NeedsRelayout;
  171. if (needs_repaint)
  172. return StyleDifference::NeedsRepaint;
  173. return StyleDifference::None;
  174. }
  175. void Element::recompute_style()
  176. {
  177. set_needs_style_update(false);
  178. VERIFY(parent());
  179. auto old_specified_css_values = m_specified_css_values;
  180. auto new_specified_css_values = document().style_computer().compute_style(*this);
  181. m_specified_css_values = new_specified_css_values;
  182. if (!layout_node()) {
  183. if (new_specified_css_values->display() == CSS::Display::None)
  184. return;
  185. // We need a new layout tree here!
  186. Layout::TreeBuilder tree_builder;
  187. tree_builder.build(*this);
  188. return;
  189. }
  190. auto diff = StyleDifference::NeedsRelayout;
  191. if (old_specified_css_values && layout_node())
  192. diff = compute_style_difference(*old_specified_css_values, *new_specified_css_values, *layout_node());
  193. if (diff == StyleDifference::None)
  194. return;
  195. layout_node()->apply_style(*new_specified_css_values);
  196. if (diff == StyleDifference::NeedsRelayout) {
  197. document().schedule_forced_layout();
  198. return;
  199. }
  200. if (diff == StyleDifference::NeedsRepaint) {
  201. layout_node()->set_needs_display();
  202. }
  203. }
  204. NonnullRefPtr<CSS::StyleProperties> Element::computed_style()
  205. {
  206. auto element_computed_style = CSS::ResolvedCSSStyleDeclaration::create(*this);
  207. auto properties = CSS::StyleProperties::create();
  208. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  209. auto property_id = (CSS::PropertyID)i;
  210. auto maybe_value = element_computed_style->property(property_id);
  211. if (!maybe_value.has_value())
  212. continue;
  213. properties->set_property(property_id, maybe_value.release_value().value);
  214. }
  215. return properties;
  216. }
  217. ExceptionOr<void> Element::set_inner_html(String const& markup)
  218. {
  219. auto result = DOMParsing::InnerHTML::inner_html_setter(*this, markup);
  220. if (result.is_exception())
  221. return result.exception();
  222. set_needs_style_update(true);
  223. document().invalidate_layout();
  224. return {};
  225. }
  226. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  227. String Element::inner_html() const
  228. {
  229. return serialize_fragment(/* FIXME: Providing true for the require well-formed flag (which may throw) */);
  230. }
  231. bool Element::is_focused() const
  232. {
  233. return document().focused_element() == this;
  234. }
  235. bool Element::is_active() const
  236. {
  237. return document().active_element() == this;
  238. }
  239. NonnullRefPtr<HTMLCollection> Element::get_elements_by_class_name(FlyString const& class_name)
  240. {
  241. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  242. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  243. });
  244. }
  245. void Element::set_shadow_root(RefPtr<ShadowRoot> shadow_root)
  246. {
  247. if (m_shadow_root == shadow_root)
  248. return;
  249. m_shadow_root = move(shadow_root);
  250. invalidate_style();
  251. }
  252. NonnullRefPtr<CSS::CSSStyleDeclaration> Element::style_for_bindings()
  253. {
  254. if (!m_inline_style)
  255. m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this);
  256. return *m_inline_style;
  257. }
  258. // https://dom.spec.whatwg.org/#element-html-uppercased-qualified-name
  259. void Element::make_html_uppercased_qualified_name()
  260. {
  261. // This is allowed by the spec: "User agents could optimize qualified name and HTML-uppercased qualified name by storing them in internal slots."
  262. if (namespace_() == Namespace::HTML /* FIXME: and its node document is an HTML document */)
  263. m_html_uppercased_qualified_name = qualified_name().to_uppercase();
  264. else
  265. m_html_uppercased_qualified_name = qualified_name();
  266. }
  267. // https://html.spec.whatwg.org/multipage/webappapis.html#queue-an-element-task
  268. void Element::queue_an_element_task(HTML::Task::Source source, Function<void()> steps)
  269. {
  270. auto task = HTML::Task::create(source, &document(), [strong_this = NonnullRefPtr(*this), steps = move(steps)] {
  271. steps();
  272. });
  273. HTML::main_thread_event_loop().task_queue().add(move(task));
  274. }
  275. // https://html.spec.whatwg.org/multipage/syntax.html#void-elements
  276. bool Element::is_void_element() const
  277. {
  278. 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);
  279. }
  280. // https://html.spec.whatwg.org/multipage/parsing.html#serializes-as-void
  281. bool Element::serializes_as_void() const
  282. {
  283. return is_void_element() || local_name().is_one_of(HTML::TagNames::basefont, HTML::TagNames::bgsound, HTML::TagNames::frame, HTML::TagNames::keygen);
  284. }
  285. }